Why your trading bot's position drifts from the broker's
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.
Contents
- What is the bot’s position while orders are still open?
- Why does a canceled order still trade?
- Why do fills and order status disagree?
- What does the new quantity mean in a cancel/replace?
- An order is missing after a reconnect: filled or canceled?
- How do you rebuild state after a reconnect without a gap?
- What may the bot trade while the position is a range?
- When does a small team need a drop copy?
- What should the bot get right before it goes live?
- What does each venue document?
- Where is the runnable code?
- What else do people ask?
- Where should I read next?
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.
- The bot buys 50. The order rests at the venue.
- The connection drops. The bot hears nothing.
- The order fills. The broker now holds 50; the bot does not know.
- The bot reconnects and lists open orders. The order is not there.
- The bot books it as canceled. It believes it holds 0.
- 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.
- 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.
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.
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 at the end.
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),
and Interactive Brokers
reports a correction
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 shows it step by step:
- An order for 10,000 is accepted. Nothing has filled.
- 2,000 fill. 8,000 can still execute.
- You send a cancel. The order keeps trading.
- 3,000 more fill, crossing the cancel request. 5,000 filled, 5,000 open.
- The venue acknowledges the cancel as pending. 5,000 still open.
- 1,000 fill while the cancel is pending. 6,000 filled, 4,000 open.
- The cancel is done. 6,000 filled; nothing is open.
Venue APIs show the same race: Bybit can send two filled messages when a cancel meets an execution, and Interactive Brokers 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):
- A buy for 100 is sent. Sum of fills: 0. Ledger: 0 to 100.
- An execution for 40 arrives. Sum of fills: 40. Ledger: 40 to 100.
- A cancel is sent. Nothing changes yet.
- The venue fills 30 more before the cancel lands. The bot hears nothing: still 40, still 40 to 100.
- The order stream reports canceled, cumulative 70. Sum of fills: 40. Ledger: 70.
- 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 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.
- 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.
- 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.
| Venue | Lookup by client order ID | More queries reach older fills |
|---|---|---|
| Binance Spot | Yes1 | Yes2 |
| Bybit V5 | Partial3 | Yes4 |
| Interactive Brokers TWS API | No5 | No6 |
Notes and sources
- A lookup by symbol and client order ID. Binance REST API.
- 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.
- The live lookup keeps only the latest 500 closed orders, cleared when Bybit restarts (open orders). Order history 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.
- At most 7 days per query, paged with a cursor. Bybit trade history.
- No lookup by ID; finished orders and fills come from separate requests. Interactive Brokers EClient.
- 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.
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.
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.
- Subscribe to the order and execution stream, wait until it is live, and buffer it.
- 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.
- Backfill the missed executions, then replay the buffer; duplicates drop.
- Look up each unknown order by ID.
- 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.
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.
What the venue’s own number is
The calls that return the venue’s position or balance are in the venue notes. 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.
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.
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); book them from there before comparing. Funding moves the margin balance, not the position quantity: keep it out of the quantity comparison.
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.
- 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.
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, Balance Reconciliation as of 0.7.0 and the v0.7.0 release.
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). 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.
Binance
- Order stream. The spot
executionReportcarries order state and the execution in one event:lis the last executed quantity,zthe cumulative filled quantity. Key fills by the trade IDt, 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 inn, its asset inN. - Lookup by ID.
GET /api/v3/orderwithsymbolandorigClientOrderId. - Backfill.
GET /api/v3/myTradespages by trade ID withfromId; astartTimetoendTimeinterval cannot exceed 24 hours. - The venue’s number on spot. The asset balance,
freepluslockedinGET /api/v3/account. - The venue’s number on futures. The
futures documentation
tells clients to use its position snapshot together with
ACCOUNT_UPDATEevents from the user data stream. - Drop copy. The spot FIX API 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.
Bybit V5
- Two channels. Order state and executions arrive on separate topics; the
order stream
warns that a cancel accepted at the moment of execution can produce two
messages with status
Filled. The execution ID isexecId. - Open orders and lookup by ID.
GET /v5/order/realtimepages open orders with a cursor and looks an order up withcategory,orderLinkIdand, forlinear, one ofsymbol,baseCoinorsettleCoin. Of closed orders it keeps only the latest 500 per account and category, and a Bybit restart clears them. Order history also acceptsorderLinkId, but returnsCancelled(no fill),RejectedandDeactivatedorders for 24 hours only, and beyond 7 days only orders with fills. - Backfill. Trade history covers at most 7 days per query, paged with a cursor.
- Position changes with no order. The
enums mark takeover
liquidation, auto-deleveraging, USDT futures delivery and inverse futures
settlement with
execTypeBustTrade,AdlTrade,DeliveryandSettle, and a laddered liquidation order withcreateTypeCreateByLiq. Funding isexecTypeFunding.
Interactive Brokers TWS API
- Two channels. Order state arrives through the
orderStatuscallback, executions throughexecDetails; duplicateorderStatusmessages are typical (order documentation). The execution ID isexecId. - Open orders.
reqOpenOrdersreturns only the orders of the same API client ID (client 0 also binds manual TWS orders;reqAllOpenOrderslists every API client’s). - No lookup by ID. Finished orders come from
reqCompletedOrders, fills fromreqExecutions. - Backfill.
reqExecutionsreturns executions since midnight by default; TWS can be configured for 7 days, IB Gateway serves only the current day. - The venue’s number.
reqPositionssends every position, then updates as they change.
Alpaca
Fill events carry
position_qty, the position after that fill.
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.
CME
Drop Copy 4.0 delivers fills, trade cancels and corrections, and order-entry acknowledgments to a target session.
Where is the runnable code?
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.
# 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?
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.
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.
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.
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: 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 and REST API.
- OpenPit SDK 0.7.0: Spot Funds and Balance Reconciliation.