piker/tests/test_ib_trade_events.py

337 lines
11 KiB
Python
Raw Normal View History

'''
Execution identity across IB fill and commission callbacks.
'''
import asyncio
from types import SimpleNamespace
from bidict import bidict
from eventkit import Event
from ib_async import (
CommissionReport,
Contract,
Execution,
Fill,
Position,
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`))
2026-10-30 22:50:06 +00:00
Order,
OrderStatus,
Trade,
)
import pytest
import trio
from piker.brokers.ib import broker
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`))
2026-10-30 22:50:06 +00:00
from piker.brokers.ib.api import NonShittyIB
from piker.brokers.ib.ledger import api_trades_to_ledger_entries
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`))
2026-10-30 22:50:06 +00:00
from piker.clearing import OrderDialogs
def make_fill(tid: str) -> Fill:
return Fill(
Contract(conId=815824267, secType='FUT', symbol='MNQ'),
Execution(
execId=tid,
acctNumber='DU_TEST',
time=1789586554.0,
),
CommissionReport(),
1789586554.0,
)
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`))
2026-10-30 22:50:06 +00:00
@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:
'''
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`))
2026-10-30 22:50:06 +00:00
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(
bidict({'DU_TEST': 'ib.algopaper'}),
[make_fill('execution-1')],
)
assert entries['ib.algopaper']['execution-1']['execId'] == (
'execution-1'
)
def test_callback_preserves_fill_and_disconnect() -> None:
'''
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`))
2026-10-30 22:50:06 +00:00
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():
ib = SimpleNamespace(**{
name: Event(name)
for name in (
'orderStatusEvent', 'commissionReportEvent',
'execDetailsEvent', 'positionEvent',
'disconnectedEvent',
)
})
emitted = []
chan = SimpleNamespace(
started_nowait=lambda _: None,
send_nowait=emitted.append,
)
client = SimpleNamespace(ib=ib, inline_errors=lambda _: None)
fill = make_fill('A')
report = CommissionReport(execId='A', commission=.61)
async def produce():
await asyncio.sleep(0)
ib.commissionReportEvent.emit(None, fill, report)
ib.disconnectedEvent.emit()
producer = asyncio.create_task(produce())
with pytest.raises(ConnectionError, match='socket'):
await broker.recv_trade_updates(chan, client)
await producer
assert emitted == [('commissionReportEvent', (fill, report))]
asyncio.run(main())
@pytest.mark.parametrize('position_first', [True, False])
def test_overlapping_execution_commissions(
monkeypatch: pytest.MonkeyPatch,
position_first: bool,
) -> None:
'''
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`))
2026-10-30 22:50:06 +00:00
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.
The deterministic channel order verifies every execution reaches
accounting once with its own fee, including a zero commission.
'''
fills = [make_fill('A'), make_fill('B')]
pos = Position('DU_TEST', fills[0].contract, 2, 58000)
recorded = []
async def capture(*args, ibpos, fill=None):
if fill is not None:
recorded.append((
fill.execution.execId,
fill.commissionReport.execId,
fill.commissionReport.commission,
ibpos.account,
))
monkeypatch.setattr(broker, 'emit_pp_update', capture)
monkeypatch.setattr(
broker, 'pack_position', lambda *args: ('815824267', {})
)
async def main():
send, recv = trio.open_memory_channel(10)
events = [
('execDetailsEvent', (
SimpleNamespace(contract=fill.contract), fill,
))
for fill in fills
]
events.extend([
('commissionReportEvent', (
fills[1], CommissionReport(execId='B', commission=0),
)),
('commissionReportEvent', (
fills[0], CommissionReport(execId='A', commission=.61),
)),
])
events.insert(0 if position_first else len(events), (
'positionEvent', pos,
))
async with send, recv:
for event in events:
send.send_nowait(event)
await send.aclose()
await broker.deliver_trade_events(
recv, None, {}, {}, {}, {}, None,
)
trio.run(main)
assert recorded == [
('B', 'B', 0, 'DU_TEST'),
('A', 'A', .61, 'DU_TEST'),
]