"""执行依据、报价、撤换及迟到成交的断网回归。""" import unit_test_guard import asyncio import copy import unittest from datetime import datetime, timedelta from unittest.mock import patch from test_wiring import install_fakes from app.core import execution_policy as policy, ws_codec from app.repo import pms_repo, qmt_repo, execution_repo from app.services import execution_orders as orders, execution_basis as basis from app.services import exec_advisor, executor, dispatcher, market, execution_conflicts, param_store from app.ws.runner import WsRunner NOW = datetime(2026, 11, 3, 10, 30, tzinfo=policy.BEIJING) CODE = '600000.SH' def fact(**extra): return {'version': 'v1', 'quality': 'VALID', 'continuation': 'CONTINUE', 'reason': '已有授权未撤销', 'generated_at': (NOW-timedelta(hours=4)).isoformat(), 'valid_until': (NOW+timedelta(minutes=5)).isoformat(), 'source_date': '2026-11-02', 'source': 'model:traceable', **extra} def quote(**extra): return {'kind': 'level1', 'source': 'test-level1', 'as_of': NOW.isoformat(), 'last': 10., 'bid': 9.99, 'ask': 10.01, 'limit_down': 9., 'limit_up': 11., 'halted': False, **extra} class ExecutionTests(unittest.TestCase): def setUp(self): self.fake = install_fakes(prices={CODE: 10.}, params={ 'PMS_EXEC_REPRICE_ENABLED': True, 'PMS_EXEC_IMPL': 'A', 'PMS_EXEC_API_BASE': 'http://fake', 'PMS_DISPATCH_MODE': 'ws', 'PMS_TOTAL_SCALE': 2000000}) self.fake.qmt.set_channel() real_now = policy.local_now patch.object(policy, 'local_now', side_effect=lambda now=None: real_now(now or NOW)).start() patch.object(market, 'execution_quote', side_effect=lambda *a, **k: quote(), create=True).start() patch.object(executor.td, 'ymd', return_value=20261103).start() patch.object(executor.td, 'trade_days_left', return_value=1).start() self.addCleanup(patch.stopall) self.parent() def parent(self, iid='P', **extra): self.fake.insert_instruction(instruction_id=iid, origin_type='strategy', origin_id='S', ts_code=CODE, side='buy', action='OPEN', qty=600, status='DISPATCHED', progress={'is_command': True, 'children': [], 'deadline': '2026-11-03', 'execution_basis_cache': {'basis': fact()}}, **extra) return self.fake.instructions[iid] def child(self, status='ACCEPTED', done=0, iid='P_D01', qty=600): self.fake.qmt.enqueue_order(instruction_id=iid, parent_id='P', ts_code=CODE, side='buy', qty=qty, limit_price=10., valid_until=int((NOW+timedelta(minutes=10)).timestamp()*1000)) row = self.fake.qmt.orders[iid] row.update(status=status, cum_qty=done, created_at=NOW-timedelta(minutes=2)) self.fake.instructions['P']['progress']['children'].append({'ref': iid, 'qty': qty, 'ymd': 20261103, 'mode': 'ws'}) return row def decide(self): parent = self.fake.instructions['P'] return exec_advisor.decide(side='buy', action='OPEN', ts_code=CODE, now=NOW, day={'price': 10}, params={}, is_last_day=True, quota=600, prog=parent['progress']) def test_basis_requires_provenance_time_and_expiry(self): self.assertEqual(policy.basis_reason(fact(), NOW), '') for override in ({'version': None}, {'source': ''}, {'source_date': None}, {'generated_at': '2026-11-03T06:30:00'}, {'valid_until': NOW.isoformat()}, {'continuation': 'UNKNOWN'}, {'quality': 'UNAVAILABLE'}): self.assertTrue(policy.basis_reason(fact(**override), NOW)) def test_stop_wins_even_invalid_quality(self): self.assertIn('已撤销', policy.basis_reason(fact(quality='UNAVAILABLE', continuation='STOP'), NOW)) def test_quote_counterparty_and_user_limits(self): self.assertEqual(orders.quote_order('buy', quote(), NOW)['limit_price'], 10.02) self.assertEqual(orders.quote_order('sell', quote(), NOW)['limit_price'], 9.98) self.assertEqual(orders.quote_order('buy', quote(), NOW, user_limit=9.95)['limit_price'], 9.95) self.assertEqual(orders.quote_order('sell', quote(), NOW, user_limit=10.05)['limit_price'], 10.05) def test_quote_follows_current_price_not_first_order_anchor(self): result = orders.quote_order('buy', quote(last=10.8, ask=10.81, bid=10.79), NOW, anchor_price=10.) self.assertEqual(result['limit_price'], 10.82) def test_quote_requires_fresh_source_and_legal_range(self): for override in ({'source': ''}, {'as_of': (NOW-timedelta(seconds=16)).isoformat()}, {'as_of': (NOW+timedelta(seconds=1)).isoformat()}, {'limit_up': None}, {'ask': None}, {'halted': True}): self.assertEqual(orders.quote_order('buy', quote(**override), NOW)['action'], 'WAIT') self.assertEqual(orders.quote_order('buy', quote(), NOW, user_limit=8)['action'], 'WAIT') def test_minute_degradation_is_explicit_and_switchable(self): value = quote(kind='minute', source='minute-cache', bid=None, ask=None) result = orders.quote_order('buy', value, NOW) self.assertTrue(result['degraded']) self.assertIn('无实时盘口', result['reason']) self.fake.params['PMS_EXEC_ALLOW_MINUTE_QUOTE'] = False param_store._cache['loaded'] = False self.assertEqual(orders.quote_order('buy', value, NOW)['action'], 'WAIT') def test_execution_uses_cache_without_http(self): with patch.object(exec_advisor, '_post', side_effect=AssertionError('执行环禁止HTTP')): self.assertEqual(self.decide()['action'], 'FIRE') self.fake.instructions['P']['progress']['execution_basis_cache']['basis']['continuation'] = 'UNKNOWN' self.assertEqual(self.decide()['action'], 'WAIT') def test_refresh_preserves_children_and_records_new_version(self): self.child() with patch.object(exec_advisor, '_post', return_value={'execution_basis': fact(version='v2')}): result = basis.refresh(NOW) self.assertEqual(result['refreshed'], ['P']) progress = self.fake.instructions['P']['progress'] self.assertEqual(len(progress['children']), 1) self.assertEqual(progress['execution_basis_cache']['basis']['version'], 'v2') def test_refresh_failure_does_not_extend_basis_expiry(self): with patch.object(exec_advisor, '_post', side_effect=TimeoutError('timeout')): result = basis.refresh(NOW) self.assertTrue(result['errors']) progress = self.fake.instructions['P']['progress'] self.assertEqual(basis.cache_reason(progress, NOW), '') self.assertTrue(basis.cache_reason(progress, NOW+timedelta(minutes=6))) def test_refresh_unknown_replaces_previous_continue(self): with patch.object(exec_advisor, '_post', return_value={'execution_basis': fact(continuation='UNKNOWN')}): basis.refresh(NOW) self.assertEqual(self.decide()['action'], 'WAIT') def test_monitor_cancels_full_inflight_on_stop_without_http(self): row = self.child() self.fake.instructions['P']['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') with patch.object(exec_advisor, '_post', side_effect=AssertionError('监控禁止HTTP')): result = basis.monitor(NOW) self.assertEqual(result['errors'], []) self.assertEqual(row['cancel_state'], 'REQUESTED') self.assertEqual(self.fake.instructions['P']['status'], 'DISPATCHED') self.assertFalse(orders.replacement_state('P')['ready']) def test_stop_blocks_buy_but_allows_authorized_nonurgent_sell(self): parent = self.fake.instructions['P'] parent['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') self.assertEqual(self.decide()['action'], 'WAIT') parent.update(side='sell', action='EXIT') result = exec_advisor.decide(side='sell', action='EXIT', ts_code=CODE, now=NOW, day={'price': 10}, params={}, is_last_day=True, quota=600, prog=parent['progress'], urgent=False) self.assertEqual(result['action'], 'FIRE') self.assertEqual(result['limit_price'], 9.98) with patch.object(exec_advisor, '_post', side_effect=AssertionError('卖出不刷新买入继续依据')): self.assertEqual(basis.refresh(NOW)['refreshed'], []) def test_stop_does_not_cancel_or_block_existing_sell(self): parent = self.fake.instructions['P'] parent.update(side='sell', action='TRIM') parent['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') row = self.child() row.update(side='sell', limit_price=9.98) self.assertFalse(execution_conflicts.queued_buy_blocker(row)) result = basis.monitor(NOW) self.assertEqual(result['errors'], []) self.assertEqual(result['replacing'], []) self.assertEqual(row['cancel_state'], 'NONE') def test_cancel_only_never_quotes_or_starts_new_replacements(self): row = self.child() with patch.object(market, 'execution_quote', side_effect=AssertionError('仅确认撤单不允许报价')): result = basis.monitor(NOW, cancel_only=True) self.assertEqual(result['errors'], []) self.assertEqual(row['cancel_state'], 'NONE') self.assertTrue(executor.cancel_instruction('P')['pending']) row.update(status='CANCELLED') confirmed = basis.monitor(NOW, cancel_only=True) self.assertEqual(confirmed['errors'], []) self.assertEqual(self.fake.instructions['P']['status'], 'CANCELLED') def test_missing_quote_cancels_old_order_and_waits_for_fresh_quote(self): row = self.child() with patch.object(market, 'execution_quote', return_value={}): result = basis.monitor(NOW) self.assertEqual(result['errors'], []) self.assertEqual(row['cancel_state'], 'REQUESTED') self.assertEqual(len(self.fake.qmt.orders), 1) def test_quote_exception_requests_cancel_without_false_confirmation(self): row = self.child() with patch.object(market, 'execution_quote', side_effect=RuntimeError('limit snapshot unavailable')): result = basis.monitor(NOW) self.assertEqual(result['errors'], []) self.assertIn('行情读取失败', result['replacing'][0]['reason']) self.assertTrue(result['replacing'][0]['pending']) self.assertEqual(row['cancel_state'], 'REQUESTED') self.assertEqual(self.fake.instructions['P']['status'], 'DISPATCHED') def test_partial_cancel_requires_cumulative_fill_booked(self): self.child(status='CANCELLED', done=200) self.assertFalse(orders.replacement_state('P')['ready']) self.fake.instructions['P']['exec_qty'] = 200 state = orders.replacement_state('P') self.assertTrue(state['ready']) self.assertEqual(state['remaining'], 400) def test_unprocessed_or_held_trade_blocks_replacement(self): self.child(status='EXPIRED') self.fake.qmt.put_trade(seq=1, instruction_id='P_D01', ts_code=CODE, side='buy', qty=100, price=10) self.assertFalse(orders.replacement_state('P')['ready']) self.fake.qmt.inbox[1]['processed'] = 3 self.assertTrue(orders.code_settlement_blocker(CODE)) def test_child_number_recovers_from_outbox_not_progress(self): self.child(status='EXPIRED', iid='P_D04') self.fake.instructions['P']['progress']['children'] = [] self.assertEqual(orders.next_child_id('P'), 'P_D05') def test_parent_cancel_waits_then_confirms_and_never_refires(self): row = self.child() first = executor.cancel_instruction('P') self.assertTrue(first['ok'] and first['pending']) self.assertEqual(self.fake.instructions['P']['status'], 'DISPATCHED') self.assertEqual(executor.run_tick(now=NOW)['fired'], []) row.update(status='CANCELLED') second = executor.cancel_instruction('P') self.assertTrue(second['confirmed']) self.assertEqual(self.fake.instructions['P']['status'], 'CANCELLED') def test_fill_during_cancel_ends_confirmed(self): row = self.child() self.assertTrue(executor.cancel_instruction('P')['pending']) row.update(status='FILLED', cum_qty=600) self.fake.instructions['P']['exec_qty'] = 600 self.assertTrue(executor.cancel_instruction('P')['confirmed']) self.assertEqual(self.fake.instructions['P']['status'], 'CONFIRMED') def test_window_expiry_waits_for_terminal_and_booked_fill(self): parent = self.fake.instructions['P'] parent['progress']['is_command'] = False row = self.child() with patch.object(executor.td, 'trade_days_left', return_value=0): first = executor.sweep_windows(now=NOW) self.assertEqual(first['errors'], []) self.assertEqual(first['expired'], []) self.assertEqual(parent['status'], 'DISPATCHED') self.assertEqual(row['cancel_state'], 'REQUESTED') row.update(status='CANCELLED', cum_qty=200) self.assertEqual(executor.sweep_windows(now=NOW)['expired'], []) self.assertEqual(parent['status'], 'DISPATCHED') parent['exec_qty'] = 200 final = executor.sweep_windows(now=NOW) self.assertEqual(final['errors'], []) self.assertEqual(final['expired'], ['P']) self.assertEqual(parent['status'], 'EXPIRED') def test_cancel_monitor_recovers_old_expired_parent_with_live_child(self): row = self.child() self.fake.instructions['P']['status'] = 'EXPIRED' result = basis.monitor(NOW, cancel_only=True) self.assertEqual(result['errors'], []) self.assertTrue(result['cancelled'][0]['pending']) self.assertEqual(row['cancel_state'], 'REQUESTED') row['status'] = 'CANCELLED' result = basis.monitor(NOW, cancel_only=True) self.assertTrue(result['cancelled'][0]['confirmed']) self.assertEqual(self.fake.instructions['P']['status'], 'EXPIRED') def test_dispatch_rechecks_inflight_and_cached_basis(self): self.child() result = dispatcher.dispatch(instruction_id='P_D02', parent_id='P', ts_code=CODE, side='buy', qty=600, limit_price=10., valid_until=NOW+timedelta(minutes=10)) self.assertFalse(result['ok']) self.assertEqual(len(self.fake.qmt.orders), 1) def test_reprice_zero_attempt_cap_keeps_following_with_frequency_guard(self): row = self.child() self.fake.params['PMS_EXEC_REPRICE_MAX_ATTEMPTS'] = 0 self.assertTrue(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, NOW)) row['created_at'] = NOW self.assertFalse(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, NOW)) def test_transmitted_cancel_or_expiry_blocks_a_new_id_not_the_other_side(self): row = self.child() row.update(sent_at=NOW-timedelta(minutes=10), final_at=NOW) for status in ('CANCELLED', 'EXPIRED'): row['status'] = status with self.subTest(status=status), patch.object(orders.policy, 'local_now', return_value=NOW): result = dispatcher.dispatch(instruction_id='P_D02', parent_id='P', ts_code=CODE, side='buy', qty=600, limit_price=10., valid_until=NOW+timedelta(minutes=10)) self.assertFalse(result['ok']) self.assertIn('当日不自动重报', result['error']) self.assertEqual(len(self.fake.qmt.orders), 1) self.assertFalse(orders.same_day_retry_blocker(CODE, 'sell', 'new', NOW)) self.assertFalse(orders.same_day_retry_blocker(CODE, 'buy', 'P_D01', NOW)) self.assertFalse(orders.same_day_retry_blocker(CODE, 'buy', 'new', NOW+timedelta(days=1))) row.update(status='ACCEPTED') self.assertFalse(orders.should_replace(self.fake.instructions['P'], {'action': 'FIRE', 'limit_price': 10.1}, NOW)) def test_queued_order_rechecks_stop_before_sending(self): row = self.child() self.fake.instructions['P']['progress']['execution_basis_cache']['basis'] = fact(continuation='STOP') self.assertTrue(execution_conflicts.queued_buy_blocker(row)) def test_progress_write_preserves_asynchronously_refreshed_cache(self): old = copy.deepcopy(self.fake.instructions['P']['progress']) execution_repo.save_basis('P', {'basis': fact(version='v2')}) pms_repo.update_instruction('P', progress=old) self.assertEqual(self.fake.instructions['P']['progress']['execution_basis_cache']['basis']['version'], 'v2') def test_cancel_reject_does_not_release_original_order(self): row = self.child() row['cancel_state'] = 'SENT' runner = WsRunner() def record_reject(iid, **fields): self.assertEqual(iid, 'P_D01') row.update(fields) return 1 with patch.object(qmt_repo, 'update_order', side_effect=record_reject) as update: asyncio.run(runner._apply_side_effects(ws_codec.T_REJECT, {'instruction_id': 'P_D01', 'code': 'ALREADY_FINAL'}, {})) update.assert_called_once() self.assertNotIn('status', update.call_args.kwargs) self.assertNotIn('cum_qty', update.call_args.kwargs) self.assertNotIn('final_at', update.call_args.kwargs) self.assertEqual(row['reject_code'], 'ALREADY_FINAL') self.assertEqual(row['status'], 'ACCEPTED') def test_cumulative_quantity_never_regresses(self): row = self.child(status='PARTIAL', done=200) runner = WsRunner() with patch.object(qmt_repo, 'update_order', side_effect=AssertionError('累计成交不得回退')): asyncio.run(runner._on_order_update('P_D01', {'status': 'PARTIAL', 'cum_qty': 100})) self.assertEqual(row['cum_qty'], 200) def test_old_local_cancelled_parent_does_not_claim_broker_confirmation(self): row = self.child() self.fake.instructions['P']['status'] = 'CANCELLED' result = executor.cancel_instruction('P') self.assertTrue(result['pending']) self.assertFalse(result['confirmed']) self.assertEqual(row['cancel_state'], 'REQUESTED') def test_remaining_is_reissued_only_after_partial_fill_booked(self): row = self.child(status='CANCELLED', done=200) first = executor.run_tick(now=NOW) self.assertEqual(first['fired'], []) self.fake.instructions['P']['exec_qty'] = 200 second = executor.run_tick(now=NOW) self.assertEqual([(i['qty'], i['limit']) for i in second['fired']], [(400, 10.02)], second) self.assertEqual(self.fake.qmt.orders['P_D02']['qty'], 400) self.assertEqual(row['cum_qty'], 200) def test_reject_backoff_does_not_block_normal_expiry(self): row = self.child(status='REJECTED') row.update(final_at=NOW, reject_code='BAD_PARAM') self.assertTrue(orders.retry_reason('P', NOW)) self.assertFalse(orders.retry_reason('P', NOW+timedelta(seconds=61))) row['status'] = 'EXPIRED' self.assertFalse(orders.retry_reason('P', NOW)) def test_command_pending_does_not_mark_cancelled_until_terminal(self): from app.services import command_service self.fake.insert_command(command_id='C', cmd_class='task', cmd_type='OPEN_STOCK', ts_code=CODE, params={}, status='EXECUTING', progress={}) self.fake.insert_plans([{'plan_id': 'PLAN', 'command_id': 'C', 'ts_code': CODE, 'action': 'OPEN', 'qty': 600, 'status': 'EXECUTING', 'amount': 6000}]) self.fake.instructions['P'].update(origin_type='plan', origin_id='PLAN') row = self.child() pending = command_service.cancel('C') self.assertEqual(pending['pending'], ['P']) self.assertEqual(self.fake.commands['C']['status'], 'EXECUTING') row.update(status='CANCELLED') command_service.refresh_progress('C') self.assertEqual(self.fake.commands['C']['status'], 'CANCELLED') def test_unsupported_exchange_never_refreshes_upstream(self): self.fake.instructions['P']['ts_code'] = '999999.BJ' with patch.object(exec_advisor, '_post', side_effect=AssertionError('排除交易所不得取数')) as post: self.assertEqual(basis.refresh(NOW)['refreshed'], []) self.assertEqual(post.call_count, 0) if __name__ == '__main__': unittest.main(verbosity=2)