# piker: trading gear for hackers # Copyright (C) Tyler Goodlet (in stewardship for pikers) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . ''' Replay a paper Gateway restart against the IB backend entry points. ''' import asyncio from collections.abc import ( AsyncIterator, ) from contextlib import ( asynccontextmanager, ) from pathlib import Path from ib_async import ( Contract, ContractDetails, IB, Order, OrderStatus, Stock, Ticker, Trade, ) import pytest import tractor import trio from piker import config from piker.accounting import MktPair from piker.brokers.ib import ( api, broker, feed, ) from piker.clearing._messages import BrokerdStatus from piker.data import _symcache class PaperPeer(IB): ''' Supply one session's ticker and its real IB callback objects. ''' ticker: Ticker | None = None def reqMktData( self, contract: Contract, options: str, ) -> Ticker: self.ticker = Ticker(contract=contract) return self.ticker def cancelMktData(self, contract: Contract) -> None: self.ticker = None async def exercise_gateway_restart( confdir: str, restart: bool, ) -> None: ''' Start the quote producer, paper dialog and one pending lookup. - Acknowledge delivery on both original consumers before EOF. - Replace the peer and publish distinct data on its callbacks. - Require a bounded lookup error and both post-restart records. ''' contract = Stock('QQQ', 'SMART', 'USD', primaryExchange='NASDAQ') peer = PaperPeer() client = api.Client(ib=peer, config={}) lookup_started = trio.Event() lookup_failed = trio.Event() quotes_tx, quotes_rx = trio.open_memory_channel[dict](16) statuses: list[str] = [] mkt = MktPair.from_fqme( 'qqq.nasdaq.ib', price_tick='0.01', size_tick='1', bs_mktid='1', _atype='stock', ) @asynccontextmanager async def clients( disconnect_on_exit: bool, ) -> AsyncIterator[dict[str, api.Client]]: yield {'ib.paper': client} async def market( symbol: str, proxy: api.MethodProxy, ) -> tuple[MktPair, ContractDetails]: return mkt, ContractDetails(contract=contract) async def snapshot( contract: Contract, raise_on_timeout: bool, ) -> Ticker: return Ticker(contract=contract, bid=99.0) async def pending(fqme: str) -> list[Contract]: assert fqme == 'qqq.nasdaq' lookup_started.set() await asyncio.Future() async def lookup() -> None: async with feed.open_data_client() as proxy: try: await proxy.get_sym_details(fqme='qqq.nasdaq') except ConnectionError: lookup_failed.set() class PaperDialog: ''' Capture EMS status messages and supply an idle order stream. ''' async def started(self, startup: tuple) -> None: assert startup == ([], ('ib.paper',)) @asynccontextmanager async def open_stream(self) -> AsyncIterator['PaperDialog']: yield self def __aiter__(self) -> 'PaperDialog': return self async def __anext__(self) -> dict: await trio.sleep_forever() async def send(self, status: BrokerdStatus) -> None: statuses.append(status.reqid) async def publish_until_received(generation: int) -> None: trade = Trade( order=Order(orderId=generation, account='PAPER'), orderStatus=OrderStatus(status='Submitted'), ) seen_quote: bool = False while ( not seen_quote or str(generation) not in statuses ): if peer.ticker is not None: peer.ticker.bid = float(generation) peer.ticker.updateEvent.emit(peer.ticker) if str(generation) not in statuses: peer.orderStatusEvent.emit(trade) await trio.sleep(0.01) while quotes_rx.statistics().current_buffer_used: msg = quotes_rx.receive_nowait() seen_quote |= msg['qqq.nasdaq']['bid'] == generation with pytest.MonkeyPatch.context() as patch: patch.setattr(config, '_config_dir', Path(confdir)) patch.setattr(api, 'load_aio_clients', clients) patch.setattr(feed, 'load_aio_clients', clients) patch.setattr(feed, 'get_mkt_info', market) patch.setattr(feed, 'is_venue_open', lambda **kw: True) patch.setattr( api.Client, 'get_quote', staticmethod(snapshot), ) patch.setattr( api.Client, 'find_contracts', staticmethod(pending), ) async with broker.open_symcache( 'ib', _no_symcache=True, ) as sc: patch.setitem(_symcache._caches, 'ib', sc) async with trio.open_nursery() as nursery: nursery.start_soon( broker.open_trade_dialog, PaperDialog(), ) await nursery.start( feed.stream_quotes, quotes_tx, ['qqq.nasdaq'], trio.Event(), ) nursery.start_soon(lookup) await lookup_started.wait() await publish_until_received(1) if restart: old_peer = peer peer = PaperPeer() client = api.Client(ib=peer, config={}) old_peer.client.apiError.emit( 'Peer closed connection.', ) old_peer.disconnectedEvent.emit() await publish_until_received(2) if restart: await lookup_failed.wait() nursery.cancel_scope.cancel() @pytest.mark.parametrize( 'restart', [False, True], ids=['continuous-session', 'gateway-restart'], ) def test_gateway_restart_preserves_consumers( reg_addr: tuple[str, int | str], tmp_path: Path, restart: bool, ) -> None: ''' Keep both consumers on one infected actor across a socket loss. The replacement paper peer accepts fresh subscriptions. A dead consumer raises at disconnect or misses the second generation. ''' (tmp_path / 'brokers.toml').write_text( '[ib]\nprefer_data_account = ["paper"]\n' '[ib.accounts]\npaper = "PAPER"\n' ) async def main() -> None: # Bound bootstrap, both delivery barriers and actor teardown. scenario_timeout_s: float = 15 with trio.fail_after(scenario_timeout_s): async with ( tractor.open_root_actor(registry_addrs=[reg_addr]), tractor.open_nursery() as nursery, ): actor = await nursery.start_actor( 'ib_restart_replay', enable_modules=[__name__], infect_asyncio=True, ) await actor.run( exercise_gateway_restart, confdir=str(tmp_path), restart=restart, ) await actor.cancel_actor() trio.run(main)