Agentic Trading Index

Handling partial fills and rejections in trading code

Trading terminal showing order status fields relevant to handling partial fills and rejections
Photo by Wolfgang Weiser on Pexels

In nearly every unattended trading setup, an order acknowledgement arrives before the first fill, and the software has to decide what to do with the remaining quantity. Treating that acknowledgement as proof of execution is a common source of duplicate exposure. A solid system tracks order state, individual executions and the quantity still working, then reconciles them before sending another instruction.

Model the order as state

An API response saying an order was accepted means the broker received it. It does not mean the order filled, reached an exchange, or will remain eligible to trade. Keep a durable record of the request and represent its state explicitly. Typical states include pending acknowledgement, working, partially filled, cancel pending, cancelled, filled, rejected and unknown.

Store quantities separately: original quantity, cumulative filled quantity, leaves quantity and cancelled quantity. For a live order, the basic invariant is that cumulative fills plus leaves quantity plus cancelled quantity must reconcile to the original quantity, subject to the broker's rules for amendments. Update the record from execution events, not from an assumption that each status message describes the latest state.

Give each submission a stable client order ID and persist it before sending the request. If a network timeout leaves the response unknown, query by that ID or reconcile from the broker's order feed before retrying. A new order ID can turn one uncertain request into two live orders. Make event processing idempotent by recording execution IDs and ignoring an execution already applied.

Reconcile fills before changing quantity

A partial fill is a completed trade plus a still-open order. If an order for 500 shares reports 180 filled and 320 leaves, the strategy must account for the 180 shares immediately.

Risk checks should use the filled position and the working exposure separately. Otherwise, the agent may submit another 500 shares when it intended to top up only the remaining 320.

Cancel and replace operations create a race. A fill can occur after the cancel request but before the broker confirms cancellation. Do not treat a cancel request as a cancellation. Wait for the terminal response, apply any execution reports received during the race, then calculate the residual from the latest cumulative fill. Some APIs report a cancel acknowledgement and a fill event in either order, so event timestamps alone are not a safe ordering mechanism.

Use a broker snapshot to reconcile after reconnects, sequence gaps or an unexplained quantity mismatch. Compare open orders and executions over an overlapping time window, deduplicate by execution ID, and retain the raw messages for diagnosis.

WebSocket events reduce delay; periodic REST reconciliation catches missed events. Polling every 1 to 5 seconds can be a practical fallback, subject to the broker's rate limits.

Classify rejections before retrying

A rejection is not one condition. Parse the broker's code and message into a small set of actions. Preserve the raw response as well as the normalised category, because brokers may change wording or expose venue-specific detail.

  • Correctable request: invalid price increment, quantity precision or required field. Fix the request, then submit a new version with a new client order ID.
  • Temporary constraint: rate limit, market state or transient service issue. Back off with jitter and check whether the original request exists before resubmitting.
  • Risk or account block: insufficient buying power, position limit or restricted instrument. Do not retry unchanged. Recalculate permitted size or stop and raise an alert.
  • Price or liquidity rejection: price collar, unavailable route or order type restriction. Reprice only if the strategy still approves the new limit and the remaining order is still useful.

Do not use a blanket retry loop. A reasonable starting policy for transient errors is a short initial delay, perhaps 250 to 500 milliseconds, followed by exponential backoff with jitter and a strict attempt limit. Respect any server-provided retry interval. A timeout is different from a rejection: the broker may have accepted the order while the client missed the response, so resolve its status before trying again.

Measure the cost of incomplete execution

Measure costs against a defined reference price, such as the mid-price at decision time or the arrival price when the order reached the broker. For liquid US-listed shares in normal conditions, the table gives typical market ranges, not audited results for a company or a promise for a particular order. The example column translates each range to a $10,000 order. At $10,000 notional, one basis point equals $1.

Cost componentTypical market rangeExample per $10,000What to record
Commission$0 to $5 per 1,000 shares$0 to $5 at $10 per shareBroker, route and filled share count
Spread crossing0.5 to 5 bps per side$0.50 to $5 per sideArrival mid-price and execution price
Slippage beyond arrival price0 to 10 bps per filled notional$0 to $10Side-adjusted shortfall at fill time
Market impact0.5 to 20 bps per filled notional$0.50 to $20Participation rate, size and volatility
Unfilled residual opportunity cost1 to 30 bps over a short evaluation window$1 to $30 on $10,000 unfilledResidual notional and price move over the chosen window

These rows are not additive without adjustment. Slippage measures an observed execution outcome and can already include spread crossing or market impact. Estimate components separately only when the reference prices and model support that separation. Opportunity cost is also directional: a missed buy that rises costs the strategy relative to its benchmark, while a price fall may improve the result.

For each order, retain intended quantity, executed quantity, average fill price, time to first fill, completion time, rejection reason and residual price movement. Report the figures by instrument, order type, session and participation rate. A single average can hide a weak tail, such as a small number of stale residuals that account for most shortfall.

Benchmark the failure paths

Test the order manager with event sequences, not only successful fills. A useful benchmark suite varies fill size, event order, delays and broker responses. Include a partial fill followed by a cancel, a fill arriving during cancellation, duplicate execution messages, a dropped connection, a timeout after acceptance and a rejection that follows a retry.

Set correctness thresholds separately from latency objectives. Duplicate applied executions and unexplained position mismatches should be zero. Every non-terminal order should have a current broker status or an explicit unknown state with a reconciliation deadline. Track p50 and p95 time to first fill, completion rate, rejection rate, cancel-to-terminal time, event lag and the number of resubmissions. Compare like with like: symbol liquidity, order size and market session change the expected ranges materially.

Run the same scenarios in a simulator and against the broker's paper environment, then inspect live API semantics before enabling real orders. Paper execution may not reproduce queue priority, exchange-specific rejects or real liquidity. Agentic Trading Index offers agentic paper trading from $9.99 a month at fx-tech.ai, which can help exercise the agent's state transitions without risking live capital. It does not replace broker-specific integration tests.

Use a pre-live checklist

Before unattended operation, verify the full path from request creation to position reconciliation. Keep the checks executable where possible, so a deployment can fail closed when core invariants break.

  1. Persist the order intent, client order ID and risk decision before submission.
  2. Handle acknowledgement, execution, cancel and rejection messages as separate events.
  3. Deduplicate executions and reconcile cumulative fills against broker snapshots.
  4. After a timeout, resolve whether the order exists before resubmitting.
  5. On cancel or replace, account for fills that arrive before terminal confirmation.
  6. Apply bounded retries only to classified transient errors, with backoff and rate-limit handling.
  7. Alert on unknown order state, stale updates, quantity mismatch and repeated rejection.
  8. Test recovery after process restart, connection loss and duplicate or out-of-order events.

Keep a manual kill switch and a bounded maximum for open notional while the system is being validated. Log the decision price, broker messages and state transitions in a form that can be replayed. This advice does not apply unchanged to all-or-none or immediate-or-cancel orders, or to broker algorithms that hide child-order state; implement those against their specific contract and reporting semantics.

Frequently Asked Questions

What should a trading bot do after a partial fill?

Update the position for the executed quantity and retain the leaves quantity as working exposure. Reconcile the order with the broker before deciding whether to wait, cancel or submit a replacement.

Should an order be retried after an API timeout?

Not until the bot checks whether the broker accepted the original request. Query by the original client order ID or reconcile the open-order feed to avoid creating duplicate exposure.

How should code handle a fill received during cancellation?

Apply the fill even if a cancel request is pending. Wait for a terminal broker update, then calculate the remaining quantity from the latest cumulative fill before creating another order.

Which costs should be measured for partial fills?

Record commissions, spread crossing, slippage, market impact and the price movement on unfilled quantity. Use a consistent arrival-price benchmark and avoid adding components that overlap.

How can partial fill handling be tested safely?

Build tests for partial executions, duplicate events, delayed cancel acknowledgements, timeouts and reconnects. Paper trading can exercise state transitions, but it may not reproduce live queue position or venue rejection behaviour.