/algo-trading-skills:order-placement-idempotencyfrom algo-trading-skills
Prevents duplicate live orders after retries, timeouts, or reconnects by maintaining a client-side order ledger. Essential for any trading bot with retry logic over unreliable networks.
Ships in algo-trading-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Invoke this any time order-placement code includes retry logic, runs over an unreliable network, or could be re-triggered by a reconnect/restart. A naive retry-on-timeout ("call failed, try again") is the single most common cause of accidental duplicate live orders, because a timeout does not mean the order failed — it may mean the order succeeded and only the response was lost.
The premise worth stating plainly: not one broker in this skill's coverage table documents
an idempotency guarantee for order placement. Kite Connect, Upstox and Alpaca all document
a client-supplied tag field, and none of the three documents duplicate suppression on it
(see references/standards.md for what each one actually says). So the client-side tag is
not a safety mechanism supplied by the broker — it is a correlation handle that lets you
answer one question after a lost response:
Did the order I cannot see a response for actually land?
Everything in this skill exists to keep that question answerable. The order becomes idempotent because you refuse to send it twice, not because the broker refuses to accept it twice.
This is also the pre-trade duplicate control that SEC Rule 15c3-5(c)(1)(ii) expects a broker-dealer with market access to have: controls reasonably designed to "[p]revent the entry of erroneous orders, by rejecting orders that exceed appropriate price or size parameters, on an order-by-order basis or over a short period of time, or that indicate duplicative orders."
broker-api-idempotent-cancel-requests.PLACED means the broker acknowledged the order, not
that it filled, and a working order can still be rejected, cancelled, or partially filled
afterwards. The ledger here tracks placement intent; the order-state stream tracks
outcomes — see webhook-based-order-fill-notifications and
zerodha-kite-postback-webhook-verification.india-sebi-algo-trading-tagging-requirements. Do not put an
idempotency key where the algo ID belongs.kill-switch-and-drawdown-circuit-breakers.orderId is a client-assigned integer seeded from the nextValidId callback and must
increase; the broker-assigned permId is the identifier that is unique across sessions.
The workflow below still applies — the key becomes an integer you allocate and store in
the ledger, and reconciliation matches on permId.tag at 20 alphanumeric characters, so this skill's 24-character default
key does not fit it. Check the length limit before deriving keys — see
references/standards.md.broker_echoes_key flag in scripts/order_ledger.py.GET /v2/orders defaults to status=open) makes an order that filled
during the timeout look absent, releases the claim, and re-sends it.strategy_id, one representation of the
signal timestamp, and one numeric type per field. qty=50 and qty=50.0 must not derive
two keys for one order.Derive a stable idempotency key. Hash the order identity — strategy, symbol, side,
signal timestamp, quantity, price — after canonicalising it, and truncate to the broker's
tag length. make_idempotency_key() upper-cases symbol/side, renders numbers at fixed
precision and normalises datetimes to UTC, so a restart that passes an int where the hot
path passed a float still derives the same key.
sequence discriminator when repeat orders are intended.
Silent suppression of a wanted order is as expensive as a duplicate.Claim the intent before the network call. Insert a PENDING row keyed by the
idempotency key before sending. The primary-key insert is the claim: it either succeeds
(this caller owns the send) or raises an integrity error (someone else owns it). That is
what makes the sequence safe across threads and across processes sharing the ledger — a
check-then-act on a SELECT is not.
Send once. Attach the key to the broker's client-tag field. One place_order call
issues at most one broker call, ever.
Classify the response into three outcomes, and be stingy with the terminal two.
PLACED, store the id.REJECTED, store the reason.UNKNOWN.{"status": "success", "data": {"order_id": …}} is Kite Connect's actual acknowledgement body; code that only accepts
{"status": "SUCCESS"} files it as a rejection, and the ledger then says no order exists
while one is working. The next signal duplicates it. Interim states such as PUT ORDER REQ RECEIVED or VALIDATION PENDING are likewise not rejections. Anything the broker
did not state unambiguously is UNKNOWN.{"status": "error", "error_type": "NetworkException"} — the same status
token it uses for a flat refusal such as InputException, but an outcome that is
genuinely unknown: the request may have reached the matching engine before the gateway
gave up. Only an explicit refusal is REJECTED: an explicit rejection status, or an
error_type naming a class the broker uses to decline a request (InputException,
OrderException, MarginException, PermissionException, TokenException). Transport
and gateway classes, unrecognised error classes and every 5xx are UNKNOWN and go to
reconciliation. Matching on the word error alone writes "no order exists" during exactly
the network event most likely to have left one working.UNKNOWN; never
fabricate a placeholder id.Reconcile UNKNOWN against the broker order book — as a tri-state, not a boolean.
PENDING/UNKNOWN is a
dead end: the next call hits the same claim, reconciles, concludes absent again, and
loops. ABSENT is the one outcome that releases the claim — archive the released row
rather than dropping it, so the placement history of a key survives. Nothing else may
release it: an unresolved intent that has not been proved absent stays claimed.user_remark is reported not to survive into responses), a miss
means nothing at all, and treating it as absence re-sends a live order.INCONCLUSIVE, not absence. The most
likely reason you cannot reach the order book is the same outage that ate your response.Fall back to attribute matching only when the broker cannot echo the key — and keep it
strict. Match on symbol, side, quantity and price, restricted to a time window around
the intent, excluding any broker order already linked to another ledger row, and refuse to
choose when more than one candidate qualifies. Matching on (symbol, side, quantity) alone
will happily adopt an earlier identical order and report a position the account does not
hold. Document the residual risk: this is strictly weaker than a broker-echoed key.
Sweep every unresolved intent at startup, before generating a single new signal.
recover_unresolved() reconciles all PENDING/UNKNOWN rows. A bot that resumes signal
generation with an in-flight order from before the crash doubles the position, and the
ledger entry that would have caught it is sitting one query away.
Full step-by-step procedure with broker-specific detail: see
references/workflows.md. Broker/framework coverage table and regulatory citations: seereferences/standards.md. Printable pre-flight checklist: seeassets/checklist.md.
PENDING or UNKNOWN. The subtler
form of the same bug: the first call handles the timeout correctly, and then the caller's
outer retry loop calls place_order again with identical arguments and the guard only
checks for PLACED. An unresolved intent must block the send, not fall through it.{"status": "success", "data": {"order_id": …}}; a strict equality check
against "SUCCESS" records a live order as rejected."error" or "failed" as a terminal rejection. Kite returns
{"status": "error", "error_type": "NetworkException"} for a gateway fault, and a 5xx is
the server failing to answer rather than declining the order. Both may leave a live order.
The error_type — not the status word — is what separates a refusal from an unknown.PENDING/UNKNOWN, the
re-invocation reconciles back to absent forever and the order is never sent — the
mirror-image failure of the duplicate, and quieter.tag as
"alphanumeric, max 20 chars". A 24-character key is either rejected or silently truncated,
and a truncated key is a key you cannot match on.user_remark, but the
official SDK repository carries an open, unanswered issue reporting that the field is not
preserved in responses. A reconciliation strategy built on reading it back never fires.(symbol, side, quantity) alone. For any strategy that scales into a
position, yesterday's identical order matches today's intent, the ledger records a phantom
fill, and the real order is never sent.qty=50 on the hot path and qty=50.0 after a restart
hash to different keys, so the restart re-sends the order the ledger was holding.SELECT.data as an
array of order ids for a single request. A ledger row that stores only the first id
leaves the rest untracked.client_order_id is documented
at 128 characters, and its uniqueness is reported to be enforced against open orders
rather than for all time; IBKR's orderId is explicitly reusable across days. Scope key
reuse to what the broker actually guarantees.ABSENT, releases the claim and sends the order again. The book has
to include the session's completed orders.python -m unittest discover -s skills/order-placement-idempotency/scripts. The suite
asserts the invariants directly: at most one broker call per place_order, no re-send
while an intent is unresolved, indeterminate responses classified UNKNOWN, absence
concluded only when the key is echoed, and eight concurrent calls on one key producing one
send.recover_unresolved() links the existing broker order and that exactly one order exists on
the broker side.PLACED row has a broker order id, no
broker order lacks a matching ledger row, and no row sat in UNKNOWN past a session
boundary without an operator record of how it was settled.broker-api-idempotent-cancel-requestskill-switch-and-drawdown-circuit-breakerswebhook-based-order-fill-notificationsindia-sebi-algo-trading-tagging-requirementssec-rule-15c3-5-risk-controls-usmulti-broker-rate-limit-handlingpaper-to-live-promotion-checklistWhat SKILL.md sets; muted values are Claude Code's defaults
36 skills in this plugin
/alpaca-paper-live-key-separationUse when a bot connects to the Alpaca Trading API and must never cross paper keys with the live endpoint; pins the base URL per environment, checks the key prefix, probes /v2/account and requires an explicit ALLOW_LIVE_TRADING flag./api-key-least-privilege-audit-toolUse before deploying a live bot, to audit existing broker API keys for scopes they do not need. Flags withdrawal, transfer and admin rights that turn a leaked execution key into theft./broker-account-margin-call-handlingUse when a bot trades a Reg T, portfolio or futures margin account and must act before the broker liquidates: tiered maintenance-margin warnings cross-checked against broker excess liquidity, initial-margin order gating and liquidity-aware de-leveraging./broker-agnostic-adapter-interfaceUse when strategy code must run across several brokers and should not import kiteconnect, alpaca-py or ibapi directly; defines an adapter contract with Decimal prices, typed exceptions and normalised order status across venues./broker-api-changelog-diffing-toolUse before upgrading a broker SDK or OpenAPI spec, to diff two schema snapshots for removed endpoints, newly required parameters, enum mutations and type changes so CI fails before the change reaches an order path./broker-api-deprecation-notice-monitoringUse when a long-running bot calls REST endpoints a broker may retire; parses RFC 8594 Sunset and RFC 9745 Deprecation headers plus changelog feeds into one dated migration deadline with an escalation tier.npx claudepluginhub himanshuj16/algo-trading-skills --plugin algo-trading-broker-integrationOther plugins' skills for the same job