From dae575e1b5a58f10dce484269eabb87626727003 Mon Sep 17 00:00:00 2001 From: goodboy Date: Fri, 30 Oct 2026 18:50:06 -0400 Subject: [PATCH] Preserve IB order state through notices and late fills IB's 10349 TIF-preset notice made `ib_async` synthesize a `Cancelled` status for an order which subsequently filled. EMS then discarded its `Order`, recreated `Error(req=None)` for the separate error callback, and crashed while routing the fill. Treat 2181 (unsupported SmartRouting opt-out) and 10349 (preset sets TIF to DAY) as notices: preserve diagnostic callbacks without manufacturing order failures or relaying them as `BrokerdError`. Leave actual cancellation handling, including code 202, intact. Also, - snapshot `ib_async.Trade` order/status fields and its fill list at callback time so queued events cannot observe later state; - retain canceled/closed dialogs in `DarkBook._closed` while the order-ID mapping exists, keeping `Order.symbol` for late-fill routing and `Order.account` for commands after a reopen; - keep late errors out of `_active` and reactivate retained dialogs only on a subsequent pending/open status; - cover cancel/close/error/fill sequences, continued msg handling, callback snapshots and notice-vs-cancellation behavior offline. Explain the `ib_async.wrapper.Wrapper.error()` state mutations apart from EMS request retention; name the retained request fields needed by client routing and reopened dialogs. Human-tested live/dark fills and order cancellation on an IB paper Gateway. Exact-tree offline checks are retained in the commit plan. (this patch was generated in some part by `opencode` using `gpt-6.1-sol` (`openai`)) --- piker/brokers/ib/api.py | 78 ++++++++++++- piker/brokers/ib/broker.py | 34 +++++- piker/clearing/_ems.py | 59 +++++++--- tests/test_ems_trade_events.py | 154 +++++++++++++++++++++++++ tests/test_ib_trade_events.py | 200 +++++++++++++++++++++++++++++++-- 5 files changed, 495 insertions(+), 30 deletions(-) create mode 100644 tests/test_ems_trade_events.py diff --git a/piker/brokers/ib/api.py b/piker/brokers/ib/api.py index 2ee7b238..3ede4dd1 100644 --- a/piker/brokers/ib/api.py +++ b/piker/brokers/ib/api.py @@ -150,6 +150,78 @@ _show_wap_in_history: bool = False # overrides to sidestep pretty questionable design decisions in # ``ib_async``: class NonShittyWrapper(Wrapper): + def error( + self, + reqId: int, + errorCode: int, + errorString: str, + advancedOrderRejectJson: str, + ) -> None: + ''' + Report known IB order notices without inventing order state. + + ``ib_async`` 2.1.0's ``ib_async.wrapper.Wrapper.error()`` + mutates orders as a side effect of handling error callbacks: + + - 2181 is classified as a warning, but still overwrites + ``ib_async.Trade.orderStatus.status`` with + ``'ValidationError'`` and emits order-status events. + Unsupported routing attributes alone do not establish + that the broker rejected the submission. + - 10349 is not classified as a warning, so an unfinished + trade is set to ``'Cancelled'`` and cancellation events + are emitted. Our Gateway trace instead continued through + ``'PreSubmitted'`` to a fill: a DAY-preset notice did not + mean that IB had canceled the order. + + Preserve logging and ``ib_async.IB.errorEvent`` for these + notices, but bypass those superclass state mutations. The + broker's actual order-status callbacks remain untouched; + all other codes, including cancellation code 202, delegate + to the superclass. + + This workaround does not replace EMS request retention: + even a genuine cancellation can precede a late fill, which + still needs its original order to identify the client route. + + ''' + # IB delivers warnings and notices through `EWrapper.error`: + # https://ibkrcampus.com/docs/tws-api/doc/error/codes + if errorCode in { + # 2181: "The OptOutFromSmartRouting order attribute is + # not supported." Our `Client.submit_limit()` requests + # that attribute, but its unsupported status does not + # mean the order was rejected. The superclass would + # overwrite `ib_async.Trade.orderStatus.status` with + # `'ValidationError'` and emit synthetic status events. + 2181, + + # 10349: "Order TIF was set to DAY based on order + # preset." TIF is time-in-force; DAY limits the order + # to the trading day. This reports the preset applied + # when `Client.submit_limit()` leaves TIF unspecified, + # not a cancellation. The superclass misclassifies + # this notice as an error, changes an unfinished trade + # to `'Cancelled'`, and emits cancellation events before + # IB can report a fill. + # This exact code/text comes from our Gateway logs; + # 10349 is not listed in the IB code table linked above. + 10349, + }: + self._logger.warning( + f'IB order notice {errorCode}, reqId {reqId}: ' + f'{errorString}' + ) + contract: Contract|None = self._reqId2Contract.get(reqId) + self.ib.errorEvent.emit( + reqId, errorCode, errorString, contract, + ) + return + + return super().error( + reqId, errorCode, errorString, advancedOrderRejectJson, + ) + def tcpDataArrived(self): """Override time stamps to be floats for now. """ @@ -1913,11 +1985,11 @@ async def relay_client_proxy_messages( ) -> None: ''' - Route one proxy's asyncio-client msgs from a single reader. + Route one proxy's ``asyncio`` client msgs from a single reader. Each `open_client_proxy()` allocates its own linked channel and - starts this task in its relay nursery. Any number of Trio caller - tasks may concurrently write tagged requests through + starts this task in its relay nursery. Any number of ``trio`` + caller tasks may concurrently write tagged requests through `MethodProxy._run_method()` and wait on their per-`mid` slots. This task alone reads the channel and dispatches each response to its waiting caller. diff --git a/piker/brokers/ib/broker.py b/piker/brokers/ib/broker.py index 54a754f1..8dfc3ef6 100644 --- a/piker/brokers/ib/broker.py +++ b/piker/brokers/ib/broker.py @@ -20,6 +20,7 @@ Order and trades endpoints for use with ``piker``'s EMS. """ from __future__ import annotations from contextlib import ExitStack +from copy import copy # from collections import ChainMap from functools import partial from pprint import pformat @@ -334,7 +335,13 @@ async def recv_trade_updates( match event_name: case 'orderStatusEvent': - emit: Trade = obj + # `ib_async` mutates this `ib_async.Trade` after + # the callback. + # Queue the state observed here, not a later status. + emit: Trade = copy(obj) + emit.order = copy(obj.order) + emit.orderStatus = copy(obj.orderStatus) + emit.fills = list(obj.fills) case 'commissionReportEvent': assert report @@ -1405,7 +1412,30 @@ async def deliver_trade_events( # "Warning:" msg codes, # https://interactivebrokers.github.io/tws-api/message_codes.html#warning_codes # - 2109: 'Outside Regular Trading Hours' - if 'Warning:' in reason: + # IB's error callback also carries notices: + # https://ibkrcampus.com/docs/tws-api/doc/error/codes + if ( + code in { + # 2181: OptOutFromSmartRouting is not + # supported. This warns about the routing + # attribute, not rejection of the order. + # See IB's code table linked above. + 2181, + + # 10349: TIF was set to DAY by the order + # preset (time-in-force: trading day only). + # Observed in Gateway logs, but not listed + # in the linked code table. The order can + # still fill; this is not a terminal error. + # `NonShittyWrapper.error()` bypasses the + # `ib_async.wrapper.Wrapper.error()` path + # which misclassifies this preset notice + # and emits synthetic cancellation events. + 10349, + } + or + 'Warning:' in reason + ): log.warning( f'Order-API-warning: {code!r}\n' f'reqid: {reqid!r}\n' diff --git a/piker/clearing/_ems.py b/piker/clearing/_ems.py index 4280dee0..03ab17ee 100644 --- a/piker/clearing/_ems.py +++ b/piker/clearing/_ems.py @@ -149,6 +149,14 @@ class DarkBook(Struct): lasts: dict[str, float] = {} # quote prices _active: dict[str, Status] = {} # active order dialogs + # `DarkBook._closed` retains `'canceled'`/`'closed'` dialogs + # for as long as `DarkBook._ems2brokerd_ids` retains their IDs. + # `Status.req` keeps the original `Order`: `Order.symbol` selects + # the FQME for `Router.client_broadcast()` on late fills/errors, + # while `Order.account` supplies the account for subsequent + # commands if the broker reopens the dialog. An ID mapping alone + # cannot recover these request fields from a symbol-less fill. + _closed: dict[str, Status] = {} _ems2brokerd_ids: dict[str, str] = bidict() @@ -983,11 +991,13 @@ async def translate_and_relay_brokerd_events( msg = BrokerdError(**brokerd_msg) - # NOTE: retreive the last client-side response - # OR create an error when we have no last msg /dialog - # on record - status_msg: Status - if not (status_msg := book._active.get(oid)): + # Retrieve the last response from `DarkBook._active` + # or `DarkBook._closed`. Only unknown dialogs need + # an `Error` without an original `Order`. + status_msg = book._active.get(oid) + if status_msg is None: + status_msg = book._closed.get(oid) + if status_msg is None: status_msg = Error( time_ns=time_ns(), oid=oid, @@ -995,12 +1005,15 @@ async def translate_and_relay_brokerd_events( brokerd_msg=msg, ) else: - # only modify last status if we have an active - # ongoing dialog.. + # Preserve `Status.req` on active and canceled/ + # closed dialogs when attaching the broker + # error. Its `Order.symbol` still selects the + # client route for this and later fill updates. status_msg.resp = 'error' status_msg.brokerd_msg = msg - book._active[oid] = status_msg + if oid not in book._closed: + book._active[oid] = status_msg log.error( 'Translating brokerd error to status:\n' @@ -1036,6 +1049,7 @@ async def translate_and_relay_brokerd_events( 'canceled', 'open', 'closed', + 'pending', ) ): msg = BrokerdStatus(**brokerd_msg) @@ -1044,6 +1058,8 @@ async def translate_and_relay_brokerd_events( # contains both the IPC stream as well the # msg-chain/dialog. status_msg = book._active.get(oid) + if status_msg is None: + status_msg = book._closed.get(oid) if not status_msg: log.warning( f'Received status for untracked dialog {oid}:\n' @@ -1067,6 +1083,10 @@ async def translate_and_relay_brokerd_events( status_msg.brokerd_msg = msg status_msg.src = msg.broker_details['name'] + if status in {'open', 'pending'}: + book._closed.pop(oid, None) + book._active[oid] = status_msg + if not status_msg.req: # likely some order change state? await tractor.pause() @@ -1082,6 +1102,8 @@ async def translate_and_relay_brokerd_events( f'oid: {oid!r}\n' ) status_msg = book._active.pop(oid, None) + if status_msg is not None: + book._closed[oid] = status_msg if status_msg is None: log.warning( f'Order was already cleared from book ??\n' @@ -1093,11 +1115,13 @@ async def translate_and_relay_brokerd_events( elif status == 'canceled': log.cancel(f'Cancellation for {oid} is complete!') status_msg = book._active.pop(oid, None) + if status_msg is not None: + book._closed[oid] = status_msg - else: # open + else: # open or pending # relayed from backend but probably not handled so # just log it - log.info(f'{broker!r} opened order {msg}') + log.info(f'{broker!r} order {status}: {msg}') # BrokerdFill case { @@ -1118,11 +1142,20 @@ async def translate_and_relay_brokerd_events( msg = BrokerdFill(**brokerd_msg) log.info(f'Fill for {oid} cleared with:\n{fmsg}') - # XXX: bleh, a fill can come after 'closed' from `ib`? - # only send a late fill event we haven't already closed - # out the dialog status locally. + # A fill can follow `'canceled'`/`'closed'` or its + # error callback. + # `DarkBook._closed` retains the original request + # without advertising that dialog as active again. status_msg = book._active.get(oid) + if status_msg is None: + status_msg = book._closed.get(oid) if status_msg: + if status_msg.req is None: + log.error( + f'Cannot route fill without an order ' + f'request for {oid}:\n{fmsg}' + ) + continue status_msg.resp = 'fill' status_msg.reqid = reqid status_msg.brokerd_msg = msg diff --git a/tests/test_ems_trade_events.py b/tests/test_ems_trade_events.py new file mode 100644 index 00000000..74a1cc41 --- /dev/null +++ b/tests/test_ems_trade_events.py @@ -0,0 +1,154 @@ +''' +Offline broker-event routing through the EMS order lifecycle. + +''' +from copy import copy +from decimal import Decimal +from types import SimpleNamespace + +import pytest +import trio + +from piker.clearing._ems import ( + DarkBook, + translate_and_relay_brokerd_events, +) +from piker.clearing._messages import Order, Status + + +@pytest.mark.parametrize('closing_status', ['canceled', 'closed']) +@pytest.mark.parametrize('late_error', [False, True]) +@pytest.mark.parametrize('reopen', [None, 'pending', 'open']) +def test_closed_order_retains_fill_routing( + closing_status: str, + late_error: bool, + reopen: str|None, +) -> None: + ''' + Route late fills using the original ``Order`` after closure. + + A ``'canceled'`` status removed ``DarkBook._active``'s request, + then a broker error recreated ``Error(req=None)``. A subsequent + fill raised ``AttributeError``; without the error, that fill was + silently lost. Replay ``'canceled'`` and ``'closed'`` with and + without the intervening error and a pending/open broker update. + + - Drive the actual EMS event loop with a finite ``trio`` memory + stream, capturing broadcasts before each ``Status`` changes. + - Assert the FQME route, original ``Order`` identity, and fill + payload: a symbol-less fill needs ``Order.symbol`` to reach + the client subscribed to that market endpoint. + - Keep canceled/closed dialogs out of ``DarkBook._active`` unless + a subsequent pending/open status reopens them. + - Send a second order's fill to prove processing continues. + + ''' + async def main() -> None: + book = DarkBook(broker='ib') + req = Order( + action='buy', + exec_mode='live', + oid='order-233', + symbol='qqq.nasdaq.ib', + account='ib.algopaper', + price=Decimal('687.98'), + size=1.0, + brokers=['ib'], + ) + next_req = copy(req) + next_req.oid = 'next-order' + for order in (req, next_req): + book._active[order.oid] = Status( + time_ns=1, + oid=order.oid, + resp='pending', + req=order, + ) + + events: list[dict] = [ + {'name': 'ack', 'oid': req.oid, 'reqid': '233'}, + { + 'name': 'ack', + 'oid': next_req.oid, + 'reqid': '234', + }, + { + 'name': 'status', + 'reqid': '233', + 'time_ns': 2, + 'status': closing_status, + 'broker_details': {'name': 'ib'}, + }, + ] + if late_error: + events.append({ + 'name': 'error', + 'oid': None, + 'reqid': '233', + 'reason': 'Order TIF was set to DAY', + 'broker_details': {'name': 'ib', 'flow': {}}, + }) + if reopen is not None: + events.append({ + 'name': 'status', + 'reqid': '233', + 'time_ns': 3, + 'status': reopen, + 'broker_details': {'name': 'ib'}, + }) + for reqid in ('233', '234'): + events.append({ + 'name': 'fill', + 'time_ns': 4, + 'broker_time': 1793402932.0, + 'reqid': reqid, + 'size': 1.0, + 'price': 687.78, + 'action': 'buy', + 'broker_details': {}, + }) + + sent: list[tuple[str, str, Order, object]] = [] + + async def capture(fqme: str, status: Status) -> None: + if status.resp == 'error': + assert req.oid not in book._active + sent.append(( + fqme, status.resp, status.req, status.brokerd_msg, + )) + + tx, rx = trio.open_memory_channel(len(events)) + router = SimpleNamespace( + get_dark_book=lambda _: book, + relays={'ib': SimpleNamespace(brokerd_stream=rx)}, + client_broadcast=capture, + ) + async with tx, rx: + for event in events: + tx.send_nowait(event) + await tx.aclose() + await translate_and_relay_brokerd_events( + 'ib', rx, router, + ) + + expected: list[str] = [closing_status] + if late_error: + expected.append('error') + if reopen is not None: + expected.append(reopen) + expected.extend(['fill', 'fill']) + assert [resp for _, resp, _, _ in sent] == expected + assert all(fqme == req.symbol for fqme, _, _, _ in sent) + assert all(order is req for _, _, order, _ in sent[:-1]) + assert sent[-1][2] is next_req + assert sent[-2][3].reqid == '233' + assert sent[-2][3].price == 687.78 + assert sent[-2][3].size == 1.0 + if reopen is None: + assert req.oid not in book._active + assert book._closed[req.oid].req is req + else: + assert req.oid not in book._closed + assert book._active[req.oid].req is req + + trio.run(main) diff --git a/tests/test_ib_trade_events.py b/tests/test_ib_trade_events.py index 963a7fd1..60019d21 100644 --- a/tests/test_ib_trade_events.py +++ b/tests/test_ib_trade_events.py @@ -13,12 +13,17 @@ from ib_async import ( Execution, Fill, Position, + Order, + OrderStatus, + Trade, ) import pytest import trio from piker.brokers.ib import broker +from piker.brokers.ib.api import NonShittyIB from piker.brokers.ib.ledger import api_trades_to_ledger_entries +from piker.clearing import OrderDialogs def make_fill(tid: str) -> Fill: @@ -34,12 +39,176 @@ def make_fill(tid: str) -> Fill: ) +@pytest.mark.parametrize('code', [2181, 10349, 202]) +def test_order_notice_does_not_synthesize_cancellation( + code: int, +) -> None: + ''' + Preserve live orders on informational IB messages. + + ``ib_async.wrapper.Wrapper.error()`` turned warning 2181 into + ``'ValidationError'`` and TIF adjustment 10349 into + ``'Cancelled'`` even though IB filled the order. + + - Feed both codes through ``NonShittyWrapper.error()`` and assert + the error callback remains without status/cancel events. + - Use code 202 as the control: real cancellation must still emit + ``'Cancelled'`` and the error callback through the superclass. + + ''' + async def main() -> None: + ib = NonShittyIB() + wrapper = ib.wrapper + wrapper.clientId = 6116 + trade = Trade( + order=Order(orderId=233, clientId=6116), + orderStatus=OrderStatus(status='PendingSubmit'), + ) + wrapper.trades[(6116, 233)] = trade + statuses: list[str] = [] + canceled: list[Trade] = [] + errors: list[tuple] = [] + ib.orderStatusEvent.connect( + lambda item: statuses.append(item.orderStatus.status), + ) + trade.cancelledEvent.connect(canceled.append) + ib.errorEvent.connect(lambda *args: errors.append(args)) + wrapper.error(233, code, 'order notice', '') + assert errors == [(233, code, 'order notice', None)] + if code == 202: + assert trade.orderStatus.status == 'Cancelled' + assert statuses == ['Cancelled'] + assert canceled == [trade] + else: + assert trade.orderStatus.status == 'PendingSubmit' + assert statuses == [] + assert canceled == [] + assert trade.log == [] + + asyncio.run(main()) + + +def test_queued_order_status_is_callback_snapshot() -> None: + ''' + Preserve callback-time status for a reused ``ib_async.Trade``. + + ``ib_async`` mutates ``Trade.orderStatus`` after emitting an + event. The ``trio`` receiver previously observed whichever status + was current when it drained the queue, losing ``'Cancelled'`` + to ``'PreSubmitted'`` or turning earlier callbacks into + ``'Filled'``. + + Emit all callbacks without yielding, then mutate the order and + fills. Check each queued status, price and fill-list snapshot + through the actual ``eventkit`` subscription callbacks. + + ''' + async def main() -> None: + ib = SimpleNamespace(**{ + name: Event(name) + for name in ( + 'orderStatusEvent', 'commissionReportEvent', + 'execDetailsEvent', 'positionEvent', + 'disconnectedEvent', + ) + }) + emitted: list[tuple] = [] + chan = SimpleNamespace( + started_nowait=lambda _: None, + send_nowait=emitted.append, + ) + client = SimpleNamespace(ib=ib, inline_errors=lambda _: None) + trade = Trade(order=Order(lmtPrice=687.98)) + + async def produce() -> None: + await asyncio.sleep(0) + for status in ('Cancelled', 'PreSubmitted', 'Filled'): + trade.orderStatus.status = status + if status == 'Filled': + trade.fills.append(make_fill('execution-233')) + ib.orderStatusEvent.emit(trade) + trade.orderStatus.status = 'Submitted' + trade.order.lmtPrice = 1.0 + trade.fills.clear() + ib.disconnectedEvent.emit() + + producer = asyncio.create_task(produce()) + with pytest.raises(ConnectionError, match='socket'): + await broker.recv_trade_updates(chan, client) + await producer + snapshots = [item for name, item in emitted] + assert [item.orderStatus.status for item in snapshots] == [ + 'Cancelled', 'PreSubmitted', 'Filled', + ] + assert all( + item.order.lmtPrice == 687.98 for item in snapshots + ) + assert [len(item.fills) for item in snapshots] == [0, 0, 1] + assert snapshots[-1].fills[0].execution.execId == ( + 'execution-233' + ) + + asyncio.run(main()) + + +def test_order_notices_do_not_become_ems_errors() -> None: + ''' + Keep informational callbacks out of EMS error-state handling. + + Preserving ``ib_async.Trade`` state in the wrapper is not enough + if ``broker.deliver_trade_events()`` still turns code 10349 into + ``BrokerdError``. Replay both known notices and cancellation + code 202 through that relay. Only 202 must reach EMS, with its + original request ID and reason; informational notices must not + enter ``OrderDialogs._flows`` as order errors. + + ''' + async def main() -> None: + flows = OrderDialogs() + sent: list = [] + + async def capture(msg: object) -> None: + sent.append(msg) + + events: list[tuple] = [ + ('error', { + 'reqid': 233, + 'error_code': code, + 'reason': reason, + }) + for code, reason in ( + (2181, 'Unsupported routing attribute'), + (10349, 'Order TIF was set to DAY'), + (202, 'Order Canceled - reason:'), + ) + ] + tx, rx = trio.open_memory_channel(len(events)) + async with tx, rx: + for event in events: + tx.send_nowait(event) + await tx.aclose() + await broker.deliver_trade_events( + rx, SimpleNamespace(send=capture), + {}, {}, {}, {}, flows, + ) + assert len(sent) == 1 + assert sent[0].name == 'error' + assert sent[0].reqid == '233' + assert sent[0].reason == 'Order Canceled - reason:' + assert len(flows.get('233').maps) == 1 + + trio.run(main) + + def test_execution_id_survives_empty_commission() -> None: ''' - Flattening a default CommissionReport erased Execution.execId, - causing a real fill to be skipped as an ID-less adjustment. Pass - a fill with a valid execution and empty commission through ledger - conversion and assert that its account and execution survive. + Preserve execution identity when flattening IB commission data. + + Flattening a default ``ib_async.CommissionReport`` erased + ``ib_async.Execution.execId``, causing a real fill to be skipped + as an ID-less adjustment. Pass a fill with a valid execution and + empty commission through ledger conversion, then assert that + its account and execution survive. ''' entries = api_trades_to_ledger_entries( @@ -53,13 +222,18 @@ def test_execution_id_survives_empty_commission() -> None: def test_callback_preserves_fill_and_disconnect() -> None: ''' - The asyncio callback dropped commissionReportEvent's exact Fill, - forcing the Trio side to guess by contract. Exercise the actual - eventkit relay and assert it preserves the supplied object. After - that callback, emit disconnectedEvent: the bridge must raise - rather than return normally and leave its Trio owner asleep. - One asyncio checkpoint lets recv_trade_updates install handlers - before the test producer emits either event. + Preserve the exact fill and report broker disconnection. + + The ``asyncio`` callback dropped the ``ib_async.Fill`` supplied + by ``ib_async.IB.commissionReportEvent``, forcing the ``trio`` + task to guess by contract. + + - Exercise the actual ``eventkit`` relay and assert it preserves + the supplied object. + - Emit ``ib_async.IB.disconnectedEvent`` afterward: the channel + must raise rather than leave its ``trio``-side parent asleep. + - Yield one ``asyncio`` checkpoint so ``recv_trade_updates()`` + installs handlers before the producer emits either event. ''' async def main(): @@ -100,7 +274,9 @@ def test_overlapping_execution_commissions( position_first: bool, ) -> None: ''' - Two executions on one contract shared a single pending Fill. + Account each ``ib_async.Fill`` with its own commission. + + Two executions on one contract shared a single pending fill. A commission for execution A could therefore account execution B. Queue both executions before either commission, delivering fees in reverse order, and exercise positions before and after fees.