Agentic Trading Index

Position reconciliation for unattended trading agents

Trading terminal showing broker positions during position reconciliation
Photo by Rafael Minguet Delgado on Pexels

Week one catches a retry; week six catches a gap

In week one, an unattended agent submits an order for 800 shares at a limit of $42.18. The request times out, so the agent cannot tell whether the broker accepted it. It retries with a new client order ID.

The broker accepts both requests. The first order fills 500 shares, the retry fills 300, and another 800 shares remain open. The agent's local position is 800 shares, which looks right. Its open-order state is wrong, and another $33,744 of exposure can still arrive.

Six weeks later, the same system reconnects after a stream interruption. It has missed a 120-share partial fill.

The local ledger says 700 shares; the broker position snapshot says 820. The market price is $43.05, so the mismatch represents $5,166 of market exposure. A position check alone catches the second fault, but only an open-order check catches the first.

These are ordinary failure modes, not exotic edge cases. A timeout can obscure an accepted request.

A websocket can disconnect between events. Position reconciliation compares the agent's records with broker records so it can detect and contain those differences before a strategy acts on false state.

Define which state is being compared

Keep separate records for intended orders, broker orders, executions and current positions. An intent describes what the strategy wanted. A broker order describes what the venue accepted, including its status and remaining quantity.

An execution is a confirmed fill. A position is the resulting inventory, including any adjustments made by the broker.

The broker is authoritative for accepted orders, fills and current position quantity. The agent still needs its own ledger: it connects each fill to a strategy, calculates realised and unrealised P&L, and explains why an order was sent. Do not overwrite that history with a position snapshot. Instead, use snapshots as a control total and investigate differences against the execution ledger.

Normalise fields before comparing them. Match account, instrument, currency and contract multiplier.

Store quantities as decimals where fractional shares or contracts are possible. Use broker order IDs and execution IDs as durable keys; a client order ID is useful for correlating requests, but it may not be globally unique across accounts or sessions. Record event time and receipt time separately, and treat cumulative filled quantity as a cumulative value, not as another fill to add.

Instrument conventions matter. A futures position is contracts, not the underlying currency value. An FX position may be reported in base units while the strategy stores lots. Corporate actions can change quantity and cost basis without an agent order. A comparison that ignores those conventions can flag false mismatches or, worse, conceal real ones.

Build a reconciliation loop that can recover

Use the execution stream for low-latency updates, but do not treat it as a durable ledger. Persist each event before applying it, make processing idempotent, and resume from a broker-supported cursor where available.

After any reconnect or suspected sequence gap, request fresh broker snapshots of orders, executions and positions. Reconcile all three, not just the position total.

For the timed-out 800-share order, first query by the original client order ID if the broker supports it. If the API offers an idempotency key, use the same key for retries. If it does not, do not send a second create request while the first request's outcome is uncertain. Query open orders and recent executions, then decide whether a new request is safe. Broker capabilities vary, so test the exact behaviour rather than assuming that a repeated request is harmless.

A practical comparison cycle can follow this sequence:

  • Pull orders, executions, positions and cash for the relevant account, with a timestamp and pagination cursor.
  • Apply unseen executions once, keyed by execution ID. Rebuild expected quantity from the opening position and confirmed fills, including broker adjustments.
  • Compare expected quantity and open-order remainder with broker snapshots. Also compare cash or buying power where those fields are available and relevant.
  • Classify the difference, persist the evidence, then apply the configured response. Never submit a corrective trade solely because two numbers differ.

That last rule prevents a reconciliation fault becoming a second trading fault. A short-lived stream delay may resolve on the next snapshot.

A confirmed unexplained position difference should block new orders that increase exposure. Cancelling an untrusted open order may reduce risk, but cancellation is also an asynchronous request: confirm its final broker status before treating it as cancelled.

Set tolerances around real API behaviour

Exact timings depend on broker, product and endpoint. The figures below are typical market ranges for designing monitoring, not service guarantees.

Test the selected API's normal latency and rate limits in paper and live-like conditions. A delayed snapshot can be normal; an unexplained quantity mismatch is not made safe by waiting.

CheckTypical rangeOperational use
Streaming fill deliveryAbout 0.1 to 5 secondsUpdate order state quickly, while retaining snapshot recovery
Polling fallback intervalAbout 5 to 30 secondsRecover updates when streaming is unavailable, within API limits
Position snapshot intervalAbout 1 to 15 minutes intradayCheck the ledger against broker inventory during active trading
Reconciliation after reconnectImmediately, then again within 1 to 5 minutesDetect missing events and allow for delayed broker updates
End-of-day account checkOnce after the broker's daily records settleCatch adjustments, fees and corporate actions that intraday checks miss

Use separate thresholds for timing and quantity. For listed whole-share equities, a one-share difference is material; a fractional-quantity product may require precision down to the broker's supported increment.

For futures, compare contracts exactly, then calculate exposure using the contract multiplier. Avoid a universal dollar tolerance: a $100 difference has a different risk meaning for a small account than for a large one.

Typical responses can be tiered:

  • Transient: the broker snapshot is stale or an event is still pending. Pause exposure-increasing orders briefly, refresh state and retain the mismatch record.
  • Confirmed and bounded: a known adjustment or missing fill explains the difference. Apply the event once, recalculate risk and record the source.
  • Unexplained or high risk: freeze new risk, cancel orders that could increase exposure if safe to do so, alert an operator and preserve request, response and event logs.

Paper trading is useful for exercising reconnects, duplicated submissions and partial-fill handling, but a sandbox may not reproduce live event timing or every corporate action. An agentic paper trading environment such as FX Tech's paper trading service can help test the control flow before live orders; plans start at $9.99 a month. Keep broker-specific API tests as a separate step.

Make mismatches measurable and actionable

For each run, save the account and instrument, snapshot timestamps, local and broker quantities, open-order totals, event cursor, difference classification and action taken. Keep enough detail to replay the comparison. Logs that say only "position mismatch" do not reveal whether the cause was a dropped fill, a duplicate order, a stale snapshot or a symbol mapping error.

Track the age of the last successful snapshot, number of unresolved differences, time to resolution, duplicate-order attempts and orders sent while state was uncertain. Set alerts on both an absolute mismatch and its age. One unresolved share for 30 minutes can matter more than a larger discrepancy corrected in seconds.

Before unattended operation, test partial fills, request timeouts, duplicate retries, out-of-order events, reconnects, pagination boundaries, market-session transitions and broker adjustments. Confirm that a restart can rebuild state from durable records and broker snapshots without replaying an execution twice. If a broker cannot provide a reliable position or order view, reduce the agent's permitted exposure or choose a different integration. A reconciliation loop cannot infer facts the API does not expose.

After deployment, review mismatches by cause, not just count. Repeated discrepancies after reconnect point to cursor handling. Repeated open-order differences point to order lifecycle logic. A mismatch that appears only after a symbol change often points to mapping or corporate-action processing. Fix the source, then verify that the same failure test now produces the expected safe state.

Check your own timeout-retry path: how many live broker orders can one agent intent create? The number should be 1.

Frequently Asked Questions

What is position reconciliation in automated trading?

It is the process of comparing an agent's recorded positions with broker-reported positions and related order and execution records. The comparison detects missing fills, stale state, duplicate orders and other inconsistencies.

How often should a trading agent reconcile positions?

Use fill events for prompt updates, then request snapshots periodically during trading and after every reconnect or suspected event gap. Intraday snapshot intervals of about 1 to 15 minutes are typical, subject to broker API limits and strategy risk.

Should the broker or the agent be authoritative for positions?

The broker is authoritative for current accepted orders, executions and position quantity. The agent should retain its own ledger for strategy attribution, accounting and audit, then compare that ledger with broker snapshots rather than replacing its history.

What should an agent do when broker and local positions disagree?

Pause orders that increase exposure while it refreshes broker orders, executions and positions. Apply confirmed events idempotently, investigate unexplained differences, and avoid sending a corrective trade until the cause is known.

How can duplicate orders be prevented after an API timeout?

Use a broker-supported idempotency key and reuse it for retries. If the broker does not support idempotency, query the original request's status and recent orders before sending another create request.