From 78df2662df60cb3be4ca89870aa4e7f78ed34693 Mon Sep 17 00:00:00 2001 From: baobao Date: Thu, 19 Nov 2026 11:01:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BD=93=E6=97=A5=E5=BE=AE=E7=9B=98=E7=AF=AE?= =?UTF-8?q?=E5=AD=90=E6=8C=89=E4=BF=9D=E6=8A=A4=E9=99=90=E4=BB=B7=E5=9C=A8?= =?UTF-8?q?QMT=E6=8C=81=E7=BB=AD=E7=AD=89=E5=BE=85=E6=88=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/rotation_day_orders.py | 112 ++++++++++++++++++++++++++++ app/services/rotation_execution.py | 50 ++++++++++--- app/services/rotation_service.py | 31 +++++++- scripts/run_tests.py | 2 +- scripts/test_intraday_rotation.py | 66 ++++++++++++++++ 5 files changed, 247 insertions(+), 14 deletions(-) create mode 100644 app/services/rotation_day_orders.py diff --git a/app/services/rotation_day_orders.py b/app/services/rotation_day_orders.py new file mode 100644 index 0000000..cc2dcaf --- /dev/null +++ b/app/services/rotation_day_orders.py @@ -0,0 +1,112 @@ +"""本日盘中授权的一篮子保护限价委托。每笔独立核对后交唯一QMT执行。""" + +from decimal import Decimal + +from app.core import strategy_book as books +from app.repo import pms_repo, qmt_repo, rotation_repo as store +from app.services import intraday_rotation as entry, param_store + + +def policy_for(progress): + ticket = progress.get('ticket') + if not ticket: + return None + policy, _ = store.get('qmt-day-orders:'+ticket) + if not policy: + return None + if policy['binding'] != entry.metadata(progress) or policy.get('account') != '155模拟': + raise ValueError('委托执行方式与盘中授权不一致') + return policy + + +def protected_price(parent, line, limits): + """核对已授权价格边界与当日涨跌停。原价仅作保护,不作实时行情。""" + if any(parent[k] != line[k] for k in ('ts_code','book_id','side','qty')): + raise ValueError('保护限价与原指令不匹配') + price = Decimal(str(line['price'])) + low = Decimal(str(limits.get('down_limit') or 0)) + high = Decimal(str(limits.get('up_limit') or 0)) + if (not all(v.is_finite() for v in (price,low,high)) or not 0 < low <= price <= high + or price != price.quantize(Decimal('.01'))): + raise ValueError('保护限价或当日价格上下限不可核实') + boundary = (parent.get('progress') or {}).get('user_limit_price') or parent.get('limit_price') + if boundary is not None: + limit = Decimal(str(boundary)) + if not limit.is_finite() or (parent['side']=='buy' and price>limit) or (parent['side']=='sell' and price= dt.datetime.fromisoformat(p['expires_at']) elif row['status'] == 'WAIT_REVIEW': continue - if expired: + reason = '轮换当日执行窗口结束' if expired else '' + ticket = p.get('ticket') + if ticket and not expired: + from app.services import rotation_day_orders as day_orders, intraday_rotation as entry + if ticket not in policies: + policies[ticket] = day_orders.policy_for(p) + policy = policies[ticket] + if policy and row['instruction_id'] in policy['lines']: + if controls is None: + release = entry.read_release(now) + rotation = (store.get('state:live')[0] or {}).get('rotation',{}) + controls = param_store.execution_controls() + reason = day_orders.cancel_reason(row,release,rotation,controls) + if reason: with books.scope(row['book_id']): - result = executor.cancel_instruction(row['instruction_id'], reason='轮换当日执行窗口结束', arbiter='system') + result = executor.cancel_instruction(row['instruction_id'], reason=reason, arbiter='system') if not result.get('ok'): raise RuntimeError('轮换委托撤销未确认') diff --git a/app/services/rotation_service.py b/app/services/rotation_service.py index 2431859..c0440ff 100644 --- a/app/services/rotation_service.py +++ b/app/services/rotation_service.py @@ -322,12 +322,23 @@ def tick(now=None): prepared = _tick(now, prepare_only=True) if not prepared.get('prepared'): return prepared + work = {} with store.account_guard(): - return _tick(now) + outcome = _tick(now, day_orders=work) + if work.get('parents'): + from app.services import rotation_day_orders + done, waits = rotation_day_orders.execute(work) + outcome.setdefault('results', []).extend(done) + outcome.setdefault('blocked', []).extend(waits) + with store.account_guard(), store.locked('state:live','state',{}) as state: + if state.get('last_tick') == work['tick']: + state.setdefault('last_results', []).extend(done) + state.setdefault('blocked', []).extend(waits) + return outcome return _tick(now) -def _tick(now=None, *, prepare_only=False): +def _tick(now=None, *, prepare_only=False, day_orders=None): now = now or dt.datetime.now(TZ) if now.tzinfo is None: now = now.replace(tzinfo=TZ) @@ -503,11 +514,22 @@ def _tick(now=None, *, prepare_only=False): from app.services import command_service black = command_service.blacklist() refreshed, refresh_waits = [], [] + managed_codes = set() if config['mode'] == 'auto' and s.get('rule_version') == core.EXECUTION_RULE and config['control'] == 'run': from app.services.rotation_execution import refresh_orders refreshable = [p for p in pending if (p.get('progress') or {}).get('ticket') == release['ticket']] if batch else pending + if batch and day_orders is not None: + from app.services import rotation_day_orders + policy = rotation_day_orders.policy_for(release) + if policy: + managed = policy['lines'] + managed_codes = {p['ts_code'] for p in refreshable if p['instruction_id'] in managed and p['side'] == 'buy'} + day_orders.update(day=day,tick=now.isoformat(),limits=limits or {},unavailable=unavailable, + parents=[(p['book_id'],p['instruction_id']) for p in refreshable if p['instruction_id'] in managed]) + refreshable = [p for p in refreshable if p['instruction_id'] not in managed] refreshed, refresh_waits = refresh_orders(refreshable, execution_quotes, now, value['snapshot_version'], set(s['target']) if s['phase'] in ('entering_micro', 'micro') else set(), unavailable) - if s['phase'] == 'entering_micro' and s.get('rule_version') == core.EXECUTION_RULE and not any(c in buy_prices and c not in unavailable for c in s['target']): + if s['phase'] == 'entering_micro' and s.get('rule_version') == core.EXECUTION_RULE and not any( + c not in unavailable and (c in buy_prices or c in managed_codes) for c in s['target']): # 先完成已有单的撤销确认,避免全部停牌时卡住递补;不新卖原仓筹资。 state['blocked'] = quote_errors+target_waits+refresh_waits+['目标成员当前没有可核实执行报价,暂不卖出原策略筹资'] return {'blocked': state['blocked'], 'phase': s['phase'], 'results': refreshed} @@ -522,6 +544,9 @@ def _tick(now=None, *, prepare_only=False): waits.extend(issues) if s.get('rule_version') == core.EXECUTION_RULE: intents = [r for r in intents if r['side'] == 'sell' or r['ts_code'] not in unavailable] + if managed_codes: + already_planned = {code+'旧仓、在途委托或黑名单阻止买入' for code in managed_codes} + waits = [reason for reason in waits if reason not in already_planned] waits.extend(quote_errors+target_waits+refresh_waits) if limits is None: limits = _limits(day) diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 6988e8d..6d99305 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -207,7 +207,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) # 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。 SUITES = [ - 'test_intraday_rotation.py', # 单日轮动授权、50个席位、撤换和委托出口(8例) + 'test_intraday_rotation.py', # 单日轮动授权、50个席位、保护限价和委托出口(11例) "test_business_evidence.py", # 历史准备覆盖与嵌套业务失败(21例) "test_signal_health.py", # 资金监测可用性与交易员提示,7例 "test_proposal_trader_view.py", # 当前分析、数据库读数保存及旧确认保护(21例) diff --git a/scripts/test_intraday_rotation.py b/scripts/test_intraday_rotation.py index 77fa999..1a22b00 100644 --- a/scripts/test_intraday_rotation.py +++ b/scripts/test_intraday_rotation.py @@ -134,6 +134,72 @@ class IntradayEntry(TestCase): eo.request_replace('p','报价过期',self.now) self.assertEqual(cancel.call_count,1) + def test_standing_order_waits_at_qmt_despite_stale_quote_and_partial_fill(self): + from app.services import rotation_day_orders as day, rotation_execution as trade + self.parent['progress'].update(execution_profile='rotation') + self.parent['status']='DISPATCHED' + self.parent['exec_qty']=40 + self.docs['qmt-day-orders:ticket']={'binding':entry.metadata(self.release),'account':'155模拟', + 'lines':{'p':dict(ts_code=self.codes[0],book_id='micro30',side='buy',qty=100,price='10.00',source_ref='p')}} + self.mock(day.store,'account_guard',side_effect=nullcontext) + self.mock(entry.pms_repo,'get_instruction',return_value=self.parent) + self.mock(entry,'local_now',return_value=self.now) + history=self.mock(day.qmt_repo,'orders_for_parent',return_value=[dict(status='PARTIAL')]) + send=self.mock(trade,'send_intent',side_effect=AssertionError('重复发单')) + cancel=self.mock(eo,'request_replace',side_effect=AssertionError('无依据撤换')) + work=dict(day=self.day,parents=[('micro30','p')],unavailable={},limits={}) + self.assertEqual(day.execute(work),([],[])) + self.assertEqual(trade.refresh_orders([self.parent],{},self.now,self.basket['snapshot_version'],set(self.codes),{}),([],[])) + history.return_value=[dict(status='CANCELLED',cancel_state='NONE')] + self.assertIn('重新授权',day.execute(work)[1][0]) + send.assert_not_called() + cancel.assert_not_called() + + def test_standing_price_serializes_to_day_end_with_only_remaining_quantity(self): + from app.services import rotation_execution as trade, dispatcher + from app.core import ws_codec + self.parent.update(limit_price=10,qty=1000,exec_qty=400,origin_id='P_p',progress=dict(self.parent['progress'],children=[])) + line=dict(ts_code=self.codes[0],book_id='micro30',side='buy',qty=1000,price='10.00',source_ref='p') + self.docs['qmt-day-orders:ticket']=dict(binding=entry.metadata(self.release),account='155模拟',lines={'p':line}) + self.mock(trade.db,'transaction',side_effect=nullcontext) + self.mock(eo,'code_settlement_blocker',return_value=None) + self.mock(eo,'replacement_state',return_value=dict(ready=True,remaining=600)) + self.mock(eo,'retry_reason',return_value='') + self.mock(eo,'next_child_id',return_value='p_D02') + self.mock(entry.pms_repo,'get_instruction',return_value=self.parent) + self.mock(entry.pms_repo,'update_instruction',return_value=1) + self.mock(dispatcher,'mode',return_value='ws') + self.mock(entry,'local_now',return_value=self.now) + wire=[] + def dispatch(**kwargs): + kwargs.pop('parent_id') + kwargs['valid_until']=int(kwargs['valid_until'].timestamp()*1000) + wire.append(ws_codec.place_order_payload(**kwargs)) + return {'ok':True} + self.mock(dispatcher,'dispatch',side_effect=dispatch) + intent=dict(id='p',ts_code=self.codes[0],side='buy',book_id='micro30',qty=1000,reason='盘中建仓', + day_limits=dict(up_limit=11,down_limit=9),limits_date=self.day) + trade.send_intent(intent,0,self.now,self.release['snapshot_version']) + self.assertEqual(wire[0]['qty'],600) + self.assertEqual(wire[0]['limit_price'],10.) + self.assertEqual(wire[0]['valid_until'],int(dt.datetime.fromisoformat(self.release['expires_at']).timestamp()*1000)) + intent['day_limits']['up_limit']=9.5 + with self.assertRaises(ValueError): + trade.send_intent(intent,0,self.now,self.release['snapshot_version']) + self.assertEqual(len(wire),1) + + def test_standing_cancel_keeps_user_controls(self): + from app.services import rotation_day_orders as day + rot=self.docs['state:live']['rotation'] + controls=dict(halt_all=False,halt_buy=False,mode='auto',control='run') + self.assertFalse(day.cancel_reason(self.parent,self.release,rot,controls)) + self.ban.return_value=True + self.assertIn('冻结',day.cancel_reason(self.parent,self.release,rot,controls)) + self.parent.update(side='sell',book_id='original') + self.assertFalse(day.cancel_reason(self.parent,self.release,rot,controls)) + self.assertIn('撤销',day.cancel_reason(self.parent,None,rot,controls)) + self.assertIn('暂停',day.cancel_reason(self.parent,self.release,rot,dict(controls,halt_all=True))) + def test_ban_removal_does_not_remove_other_ban(self): rows=self.mock(entry.repo.db,'fetch_all',return_value=[{'cmd_type':t} for t in ('UNFREEZE_STOCK','BLACKLIST_ADD','FREEZE_STOCK')])