Model the order as events, not a response
An HTTP success is not a fill, and a timeout is not proof that an order failed. Treating either as a final answer is how an unattended process submits duplicates or loses track of its exposure. The order lifecycle needs a durable record of what the agent intended, what it sent and what the broker later confirmed.
Keep the order intent separate from each submission attempt and from the broker's order identifier. Give every intent a unique client order ID and persist it before sending.
Store broker acknowledgements, executions, rejects and cancel responses as events. A reducer can then build the current state from that event history, rather than relying on whichever status response arrived last.
Track cumulative filled quantity and remaining quantity independently. For a 100-share order with 35 shares executed, the remaining quantity is 65, even if a delayed status message still says working.
Deduplicate executions using the broker's execution ID. If the API provides cumulative quantity but no unique execution ID, record the source message and reconcile changes without adding the same cumulative quantity twice.
Statuses also need more nuance than a single enum. A cancelled order can have a non-zero fill; a cancel request can race with an execution; and an acknowledgement can arrive after a client timeout. Preserve the event history and represent both order state and filled quantity. The following are typical implementation ranges, not service guarantees. Actual timings vary with broker, venue, instrument and load.
| Operation | Typical ranges | What it means | Safe response |
|---|---|---|---|
| Order acknowledgement | 50 ms-2 s | A response may confirm receipt, not execution | Wait for order and execution updates |
| Cancel acknowledgement | 100 ms-2 s | Fills can arrive before the cancel takes effect | Keep the order live until confirmed |
| Status polling interval | 250 ms-2 s | Polling faster may add load without fresher data | Use event updates plus bounded polling |
| Transient retry backoff | 250 ms-5 s | Rate limits and brief network faults need space | Use jitter and check order state first |
Build around the broker's actual API semantics. Some APIs provide execution streams, others require polling, and some expose both with different timing. Document which source is authoritative for each field before using the data to update positions or risk.
Days 1-10: build the durable order record
Start with the data model and the write path. A practical minimum is an order intent table, an event journal and a position ledger derived from executions.
Persist the intent and its client order ID before making the network call. If the process stops between those steps, it should be possible to tell whether there is an order to submit, an attempt in flight or an unresolved outcome.
Use the first ten days to deliver these checkpoints:
- Days 1-2: Document the broker's order, execution, reject, cancel and replace fields. Record which identifiers remain stable across reconnects and which messages can arrive out of order.
- Days 3-4: Define order states and allowed transitions. Include unknown and pending states. Do not treat a missing acknowledgement as rejected.
- Days 5-6: Write intents and submission attempts durably. Enforce uniqueness for the client order ID in your database.
- Days 7-8: Build an event reducer that deduplicates executions and updates cumulative and remaining quantities.
- Days 9-10: Test restarts after every network boundary: before send, after send, after acknowledgement and after an execution.
The difficult case is a submission timeout. The broker may have accepted the order while the client missed the response. Mark the outcome unknown, then query by client order ID or reconcile open orders before deciding what to do.
If the broker has no lookup by client ID, compare open orders using a carefully scoped combination of account, instrument, side, quantity, price and time. That fallback is weaker, so keep the agent from submitting another order until the ambiguity is resolved or an explicit risk policy permits it.
Do not invent idempotency by retrying the same HTTP request and assuming the broker will recognise it. Verify whether the broker guarantees uniqueness for client IDs, how long it retains them and what happens if the same ID is reused with changed parameters.
Days 11-20: make rejects and retries deliberate
A rejection is a broker decision, not a generic error. Save the raw reason code and message, then map it to a small internal classification: invalid request, risk or permission constraint, market or instrument state, rate limit, or transient service failure.
Retain the original broker text for diagnosis. Do not let a mapping layer erase an unfamiliar code; classify it as unknown and stop automatic retry until its behaviour is understood.
Retry only failures that can plausibly clear without changing the order. A rate limit may merit a delayed retry. A malformed tick size, insufficient buying power or closed market needs a changed input or a later session, not the same request again.
A timeout is different from a rejection: check whether an order exists first. Use bounded exponential backoff with jitter, a maximum attempt count and a deadline. Respect any broker retry-after instruction.
Partial fills need their own policy. Once an order has executed part of its quantity, calculate remaining exposure from confirmed executions, not the original requested size.
Decide in advance whether the remainder stays working, is cancelled after a time limit, or is repriced under a specific rule. A marketable limit order may fill quickly in a liquid market, but a passive limit can sit unfilled. Never assume a remainder will fill simply because the first portion did.
- Cap remaining quantity by the strategy's current target and the account's available risk budget.
- Check whether the price is still valid before replacing a remainder.
- Keep the original order linked to any replacement, so a late fill on the original can be reconciled.
- Make retry decisions on a single execution path, not independently in the strategy and transport layers.
Cancel and replace operations require particular care. Some brokers implement replace atomically; others cancel the old order and submit a new one. In the second case, the old order may fill during the gap. Wait for a terminal confirmation where the API supports it, then recalculate the residual. If you cannot wait, reserve risk for both possible outcomes until reconciliation resolves the race.
Days 21-26: test the failures that change exposure
Tests should focus on event sequences, not isolated status values. Build a deterministic simulator that can delay, duplicate and reorder acknowledgements, fills and cancels. Feed the same event sequence into the reducer more than once. The resulting position and remaining quantity should be unchanged after duplicate delivery.
Include a partial fill followed by a cancel, a fill arriving after a cancel request, a rejected replacement while the original remains live, and a timeout after the broker accepted an order. Also test a disconnect while an execution stream is active, then reconnect and replay events. A good invariant is that the position ledger changes only when a unique execution is applied, not when an order is acknowledged, cancelled or rejected.
Use paper trading to exercise the workflow, but do not assume a sandbox reproduces production timing, queue priority or reject behaviour. Record the differences you can observe and inject the missing cases in tests. Agentic paper trading through FX-Tech.ai starts at $9.99 a month, which can provide a practical environment for testing an agent's order-handling loop alongside your own simulated failure cases.
For each test, assert both the expected state and the action the agent is allowed to take next. For example, after a submission timeout with no lookup result, it should not send a second order blindly. After a partial fill and confirmed cancellation, it may consider a new order for the residual only after recalculating the target and risk budget.
Days 27-30: reconcile before enabling unattended orders
Use the final four days to build a reconciliation loop and operating limits. Compare local open orders and positions with broker snapshots at startup, after reconnect and on a schedule. Use executions as the preferred source for trade quantity.
Position snapshots can reveal gaps, but may include manual activity, corporate actions or delayed updates. When local and broker state differ, stop new orders for the affected instrument or account until the discrepancy is explained.
Log every intent, request, response, event, state transition and retry with a correlation ID. Avoid logging credentials or sensitive account data. Monitor a compact set of measures:
- Orders with unknown outcomes and their age.
- Duplicate or out-of-order events detected.
- Reject counts by reason code.
- Time from submission to acknowledgement and execution.
- Differences between local and broker positions.
Set thresholds from observed behaviour in your own environment rather than copying a universal limit. For example, an unknown order outcome that persists beyond the normal acknowledgement window should page an operator or halt new submissions, not trigger unlimited polling. Rate-limit warnings and repeated risk rejects should also stop the strategy from creating more orders. Define a kill switch that prevents new intents while still allowing reconciliation and, where safe, cancellation.
When the outcome is unknown, preserve risk first and resolve the order second.
Run the agent in shadow or paper mode with the production state machine and alerting enabled. Then permit live orders only under explicit limits for order size, open-order count, daily loss and unresolved states. Keep a manual recovery procedure for cases the code cannot classify, including how to freeze new submissions and compare broker records with the local event journal.
The mistake most readers will still make is treating a partial fill as a smaller completed order, then submitting the full original quantity again instead of calculating and controlling the residual.
Frequently Asked Questions
How should trading code handle a partial fill?
Update the position from the confirmed execution and calculate the remaining quantity as original quantity minus cumulative fills. Apply a defined policy to the remainder, such as leaving it live, cancelling it after a time limit or repricing it after checking current risk and price conditions.
Should an order be retried after a broker API timeout?
Not until the system has checked whether the broker accepted the original order. Mark the outcome unknown and query by client order ID or reconcile open orders. A blind retry can create duplicate exposure.
What is the safest way to handle a rejected order?
Store the broker's reason code and classify the rejection before taking action. Retry only when the cause is transient and the order's state is known. Correct invalid parameters or risk constraints rather than resending the same request.
How do you test cancel and fill races?
Use a deterministic simulator that can deliver fills before or after cancel acknowledgements and can duplicate or delay events. Assert that executions change positions once, and that the agent reserves risk until the old order's final state is known.