m/market labResearch, with a record.
Source on GitHub ↗

test_prepared_market.py

1"""Independent price/sequence expectations and real native/UOW probes."""23from support.financial import assemble_probe4from support.book import PreparedBookFixture, fixture56from dataclasses import asdict, replace7from pathlib import Path8from threading import Event, Thread9import struct10import sys11import unittest12from unittest.mock import patch1314ROOT = Path(__file__).resolve().parents[2]15sys.path.insert(0, str(ROOT / 'tests'))16from itch_fixtures import directory, add, reduce, common, frame17from sim_platform import Platform, Intent, ContractError18from sim_platform.market.session import MarketSession19from sim_platform.market.models import FutureDataError, DataUnavailable20from sim_platform.market.prepared.builder import build, PreparationCancelled21from sim_platform.market.prepared.reader import PreparedMarket, VisibleMarket22from sim_platform.market.prepared.job import PreparationJob23from sim_platform.experiments.execution.timeline.sequencer import Sequencer24from sim_platform.execution.models import ExecutionConfig252627class PreparedMarketTests(PreparedBookFixture, unittest.TestCase):2829    def test_asof_is_direct_version_lookup_with_equal_timestamp_prefix(self):30        reader = self.ready()31        with patch(32            'sim_platform.market.native.NativeEngine',33            side_effect=AssertionError('no reconstruction'),34        ):35            self.assertEqual(reader.snapshot_at(0).sequence, 0)36            self.assertEqual(reader.snapshot_at(3).asks, ((101, 2),))37            self.assertEqual(reader.snapshot_at(9).sequence, 3)38            self.assertEqual(reader.snapshot_at(10).sequence, 5)39            self.assertEqual(reader.snapshot_at(10).asks, ((101, 2), (102, 3), (103, 4)))40            self.assertEqual(reader.snapshot_at(29).asks, ((101, 2), (102, 3), (103, 4)))41            self.assertEqual(reader.snapshot_at(30).asks[0], (101, 12))42        self.assertEqual(reader.manifest['frames'], 7)4344    def test_visible_query_rejects_future_and_fixes_delivery_cutoff(self):45        reader = self.ready()46        now = [9]47        visible = VisibleMarket(reader, lambda: now[0])48        captured = visible.capture()49        now[0] = 3050        self.assertEqual(captured['prefix'], 3)51        self.assertEqual(captured['snapshot'].asks, ((101, 2),))52        self.assertEqual(visible.capture(10)['prefix'], 5)53        now[0] = 3254        with self.assertRaises(DataUnavailable):55            visible.capture(31)56        now[0] = 3057        with self.assertRaises(FutureDataError):58            visible.capture(31)5960    def test_each_event_matches_original_native_session(self):61        reader = self.ready()62        market = MarketSession('AAPL')63        self.addCleanup(market.close)64        market.load(self.source)65        market.play()66        for index in range(reader.manifest['frames']):67            self.assertEqual(asdict(reader.event(index)), asdict(market.pump(1)[0]))6869    def test_later_broken_trade_does_not_rewrite_earlier_event(self):70        trade = frame(71            common('P', timestamp=4)72            + struct.pack('>Q', 55)73            + b'B'74            + struct.pack('>I', 2)75            + b'AAPL    '76            + struct.pack('>I', 101)77            + struct.pack('>Q', 77)78        )79        self.source.write_bytes(80            directory('AAPL', timestamp=1)81            + add(1, 'S', 4, 101, 'AAPL', timestamp=2)82            + trade83            + frame(common('B', timestamp=8) + struct.pack('>Q', 77))84            + b'\0\0'85        )86        reader = self.ready()87        self.assertEqual(reader.event(2).trade.match_id, 77)88        self.assertIsNone(reader.event(2).broken_match_id)89        self.assertEqual(reader.event(3).broken_match_id, 77)90        self.assertEqual(reader.snapshot_at(7).sequence, 3)9192    def test_invalid_source_cancel_and_existing_destination_never_publish(self):93        self.source.write_bytes(self.source.read_bytes()[:-1])94        with self.assertRaises(ContractError):95            build(self.source, self.destination)96        self.assertFalse(self.destination.exists())97        fixture(self.source)98        with self.assertRaises(PreparationCancelled):99            build(self.source, self.destination, cancelled=lambda: True)100        self.assertFalse(self.destination.exists())101        self.ready()102        original = (self.destination / 'manifest.json').read_bytes()103        with self.assertRaises(ContractError):104            build(self.source, self.destination)105        self.assertEqual((self.destination / 'manifest.json').read_bytes(), original)106        self.assertEqual(list(self.root.glob('.prepared-*')), [])107108    def test_corrupt_length_and_nonmonotone_index_are_rejected(self):109        reader = self.ready()110        reader.close()111        path = self.destination / 'events.bin'112        data = path.read_bytes()113        path.write_bytes(data[:-1])114        with self.assertRaises(ContractError):115            PreparedMarket(self.destination)116        path.write_bytes(data[:0] + (99).to_bytes(8, 'big') + data[8:])117        with self.assertRaises(ContractError):118            PreparedMarket(self.destination)119120    def test_wrong_symbol_and_backwards_time_reject_before_ready(self):121        with self.assertRaises(ContractError):122            build(self.source, self.destination, symbol='ZZZZ')123        self.assertFalse(self.destination.exists())124        self.source.write_bytes(125            directory('AAPL', timestamp=10) + add(1, 'S', 1, 101, 'AAPL', timestamp=9) + b'\0\0'126        )127        with self.assertRaises(ContractError):128            build(self.source, self.destination)129        self.assertFalse(self.destination.exists())130131    def test_cancel_spawn_cleans_only_owned_staging(self):132        source = self.root / 'large.bin'133        with source.open('wb') as stream:134            stream.write(directory('AAPL', timestamp=1))135            for index in range(10000):136                stream.write(add(index + 1, 'S', 1, 101, 'AAPL', timestamp=index + 2))137            stream.write(b'\0\0')138        job = PreparationJob(source, self.destination)139        self.addCleanup(job.close)140        job.cancel()141        with self.assertRaises(ContractError):142            job.result(10)143        job.close()144        self.assertFalse(self.destination.exists())145        self.assertEqual(list(self.root.glob('.preparation-job-*')), [])146147    def test_spawn_preparation_returns_ready_artifact_and_reaps(self):148        job = PreparationJob(self.source, self.destination)149        self.addCleanup(job.close)150        self.assertEqual(job.result(10), self.destination.resolve())151        job.close()152        self.assertFalse(job.snapshot()['alive'])153        self.assertEqual(job.snapshot()['frames'], 7)154155156class PreparedImportTests(unittest.TestCase):157    setUp = PreparedBookFixture.setUp158    ready = PreparedBookFixture.ready159160    def test_foreign_events_are_scanned_but_not_stored_and_raw_sequence_survives(self):161        self.source.write_bytes(162            directory('MSFT', locate=8, timestamp=1)163            + directory('AAPL', timestamp=2)164            + directory('MSFT', locate=8, timestamp=3)165            + add(1, 'S', 4, 101, 'AAPL', timestamp=4)166            + directory('MSFT', locate=8, timestamp=4)167            + reduce('X', 1, 1, timestamp=4)168            + directory('MSFT', locate=8, timestamp=9)169            + b'\0\0'170        )171        reader = self.ready()172        self.assertEqual(reader.manifest['source_frames'], 7)173        self.assertEqual(reader.manifest['frames'], 3)174        self.assertEqual(reader.manifest['last_ns'], 9)175        self.assertEqual(reader.prefix(4), 3)176        self.assertEqual([reader.source_sequence(i) for i in range(4)], [0, 2, 4, 6])177        self.assertEqual(reader.snapshot_at(8).sequence, 3)178        self.assertEqual(reader.snapshot_at(8).asks, ((101, 3),))179        captured = VisibleMarket(reader, lambda: 9).capture()180        self.assertEqual(captured['source_time_ns'], 4)181        self.assertEqual(captured['source_sequence'], 6)182        self.assertEqual(captured['target_ns'], 9)183        market = MarketSession('AAPL')184        self.addCleanup(market.close)185        market.load(self.source)186        market.play()187        index = 0188        while market.status == 'playing':189            event = market.pump(1)[0]190            if event.kind != 'market':191                continue192            actual = reader.event(index)193            expected = replace(194                event, sequence=index + 1, snapshot=replace(event.snapshot, sequence=index + 1)195            )196            self.assertEqual(asdict(actual), asdict(expected))197            index += 1198        self.assertEqual(index, 3)199200    def test_skipped_messages_still_reject_bad_lengths_and_backwards_time(self):201        for bad in (202            frame(common('R', locate=8, timestamp=4)),203            directory('MSFT', locate=8, timestamp=1),204        ):205            self.source.write_bytes(directory('AAPL', timestamp=2) + bad + b'\0\0')206            with self.assertRaises(ContractError):207                build(self.source, self.destination)208            self.assertFalse(self.destination.exists())209210    def test_implicit_eof_system_halt_and_trade_metadata_keep_shared_semantics(self):211        trade = frame(212            common('P', timestamp=5)213            + struct.pack('>Q', 55)214            + b'B'215            + struct.pack('>I', 2)216            + b'AAPL    '217            + struct.pack('>I', 101)218            + struct.pack('>Q', 77)219        )220        self.source.write_bytes(221            directory('AAPL', timestamp=1)222            + add(1, 'S', 4, 101, 'AAPL', timestamp=2)223            + frame(common('H', timestamp=3) + b'AAPL    ' + b'H' + b' ' + b'    ')224            + trade225            + frame(common('S', locate=0, timestamp=8) + b'C')226        )227        build(self.source, self.destination, allow_implicit_eof=True)228        with PreparedMarket(self.destination, verify=True) as reader:229            self.assertEqual(reader.event(2).snapshot.trading_state, 'H')230            self.assertEqual(reader.event(3).trade.match_id, 77)231            self.assertEqual(reader.event(4).snapshot.system_event, 'C')232            self.assertEqual(reader.manifest['source_frames'], 5)233        with self.assertRaises(ContractError):234            build(self.source, self.root / 'strict')235236    def test_normal_open_does_not_rescan_but_explicit_validation_checks_middle(self):237        reader = self.ready()238        reader.close()239        with patch.object(PreparedMarket, 'validate', side_effect=AssertionError('no scan')):240            with PreparedMarket(self.destination) as reopened:241                self.assertEqual(reopened.snapshot_at(10).sequence, 5)242        import json243244        event_path = self.destination / 'events.bin'245        data = bytearray(event_path.read_bytes())246        from sim_platform.market.prepared.codec import EVENT247248        data[3 * EVENT.size : 3 * EVENT.size + 8] = (1).to_bytes(8, 'big')249        event_path.write_bytes(data)250        # Metadata changes are rejected even before full validation.251        with self.assertRaises(ContractError):252            PreparedMarket(self.destination)253        manifest_path = self.destination / 'manifest.json'254        manifest = json.loads(manifest_path.read_text())255        stat = event_path.stat()256        manifest['files']['events.bin'] = dict(bytes=stat.st_size, mtime_ns=stat.st_mtime_ns)257        manifest_path.write_text(json.dumps(manifest))258        with self.assertRaises(ContractError):259            PreparedMarket(self.destination, verify=True)260261    def test_old_format_requires_rebuild_and_never_silently_reinterprets_sequence(self):262        reader = self.ready()263        reader.close()264        import json265266        path = self.destination / 'manifest.json'267        value = json.loads(path.read_text())268        value['version'] = 'prepared-market/v1'269        path.write_text(json.dumps(value))270        with self.assertRaises(ContractError):271            PreparedMarket(self.destination)272273    def test_cancel_after_native_batch_and_source_mutation_do_not_publish(self):274        with self.source.open('wb') as stream:275            stream.write(directory('AAPL', timestamp=1))276            for index in range(20000):277                stream.write(directory('MSFT', locate=8, timestamp=index + 2))278            stream.write(b'\0\0')279        progress = []280        with self.assertRaises(PreparationCancelled):281            build(282                self.source,283                self.destination,284                progress=progress.append,285                cancelled=lambda: bool(progress),286            )287        self.assertEqual(progress, [8192])288        self.assertFalse(self.destination.exists())289        fixture(self.source)290291        def mutate(_):292            with self.source.open('ab') as stream:293                stream.write(b'x')294295        with self.assertRaises(ContractError):296            build(self.source, self.destination, progress=mutate)297        self.assertFalse(self.destination.exists())298        self.assertEqual(list(self.root.glob('.prepared-*')), [])299300    def test_optional_native_stage_timings_and_output_failure_are_explicit(self):301        timings = {}302        build(self.source, self.destination, timings=timings, profile_native=True)303        self.assertGreater(timings['native_read_ns'], 0)304        self.assertGreater(timings['native_apply_ns'], 0)305        self.assertGreater(timings['native_encode_write_ns'], 0)306        from sim_platform.market.prepared.native import NativePreparation307308        with self.assertRaises(ContractError):309            NativePreparation(self.source, self.root / 'missing', 'AAPL', 5, None, False, False)310311312class SparsePreparedFinanceTests(unittest.TestCase):313    setUp = PreparedBookFixture.setUp314315    def test_sparse_timeline_uses_original_finance_without_sequence_gaps_or_early_fills(self):316        self.source.write_bytes(317            directory('AAPL', timestamp=1)318            + add(1, 'S', 2, 101, 'AAPL', timestamp=2)319            + directory('MSFT', locate=8, timestamp=4)320            + directory('MSFT', locate=8, timestamp=10)321            + add(2, 'S', 10, 101, 'AAPL', timestamp=20)322            + directory('MSFT', locate=8, timestamp=30)323            + b'\0\0'324        )325        build(self.source, self.destination)326        with PreparedMarket(self.destination) as reader, Platform(self.root / 'accounts') as app:327            profile = app.create_profile('sparse')328            account = app.create_account(profile, 'cash', 10000)329            maker = app.create_maker(profile, 'human', 'human', 'v1')330            now = [4]331            probe = assemble_probe(332                app._operations,333                app._new_execution,334                profile,335                account,336                maker,337                reader,338                lambda: now[0],339                start_ns=2,340                end_ns=31,341                config=ExecutionConfig(latency_ns=10),342            )343            self.addCleanup(probe.close)344            probe.submit('buy', Intent('buy', 'AAPL', 'buy', 5, 101))345            now[0] = 15346            probe.turn()347            self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 0)348            now[0] = 21349            probe.turn()350            self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 5)351            self.assertEqual(probe.execution.snapshot.account.cash, 9495)352            self.assertEqual(probe.execution.snapshot.reserved_cash, 0)353            native_account = app.create_account(profile, 'native', 10000)354            run = app.create_execution_run(355                profile, native_account, maker, 'AAPL', config=ExecutionConfig(latency_ns=10)356            )357            market = app.open_market('AAPL')358            self.addCleanup(market.close)359            market.load(self.source)360            session = app.execution_session(profile, run, maker, market)361            self.addCleanup(session.close)362            for _ in range(3):363                session.step()364            session.submit(Intent('buy', 'AAPL', 'buy', 5, 101))365            for _ in range(3):366                session.step()367            self.assertEqual(session.snapshot.account.cash, probe.execution.snapshot.account.cash)368            self.assertEqual(session.snapshot.account.orders[0].filled, 5)369            session.close()370            probe.close()371372373class SequencerTests(unittest.TestCase):374    def test_equal_tick_admission_after_claim_is_not_backdated(self):375        now = [10]376        seq = Sequencer(lambda: now[0], start_ns=0, end_ns=100)377        batch = seq.claim()378        command = seq.admit('one', {'kind': 'test'})379        self.assertEqual(command.time_ns, batch.until_ns)380        self.assertNotIn(command, batch.commands)381        seq.release(batch)382        self.assertEqual(seq.claim().commands, ())383        seq.release(seq._batch)384        now[0] = 11385        self.assertEqual(seq.claim().commands, (command,))386387    def test_stamp_and_append_cannot_be_overtaken_by_execution_claim(self):388        entered, release, claimed = Event(), Event(), Event()389        calls = [0]390391        def clock():392            calls[0] += 1393            if calls[0] == 1:394                entered.set()395                if not release.wait(2):396                    raise RuntimeError('test release missing')397                return 10398            return 11399400        seq = Sequencer(clock, start_ns=0, end_ns=100)401        admitted, batches = [], []402        producer = Thread(target=lambda: admitted.append(seq.admit('one', {})))403        consumer = Thread(target=lambda: (batches.append(seq.claim()), claimed.set()))404        producer.start()405        self.assertTrue(entered.wait(1))406        consumer.start()407        self.assertFalse(claimed.wait(0.03))408        release.set()409        producer.join(2)410        consumer.join(2)411        self.assertFalse(producer.is_alive() or consumer.is_alive())412        self.assertEqual(batches[0].commands, tuple(admitted))413414    def test_multiple_producers_and_owner_never_cross_sealed_prefix(self):415        from time import monotonic_ns416417        origin = monotonic_ns()418        seq = Sequencer(419            lambda: monotonic_ns() - origin,420            start_ns=0,421            end_ns=10_000_000_000,422            capacity=2000,423            retained=2000,424        )425        errors = []426        processed = []427428        def produce(number):429            try:430                for index in range(300):431                    seq.admit(str(number) + '-' + str(index), {'n': number, 'i': index})432            except Exception as exc:433                errors.append(exc)434435        producers = [Thread(target=produce, args=(number,)) for number in range(4)]436        for thread in producers:437            thread.start()438        while any(thread.is_alive() for thread in producers) or seq.snapshot()['pending']:439            batch = seq.claim()440            for command in batch.commands:441                self.assertLess(command.time_ns, batch.until_ns)442                seq.begin(command)443                seq.complete(command, {'ok': True})444                processed.append(command)445            seq.release(batch)446        for thread in producers:447            thread.join(1)448        self.assertEqual(errors, [])449        self.assertEqual(len(processed), 1200)450        self.assertEqual([c.sequence for c in processed], list(range(1, 1201)))451        self.assertEqual([c.time_ns for c in processed], sorted(c.time_ns for c in processed))452453    def test_capacity_duplicate_conflict_and_end_pending(self):454        now = [10]455        seq = Sequencer(lambda: now[0], start_ns=0, end_ns=20, capacity=1)456        command = seq.admit('one', {'value': 1})457        self.assertEqual(seq.admit('one', {'value': 1}), command)458        with self.assertRaises(ContractError):459            seq.admit('one', {'value': 2})460        with self.assertRaises(ContractError):461            seq.admit('two', {})462        now[0] = 20463        self.assertIsNone(seq.claim())464        self.assertEqual(seq.result('one'), dict(status='cancelled', reason='end'))465466    def test_stop_cancels_unstarted_but_started_commit_may_complete(self):467        now = [10]468        seq = Sequencer(lambda: now[0], start_ns=0, end_ns=100)469        one = seq.admit('one', {})470        two = seq.admit('two', {})471        now[0] = 11472        batch = seq.claim()473        self.assertTrue(seq.begin(one))474        seq.stop()475        seq.complete(one, {'status': 'accepted'})476        self.assertFalse(seq.begin(two))477        self.assertEqual(seq.result('one')['status'], 'accepted')478        self.assertEqual(seq.result('two')['status'], 'cancelled')479        seq.release(batch)480481482class PreparedFinanceTests(unittest.TestCase):483    setUp = PreparedBookFixture.setUp484    ready = PreparedBookFixture.ready485486    def probe(self, *, cash=10000, config=None):487        reader = self.ready()488        app = Platform(self.root / 'accounts')489        self.addCleanup(app.close)490        profile = app.create_profile('probe')491        account = app.create_account(profile, 'cash', cash)492        maker = app.create_maker(profile, 'human', 'human', 'v1')493        now = [4]494        probe = assemble_probe(495            app._operations,496            app._new_execution,497            profile,498            account,499            maker,500            reader,501            lambda: now[0],502            start_ns=3,503            end_ns=31,504            config=config,505        )506        self.addCleanup(probe.close)507        return app, profile, account, probe, now508509    def test_partial_fill_then_cancel_and_same_id_replay(self):510        app, profile, account, probe, now = self.probe()511        command = probe.submit('r1', Intent('buy', 'AAPL', 'buy', 5, 101))512        now[0] = 11513        probe.turn()514        first = probe.sequencer.result('r1')515        self.assertEqual(first['status'], 'accepted')516        snapshot = probe.execution.snapshot517        self.assertEqual(snapshot.account.orders[0].filled, 2)518        self.assertEqual(snapshot.account.cash, 9798)519        self.assertEqual(snapshot.reserved_cash, 303)520        self.assertEqual(probe.timeline.trace[0]['source_prefix'], 3)521        self.assertEqual(command.time_ns, 4)522        self.assertEqual(probe.submit('r1', Intent('buy', 'AAPL', 'buy', 5, 101)), command)523        now[0] = 15524        probe.cancel('r2', first['order_id'])525        now[0] = 21526        probe.turn()527        now[0] = 30528        probe.turn()529        self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 2)530        self.assertEqual(probe.execution.snapshot.account.orders[0].status, 'cancelled')531        self.assertEqual(probe.execution.snapshot.reserved_cash, 0)532        self.assertEqual(len(app.snapshot(profile, account).orders), 1)533534    def test_receipt_after_price_change_and_no_repeated_liquidity(self):535        _, _, _, probe, now = self.probe()536        now[0] = 10537        probe.submit('a', Intent('a', 'AAPL', 'buy', 2, 101))538        probe.submit('b', Intent('b', 'AAPL', 'buy', 2, 101))539        now[0] = 21540        probe.turn()541        orders = probe.execution.snapshot.account.orders542        by_id = {o.order_id: o.filled for o in orders}543        self.assertEqual(by_id[probe.sequencer.result('a')['order_id']], 2)544        self.assertEqual(by_id[probe.sequencer.result('b')['order_id']], 0)545        self.assertEqual(probe.timeline.trace[0]['source_prefix'], 5)546        self.assertEqual(probe.timeline.trace[1]['source_prefix'], 5)547548    def test_prepared_finance_matches_native_with_same_effective_boundary(self):549        app, profile, account, probe, now = self.probe()550        now[0] = 3551        # Sequencer clock has not been sampled yet; start includes exactly prefix 3.552        probe.submit('buy', Intent('buy', 'AAPL', 'buy', 5, 101))553        now[0] = 21554        probe.turn()555        expected = probe.execution.snapshot556        other = app.create_account(profile, 'native', 10000)557        maker = app.create_maker(profile, 'native', 'human', 'v1')558        market = app.open_market('AAPL')559        self.addCleanup(market.close)560        market.load(self.source)561        run = app.create_execution_run(profile, other, maker, 'AAPL')562        session = app.execution_session(profile, run, maker, market)563        self.addCleanup(session.close)564        for _ in range(3):565            session.step()566        session.submit(Intent('buy', 'AAPL', 'buy', 5, 101))567        for _ in range(3):568            session.step()569        actual = session.snapshot570        self.assertEqual(actual.account.cash, expected.account.cash)571        self.assertEqual(actual.reserved_cash, expected.reserved_cash)572        self.assertEqual(actual.account.positions, expected.account.positions)573        self.assertEqual(actual.account.orders[0].filled, expected.account.orders[0].filled)574575    def test_sell_reservation_still_uses_original_financial_rules(self):576        app, profile, account, probe, now = self.probe()577        probe.submit('buy', Intent('buy', 'AAPL', 'buy', 5, 101))578        now[0] = 11579        probe.turn()580        now[0] = 12581        probe.submit('sell', Intent('sell', 'AAPL', 'sell', 2, 200))582        probe.submit('short', Intent('short', 'AAPL', 'sell', 1, 200))583        now[0] = 13584        probe.turn()585        self.assertEqual(probe.sequencer.result('sell')['status'], 'accepted')586        self.assertEqual(probe.sequencer.result('short')['status'], 'rejected')587        self.assertEqual(dict(probe.execution.snapshot.reserved_shares), {'AAPL': 2})588589    def test_latency_and_fee_are_not_bypassed_by_prepared_events(self):590        _, _, _, probe, now = self.probe(config=ExecutionConfig(latency_ns=15, fee_per_share=1))591        probe.submit('buy', Intent('buy', 'AAPL', 'buy', 2, 101))592        now[0] = 11593        probe.turn()594        self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 0)595        self.assertEqual(probe.execution.snapshot.reserved_cash, 204)596        now[0] = 21597        probe.turn()598        self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 2)599        self.assertEqual(probe.execution.snapshot.account.cash, 9796)600        self.assertEqual(probe.execution.snapshot.account.fees, 2)601602    def test_two_80_value_orders_cannot_reserve_more_than_100(self):603        _, _, _, probe, now = self.probe(cash=100)604        probe.submit('a', Intent('a', 'AAPL', 'buy', 1, 80))605        probe.submit('b', Intent('b', 'AAPL', 'buy', 1, 80))606        now[0] = 5607        probe.turn()608        self.assertEqual(probe.sequencer.result('a')['status'], 'accepted')609        self.assertEqual(probe.sequencer.result('b')['status'], 'rejected')610        self.assertEqual(probe.execution.snapshot.available_cash, 20)611612    def test_end_cancels_unexecuted_and_releases_existing_orders(self):613        _, _, _, probe, now = self.probe()614        probe.submit('a', Intent('a', 'AAPL', 'buy', 5, 101))615        now[0] = 5616        probe.turn()617        now[0] = 30618        probe.cancel('late', probe.sequencer.result('a')['order_id'])619        now[0] = 31620        probe.turn()621        self.assertEqual(probe.sequencer.result('late')['status'], 'cancelled')622        self.assertTrue(probe.execution.closed)623        # Old accepted order consumes pre-end events even when execution was late.624        self.assertEqual(probe.execution.snapshot.account.orders[0].filled, 5)625626627class PreparedFailureTests(unittest.TestCase):628    setUp = PreparedBookFixture.setUp629    ready = PreparedBookFixture.ready630    probe = PreparedFinanceTests.probe631632    def test_fault_during_commit_does_not_publish_result_or_reexecute(self):633        _, _, _, probe, now = self.probe()634        probe.submit('a', Intent('a', 'AAPL', 'buy', 1, 101))635        now[0] = 5636        with patch.object(637            probe._commands, 'commit', side_effect=OSError('injected financial failure')638        ):639            with self.assertRaises(OSError):640                probe.turn()641        self.assertTrue(probe.execution.closed)642        self.assertEqual(probe.sequencer.snapshot()['state'], 'failed')643        self.assertEqual(probe.sequencer.result('a')['status'], 'failed')644645    def test_end_arrives_during_first_commit_second_command_is_cancelled(self):646        _, _, _, probe, now = self.probe()647        probe.submit('a', Intent('a', 'AAPL', 'buy', 1, 80))648        probe.submit('b', Intent('b', 'AAPL', 'buy', 1, 80))649        now[0] = 5650        original = probe._apply651652        def delayed(command):653            result = original(command)654            now[0] = 31655            return result656657        probe.timeline.apply = delayed658        probe.turn()659        self.assertEqual(probe.sequencer.result('a')['status'], 'accepted')660        self.assertEqual(probe.sequencer.result('b')['status'], 'cancelled')661        self.assertTrue(probe.execution.closed)