# Why your trading bot's position drifts from the broker's

A trading bot's position is the confirmed filled quantity plus the open quantity of every order without a final outcome. Track cumulative fills per order, rebuild after a reconnect by buffering the stream before the snapshot, and check new orders against the worst side of that range.

Canonical: <https://pitofficer.com/blog/trading-bot-position-out-of-sync-with-broker/>
Author: Eugene Palchukovsky <https://github.com/palchukovsky>
Description: A fill during a reconnect can leave your bot holding a position it cannot see: track the position as a range and rebuild state without a gap.
Published: 2026-09-03T21:25:26+03:00
Updated: 2026-09-03T21:25:26+03:00
Tags: reconciliation, order-management, risk-controls, trading-bots

An order that fills while your trading bot is reconnecting drops out of the
open-orders list, and a bot that reads its absence as "canceled" now holds a
position it does not know about.

:::stat
**0 vs 50**

What the bot believes it holds, and what the broker holds, after its buy for
50 fills during a reconnect and the bot books the missing order as canceled.
Illustrative quantities.
:::

:::timeline

1. **The bot buys 50.** The order rests at the venue.
2. **The connection drops.** The bot hears nothing.
3. **The order fills.** The broker now holds 50; the bot does not know.
4. **The bot reconnects and lists open orders.** The order is not there.
5. **The bot books it as canceled.** It believes it holds 0.

:::

:::cards

- **A position is a range.** It is the confirmed filled quantity plus the open
  quantity of every order without a final outcome: open buys widen it upward,
  open sells downward.
- **Cumulative quantity beats counted fills.** Order state and executions often
  arrive on separate channels, and a client cannot assume which comes first;
  take the larger of the cumulative quantity the venue reports and the sum of
  distinct executions.
- **Absent is not canceled.** An order missing from the open-orders snapshot has
  no known outcome until you look it up by ID.
- **Subscribe, then snapshot.** Buffer the live stream before the snapshot and
  replay it after: overlap is harmless when every update is idempotent, a gap
  is not.
- **Trade against the worst case.** Until the range closes, size new orders
  against its worst side, and open no new risk while a difference with the
  venue is unexplained.

:::

## What is the bot's position while orders are still open?

**A range: the quantity the venue has confirmed as filled, widened by every
order that can still change it.**

:::outcomes

- **Lowest possible: 90.** Confirmed, minus the sell for 30 sent and not yet
  acknowledged.
- **Confirmed: 120.** Long 100 shares, plus 20 filled on a buy for 50.
- **Highest possible: 150.** Confirmed, plus the 30 still working on the buy.

:::

The bot stores one number while the venue's answer is still moving, and it
hears about each change late, twice or out of order. A ledger keeps the range
with two rules: an execution counts once per execution ID, and a stale update
never reopens a final state.

:::more[Terms this article uses]
The **confirmed position** is the quantity the venue has reported as filled.
The **cumulative filled quantity** is the total the venue reports as filled for
one order so far. The **working quantity** is the part of an order that can
still execute. An **execution ID** is the venue's identifier for one fill. An
**in-flight order** is one the bot has sent and the venue has not yet
acknowledged. An order has an **unknown outcome** when the bot cannot
establish its current state: no acknowledgment, a missed message, or absence
from a snapshot. Each venue's names for these are in
[the venue notes](#what-does-each-venue-document).

The **position range** is `[confirmed - open sells, confirmed + open buys]`,
where "open" counts working and unknown quantity alike. The ledger is in
[the runnable code](#where-is-the-runnable-code) at the end.
:::

:::more[Busts and corrections can lower what has filled]
The ledger assumes cumulative quantity only grows. A trade bust breaks that: in
FIX a bust lowers CumQty and can move a filled order back to partially filled
(scenarios J.1.a and J.1.b of the
[FIX order-state document](https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX-Latest-as-of-EP284-Order-State-Changes.pdf)),
and Interactive Brokers
[reports a correction](https://interactivebrokers.github.io/tws-api/executions_commissions.html)
under an `execId` that differs from the original only after its last period,
which this ledger would count as a new fill: it covers ordinary fills only. A
bust can legitimately reopen a final state; a stale update cannot. Handle busts
and corrections as explicit events that replace the earlier execution and
recompute the filled quantity, never as new fills.
:::

## Why does a canceled order still trade?

**A cancel is a request, and until the venue confirms it the order keeps
trading.** Scenario B.1.b of the
[FIX order-state document](https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX-Latest-as-of-EP284-Order-State-Changes.pdf)
shows it step by step:

:::timeline

1. **An order for 10,000 is accepted.** Nothing has filled.
2. **2,000 fill.** 8,000 can still execute.
3. **You send a cancel.** The order keeps trading.
4. **3,000 more fill, crossing the cancel request.** 5,000 filled, 5,000 open.
5. **The venue acknowledges the cancel as pending.** 5,000 still open.
6. **1,000 fill while the cancel is pending.** 6,000 filled, 4,000 open.
7. **The cancel is done.** 6,000 filled; nothing is open.

:::

Venue APIs show the same race:
[Bybit](https://bybit-exchange.github.io/docs/v5/websocket/private/order) can
send two filled messages when a cancel meets an execution, and
[Interactive Brokers](https://interactivebrokers.github.io/tws-api/order_submission.html)
calls duplicate order-status messages typical.
Read the quantities, not the status label: when several states apply at once,
FIX reports the one with the highest precedence, and pending cancel outranks
filled.

## Why do fills and order status disagree?

**Order state and executions often travel on separate channels, so one can run
ahead of the other; take the larger of the reported cumulative quantity and the
sum of distinct fills.**

Interactive Brokers and Bybit deliver order state and executions separately;
Binance spot carries both in one event. With two streams, the order update can
already report a cumulative 70 while the execution stream has delivered fills
for 40 (quantities illustrative):

:::timeline

1. **A buy for 100 is sent.** Sum of fills: 0. Ledger: 0 to 100.
2. **An execution for 40 arrives.** Sum of fills: 40. Ledger: 40 to 100.
3. **A cancel is sent.** Nothing changes yet.
4. **The venue fills 30 more before the cancel lands.** The bot hears nothing:
   still 40, still 40 to 100.
5. **The order stream reports canceled, cumulative 70.** Sum of fills: 40.
   Ledger: 70.
6. **The execution for 30 arrives late.** Sum of fills: 70. Ledger: still 70.

:::

A bot that sums fills is wrong by 30 from the fourth step to the sixth and
cannot tell; a ledger that takes the larger of the two numbers is exact from
the fifth and does not double-count at the sixth.

## What does the new quantity mean in a cancel/replace?

**Under FIX, a replacement's quantity is the order's new total, including what
has already filled.** In scenario C.1.b of the
[FIX order-state document](https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX-Latest-as-of-EP284-Order-State-Changes.pdf)
an order for 10,000 has filled 1,100 when a replace to 12,000 is accepted: what
can still execute becomes 10,900, not 12,000.

:::cards

- **Send the new total.** Sending the quantity you still want under-sizes the
  order by everything already filled.
- **Count the larger quantity.** Until the venue accepts the replace, either
  quantity can be live, so the range uses the larger of the old and the new
  open quantity.
- **Key the ledger by the order, not its latest client order ID.** In FIX the
  replacement carries a new client order ID and keeps the cumulative quantity,
  so both IDs map to one ledger order, or its fills count twice; a cancel
  followed by a new order starts from zero. Check which of the two your venue
  does.

:::

## An order is missing after a reconnect: filled or canceled?

**You do not know yet: absence from the open-orders snapshot does not establish
an order's state.** A snapshot is a point-in-time answer from the venue's REST
API: the open orders, the fills in a window, or the positions.

:::outcomes

- **Final at the venue.** It filled, was canceled, expired or was rejected.
- **Outside the snapshot.** Interactive Brokers' per-client open-orders request
  lists only that API client's orders (client 0 also gets manual TWS orders),
  and Bybit pages its open orders.
- **Still in flight.** It may not be listed yet.
- **Not found by ID either.** An order sent just before the disconnect may not
  have reached the venue yet: it stays unknown.

:::

Treat the order as unknown, keep its whole open quantity in the range, and ask
the venue about that order by ID. "Not found" is not an outcome either: the
order stays unknown until a deadline passes and a second source or a person
confirms it does not exist.

Then backfill the executions you missed. Retention is the hard limit: when the
venue no longer returns the fills you missed, the position snapshot is what
remains, and every difference from it has to be explained by hand.

:::matrix

| Venue | Lookup by client order ID | More queries reach older fills |
| --- | --- | --- |
| Binance Spot | ✓ [1] | ✓ [2] |
| Bybit V5 | ~ [3] | ✓ [4] |
| Interactive Brokers TWS API | ✗ [5] | ✗ [6] |

1. A lookup by symbol and client order ID. Binance
   [REST API](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md).
2. Trade history pages by trade ID; one time-window query spans at most 24
   hours, so a longer outage takes several queries. Binance
   [REST API](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md).
3. The live lookup keeps only the latest 500 closed orders, cleared when Bybit
   restarts ([open orders](https://bybit-exchange.github.io/docs/v5/order/open-order)).
   [Order history](https://bybit-exchange.github.io/docs/v5/order/order-list)
   also takes the client ID, but returns orders canceled with no fill,
   rejected or deactivated for 24 hours only, and beyond 7 days only orders
   with fills.
4. At most 7 days per query, paged with a cursor. Bybit
   [trade history](https://bybit-exchange.github.io/docs/v5/order/execution).
5. No lookup by ID; finished orders and fills come from separate requests.
   Interactive Brokers
   [EClient](https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html).
6. A horizon, not a page size: executions since midnight by default; TWS can be
   configured for 7 days, IB Gateway serves only the current day. Interactive
   Brokers
   [executions](https://interactivebrokers.github.io/tws-api/executions_commissions.html).

:::

## How do you rebuild state after a reconnect without a gap?

**Subscribe and buffer first, take the snapshot once the subscription is live,
replay the buffer third.** The two sources race, and only one order loses
nothing.

```d2 title="Snapshot and stream: the order that loses nothing"
grid-columns: 2
horizontal-gap: 12
wrong: "Snapshot\nfirst:\na gap" {
  direction: down
  a: "Take the\nsnapshot"
  b: "Events\narriving now\nare in neither\nsource: lost"
  c: "Subscribe"
  a -> b -> c
}
right: "Subscribe\nfirst:\nan overlap" {
  direction: down
  d: "Subscribe;\nonce live,\nbuffer\nevents"
  e: "Take the\nsnapshot:\nevents\narriving now\ncan be\nin both"
  f: "Replay the\nbuffer,\nduplicates\ncount once"
  d -> e -> f
}
```

The gap is invisible: the position simply drifts. The overlap is harmless when
applying an update twice changes nothing, and a ledger that keys executions by
ID and keeps the highest cumulative quantity has that property.

1. Subscribe to the order and execution stream, wait until it is live, and
   buffer it.
2. Read the open orders; mark as unknown every order the bot tracks without a
   final outcome, acknowledged or not, that the snapshot does not list.
3. Backfill the missed executions, then replay the buffer; duplicates drop.
4. Look up each unknown order by ID.
5. Read the venue's own position, apply what arrived meanwhile, and compare.

**Reconciliation** is comparing the bot's records of orders, fills and
positions with the venue's and explaining every difference; step 5 is its
position check. A **break** is a difference nobody can explain yet. Once the unknown orders are
resolved, the confirmed position must equal the venue's. A difference that
remains - a manual trade, a fill older than the backfill window - is not
absorbed into the position; the bot opens no new risk until it is explained.

The cost: the bot does not trade until recovery finishes, and every snapshot
and backfill call spends rate-limit budget, so a connection that drops
repeatedly can keep the bot out of the market longer than the drops themselves.

:::more[Orders the bot never recorded]
The snapshot also shows open orders the bot never recorded: it crashed after
sending and before writing them down. The recovery code adopts every such
order, which is right for an account only the bot trades. On a shared account,
adopt only client order IDs with your bot's own prefix; an order from another
program or a person is a break, not yours to manage.
:::

:::more[What the venue's own number is]
The calls that return the venue's position or balance are in
[the venue notes](#what-does-each-venue-document). On Binance Spot the
venue's number is the asset balance: compare it with a balance built from the
opening holdings, the fills, the commissions charged in that asset, and
deposits and withdrawals. The ledger here tracks fills only.
:::

:::more[When a difference becomes a break]
Neither a non-zero difference nor a late event of an unknown order is a break
yet: a fill can land between reading the venue's number and the last drain.
Keep new risk paused and compare again where nothing is in flight - at a
watermark, when the venue's snapshot carries the sequence number of the last
event it includes, or in a quiet interval with no order working and nothing
arriving. A difference that survives that comparison is a break. After recovery
the same subscription keeps feeding the live path; there is no second
subscribe.
:::

:::more[Liquidation, delivery and settlement change the position with no order]
On derivatives, liquidation, auto-deleveraging, delivery and settlement change
the position with no order of yours. Bybit marks each of them in its
execution and order types ([the venue notes](#what-does-each-venue-document)); book them from
there before comparing.
Funding moves the margin balance, not the position quantity: keep it out of
the quantity comparison.
:::

:::more[Without sequence numbers, a lost message shows only at the next comparison]
Where a venue numbers neither its stream messages nor its executions, a lost
message shows only at the next comparison: comparing positions catches net
drift, and comparing execution records with the backfill catches an unseen buy
and sell that offset.
:::

## What may the bot trade while the position is a range?

**Size every new order against the worst side of the range, and open no new
risk while a difference with the venue is unexplained.**

:::outcomes

- **A buy for 30: refused.** With a long limit of 100 and an unacknowledged buy
  for 80, the worst case is 110, if both orders fill.
- **A buy for 20: passes.** The worst case is exactly the limit.

:::

The cost is idle capacity: while orders are in flight, the check keeps room for
fills that may never happen, and a strategy with many resting orders will see
safe orders refused. The alternative is a limit that holds only when nothing is
in flight.

:::more[With the OpenPit SDK 0.7.0]
A pre-trade engine can carry part of this by construction. In the OpenPit SDK
0.7.0, the built-in Spot Funds policy reserves an order's amount when it passes
the pre-trade check, and execution reports that carry the order's pre-trade lock
settle the reservation as fills arrive, so orders in flight count against
available funds. That covers funds on spot only - the policy is long-only,
without leverage - not a position limit like the one above. The engine is an
embedded, in-process component, not the system of record: reconciling with the
venue stays your job. See
[Spot Funds as of 0.7.0](https://github.com/openpitkit/pit/wiki/Spot-Funds/af8ea238c399945239519fb5ef9d6f0d994107ff),
[Balance Reconciliation as of 0.7.0](https://github.com/openpitkit/pit/wiki/Balance-Reconciliation/af8ea238c399945239519fb5ef9d6f0d994107ff)
and the [v0.7.0 release](https://github.com/openpitkit/pit/releases/tag/v0.7.0).
:::

## When does a small team need a drop copy?

**When an unexplained position costs more than running and watching a second
session, and the venue offers one for its account type.**

A **drop copy** is a separate session on which the venue sends copies of your
order and execution reports; CME and Binance spot both offer one
([the venue notes](#what-does-each-venue-document)). It does not share the
trading session's connection, so a gap in one shows up as a difference against
the other.

Where the venue offers none, a second process that reads fills and positions
through the REST API on its own timer and compares them with the trading
process's ledger does much of the same job: a separate process, not a separate
venue feed, at the cost of another process, its own rate-limit budget and its
own failure modes.

## What should the bot get right before it goes live?

- The position is stored as a confirmed quantity plus each order's open
  quantity, not as one number.
- Fills are keyed by execution ID; the filled quantity is the larger of the
  reported cumulative quantity and the sum of distinct executions.
- A stale update never reopens a final order state; a bust can, and busts and
  corrections replace the earlier execution instead of adding to it.
- An order missing from the open-orders snapshot, or not found by ID, is unknown
  until a lookup or a person settles it; an open order the bot never recorded is
  adopted only under the bot's own ID prefix.
- On reconnect and at startup: subscribe and buffer, snapshot, replay - never
  snapshot first.
- You know your venue's backfill window, and what happens when the bot is down
  longer than that.
- Pre-trade checks use the worst side of the range.
- A difference from the venue's position pauses new risk; one that survives a
  comparison with nothing in flight alerts a person.

## What does each venue document?

**The fields, calls and limits behind everything above, venue by venue.**

:::more[Binance]

- **Order stream.** The spot
  [`executionReport`](https://github.com/binance/binance-spot-api-docs/blob/master/user-data-stream.md)
  carries order state and the execution in one event: `l` is the last executed
  quantity, `z` the cumulative filled quantity. Key fills by the trade ID `t`,
  which the trade history also returns and which is -1 on a report that is not
  a fill; `I`, which Binance labels the execution ID, is set on every report.
  The commission charged is in `n`, its asset in `N`.
- **Lookup by ID.**
  [`GET /api/v3/order`](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md)
  with `symbol` and `origClientOrderId`.
- **Backfill.**
  [`GET /api/v3/myTrades`](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md)
  pages by trade ID with `fromId`; a `startTime` to `endTime` interval cannot
  exceed 24 hours.
- **The venue's number on spot.** The asset balance, `free` plus `locked` in
  [`GET /api/v3/account`](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md).
- **The venue's number on futures.** The
  [futures documentation](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V2)
  tells clients to use its position snapshot together with `ACCOUNT_UPDATE`
  events from the user data stream.
- **Drop copy.** The spot
  [FIX API](https://github.com/binance/binance-spot-api-docs/blob/master/fix-api.md)
  offers a Drop Copy session: every execution report of the account, delayed
  by 1 second, to an Ed25519 API key that may hold read-only FIX permission.

:::

:::more[Bybit V5]

- **Two channels.** Order state and executions arrive on separate topics; the
  [order stream](https://bybit-exchange.github.io/docs/v5/websocket/private/order)
  warns that a cancel accepted at the moment of execution can produce two
  messages with status `Filled`. The execution ID is `execId`.
- **Open orders and lookup by ID.**
  [`GET /v5/order/realtime`](https://bybit-exchange.github.io/docs/v5/order/open-order)
  pages open orders with a cursor and looks an order up with `category`,
  `orderLinkId` and, for `linear`, one of `symbol`, `baseCoin` or
  `settleCoin`. Of closed orders it keeps only the latest 500 per account and
  category, and a Bybit restart clears them.
  [Order history](https://bybit-exchange.github.io/docs/v5/order/order-list)
  also accepts `orderLinkId`, but returns `Cancelled` (no fill), `Rejected`
  and `Deactivated` orders for 24 hours only, and beyond 7 days only orders
  with fills.
- **Backfill.** [Trade history](https://bybit-exchange.github.io/docs/v5/order/execution)
  covers at most 7 days per query, paged with a cursor.
- **Position changes with no order.** The
  [enums](https://bybit-exchange.github.io/docs/v5/enum) mark takeover
  liquidation, auto-deleveraging, USDT futures delivery and inverse futures
  settlement with `execType` `BustTrade`, `AdlTrade`, `Delivery` and `Settle`,
  and a laddered liquidation order with `createType` `CreateByLiq`. Funding is
  `execType` `Funding`.

:::

:::more[Interactive Brokers TWS API]

- **Two channels.** Order state arrives through the `orderStatus` callback,
  executions through `execDetails`; duplicate `orderStatus` messages are
  typical ([order documentation](https://interactivebrokers.github.io/tws-api/order_submission.html)).
  The execution ID is `execId`.
- **Open orders.**
  [`reqOpenOrders`](https://interactivebrokers.github.io/tws-api/open_orders.html)
  returns only the orders of the same API client ID (client 0 also binds manual
  TWS orders; `reqAllOpenOrders` lists every API client's).
- **No lookup by ID.** Finished orders come from
  [`reqCompletedOrders`](https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html),
  fills from `reqExecutions`.
- **Backfill.**
  [`reqExecutions`](https://interactivebrokers.github.io/tws-api/executions_commissions.html)
  returns executions since midnight by default; TWS can be configured for 7
  days, IB Gateway serves only the current day.
- **The venue's number.**
  [`reqPositions`](https://interactivebrokers.github.io/tws-api/positions.html)
  sends every position, then updates as they change.

:::

:::more[Alpaca]
[Fill events](https://docs.alpaca.markets/us/docs/websocket-streaming) carry
`position_qty`, the position after that fill.
:::

:::more[FIX]

- **Quantities.** CumQty is the cumulative filled quantity, LeavesQty the
  working quantity.
- **Fills across a cancel, scenario B.1.b.** The steps above, as ExecType /
  OrdStatus: New / New (CumQty 0, LeavesQty 10,000); Trade / Partially Filled
  (2,000 / 8,000); the cancel request is sent; Trade / Partially Filled (5,000
  / 5,000); Pending Cancel / Pending Cancel (5,000 / 5,000); Trade / Pending
  Cancel (6,000 / 4,000); Canceled / Canceled (6,000 / 0).
- **Precedence.** When several states apply at once, OrdStatus reports the one
  with the highest precedence, and Pending Cancel outranks Filled.
- **Cancel/replace, scenario C.1.b.** The replacement's OrderQty is the new
  total; after 1,100 filled, a replace to 12,000 leaves LeavesQty at 10,900.
  The replacement carries a new ClOrdID and keeps CumQty.
- **Busts, scenarios J.1.a and J.1.b.** A bust lowers CumQty and can move a
  filled order back to partially filled.

Source: [FIX order-state document](https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX-Latest-as-of-EP284-Order-State-Changes.pdf).
:::

:::more[CME]
[Drop Copy 4.0](https://cmegroupclientsite.atlassian.net/wiki/spaces/EPICSANDBOX/pages/665321494)
delivers fills, trade cancels and corrections, and order-entry acknowledgments
to a target session.
:::

## Where is the runnable code?

:::more[The ledger, the recovery and the limit check, with their tests, in one file]
The ledger keys executions by ID and keeps the highest cumulative quantity;
`recover` is the five-step rebuild; `allows` is the worst-side check. The
in-memory venue and stream run the recovery and limit scenarios without an
account.

```python
# Standard library only. Tested with CPython 3.13 and 3.14.
from dataclasses import dataclass, field
from decimal import Decimal

OPEN = {"pending_new", "working", "pending_cancel", "unknown"}


@dataclass
class Order:
    client_id: str
    side: int                                # +1 buy, -1 sell
    qty: Decimal
    state: str = "pending_new"
    reported_cum: Decimal = Decimal(0)       # highest cumulative qty reported
    execs: dict[str, Decimal] = field(default_factory=dict)  # exec ID -> qty

    @property
    def filled(self) -> Decimal:
        fills = sum(self.execs.values(), Decimal(0))  # distinct executions
        return max(fills, self.reported_cum)

    @property
    def open_qty(self) -> Decimal:
        return self.qty - self.filled if self.state in OPEN else Decimal(0)


class Ledger:
    def __init__(self, start: Decimal = Decimal(0)) -> None:
        self.start = start
        self.orders: dict[str, Order] = {}

    def submit(self, client_id: str, side: int, qty: str) -> None:
        self.orders[client_id] = Order(client_id, side, Decimal(qty))

    def on_execution(self, client_id: str, exec_id: str, qty: str) -> None:
        order = self.orders[client_id]
        execs = {**order.execs, exec_id: Decimal(qty)}  # the same ID never adds twice
        if sum(execs.values()) > order.qty:  # a break; the ledger stays unchanged
            raise ValueError(f"{client_id}: fills exceed the order")
        order.execs = execs

    def on_order_update(self, client_id: str, state: str, cum_qty: str) -> None:
        order = self.orders[client_id]
        order.reported_cum = max(order.reported_cum, Decimal(cum_qty))
        if order.state in OPEN:              # stale updates never reopen a final state
            order.state = state

    def mark_unknown(self, client_id: str) -> None:
        if self.orders[client_id].state in OPEN:
            self.orders[client_id].state = "unknown"

    def unknown(self) -> list[str]:
        return [o.client_id for o in self.orders.values() if o.state == "unknown"]

    def position(self) -> tuple[Decimal, Decimal, Decimal]:
        """(lowest possible, confirmed, highest possible)"""
        orders = self.orders.values()
        confirmed = self.start + sum((o.side * o.filled for o in orders), Decimal(0))
        buys = sum((o.open_qty for o in orders if o.side > 0), Decimal(0))
        sells = sum((o.open_qty for o in orders if o.side < 0), Decimal(0))
        return confirmed - sells, confirmed, confirmed + buys


def apply(ledger: Ledger, event: tuple) -> None:
    kind, client_id, *rest = event           # ("exec", id, exec_id, qty)
    if kind == "exec":                       # ("order", id, state, cum_qty)
        ledger.on_execution(client_id, *rest)
    else:
        ledger.on_order_update(client_id, *rest)


def recover(ledger: Ledger, venue, stream) -> tuple[Decimal, list[tuple]]:
    """Rebuild state; return the difference and late events of unknown orders."""
    stream.start_buffering()                 # 1. subscribe before any snapshot
    open_now = venue.open_orders()           # 2. {id: (side, qty, state, cum_qty)}
    for client_id, (side, qty, state, cum) in open_now.items():
        if client_id not in ledger.orders:   # sent, then a crash before recording
            ledger.submit(client_id, side, qty)
        ledger.on_order_update(client_id, state, cum)
    for client_id, order in ledger.orders.items():
        if order.state in OPEN and client_id not in open_now:
            ledger.mark_unknown(client_id)   # absent is not the same as canceled
    backlog = venue.recent_executions() + stream.drain()  # 3. backfill, then buffer
    for event in backlog:                    # duplicates drop; overlap is harmless
        if event[1] in ledger.orders:        # fills of unrecorded orders show at 5
            apply(ledger, event)
    for client_id in ledger.unknown():       # 4. resolve each missing order by ID
        found = venue.order(client_id)       # None: not found, stays unknown
        if found:
            ledger.on_order_update(client_id, *found)
    venue_pos = venue.position()             # 5. read the venue's number, then
    late = stream.drain()                    #    apply what arrived meanwhile
    for event in late:
        if event[1] in ledger.orders:
            apply(ledger, event)
    strangers = [e for e in late if e[1] not in ledger.orders]
    _, confirmed, _ = ledger.position()
    return venue_pos - confirmed, strangers  # either one non-empty: no new risk


def allows(ledger: Ledger, side: int, qty: str, limit: str) -> bool:
    """Check a new order against the worst side of the range."""
    low, _, high = ledger.position()
    if side > 0:
        return high + Decimal(qty) <= Decimal(limit)
    return low - Decimal(qty) >= -Decimal(limit)


# In-memory venue and stream, so the scenarios below run without an account.
class FakeVenue:
    def __init__(self) -> None:
        self.orders: dict[str, list] = {}    # id -> [side, qty, state, cum_qty]
        self.execs: list[tuple] = []
        self.pos = Decimal(0)

    def accept(self, client_id: str, side: int, qty: str) -> None:
        self.orders[client_id] = [side, Decimal(qty), "working", Decimal(0)]

    def fill(self, client_id: str, exec_id: str, qty: str) -> list[tuple]:
        order = self.orders[client_id]
        order[3] += Decimal(qty)
        self.pos += order[0] * Decimal(qty)
        if order[3] == order[1]:
            order[2] = "filled"
        self.execs.append(("exec", client_id, exec_id, qty))
        return [self.execs[-1], ("order", client_id, order[2], str(order[3]))]

    def cancel(self, client_id: str) -> list[tuple]:
        order = self.orders[client_id]
        order[2] = "canceled"
        return [("order", client_id, "canceled", str(order[3]))]

    def open_orders(self) -> dict[str, tuple]:
        return {i: (o[0], str(o[1]), o[2], str(o[3]))
                for i, o in self.orders.items() if o[2] in OPEN}

    def recent_executions(self) -> list[tuple]:
        return list(self.execs)

    def order(self, client_id: str) -> tuple[str, str] | None:
        order = self.orders.get(client_id)
        return (order[2], str(order[3])) if order else None

    def position(self) -> Decimal:
        return self.pos


class FakeStream:
    def __init__(self) -> None:
        self.buffer: list[tuple] = []

    def start_buffering(self) -> None:
        pass                                 # a real stream subscribes here

    def drain(self) -> list[tuple]:
        events, self.buffer = self.buffer, []
        return events


D = Decimal

# A fill crosses the cancel; the order stream is ahead of the execution stream.
bot, venue = Ledger(), FakeVenue()
bot.submit("A", +1, "100")
venue.accept("A", +1, "100")
for e in venue.fill("A", "x1", "40"):
    apply(bot, e)
bot.on_order_update("A", "pending_cancel", "40")
late = venue.fill("A", "x2", "30")           # fills while the cancel is in flight
for e in venue.cancel("A"):
    apply(bot, e)                            # canceled, cumulative 70
assert bot.position() == (D(70), D(70), D(70))
for e in late:
    apply(bot, e)                            # the execution stream catches up
assert bot.position() == (D(70), D(70), D(70))

# The order fills while the bot is disconnected and vanishes from open orders.
bot, venue, stream = Ledger(), FakeVenue(), FakeStream()
bot.submit("B", +1, "50")
venue.accept("B", +1, "50")
venue.fill("B", "y1", "50")                  # the bot never sees this
assert bot.position() == (D(0), D(0), D(50))
assert recover(bot, venue, stream) == (D(0), [])
assert bot.orders["B"].state == "filled"
assert bot.position() == (D(50), D(50), D(50))

# A fill lands in both the backfill and the buffer; it counts once.
bot, venue, stream = Ledger(), FakeVenue(), FakeStream()
bot.submit("C", -1, "10")
venue.accept("C", -1, "10")
stream.buffer = venue.fill("C", "z1", "10")  # arrives after the subscription
assert recover(bot, venue, stream) == (D(0), [])
assert bot.position() == (D(-10), D(-10), D(-10))

# A trade the bot never sent is a break, not drift to absorb.
venue.pos += D(5)
assert recover(bot, venue, stream) == (D(5), [])

# The bot crashed after sending an order and before recording it.
bot, venue, stream = Ledger(), FakeVenue(), FakeStream()
venue.accept("F", +1, "20")
venue.fill("F", "w1", "5")
assert recover(bot, venue, stream) == (D(0), [])
assert bot.position() == (D(5), D(5), D(20))

print("recovery scenarios pass")

# An unacknowledged order still counts against the limit.
bot = Ledger()
bot.submit("E", +1, "80")
assert not allows(bot, +1, "30", limit="100")
assert allows(bot, +1, "20", limit="100")
print("limit scenario passes")
```

:::

## What else do people ask?

:::more[Why does my bot show a position the exchange does not have?]
The bot may have applied a fill twice or to the wrong order: a duplicate
delivery counted again because fills were not keyed by execution ID, or a
replaced order whose fills were booked a second time under the new order ID.
Other causes: a manual trade on the same account, a fee charged in the asset
you bought, a fill the bot missed and never backfilled, or a liquidation or
auto-deleveraging on derivatives. Key every fill by execution ID and compare
the confirmed position with the venue's after every reconnect.
:::

:::more[What is position reconciliation?]
Position reconciliation is comparing the bot's records of orders, fills and
positions with the venue's, and explaining every difference before the bot
opens new risk on top of it. A difference nobody can explain yet is a break.
:::

:::more[Can position reconciliation be automated?]
The comparison can: snapshot, backfill, compare, at startup, after every
reconnect and on a timer. Explaining a break may need a person when the
available records cannot: a manual trade or a fill older than the venue's
backfill window leaves nothing in the bot's records to explain it with.
Automate the halt on a break, not its absorption into the position.
:::

:::more[How often should a bot reconcile?]
At startup before the first order, after every reconnect, and on a timer: the
timer catches what the stream lost without reporting it.
:::

## Where should I read next?

- [FIX Order State Changes](https://www.fixtrading.org/wp-content/uploads/download-manager-files/FIX-Latest-as-of-EP284-Order-State-Changes.pdf):
  scenarios B.1.b (fill during a pending cancel), C.1.b (fill before a replace
  is accepted), J.1 (corrections and busts).
- Binance Spot:
  [user data stream](https://github.com/binance/binance-spot-api-docs/blob/master/user-data-stream.md)
  and [REST API](https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md).
- OpenPit SDK 0.7.0:
  [Spot Funds](https://github.com/openpitkit/pit/wiki/Spot-Funds/af8ea238c399945239519fb5ef9d6f0d994107ff)
  and
  [Balance Reconciliation](https://github.com/openpitkit/pit/wiki/Balance-Reconciliation/af8ea238c399945239519fb5ef9d6f0d994107ff).
