Agentic Trading Index

Handling partial fills and rejections in trading code

Trader reviewing an order dashboard while considering how code should handle partial fills and rejections
Photo by Rafael Minguet Delgado on Pexels

A bad week starts with a misleading position

It is Friday afternoon. A developer is looking at a dashboard after a bad week: the strategy says it bought 500 shares, the broker shows 320 filled, and the internal position says zero. A timeout occurred during submission. The retry may have created a second order. The logs contain both an acknowledgement and a rejection, but nobody can tell which one describes the live order.

This is not a corner case. Brokers send asynchronous updates, requests time out after the broker has accepted them, and cancel requests can race with fills. A solid order manager must preserve what is known, mark what is uncertain, and avoid changing exposure until it has enough evidence.

Keep three records distinct: the strategy's desired position, the orders intended to reach it, and the executions that actually changed the account. The position should come from starting inventory plus confirmed fills, not from submitted quantity or an order acknowledgement. That separation turns confusing events into a state-reconciliation problem.

Represent orders as state, not messages

Persist an order intent before sending it. Give it an internal intent ID, a client order ID where supported, and a broker order ID once returned.

Store the account, instrument, side, requested quantity, limit price, time-in-force, creation time and strategy version. Do not assume a client ID makes submissions idempotent unless that broker explicitly guarantees it.

Track each order through explicit states such as pending submission, accepted, partially filled, cancel pending, cancelled, filled, rejected and unknown. "Unknown" matters: a network timeout is not a broker rejection.

It means the request outcome has not yet been established. Keep the original intent unchanged and reconcile before deciding whether to submit anything else.

Broker events may arrive more than once or out of order. Deduplicate executions using the broker's execution ID, scoped to the account and order. Keep raw events for audit, then update a normalised order record. If the API provides sequence numbers or event cursors, persist them and detect gaps. Where it does not, compare event-stream state against order and execution snapshots.

Use decimal quantities and prices, and apply the instrument's lot and tick rules before submission. Record cumulative filled quantity and average fill price, but retain individual executions as the accounting source. Corrections, busts or trade amendments need an explicit path; silently overwriting a fill can leave positions and cash inconsistent.

Book partial fills as exposure immediately

A partial fill is a real position, not an incomplete request to ignore. If a buy order for 500 shares has executed 320, book 320 shares and treat only the remaining 180 as potential additional exposure. Recompute risk limits, cash, borrow or margin requirements, and target-position difference from the confirmed execution.

Do not resubmit the original 500. First establish the broker's leaves quantity or derive it from accepted quantity minus cumulative fills, taking any cancel or replace state into account. A cancel request is only a request. Until cancellation is confirmed, the unfilled balance may still execute. A fill that arrives during a cancel race must update the position even if the strategy already asked to stop.

Set a policy for what to do with the remainder. A passive strategy might leave the limit order working until a defined expiry. An urgency-sensitive strategy might cancel and cross the spread after a time or price threshold. The threshold belongs to the strategy and instrument: a 2-second wait might be excessive for one signal and immaterial for another. Store the reason for each change so later analysis can separate strategy decisions from API recovery.

After a replace, treat the old and new broker orders as separate records connected to one intent. Do not assume the replace was atomic.

Some APIs cancel the old order before accepting the new one; others can reject the replacement while the original remains live. Reconcile both IDs and calculate total live leaves across them before sending another order.

Classify rejections before retrying

A rejection should carry a reason code and a decision, not trigger a generic retry loop. Map broker-specific codes into a small internal set, retain the original response, and alert when an unknown code appears. Useful categories include:

  • Permanent request errors: invalid symbol, unsupported order type, bad tick size or malformed quantity. Fix the request; do not retry it unchanged.
  • Account or risk blocks: insufficient buying power, restricted instrument or risk limit breach. Stop, refresh the relevant state, and require the strategy's risk policy to permit a new attempt.
  • Potentially transient failures: rate limit, temporary service error or venue unavailable. Back off with jitter, respect any retry-after value, and cap attempts.
  • Ambiguous submission outcomes: connection loss or timeout without a definitive broker response. Query by client ID or inspect open orders and executions before sending again.

For a transient error, a starting policy might allow three attempts with delays around 250 ms, 1 second and 4 seconds, subject to broker limits and the strategy's time horizon. These are configurable starting values, not universal timings. If the broker confirms a rejection, a new submission should have a new attempt record linked to the same intent. If the outcome is ambiguous, do not create a fresh order merely because the request call returned an error.

Repeated rejects should trip a circuit breaker for that instrument, account or API route. A threshold such as five consecutive rejects within 60 seconds can be a useful test setting. Alert, pause new exposure and continue reconciliation. A circuit breaker should not discard working orders or stop processing fills already in flight.

Price the failure paths

These are typical planning ranges for liquid, frequently traded instruments under ordinary conditions, not venue guarantees. Thin markets, large orders and fast news can produce higher costs. Use live execution records to replace assumptions.

Failure pathTypical rangeCost basis
Crossing the spread on a residual0.5-5 bpsResidual notional, for a quoted spread of roughly 1-10 bps
Market impact for a modest order0.5-10 bpsOrder notional; size and available depth drive the result
Waiting to complete a residual0-10+ bpsResidual notional over seconds to a minute; direction is uncertain
Blind retry after an ambiguous timeoutUp to 100% extra quantityOriginal order quantity, if the first submission was accepted

Track costs against the unfilled amount, not just the initial order. Record arrival mid-price, fill prices, fees, filled quantity, decision delay and the price when the residual was cancelled or completed. Compare like with like: a passive fill rate and a marketable-order slippage figure describe different choices.

Build tests that inject duplicate events, delayed fills, a reject after a timeout, and a fill between cancel request and cancel acknowledgement. An agentic paper trading environment such as Agentic Trading Index paper trading from $9.99 a month can help exercise the order manager without risking live capital. Paper results still need limits: simulated liquidity and venue timing may not reproduce live queue position, partial execution or market impact.

Run this checklist before unattended deployment

  1. Persist order intent before the network call, and assign stable internal and client IDs.
  2. Test the distinction between rejected, accepted, partially filled, cancelled, filled and unknown states.
  3. Make duplicate execution events harmless, and verify that cumulative fills never create duplicate position changes.
  4. Test a timeout after broker acceptance. Confirm that recovery queries state instead of blindly resubmitting.
  5. Test cancel and replace races, including a fill arriving before the cancellation acknowledgement.
  6. Set bounded retry counts, backoff, rate-limit handling and circuit-breaker thresholds.
  7. Reconcile open orders, executions, cash and positions at startup, after stream gaps, and on a schedule during operation.
  8. Alert on unknown broker codes, position differences, stale orders and reconciliation failures. Include order IDs and timestamps in each alert.
  9. Run the same scenarios against recorded event sequences, then review logs to confirm that each position change has an execution behind it.

Keep a kill switch that blocks new orders without suppressing cancellation, fill processing or reconciliation. Before enabling unattended trading, define who or what can reset the breaker and what evidence is required. The mistake most readers will still make is treating an order timeout as a rejection and sending the same quantity again.

Frequently Asked Questions

What should a trading bot do after a partial fill?

Book the confirmed filled quantity as exposure immediately. Recalculate the remaining quantity from broker state, then follow the strategy's policy for leaving, cancelling or replacing the remainder. Do not submit the original quantity again.

Should code retry an order after a broker timeout?

Not until it establishes whether the broker accepted the first request. Query by client order ID or reconcile open orders and executions. A timeout is an unknown outcome, not proof of rejection.

How should order rejections be handled in an API?

Classify each rejection by reason and retain the broker response. Correct permanent request errors, stop on account or risk blocks, and apply bounded backoff only to failures known to be transient.

How can a bot avoid duplicate fills in its position ledger?

Deduplicate executions with broker execution IDs scoped to the account and order. Keep raw events for audit, and derive position changes from confirmed executions rather than acknowledgements or requested quantities.

What does a cancel acknowledgement mean if a fill arrives at the same time?

Reconcile both events against the broker's order and execution state. A cancel request does not guarantee that the remaining quantity stopped being executable, so a fill during the race must still update the position.