A broker's position display is not the truth your trading agent should blindly copy.
It is a record of the broker's view at a particular time, and it may lag fills, omit strategy-level attribution or reflect account adjustments the agent has not processed. The agent has its own view, built from submitted orders and execution events. Position reconciliation compares these views, identifies why they differ and decides whether the system can safely continue trading.
For an unattended system, this is a control loop, not a dashboard check. A mismatch can leave the agent adding to a position it already holds, or closing exposure that has already been sold. Both mistakes can compound within seconds if the strategy continues to submit orders.
What reconciliation means in a live system
Keep three kinds of state separate. Strategy intent is what the strategy wants to hold. The order ledger records requests, acknowledgements, cancellations and fills.
Broker position state is the broker's reported exposure for an account and instrument. Reconciliation connects them, but should not overwrite one with another without explanation.
The broker is usually the best authority for current account exposure. The agent's ledger is still necessary to explain how that exposure arose, allocate it among strategies and detect missing events. If a broker reports 40 shares and the agent expected 25, copying 40 into internal state may stop the immediate double-buy, but it does not explain the extra 15 shares or establish which strategy owns them.
Represent positions with a stable key, such as account, instrument identifier and contract expiry. Store signed quantity, unit, multiplier and currency.
A signed quantity distinguishes long from short; a contract multiplier prevents a count of futures contracts being mistaken for an equivalent count of shares. In a netting account, the broker may expose one net position where the agent maintains several strategy allocations. Preserve that distinction rather than inventing broker-side subpositions.
- Record order IDs and execution IDs, including the broker's identifiers.
- Store both event time and the time your system received the event.
- Track cumulative filled quantity as well as individual fill deltas.
- Represent adjustments, corrections and reversals as explicit events.
This model is useful in paper trading too. An agentic paper-trading environment can test whether delayed or duplicated events leave the agent's ledger in a recoverable state.
Define the state before comparing it
A position snapshot is not necessarily a consistent account-wide snapshot. Positions, open orders and executions may be fetched through separate API calls.
A fill can occur between calls, so a position difference may be real but temporary. Treat each record as time-stamped evidence, not as a single atomic truth, unless the broker documents an atomic snapshot mechanism.
Before comparing quantities, normalise identifiers and units. One API may report FX exposure in base-currency units while an internal strategy uses lots.
A broker may represent a short as a negative quantity or as a separate side. Options require the contract identifier, expiry, strike and right. Futures need contract and multiplier. Avoid matching instruments by display symbol alone, especially across venues or expiries.
Typical operational timing varies by broker, API and market conditions. The figures below are typical ranges for planning tests, not guarantees or service levels. Measure the actual account connection and use its documented semantics.
| Observation | Typical range | Possible cause | Safe initial response |
|---|---|---|---|
| Streaming fill reaches agent | About 100 ms to 2 s | Network or event processing delay | Keep the order unresolved until an execution or terminal status arrives |
| Position snapshot trails a fill | About 1 to 5 s | Snapshot refresh lag | Recheck after a short wait and compare executions |
| Partial fill completes or rests | About 100 ms to 10 s, or longer in thin markets | Available liquidity and venue behaviour | Use confirmed filled quantity, not requested quantity |
| Account adjustment appears | Minutes to one business day | Exercise, expiry, transfer or corporate action | Pause affected instruments and classify the adjustment |
Snapshots and execution history answer different questions. A snapshot says what the broker reports now.
Execution history helps explain changes since a known point. If history is queried with a cursor, request an overlap window and deduplicate by execution ID. This handles delayed delivery without counting the same fill twice. Do not assume a missing event means a missing trade.
Reconcile in a controlled sequence
Use a repeatable cycle. Persist each input and the decision made from it, so an operator can reconstruct why the agent paused or resumed. A practical sequence is:
- Set a reconciliation timestamp and mark the account as under review. Continue to accept risk-reducing actions, but gate new exposure if the mismatch could affect limits.
- Fetch open orders, recent executions and the broker's current positions. Include a small overlap in execution history, then deduplicate events by stable broker ID.
- Rebuild expected positions from confirmed fills and explicit adjustments. Do not count an accepted order as a fill. A working order changes potential exposure, not filled position.
- Normalise both states to the same account, instrument, unit and sign convention. Compare quantity, and where supported compare average cost and currency as separate fields.
- Classify every difference, record evidence and apply the relevant response. Resume new orders only when the difference is resolved or explicitly accepted under a policy.
Repeated cycles are often safer than trying to force a perfect one-time snapshot. For example, if a market order is partially filled while the position request is in flight, the first comparison may disagree.
Fetching executions again and checking the order's terminal status can explain the change. Use bounded retries with backoff, and stop after a defined deadline rather than polling indefinitely.
Order updates need the same care. Some APIs emit both a fill delta and a new cumulative filled quantity. Applying both as increments doubles the position.
Keep the last cumulative quantity per order and derive the new delta from it, or use unique execution records as the source of fill increments. A correction or trade bust must reverse or replace the original event, not silently edit history.
Never turn an unexplained quantity difference into a new order.
Classify mismatches and choose safe responses
Not every difference has the same urgency. A one-lot discrepancy in a liquid equity position may come from a delayed fill event. A missing futures contract can represent much more exposure.
Use instrument-aware limits and identify whether the mismatch can increase risk. A generic percentage tolerance is poor protection: one share in a small account and one contract in a leveraged product are not equivalent errors.
- Likely timing difference: a recent execution exists and the position snapshot has not caught up. Wait briefly, refresh and avoid placing an order that assumes either state is final.
- Ledger or event gap: broker quantity is stable, but the agent lacks a corresponding fill. Pause new exposure, retrieve overlapping history and rebuild from executions.
- External account activity: a manual trade, transfer, exercise or allocation changed the broker position. Mark it as external until attribution is confirmed.
- Unexplained or material difference: the cause is unknown or the mismatch breaches a risk threshold. Disable affected strategy orders and escalate to an operator.
Automatic correction has a narrow safe use. If policy permits closing exposure, the system must first establish the current position, check working orders and ensure the action cannot reverse into a new position after a delayed fill. A "sell the difference" repair can create a short position when an unreported sale is already in flight. Default to blocking new risk, not trading toward whichever number looks more plausible.
Keep thresholds explicit: maximum absolute quantity difference, maximum notional difference, age of unresolved state and which actions remain allowed. A strategy may tolerate a fraction of a share in an instrument that supports fractional trading, while a futures position generally requires exact contract counts. The threshold should reflect instrument granularity and account risk, not merely API convenience.
Test recovery, not just happy path
Testing should include event orderings that occur during live execution. A clean sequence of submit, acknowledge, fill and position update proves little about whether the system recovers when messages arrive late or twice. Inject faults in paper trading or a controlled test account, and check both the resulting position and the orders the agent is allowed to place.
- Deliver the same execution twice and confirm quantity changes once.
- Delay a fill event until after a position snapshot, then verify the next cycle reconciles.
- Return a partial fill followed by a cancellation, and ensure the unfilled remainder is not treated as exposure.
- Restart the agent with working orders and persisted state, then rebuild from broker records without duplicating fills.
- Introduce an external position change and check that the agent pauses rather than attributing it to a strategy.
Measure time to detect a mismatch, time to classify it and time until new risk is allowed again. Also record unresolved mismatch age, duplicate-event count and the number of orders blocked by reconciliation. These metrics distinguish a system that notices problems from one that can contain them. A short weekly review of these records can reveal repeated API gaps or symbols that are being normalised inconsistently.
Broker APIs differ in snapshot semantics, event retention and treatment of corrections. Document those behaviours per connection and keep the reconciler independent of strategy logic. Then a strategy can request exposure, while a separate control decides whether the account state is trustworthy enough to act.
Most trading systems call reconciliation routine only after it fails.
Frequently Asked Questions
What is position reconciliation in automated trading?
It compares the agent's expected holdings with the broker's reported positions and execution records. The process identifies stale data, missing fills and external account changes before the agent places more orders.
Which system should be the source of truth for positions?
The broker is usually the authority for current account exposure, while the agent's event ledger explains how that exposure arose. A safe system compares both rather than blindly replacing one state with the other.
How often should a trading agent reconcile positions?
Reconcile after material order events and on a regular schedule appropriate to the strategy and API limits. Many systems also reconcile at startup and after reconnects, since missed events can leave local state stale.
Should an agent automatically trade to fix a position mismatch?
Usually not until it has established the current position, checked working orders and classified the cause. Blocking new risk is safer than submitting a corrective order against stale or incomplete data.
How can duplicate broker fills be prevented from changing positions twice?
Deduplicate executions using stable broker execution IDs, or track cumulative filled quantity per order and apply only the difference. Persist this state so a restart does not replay already processed fills.