An automated trading system cannot treat an order as a single instruction that either “worked” or “failed.” An order may be accepted, routed, partly executed, canceled with some quantity already filled, or updated while a cancel or replacement request is still pending. Each event can change the account’s exposure. If the system records only the final status, it can miss a real position or submit a duplicate order while the original is still active.
Reliable order management tracks two related but different things: the order’s current state and the executions that have occurred. A partially filled order, for example, has an executed quantity and a remaining quantity. A cancellation request does not prove the remainder has been canceled. The trading system must process execution updates, preserve their identifiers, and compare its own records with the broker or venue’s records. This is the practical work of position reconciliation. It matters whether the strategy is manual, AI assisted, or fully automated; the model’s signal is only one part of the trade.
Order status and execution are different records
An order is an instruction to buy or sell a defined quantity under stated conditions. An execution, often called a fill, is a trade completed for some or all of that quantity. One order can produce several executions, each with its own quantity, price, timestamp, and identifier. A system that stores only one “filled” price can lose useful information about the actual transaction, particularly when the order trades at different prices or incurs fees on separate fills.
Order status describes where the order stands in its lifecycle. Common states include new, partially filled, filled, pending cancel, canceled, pending replace, replaced, rejected, and expired. The exact names and transitions vary across APIs and venues, so software should map the provider’s documented states into its own internal model rather than assume every platform uses the same labels. FIX, a widely used electronic trading messaging standard, distinguishes the current order status from the purpose of an update. Its order-state guidance also makes clear that a pending cancel means a request is being processed, not that cancellation has been confirmed. FIX guidance on order states and pending cancellations is a useful reference for this distinction.
The execution record answers a separate question: what quantity actually traded, and at what price? The order record may show the requested quantity, cumulative quantity filled, and leaves quantity still working. The execution ledger should preserve every individual fill. Together, these records let the system calculate the current order state and the resulting position without treating a status message as if it were itself a trade.
How partial fills change exposure
A partial fill occurs when only part of an order’s quantity executes. Suppose a system submits a buy order for 100 shares. It receives a fill for 35 shares, leaving 65 shares unfilled. The position has already increased by 35 shares, even if the order remains active. If the remaining quantity later fills, the total bought becomes 100. If the order is canceled before that happens, the final result may be a 35 share position and a canceled order—not a failed trade and not a 100 share position.
The arithmetic is simple, but the timing can trip up a system. The first fill may arrive before a cancellation acknowledgement. More executions may arrive while a cancel or replace request is pending. The order’s displayed status can also lag the latest execution message, depending on the provider’s event delivery and update model. A trading process therefore should not wait for a “filled” status before adjusting its exposure. Each confirmed execution changes the position as soon as it is processed.
| Order event | Order interpretation | Position effect |
|---|---|---|
| New order accepted or routed | The instruction is being handled; it may not have traded. | No position change until an execution is reported. |
| Partial fill | Some quantity traded; a remainder may still be active. | Update the position by the executed quantity. |
| Pending cancel | A cancellation request is awaiting a response. | Do not assume the remaining quantity is canceled. |
| Canceled | The provider confirms the order is no longer working. | Keep any earlier executions in the position. |
| Filled | The full order quantity has executed. | Position reflects all executions, not the requested amount alone. |
| Rejected or expired | The order did not remain active or its time condition ended. | Check for any executions reported before the final state. |
For a market order, multiple fills can occur at different prices as available liquidity is consumed. A limit order controls the maximum price for a buy, or minimum price for a sell, but it does not guarantee execution. That means a limit order can remain open after trading only in part. The SEC’s investor bulletin on market and limit orders describes these basic execution tradeoffs, including that a market order’s price is not guaranteed and a limit order may not fill.
Track requested, filled, and remaining quantity
For each live order, the system should retain at least three quantities: the original requested amount, the cumulative amount executed, and the amount still eligible to execute. In a straightforward order, the remaining amount is the requested quantity minus the cumulative executed quantity. But amendments, canceled quantities, fractional units, contract multipliers, and venue-specific rules can make a naïve calculation wrong. Keep the provider’s reported values as well as any locally derived values, then verify that they agree under the provider’s documented semantics.
Do not overwrite the original order when it is amended. Store the order chain: the initial instruction, each replacement request, the provider’s acknowledgement or rejection, and every execution. Use stable client order identifiers so a request can be matched to its response, and retain provider-assigned order identifiers and execution identifiers too. If a replacement creates a new order identifier, preserve the link to the prior order rather than treating it as an unrelated trade. This history helps explain what happened when local state and the account record diverge.
A useful internal record distinguishes requested quantity from filled quantity, leaves quantity, average fill price, and the individual executions that contribute to the average. It also records side, instrument, account, order type, limit or stop price where relevant, time in force, timestamps, and current status. Store timestamps in a consistent time standard, usually UTC, while retaining any provider timestamp or sequence number needed to interpret event order. The order-management portion of a trading system connected to a broker API needs this structure whether updates arrive through a stream or are recovered through queries.
Why cancellation is not immediate
A cancel request is a request, not a guarantee that the order has stopped. The order may execute while the cancellation is traveling through the broker, router, or venue. The system should keep the order in a pending-cancel state until it receives a definitive response, and continue processing fills against the order during that interval. If the cancel is rejected, the original order may remain active. If it is accepted, the final canceled quantity may still be less than the requested quantity because some shares or contracts already traded.
Consider an order to buy 100 shares. It fills 20. The system requests cancellation of the remaining 80. While the request is pending, another 15 shares execute. If cancellation is then confirmed, the position increase is 35 shares and the remaining 65 shares are canceled. Treating the cancel request as an immediate stop would leave the system believing it owns 20 shares when it owns 35. A follow-on order based on that false position could add exposure unintentionally.

The same race can happen during a replacement. A trader or algorithm requests a new limit price or smaller quantity, but the original order may still be executable until the replacement is confirmed. The system should not assume the new terms are active because it sent the request. It should preserve the old terms as current until acknowledgement, handle fills that arrive against the old instruction, and then apply the confirmed replacement. FIX order-state material describes fills that can occur while an order is pending a cancel or replacement; the sequence is why event handling must distinguish request submission from confirmed state change.
Process execution updates without double counting
Execution updates should be processed idempotently: receiving the same event twice must not increase the position twice. Use a unique execution ID when the provider supplies one, and persist processed IDs or an equivalent durable event ledger. If an event lacks a unique identifier, use the strongest combination available from the documented API, such as order ID, execution time, quantity, price, and sequence. A homemade composite key is less reliable than a provider’s execution identifier, so treat it as a fallback and flag ambiguous records for reconciliation.
Do not rely on messages arriving exactly once or in perfect order. Networks disconnect, clients restart, messages may be replayed, and snapshots may overlap with streamed updates. Save incoming events before applying them, validate them, then update order and position state in a controlled transaction. If the process crashes between recording a fill and updating the position, it should be able to resume safely without losing the execution or applying it twice. Streaming is useful for prompt updates; a query or snapshot is needed to recover the state after an interruption. The exact event types and recovery options depend on the provider’s API, so follow its official documentation for both streaming and order queries.
When updates are delivered through alerts or webhooks connected to execution, the receiver should acknowledge delivery only after the event has been durably recorded, where the provider’s delivery protocol allows that approach. If the connection fails, use a documented recovery process: reconnect, retrieve open orders and recent executions, and reconcile them against the local ledger. If the provider offers sequence numbers or event cursors, store and resume from them. Do not assume a fresh connection will automatically replay every event missed during downtime.

Reconcile the order book and the position book
Order reconciliation compares the system’s view of live and recently completed orders with the broker or venue’s view. Position reconciliation compares the system’s calculated holdings with the account’s reported holdings. Both are necessary. A list of open orders cannot reveal every fill that occurred before a disconnect, while a position snapshot alone may show a mismatch without explaining which order caused it.
At startup, after a network interruption, and on a regular schedule, obtain the provider’s current open orders, recent executions, and positions. Compare records using account, instrument, order identifiers, execution identifiers, and timestamps. For each order, check that its cumulative fills and remaining amount are consistent with the execution ledger and current status. For each instrument, recompute the net position from executions and compare it with the provider’s position. Account for pre-existing holdings, manual trades, transfers, corporate actions, contract multipliers, and any other activity that the strategy did not generate.
A mismatch should trigger a defined response, not a guess. The system might pause new orders for the affected instrument, request fresh snapshots, inspect recent executions and corrections, and alert an operator. It should not automatically place a “fixing” trade until it has identified whether the discrepancy comes from a missed event, duplicate processing, an external manual trade, or a genuine difference in position. A blind correction can convert a bookkeeping problem into a real unwanted trade. For a system designed to resume after outages, see the guidance on duplicate orders and connection failures.

Calculate the position from executions
Position quantity is derived from executed trades, not from submitted order quantity. For a simple cash instrument, a buy adds quantity and a sell subtracts it. For derivatives, quantity may represent contracts, lots, or units with a multiplier, so position value and risk exposure require instrument-specific rules. The execution ledger should retain the instrument definition and contract multiplier used for the calculation. Never apply a share-based formula to a futures or options position without adapting it to the contract.
Average entry price also needs careful handling. If a 35 share buy fills 20 shares at one price and 15 at another, the order’s average price is a quantity-weighted average of those executions, not the price of the latest fill. The broker’s reported average can be used as a cross-check, but the ledger should retain individual prices to support fees, realized profit and loss, corrections, and audits. If the strategy scales in or out over several orders, position-level average cost is a separate calculation from the average price of any one order.
Commissions and other charges may be reported separately from the fill, or included in later account records, depending on the provider and product. Keep them distinct from the execution price unless the provider’s accounting convention explicitly combines them. This makes it possible to compare gross trade performance with net results without altering the fill history. For system research, execution costs should also be represented in backtests, rather than treating a modeled signal price as the price actually achieved. The related guide to including trading costs in AI backtests covers that separate testing problem.
Handle corrections, busts, and unusual event sequences
Execution records are usually stable, but operational systems should allow for a provider to correct or cancel a previously reported execution. If that occurs, apply the correction to the referenced execution and recalculate the affected order totals and position. Do not simply append a negative fill without retaining the original event and its correction link; otherwise, an audit cannot show which record was superseded. The rules for corrections and their message format are provider specific.
Order event sequences can also include an acknowledgement followed by a rejection, a partial fill followed by cancellation, or a final status that differs from what the strategy expected. Model these as valid outcomes, validate the provider’s sequence rules, and raise an exception when an event cannot be matched to a known order or account. Avoid hard-coding the assumption that every new order first produces a “new” status and only later becomes partially filled. Some systems report an order’s initial response with an already executed status if it trades immediately.
When a message contradicts the current state, preserve the raw event and request an authoritative order or execution snapshot. Do not silently discard the update because it arrived “late.” A delayed fill can still represent a real trade. The system should use provider timestamps, sequence data, execution IDs, and documented correction rules to determine how the event affects the ledger. If the records remain inconsistent, pause activity that could compound the uncertainty and notify an operator.
Manage risk while an order is partly filled
Risk controls should use actual exposure plus any remaining order quantity that could still execute. If the system has bought 35 of 100 shares, it has 35 shares of position exposure and may have up to 65 more shares pending. Treating only the filled amount as relevant can understate potential exposure; treating the entire original order as already filled can overstate current holdings and distort stop or exit decisions. A practical risk calculation tracks both current position and contingent exposure from working orders.
For a strategy that sends a protective exit after an entry fill, define whether the exit quantity follows each partial execution or waits for the entry order to finish. If it responds to each fill, it must adjust the exit when later entry fills arrive and prevent the combined open orders from reversing the position. If it waits, the position may remain partly unprotected during execution. Neither policy is universally correct; the choice depends on the strategy, instrument, venue, and order type. The important point is to define the behavior before live deployment, then test partial fills and cancel races rather than only ideal full fills.
Set limits for maximum position, open order quantity, order frequency, and loss exposure. Include safeguards for a position mismatch, a stale market or account feed, and repeated order submission after a timeout. A request that times out may still have reached the provider, so retrying without checking the order book can create duplicates. Document how the system stops new entries and manages existing orders when a critical state cannot be confirmed. Trading limits, kill switches, and human oversight are part of the same operational design.
Test partial fills before live deployment
Testing should include more than a clean full fill. Simulate an order that fills in several pieces at different prices, a fill arriving during pending cancellation, a replacement that is rejected, a disconnect after a fill, duplicate event delivery, a missing event recovered by a snapshot, and a correction to a prior execution. Check that order state, remaining quantity, position, average price, and risk limits remain correct after each sequence. Test both a restart from persisted records and recovery from a fresh provider snapshot.
Paper trading can expose basic integration mistakes, but it may not reproduce the exact queue position, liquidity, latency, or fill behavior of a live venue. Treat simulated fills as a test of process logic, not proof that every live execution will match the simulation. A staged move from paper trading to live trading with defined risk limits gives the operator a chance to verify order records and position reconciliation with small exposure before increasing activity.
Monitor operational measures alongside trading performance: unmatched execution events, time between an execution and its processing, stale open orders, repeated reconciliation mismatches, and the age of the last successful account snapshot. Log state transitions and the reason for each cancel, replacement, retry, or pause. Alerts should identify the account and instrument, show the affected order identifiers, and describe the action needed. Logs and alerts for an automated trading system make these failures easier to diagnose before they spread across multiple orders.
A practical processing sequence
For every order update, identify the account, order chain, and event type before changing state. Validate the message, save it durably, and check whether its execution identifier has already been processed. If it reports a new fill, append the execution and update cumulative quantity, remaining quantity, average fill price, and position. If it reports a cancel or replacement request, mark the request as pending without treating it as complete. Apply the final state only when the provider confirms the outcome, while continuing to process any fills that arrive during the wait.
Then compare the updated order and position records with provider snapshots on the recovery schedule. If quantities disagree, preserve the event history, pause risky new activity for the affected instrument, and investigate before placing a corrective order. This approach does not eliminate market or network uncertainty. It does give the system a disciplined account of what was requested, what actually traded, what remains active, and whether its own position agrees with the account record.