Live Trading Reconciliation of Orders, Fills, and Positions
Summary
This guide explains how a live trading system rebuilds and checks its internal order and position state against venue reports. At startup, it uses cached state when available, or creates state from venue orders and positions. During runtime, recurring checks identify discrepancies. Explicit open or flat position reports define the quantity target; a missing report does not imply a flat account. Reconciliation can generate synthetic orders and fills to align state, subject to tolerances and configured behavior.
The guide describes how order status, standalone fill, order-with-fills, and position reports affect recovery, and why snapshot timing matters when assessing possible fill corrections. It also covers execution-client attribution, incomplete venue history, delayed or duplicate reports, split strategy ownership, and instrument or precision mismatches. Its invariants include deterministic synthetic event identifiers and order-state recovery even when fills cannot be applied to position economics. These are operational rules for maintaining consistency, not evidence of trading profitability; results depend on available reports, retained events, filters, and venue history.
Key ideas
- An explicit venue position report is the target for reconciliation, while a missing report cannot establish that the account is flat.
- Cached execution events improve recovery when venue history is limited.
- Order and fill report types differ in how they rebuild missing local state.
- A late-arriving snapshot may describe an earlier state and should not automatically void a later fill.
- Synthetic reconciliation can align quantity but does not recreate missing historical profit and loss.
Tags
Full text
# Execution Reconciliation
# Execution Reconciliation
Execution reconciliation aligns the venue's actual order and position state with the system's
internal event-sourced state. Use this guide to understand startup state recovery and the
continuous checks that detect runtime discrepancies.
Unresolved live command outcomes are one source of state divergence. For how Nautilus classifies
local failures, definitive results, and unknown outcomes, see
[Command outcomes](policies.md#command-outcomes).
For the complete node lifecycle, see [Live trading](../live.md). For the available settings and
recommended values, see
[Configure a live trading node](../../how_to/configure_live_trading.md#executionengine-configuration).
## Reconciliation model
Live execution reconciles local state against venue reports. Backtesting controls both order
execution and the resulting state, so it does not need venue reconciliation.
Two scenarios:
- **Cached state exists**: report data generates missing events to align the state.
- **No cached state**: all orders and positions at the venue are generated from scratch.
:::info[Position reports are market exposure]
**An explicit position report is authoritative. During startup reconciliation,
the engine either aligns to that report within reconciliation tolerances or fails closed.**
Authoritative position reports:
- An explicit open report, including quantity and direction.
- An explicit flat report.
Not evidence of a flat position:
- A missing report.
- A null quantity.
- A venue that does not publish positions.
The fill window does not decide whether the report is authoritative. Missing reports do
not mean flat.
By default, `generate_missing_orders` is enabled. The engine generates the
orders and fills needed to align local state to the report. Disabling generation
does not allow an unresolved report through startup.
This guarantee covers reports included by the position-report and instrument
filters, with reconciliation enabled. Unresolved reports prevent actors and
strategies from starting.
:::
:::tip
Persist all execution events to the cache database. This reduces reliance on venue history
and gives reconciliation the retained order and position state needed to interpret short history
windows.
:::
### Component responsibilities
`LiveNode` owns the `ExecutionManager` and schedules recurring reconciliation. The manager tracks
activity, retries, and fill identities, interprets cached state, and prepares reconciliation events.
`ExecutionEngine` applies events to orders and positions and handles individual execution reports.
The UML diagram shows ownership and dependencies. A filled diamond denotes ownership. Dashed arrows point from
a caller to a component it uses. The kernel owns the engine and shared cache. It is omitted here to focus on
reconciliation.
```mermaid
classDiagram
direction LR
namespace nautilus_live {
class LiveNode
class ExecutionManager
}
namespace nautilus_execution {
class ExecutionEngine
}
namespace nautilus_common {
class ExecutionClient {
<<interface>>
}
class Cache
}
LiveNode *-- ExecutionManager : owns
LiveNode ..> ExecutionClient : requests recurring reports
LiveNode ..> ExecutionEngine : dispatches through kernel
ExecutionManager ..> ExecutionClient : polls reports for standalone checks
ExecutionManager ..> ExecutionEngine : applies startup events
ExecutionManager ..> Cache : reads state and registers external orders
ExecutionEngine ..> ExecutionClient : routes commands and requests reports
ExecutionEngine ..> Cache : updates orders and positions
```
The live client facade shares one adapter instance between the node and engine. Pending report requests can
keep client borrows while the event loop handles other work. Instrument updates are deferred until those
borrows are released, then flushed on request completion or cancellation.
Within `nautilus-live`, the source modules divide these responsibilities as follows:
| Module | Responsibility |
| ----------------------------- | ------------------------------------------------------------------------ |
| `node/mod.rs` | Node lifecycle, event loop, and event dispatch. |
| `node/reconciliation.rs` | Recurring report tasks, deadlines, cancellation, and result handling. |
| `execution/manager.rs` | Reconciliation state, decisions, and individual reconciliation checks. |
| `execution/reconciliation.rs` | Shared types, state-independent decisions, and targeted report requests. |
The separate `nautilus_execution::reconciliation` module supplies report-to-event and arithmetic
operations shared with the execution engine.
Reconciliation follows different paths at startup and during continuous checks:
- **Startup**: the manager publishes raw reports, applies order and fill events, verifies historical
fill application, and then evaluates positions against the updated cache.
- **Continuous position checks**: the node coordinates authoritative fill queries and dispatch before asking
the manager to generate synthetic events. Activity revisions detect local changes during requests or
callbacks. Applying authoritative fills defers synthetic reconciliation until a fresh position report.
A fill that fails preparation or that the engine does not apply also defers synthetic reconciliation. This
deferral lasts only until `position_check_threshold_ms` has passed since its first failure. Later checks skip
that fill and reconcile the position synthetically. Each check stops at the first such fill for an instrument
and account, so each refused fill delays the fallback by at least one check. If a skipped fill later applies
through another path (such as the execution stream), it can add to the synthetic correction. The next position
check reconciles the difference.
The manager stays available without the `node` feature. Standalone callers can use its individual polling
methods and apply the returned events themselves. Standalone position polling directly returns synthetic
discrepancy events. The node adds the authoritative-fill recovery sequence.
### Execution-client origins
An **execution-client origin** is a write-once binding between an order and the client responsible
for its execution.
An origin is recorded:
- From an explicit client on submission, or from the final client selected after routing and venue
validation and before transport.
- When non-synthetic external orders are materialized during startup reconciliation, from the
reporting mass-status client.
- When external orders are materialized from runtime venue reports and the report's account
matches exactly one registered client that handles the instrument venue.
An origin may be absent for:
- Cache data written before resolved origins were persisted.
- Orders restored after an origin write failed or the process exited before it committed.
- External orders whose runtime report does not identify exactly one registered client by account
and instrument venue.
- Synthetic reconciliation orders.
The built-in cache backends attempt to enqueue a resolved origin for persistence before transport.
Enqueue failures are logged without blocking transport. These writes are asynchronous, so enqueue order
does not guarantee that the origin is durable before the order reaches the client.
At startup, each client's mass status is checked against the cached origins. An order the client reports is
expected to be bound to that same client.
- **Missing origin**: logs an aggregated warning and stays compatible with existing cache data.
- **Conflicting origin**: logs an aggregated deprecation warning and reconciles for compatibility.
A future release rejects the conflict as a startup error.
See the origin rows in [Startup scenarios](#startup-scenarios).
This is separate from [external order claims](#external-order-creation), which attribute
venue-sourced orders to a *strategy*. The execution-client origin records which *client* an order
belongs to.
### Reconciliation reports
The execution engine consumes four reconciliation report variants from live adapters. Each variant
has a different normal role when its matching order is absent from the cache. Explicitly bounded
history can instead use [order-only fill projection](#order-only-fill-projection).
| Variant | Purpose | Missing-order action |
| ---------------------- | ------------------------ | ---------------------------------------------------- |
| `OrderStatusReport` | Order state update. | Creates an order and infers any reported fill. |
| `FillReport` | Standalone fill. | Creates a market order, then applies fill metadata. |
| `OrderWithFills` | Order state plus fills. | Creates an order, applies fills, and infers residue. |
| `PositionStatusReport` | Venue position snapshot. | Logs the report. Positions stay fill-derived. |
When a `FillReport` has no cached order, the execution engine creates a market order tagged `FILL_REPORT`.
Each distinct trade can increase its quantity, including after an earlier fill closes the order.
Status reports do not generate inferred fills for these orders or cap their quantity against later distinct trades.
Replaying an unchanged fill leaves order and position totals unchanged.
Orders without this marker retain their existing overfill checks.
Older versions that reject additional fills on filled orders cannot replay these order histories.
Clients that require authoritative fills, such as OKX, do not infer executions from order status.
Missing fills and dependent status transitions wait for venue fill reports or private fill events.
An uncached runtime order status creates and accepts the order while its executions remain pending.
#### When to use each variant
Adapters choose the variant that matches the venue event:
- Use `OrderStatusReport` for order lifecycle updates when fill details arrive on a separate
stream.
- Use `FillReport` for a venue-initiated closure that has a fill but no user-level order.
Hyperliquid liquidations follow this pattern.
- Use `OrderWithFills` when one venue event contains both an order status and its fills. Binance
Futures uses this for exchange-generated ADL, liquidation, and settlement orders.
Streamed `OrderWithFills` reports can infer fill voids from a lower cumulative filled quantity only
when their status is `VOIDED`. Use mass status for authoritative snapshot corrections.
### Snapshot freshness and fill corrections
A snapshot must not undo a fill that occurs after the state it describes. Receiving a snapshot after a stream
event does not make the snapshot newer: REST requests and stream delivery can overlap during recovery. For
example, a request can observe zero filled quantity. A stream can then deliver a fill of five units, and the
older response can arrive last. Interpreting that response as a correction would wrongly void the five units.
Snapshot corrections require a distinction between:
- **A snapshot that predates a fill**: its lower filled quantity does not establish that the fill
was voided.
- **A snapshot that covers the fill and reports a reduction**: the reduction can represent a
genuine correction, derived from retained fill history.
- **An explicit venue fill-void event**: process it under the
[OrderFillVoided contract](../events/order_fill_voided.md), including its identity, quantity,
and ordering checks. It does not depend on inferring a correction from a snapshot total.
Timestamp meaning matters when establishing coverage:
- The Derive adapter reports an order-update timestamp.
- Betfair's `matchedDate` describes the last match, not the time of a snapshot or correction.
Response arrival time, equal timestamps, or timestamps from different clocks do not by themselves
prove that a snapshot includes a fill.
Rejecting a genuine correction as stale can leave local filled quantity and exposure overstated
until later reconciliation resolves the discrepancy. Conversely, a stale snapshot carrying a
misleadingly newer timestamp can still cause a false void if freshness checks trust that timestamp.
The execution engine applies mass-status filled-quantity decreases to retained fills even when the
snapshot contains no companion trades.
**Overlapping fill activity**: collection starts at `ExecutionMassStatus.ts_init`. The engine automatically
skips an order snapshot when a cached fill or fill void has a local initialization timestamp at or after that
boundary. This skips all changes from that order report, including status, quantity, and price updates.
The engine still publishes the raw report and processes companion trades through normal
deduplication. It does not queue the skipped snapshot. A later snapshot can apply a genuine
correction once collection starts after the cached fill activity. The skip requires no
configuration and does not suppress explicit fill-void events.
This protection applies to runtime mass-status handling in `ExecutionEngine`. Startup reconciliation
uses `ExecutionManager`, which does not apply this timestamp boundary.
For runtime protection, adapters must capture the mass-status timestamp before collecting reports, using the
same local clock as fill events. This boundary protects against overlapping local activity. It cannot detect
venue state that is already stale when collection starts.
### Order-only fill projection
During startup reconciliation, a bounded historical fill normally updates only order state when its
instrument has no in-scope explicit position report. Omission is not a flat report. Explicit closing fills
can reduce a retained position under the [retained closing recovery](#retained-closing-recovery) rules.
An explicit position report, open or flat, is the quantity target. The engine applies the available fills,
generates the difference when configured, or leaves the position unresolved.
This projection applies only to reconciliation recovery. Raw reports stay available. Setting
`filter_position_reports` makes bounded historical fills order-only, even when the mass status contains
position reports. See [Bounded history safety](#bounded-history-safety) for the undeclared-window exception
and retained-fill rules.
### External order creation
When a report references an order that is absent from the cache, the engine creates an **external
order**. This covers venue-initiated ADL, liquidation, or settlement, orders placed by another
process, and orders not yet observed locally.
The naming distinguishes configuration intent from live ownership state:
- `external_order_instrument_ids` is the serializable strategy configuration intent. It names the
instruments whose external orders should be assigned to the strategy when it is registered.
- An **external order claim** is an active cache entry that maps one `InstrumentId` to one `StrategyId`.
The code uses `external_order_claims` for the collection of these live entries.
Live strategy registration materializes the configured instrument IDs with `register_external_order_claims`.
This operation is additive and strict. It rejects a repeated instrument or any instrument that already has a
claim, including a claim for the same strategy.
The strategy method `set_external_order_instrument_ids(...)` delegates to the cache operation
`set_external_order_claims`. This operation treats its input as the strategy's complete desired active set. It
can keep or release that strategy's existing claims and acquire unclaimed instruments, but it cannot take a
claim from another strategy.
Validation covers the complete input before changing the cache, so a conflict leaves each existing claim
unchanged.
The `ExecutionManager` and `ExecutionEngine` read the same canonical claim map from the cache when
they process external reports. They assign an external order to:
- The strategy identified by the active claim for the report's instrument.
- The `EXTERNAL` strategy as a default fallback.
An active-claim update is thus visible to both components without a coordination message. The claim present
when an external order is created determines the assignment. Existing cached orders keep their assigned
`StrategyId`. Changing a claim does not reassign them.
To transfer an instrument between strategies, the current owner must release it before the new owner claims
it. The handoff across strategies is not atomic. A report processed between the release and acquisition has no
active claim and is assigned to `EXTERNAL`.
Cache resets preserve active claims so registered routing stays configured, while retiring a strategy clears
its claims.
The external order uses the report's `client_order_id` when present and otherwise derives one from
the `venue_order_id`. The engine adds the order to the cache, registers its venue order ID, and
emits the applicable `OrderAccepted`, `OrderFilled`, `OrderCanceled`, or `OrderExpired` events.
Positions then update through the normal event pipeline.
See [Claiming external orders](../strategies.md#claiming-external-orders) for strategy configuration
and runtime updates.
### Reducing external positions
A strategy can use reduce-only fills to reduce inherited `EXTERNAL` inventory under NETTING.
#### Position selection
Existing cached position links stay authoritative. Without a cached link, a reduce-only fill uses the
strategy's own open position when available. If that position is absent or closed, the engine looks for
positions that meet all of these conditions:
- Belong to `EXTERNAL` and use NETTING.
- Are open on the opposite side of the fill.
- Match the fill's instrument and account.
The engine selects a fallback only when **exactly one** position matches. The fill quantity must
not exceed that position's quantity, though the order's remaining quantity can be larger.
If no safe fallback exists, an otherwise valid fill updates the order but neither opens nor
updates a position.
#### Ownership and events
After a successful reduction, the engine links the order to the external position so subsequent fills use the
same target. The position keeps `EXTERNAL` ownership:
- `OrderFilled` keeps the reducing strategy's ID and identifies the external position.
- `PositionChanged` and `PositionClosed` use the `EXTERNAL` strategy's event topic.
#### Linked reduction checks
When applying position economics, each linked reduction must match the external position's account
and reduce its open quantity without flipping or reopening it. If a fill violates these checks,
the engine rejects it **before changing the order or position**.
[Order-only fill projection](#order-only-fill-projection) bypasses these reduction checks because
it repairs order history without changing the position.
## Reconciliation configuration
Unless `reconciliation` is set to false, the live node runs startup reconciliation for each execution client.
The `reconciliation_lookback_mins` parameter controls how far back it requests history through the execution
engine. Startup enablement and polling intervals belong to the node's `LiveExecutionEngineConfig`. The manager
receives the thresholds, retry limits, filters, and lookbacks used to make reconciliation decisions.
:::tip
Leave `reconciliation_lookback_mins` unset to use the adapter's documented default. Many adapters
request the maximum execution history the venue provides, while others use a bounded default to
match venue retention and request limits. See the integration guide for the selected venue.
:::
:::warning
A bounded history window can begin after the fill that opened a position. Some venues also filter
or drop older execution data. That does not change the position-report rule above: an explicit
report is still the quantity target.
:::
For all live trading options, see the `LiveExecutionEngineConfig`
[API reference](/docs/python-api-latest/config.html#nautilus_trader.live.LiveExecutionEngineConfig).
### Order ownership and tags
Each strategy can configure `external_order_instrument_ids` as its intent to claim venue-sourced
external orders and materialized reconciliation activity for specific instruments. Live strategy
registration materializes that intent as active claims, which the strategy can replace at runtime.
This lets a strategy resume managing open orders and positions when no cached state exists.
An external order's strategy ID and origin tag depend on its source and on whether a strategy
claims its instrument. Claimed orders and fills use the claiming strategy ID, so the strategy can
continue managing the recovered state.
| Order source | Unclaimed | Claimed |
| ----------------------------- | -------------------------------- | --------------------------------------- |
| Venue order | `EXTERNAL`, tag `VENUE` | Claiming strategy, no tag |
| Position reconciliation order | `EXTERNAL`, tag `RECONCILIATION` | Claiming strategy, tag `RECONCILIATION` |
:::tip
To detect unclaimed external orders in your strategy, check `order.strategy_id.value == "EXTERNAL"`.
Ownership does not exclude these orders from position tracking or portfolio calculations. Historical
fills still follow the [bounded history safety](#bounded-history-safety) rules when applicable.
:::
### Submission recovery
`submission_recovery_policy` defaults to `RetainUnresolved`, which enables:
- Submission identity tracking.
- Exhaustion diagnostics.
- Preservation of the submission's recovery budget until acknowledgement.
Exhausted unacknowledged submissions stay unresolved, with further automatic per-order recovery queries
stopped. Select `ResolveLocally` to close them through the local resolution rules instead. Clients can also
require retention when `ResolveLocally` is selected. Polymarket enables this protection automatically.
The policy also selects how [in-flight checks](#in-flight-checks) resolve a pending cancel or update on an
accepted order.
Retained submissions also affect the [node shutdown result](../live.md#submission-recovery-at-shutdown).
Rust `LiveNode::stop` and `run`, and hosted runs, report unresolved client order IDs after teardown
when submission recovery is incomplete at the `delay_post_stop` boundary. This includes Polymarket
without an explicit opt-in. Exhaustion diagnostics and successful teardown do not establish a venue
outcome or position flatness.
#### Exhaustion diagnostic
With tracking enabled, a native `LiveNode` publishes `SubmissionRecoveryExhausted` on
`reconciliation.SubmissionRecoveryExhausted` when an unacknowledged submission reaches an existing
recovery limit. It publishes the diagnostic after processing reconciliation events, once per tracked
submission.
The diagnostic carries the original submission identity, recovery source, check count, and event
timestamp. It is not an order event and does not establish a venue outcome.
#### Recovery budget
A cancel or modify dispatched before acknowledgement shares the submission's remaining recovery
budget. Duplicate registration and missing-order bookkeeping cannot restart that budget.
Acknowledgement retires it without transferring recovery to an overlapping command.
A command dispatched after acknowledgement starts its own in-flight check at dispatch, even if its pending
event has not arrived. It uses the existing command cleanup rules. For example, a `PARTIALLY_FILLED` order
status report stops a pending cancel's timeout under both policies. That cleanup rule does not apply to
standalone fill reports.
Without submission tracking (`ResolveLocally` and no client-required retention), command dispatch
starts a fresh recovery budget, and native fill or `Triggered` events do not retire the pending
command's timeout.
#### Acknowledgement
A matching `Submitted` report with a venue order ID retires the original submission's recovery. Incoming
reports and bulk or targeted query responses use the same confirmation checks. An applied `OrderUpdated` with
venue identity also confirms the submission. Local updates without venue identity do not.
The registry preserves submission identity across later activity:
- **Confirmed submission**: report-only confirmation is remembered, including for cached orders not
yet registered for recovery, so duplicate submission registration cannot restart the timeout.
Missing-order bookkeeping does not register an acknowledged submission again.
- **Exhausted submission**: its identity stays in the registry until venue evidence resolves it. Duplicate
registration and cancel or modify dispatch cannot restart its automatic recovery.
Later commands do not produce submission-exhaustion diagnostics.
#### Registration
- **Live node**: `LiveNode` registers submission identity before dispatch and client-required
retention automatically.
- **Direct `ExecutionManager` callers**: use `register_submission` for submissions. `register_inflight`
only starts command recovery and does not infer submission identity from the cache. Direct manager
hosts must select `RetainUnresolved` or run `check_open_orders` with their clients before relying on
client-required retention in inflight checks.
#### Recovery limits
The existing limits and coverage checks still apply:
- **In-flight checks**: `inflight_check_retries` counts checks. A limit of `N` permits `N - 1`
intermediate order queries before exhaustion.
- **Full-history missing-order checks**: use `open_check_missing_retries` and require completed, matching client
coverage plus a successful targeted query with no order found before reporting exhaustion. Failed
or deferred targeted queries do not produce that diagnostic.
### Instrument availability
Adapters parse reconciliation reports using the instrument, so each instrument a report references must
already be loaded. Adapters do not fetch missing instruments from the venue during reconciliation.
Instrument scope comes from the adapter's provider config rather than the engine.
`InstrumentProviderConfig.load_ids` decides which instruments the adapter holds, while
`reconciliation_instrument_ids` filters reports only after the adapter has produced them.
Reports for instruments outside an explicit `load_ids` scope are expected and dropped at debug level. Thus, a
node scoped to one instrument stays quiet about the rest of the venue. An in-scope instrument that does not
resolve means something is wrong, whether it was named in `load_ids` or covered by `load_all=True`. The
outcome depends on what the report describes:
- An open order or position report fails reconciliation, so the system does not start. A live
position that cannot be priced is never silently dropped.
- A closed or historical record logs a warning instead of aborting startup. When the adapter
declares a bounded history, the record also marks the report set incomplete, applying the
[bounded history safety](#bounded-history-safety) rules. Expiries routinely retire instruments
that older fills still reference.
## Startup reconciliation
All adapter execution clients follow the same reconciliation procedure, calling three methods
to produce an execution mass status:
- `generate_order_status_reports`
- `generate_fill_reports`
- `generate_position_status_reports`
```mermaid
flowchart TD
Start[Startup Reconciliation] --> Fetch[Fetch venue reports<br/>orders, fills, positions]
Fetch --> Dedup[Deduplicate reports<br/>log warnings for duplicates]
Dedup --> Orders[Order Reconciliation<br/>align order states, generate missing events]
Orders --> Fills[Fill Reconciliation<br/>verify fills, generate missing OrderFilled events]
Fills --> Pos[Position Reconciliation<br/>compare net positions per instrument]
Pos --> Match{Positions<br/>match venue?}
Match -->|Yes| Done[Reconciliation complete<br/>system ready for trading]
Match -->|No| Gen[Generate missing orders<br/>Claiming strategy or EXTERNAL<br/>Tag RECONCILIATION]
Gen --> Recovered{In-scope reports match<br/>within tolerances?}
Recovered -->|Yes| Done
Recovered -->|No| Abort[Startup fails<br/>actors and strategies do not start]
```
These reports represent external reality. The procedure processes them in the order shown so each
position check builds on reconciled order and fill state.
### Mass-status history contract
An `ExecutionMassStatus` can declare the provenance of its historical reports:
- `lookback_start=None` means that the adapter has not declared an explicit lower time bound.
- `lookback_start=Some(timestamp)` means that historical order and fill reports exclude venue
activity before that timestamp.
- `reports_complete=true` means that each order, fill, and position source needed to interpret the bounded
history completed and all required records were mapped successfully.
An adapter can still return authoritative active orders and position reports when a historical
source fails. It marks the mass status incomplete to record the missing history. Incompleteness
does not prevent recovery from an explicit position report.
### Report deduplication
- Deduplicates order reports within the batch and logs warnings.
- Logs duplicate trade IDs as warnings for investigation.
- Counts a position report once in startup validation and continuous position checks when it matches an
earlier report apart from `report_id` and `ts_init`. Logs a warning for each duplicate. Reports that differ
in any other field, including `ts_last`, count separately.
### Order reconciliation
- Generates and applies events to move orders from cached state to current state.
- Generates external order events for unrecognized client order IDs or reports missing a client
order ID.
### Fill reconciliation
- Infers `OrderFilled` events for missing trade reports unless the client requires authoritative fills.
- Verifies fill report data consistency with tolerance-based price and commission comparisons.
- Drops a fill group that has neither an order report nor a cached order. Logs one aggregated warning per mass
status for the dropped groups. A group whose fills carry a `venue_position_id` is handled separately. The
engine builds a filled order from it when `generate_missing_orders` is enabled, and skips it otherwise.
### Event ordering
Startup reconciliation applies the order and fill events it generates in time order:
- Fills apply in order of their event time: the venue execution time from `FillReport.ts_event`,
or the report's `ts_last` for an inferred fill.
- Each venue order's other events, such as its acceptance, apply no later than the earliest fill that follows
them for that venue order. Reported acceptance can follow an order's own fills if the venue reports a last
update time or the adapter uses local time. The order is still accepted before its fills apply.
- Events of different venue orders keep their own times, including a replaced order that shares
its client order ID with the order that replaced it.
Ordering changes only when events apply. Each event keeps its reported timestamp.
### Position reconciliation
- Matches the net position per account and instrument against venue position reports using
the account's quantity tolerance.
- Generates external order events when order reconciliation leaves a position that differs from
the venue.
- When `generate_missing_orders` is enabled (default: True), generates orders tagged
`RECONCILIATION` to align discrepancies. The orders belong to the claiming strategy for the
instrument, or to `EXTERNAL` if there is no active claim.
- Logs a warning when NETTING ownership is split across multiple strategies for the same account
and instrument, since venue position reports are account-level net positions.
#### Synthetic orders
Reconciliation generates synthetic MARKET order reports and fills with a known price:
- Opening from flat uses the reported `avg_px_open`.
- Increasing an existing position uses a calculated price targeting the reported entry average.
- Reducing an existing position uses the reported entry average, falling back to the cached average
when the report omits it. A reduction does not change the remaining position's entry average.
- Closing to flat uses the cached entry average.
- Reversing direction closes the cached position, then opens the reported position at its entry average.
A report that marks its average changes some of these prices. See
[reported entry averages](#reported-entry-averages).
The engine skips quantity differences that round to zero at instrument size precision. Startup
validation still checks the remaining difference against the account's quantity tolerance.
#### Replayed fills
Reconciliation can open, adjust, or close a position from a venue position report. A late execution can
already be included in that report.
Reconciliation fills that predate a cached synthetic correction **update the order only**, within the
scope below. This avoids duplicate exposure or reopening a reconciled closure, including after startup.
Ordinary private fills and price restatement events retain normal position handling.
Coverage for the same instrument and account:
| Fill source | NETTING scope | HEDGING scope |
| ---------------------------------------- | -------------- | -------------------- |
| Runtime standalone report | All strategies | All strategies |
| Bundled or inferred from an order report | All strategies | Routed position only |
Continuous position checks also keep earlier fill reports off cached positions already covered by
synthetic corrections for the same instrument and account.
**Known gaps**:
- **Reconciliation window**: the synthetic correction fill carries the reconciliation time rather than the report
time. Thus, a real fill that lands between the position report query and reconciliation also stays off the
position. Continuous position checks align it only when they run with `generate_missing_orders` enabled.
- **Position cycles**: reopening a NETTING position archives the prior cycle; this check does not read
archived snapshots. Closed-position purging also removes its correction history. Late reconciliation
fills can then apply to a new cycle. Recover missing executions before reopening or purging the position.
- **Correction order purge**: the protection needs the synthetic correction order in the cache. When
closed-order purging is enabled, a `purge_closed_orders_buffer_mins` shorter than the venue's
replay delay can remove it first.
- **Inferred timestamps**: inferred fills use the order report's last-update time. If the venue supplies
creation time instead of execution time, a fill executed after the snapshot can appear older and stay off
the position. Position checks with `generate_missing_orders` enabled can correct the difference.
**Order-only effects** (see [order-only fill projection](#order-only-fill-projection)):
- **Event store restore**: restoring the cache from the event store applies the fill to a
position, so the restored position can overstate the venue quantity.
- **Fill voids**: a venue fill void for the fill is rejected, so its order stays filled.
- **Locked balance**: an open order that the fill closes keeps its locked balance until the next
order event for that instrument and account.
- **Position checks**: if the reconciled position closes before a continuous position check aligns it, later
checks stop at the fill. They wait until `position_check_threshold_ms` has passed since it first failed to
apply, then align the position synthetically.
#### Startup position validation
After applying startup reports, the live node checks each **in-scope explicit position report,
including flat reports,** against the cache. An unresolved position stops startup **before actor or
strategy `on_start`**. The error identifies the account, instrument, venue quantity, and recovery
failure.
| Position case | Cache identity | Quantity requirement |
| ------------------------------------------ | ----------------------- | ------------------------ |
| HEDGING with venue position IDs | Exact venue position ID | Exact quantity |
| NETTING with or without venue position IDs | Account and instrument | Within account tolerance |
| Net reports without position IDs | Account and instrument | Within account tolerance |
When the venue reports both long and short positions, both side totals must also match. Equal net quantities
alone are insufficient. A residual difference outside the account tolerance stays unresolved even if it rounds
to zero at the instrument size precision. Differences within the tolerance stay acceptable, including tiny
residuals around zero.
For an open position with a reported `avg_px_open`, startup also checks the entry average using the
fill-adjustment relative tolerance of 0.01%. Average entry prices can fall between instrument price ticks. The
comparison does not round them to instrument price precision.
NETTING reports use quantity-weighted entry averages for each reported side. If a side spans several
reports, all contributing reports must supply an average to establish that side's price target. A
report can skip this check or widen its tolerance, as described in
[reported entry averages](#reported-entry-averages).
Matching quantity alone does not resolve a reported entry-price mismatch. When quantities already match,
position reconciliation does not generate a correction solely to change the entry average. The remaining price
mismatch fails startup. When it corrects quantity, startup still fails if the resulting average stays outside
tolerance. Synthetic recovery does not establish historical realized PnL.
#### Reported entry averages
Two `PositionStatusReport` fields tell reconciliation how to read `avg_px_open`. Their defaults
keep the behavior described above.
- `avg_px_open_reconciliation`: `MATCH` (default) compares the average with the cached entry average and
prices synthetic fills from it. `OPENING_ONLY` marks an average computed by a different method, such as the
remaining FIFO lots. This average legitimately differs from the cached quantity-weighted average once a
position has been reduced.
- `avg_px_open_precision`: the decimal places the venue kept when it rounds or truncates the
average. When unset, comparisons add no allowance.
| Use of the average | `OPENING_ONLY` | `avg_px_open_precision` set |
| --------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------ |
| Startup entry-price check | Skipped for the side. Quantity checks still apply. | Passes within 0.01% plus one unit at the coarsest precision on the side. |
| Fill adjustment match | Quantity only, so a price difference keeps real fills. | Uses the same price allowance. Quantity must still match exactly. |
| Opening from flat or reversing | Uses the reported average. | Uses the reported average. |
| Increasing or reducing a position | Uses the cached average. | Uses the cached average when it already matches the report. |
For `OPENING_ONLY`, opening from flat includes the synthetic opening fill that
[fill adjustment](#fill-adjustment) adds before a partial window. A precision-marked report prices that fill
at the window fills' average if two conditions hold. The window position must have the same side as the
report, and its average must already match the report. If either condition fails, the fill uses the default
price.
One `OPENING_ONLY` report makes its whole side incomparable, because the side's weighted average
would mix methods. Pricing a change to an existing position at the cached average keeps its entry
average and books no synthetic trading PnL on a reduction. When no cached average exists, synthetic
fills fall back to the reported average.
#### Recovery prerequisites and filters
Creating a position in an empty cache from a report without order or fill history requires
`avg_px_open`. The engine does not invent an entry price.
- **Missing-order generation**: disabling `generate_missing_orders` does not bypass startup validation.
- **Report scope**: position-report and instrument filters still apply. Excluded reports are not checked.
- **Reconciliation disabled**: disabling reconciliation skips the check entirely.
### Fill adjustment
The engine can analyze zero-crossings, remove closed lifecycles, and generate a synthetic fill when
the reported fills do not explain the current venue position.
The following conditions govern fill adjustment:
- A declared `lookback_start` does not skip the adjustment.
- Without a reported `avg_px_open`, the engine preserves the original orders and fills instead of
inventing a price for synthetic fill adjustment.
- Setting `filter_position_reports` skips fill adjustment for both declared and undeclared windows.
Fill adjustment uses these terms:
- **Zero-crossing**: position quantity crosses through zero (FLAT), marking a lifecycle boundary.
- **Lifecycle**: a sequence of fills between zero-crossings representing one open-close cycle.
- **Synthetic fill**: a calculated fill report representing missing activity, priced to achieve the
correct average position.
- **Tolerance**: fill adjustment uses a relative entry-price tolerance of 0.0001 (0.01%) to absorb
minor calculation differences. Startup validation uses the same price tolerance and the account's
separate quantity tolerance. A report that sets `avg_px_open_precision` adds one unit at that
precision to the price tolerance.
When `generate_missing_orders` is disabled, the engine still processes raw venue order reports. It filters
completed lifecycles when the current lifecycle explains the venue position. But it does not add or replace
synthetic reports to align a fill window with the venue position. It also does not materialize an order for a
fill group that has no order report.
Adapters that apply a history cutoff should still declare it through the
[mass-status history contract](#mass-status-history-contract). The declaration records provenance.
It does not authorize leaving an explicit position report unmatched.
### Bounded history safety
An **explicit position report** is authoritative for the position, whether open or flat. The engine
either aligns to that report within reconciliation tolerances or fails closed. It does not replay
the bounded window to decide whether the report is authoritative.
The engine applies the available orders and fills, and by default generates the orders and fills
required to reach the report. Disabling `generate_missing_orders` does not allow a mismatch to stand.
Without an in-scope explicit position report, bounded fills update order state only, except for
[retained closing recovery](#retained-closing-recovery). They cannot open or flip exposure through that
exception. Raw reconciliation reports stay available.
For compatibility, a mass status without a declared `lookback_start` can still apply historical fills when no
position report exists. This exception does not treat a missing report as flat. Retained-fill deduplication
and projection of older lifecycles continue to apply in both paths.
Reports with an explicit `venue_position_id` follow the position-specific reconciliation path and
do not require NETTING lifecycle inference.
#### Retained closing recovery
Explicit venue fills can reduce or close a retained position even when its opening trade predates the
lookback window. Each fill records its price and commission once. Recovery requires:
- A bounded, complete history with `filter_position_reports=False`, no explicit position report for the instrument,
and no bulk position coverage for it.
- A cached order, including one created during reconciliation, whose normal routing resolves an open,
unsettled position for the same account and instrument. HEDGING requires an existing order-to-position
link or an explicit position ID.
- An explicit fill from the position's current lifecycle, on its closing side, no larger than its remaining
quantity. Orders with active inferred fill history are excluded. Other historical projection exclusions apply.
Recovery applies fills independently in event order. It does not validate the instrument's entire history
as a batch: a skipped, unresolved, or inferred execution does not veto another order's valid closing fill.
A valid close can therefore apply while another execution stays order-only. Recovery cannot open or flip a
position, and it does not split a fill that exceeds the remaining quantity.
This automatic recovery covers straightforward offline closes. Histories containing additions to a position,
re-entry, fill corrections, missing executions, or mixed inferred and explicit fills may require manual
reconciliation of exposure and PnL. An order reaching `FILLED` does not establish that every execution updated
the position. Reconcile the retained state before resuming trading in those cases.
For instruments without bulk position coverage, startup logs a warning for bounded fills that stay order-only.
It names the account, the instrument, and the position the fills route to, where one resolves, with sample trade
IDs and their orders. It skips fills that retained-fill deduplication or older-lifecycle projection already
accounts for, and fills their cached order already holds, so a restart with the orders cached does not repeat it.
Without a persisted cache, it repeats on every start. It does not flag fill corrections or executions missing
from the reports.
### Failure handling
During startup, an execution client's mass-status request has three outcomes:
- **Available (`Ok(Some(...))`)**: Reconcile the supplied reports. An unresolved in-scope position
report prevents actors and strategies from starting.
- **Unavailable (`Ok(None)`)**: Log a warning and continue startup. This compatibility policy does
not establish that the venue is flat; no position target can be inferred from the missing report.
- **Failed (`Err(...)`) or timed out**: Abort startup and follow the startup cleanup path.
Report processing also follows these rules:
- An adapter can preserve successful report legs after an individual source failure. Explicitly
bounded mass statuses must mark the result incomplete. Incompleteness does not veto an explicit
position report. A bounded fill from incomplete history with no explicit position report does not change
a position.
- Fill reports arriving before order status reports are deferred until order state is available.
#### Commission failures
An adapter fill commission that cannot be calculated or represented fails the report request under
the [adapter contract](../../developer_guide/adapters.md#commission-failure-handling). The adapter does
not drop that fill or replace its commission with zero or a generic formula. Startup stops before
applying that client's mass status.
The engine asks the responsible execution client to calculate an inferred-fill commission. A failure defers
the inferred quantity and dependent terminal transition until a later reconciliation cycle succeeds. Valid
explicit fills from the same report set can still apply. For an external order, the engine resolves the
commission before adding the order to the cache or publishing its initial event. Thus, a failure defers the
entire external order. An unavailable responsible execution client has the same fail-closed result.
An inferred-fill commission failure while applying an otherwise successful mass status does not by itself stop
startup. Startup still fails if an in-scope explicit position report stays unresolved. Otherwise, the
unresolved work stays pending for a later reconciliation cycle.
If startup reconciliation fails for any other reason, the system logs an error and does not start.
## Runtime checks
Continuous reconciliation starts after startup reconciliation completes. It:
- Monitors in-flight orders for delays exceeding a configured threshold.
- Reconciles open orders with the venue at configured intervals.
- Checks position status with the venue at configured intervals.
- Audits internal *own* order books against the venue's public books.
The `reconciliation_startup_delay_secs` parameter adds a further delay *after* startup
reconciliation completes, giving the system time to stabilize. [Runtime scenarios](#runtime-scenarios)
lists the outcome of each check.
### In-flight checks
After exhausting the configured retries, the in-flight checker resolves timed-out orders as follows,
unless the order has never been accepted and submission retention applies:
- `SUBMITTED`: rejects the order with reason `INFLIGHT_TIMEOUT`.
- `PENDING_CANCEL` or `PENDING_UPDATE` under `ResolveLocally`: resolves the order to `CANCELED` with reason
`INFLIGHT_TIMEOUT`.
- `PENDING_CANCEL` or `PENDING_UPDATE` under `RetainUnresolved`: rejects the pending command with reason
`INFLIGHT_TIMEOUT` and restores the order's status from before the command. The order stays open
for later venue evidence.
For orders that have never been accepted, `SubmissionRecoveryPolicy::RetainUnresolved` requires
retention, as does Polymarket regardless of the configured policy. Retention stops automatic
per-order recovery queries while allowing later venue evidence to resolve the order. See
[Submission recovery](#submission-recovery) for the retention rules.
:::warning[Restored orders rely on later venue evidence]
Under `RetainUnresolved`, no order closes on a timeout alone. If a venue cancel event is lost, the restored
order needs a later event or report to close it. When periodic open-order checks are enabled, either mode
can obtain that report; open-only checks use a targeted query, subject to the adapter's report semantics and
the configured lookback. Use full-history checks when an adapter supplies closed orders only through bulk
history. See [Open-only mode](#open-only-mode).
:::
[Terminal reconciliation provenance](policies.md#terminal-reconciliation-provenance) distinguishes
local policy resolutions from venue-reported outcomes.
### Order consistency checks
An open-order check queries all execution clients before running their deferred report processing.
Each client stays busy until that work finishes or its reports are discarded; other report requests to
that client fail as already running.
The timeout starts when the check starts and uses `timeout_reconciliation`
(`timeout_reconciliation_secs` in Python). The node accepts the batch only before the deadline.
A batch ready exactly at the deadline is discarded.
Once the batch is accepted, deferred adapter processing and report application run synchronously,
without another deadline check or cancellation point. Slow processing does not discard accepted reports.
Discarding a batch or targeted response skips deferred adapter work; it cannot undo state changes an adapter
makes during collection.
Targeted follow-up queries use one timeout budget starting when their task starts. For each order, the node
tries available responsible clients in order and stops at the first matching status. It queries any required
companion fills before starting the next order's status query. Each status query keeps its client busy until
deferred processing or disposal. A companion fill query releases that client before the next order's query.
The node accepts each status or fill response only before the original deadline, then runs deferred
processing.
A response ready exactly at the deadline is discarded. Accepted results stay under node ownership until
reconciliation, including after fill timeout, fill error, cancellation, or normal shutdown. Slow processing
cannot discard accepted results. A canceled or expired status with unaccounted fills stays deferred until
those fills arrive. Clients requiring authoritative fills defer any status with unaccounted fills.
A timed out or canceled task does not resolve orders as missing. Fatal callback failure
stops further dispatch and discards the retained results.
The table below applies when cache state differs from venue state. A missing open-order report does not by
itself prove a pending modify or cancel outcome. Thus, these checks leave those states unresolved until
another check can determine the venue state.
:::info[Full-history checks]
The *Not found* resolutions apply only in full-history mode (`open_check_open_only=False`), after a targeted
query confirms absence. The default [open-only mode](#open-only-mode) also queries missing orders outside
in-flight recovery, but leaves a "not found" result unresolved. In full-history mode, an unacknowledged
`SUBMITTED` order stays unresolved when the policy or its client requires retention.
:::
| Cache status | Venue status | Resolution | Rationale |
| ------------------ | ------------ | ------------ | ------------------------------------------------------------------------ |
| `SUBMITTED` | *Not found* | `REJECTED` | Order never confirmed by venue (for example, lost during network error). |
| `ACCEPTED` | *Not found* | `REJECTED` | Order does not exist at venue, likely was never successfully placed. |
| `ACCEPTED` | `CANCELED` | `CANCELED` | Venue canceled the order (user action or venue-initiated). |
| `ACCEPTED` | `EXPIRED` | `EXPIRED` | Order reached GTD expiration at venue. |
| `ACCEPTED` | `REJECTED` | `REJECTED` | Venue rejected after initial acceptance (rare but possible). |
| `PENDING_UPDATE` | *Not found* | *Unresolved* | Modification outcome stays unknown. |
| `PENDING_CANCEL` | *Not found* | *Unresolved* | Cancellation outcome stays unknown. |
| `PARTIALLY_FILLED` | `CANCELED` | `CANCELED` | Order canceled at venue with fills preserved. |
| `PARTIALLY_FILLED` | *Not found* | `CANCELED` | Order does not exist but had fills (reconciles fill history). |
#### Open-only mode
Venue "open orders" endpoints exclude recently filled or canceled orders, so bulk absence alone cannot
distinguish missing orders from recently closed ones. After `open_check_missing_retries` eligible missing
checks with complete client coverage, the engine issues a targeted `GenerateOrderStatusReport` query.
In-flight statuses and orders registered for in-flight recovery are excluded from missing-order queries.
The in-flight checker handles registered commands. After a timeout restores an order's prior status, it
becomes eligible for missing-order queries. Persisted in-flight orders without a registered command are also
excluded; they still need a returned report, venue event, or full-history reconciliation.
Recent local activity and query recency defer the query. Orders whose last update predates
`open_check_lookback_mins` are skipped. With the default 60-minute window, an order with no update for an
hour remains unqueried through this path.
A returned report reconciles status and fills normally. If the targeted query returns no report or fails,
the engine keeps the order open; it generates no `NOT_FOUND_AT_VENUE` rejection or synthetic cancel from
that result. Adapter report semantics still apply, including any adapter-local status inference.
Sending a missing-order query resets the retry counter, including when collection later times out.
Persistent absence can therefore trigger another query after `open_check_missing_retries` eligible checks.
The existing `max_single_order_queries_per_cycle` cap and query spacing apply to logical status requests;
an adapter can make several HTTP requests to produce one report.
Some adapters time-filter bulk open-order reports. For example, Bybit filters by the venue's last-update
time. After a local timeout restore, a still-open order can remain absent from bulk reports while targeted
queries repeatedly find it open. Each positive report clears the missing-order counter, but this can repeat
until the cached last update falls outside the lookback window.
#### Recent order protection
The engine skips reconciliation for orders whose last event falls within the
`open_check_threshold_ms` window. This prevents false positives from race conditions where the
venue is still processing.
#### Targeted query safeguard
Before applying a terminal "not found" resolution, the engine issues a single-order query to the
venue. This catches false negatives from bulk query limitations or timing delays.
#### Completed orders
`FILLED` orders that are "not found" at the venue are silently ignored. Venues commonly drop
completed orders from their query results.
### Position checks
#### Report acceptance
Position snapshots and their authoritative fill queries use separate `timeout_reconciliation` deadlines.
Each stage collects all results before accepting them, and accepts only while `now < deadline`. Each
client stays busy until all its retained report processing finishes or its results are discarded.
Accepted stages run deferred processing and pass reports to reconciliation synchronously, even if processing
crosses the deadline. Expiry or cancellation skips deferred processing; it cannot undo state changes
an adapter makes during collection.
During shutdown, the node discards unused position snapshots without running deferred processing, applies accepted
fill stages, and retains ownership of collection workers until they drain.
#### Retries and query failures
Position checks use separate retry counters per instrument and account. A successful position
match clears the counter, while repeated unresolved discrepancies stop active reconciliation for
that pair until the discrepancy clears.
If a venue position query fails, the engine skips cached positions for that venue during the cycle
instead of treating missing reports as flat.
### Retry coordination
The in-flight loop counts per-order retries against `inflight_check_retries` and mirrors that count into
missing-order tracking. The open-order loop uses `open_check_missing_retries`. In open-only mode, missing-order
queries skip in-flight orders and registered in-flight checks, so they neither consume nor reset the in-flight
budget. Timeout exhaustion clears the tracking before later checks query a restored order.
Full-history checks can query missing in-flight orders. Each loop applies its own limit; neither setting
automatically overrides the other. A returned targeted report reconciles normally and clears missing-order
tracking. If missing-order resolution leaves a pending cancel or update unresolved, it resets the in-flight
count before checking again after the configured threshold.
When `RetainUnresolved` or the registered client requires retention, a tracked submission that has not been
acknowledged keeps its original in-flight budget instead of resetting it. Repeated missing-order checks cannot
postpone exhaustion of that budget. Exhaustion keeps the unresolved submission without a synthetic terminal
event.
### Single-order query throttling
The engine caps single-order queries per cycle with `max_single_order_queries_per_cycle`. RemainingShown in full with attribution under the source's licence. Licence: LGPL-3.0
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.