当日微盘篮子按保护限价在QMT持续等待成交

This commit is contained in:
baobao 2026-11-19 11:01:52 +08:00
parent edef84bc50
commit 78df2662df
5 changed files with 247 additions and 14 deletions

View File

@ -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<limit):
raise ValueError('保护限价越过原指令价格边界')
return float(price)
def cancel_reason(parent, release, rotation, controls):
p = parent['progress']
if not release or entry.metadata(release) != entry.metadata(p):
return '本批授权已撤销或到期'
if rotation.get('consumed_entry') != release['snapshot_version']:
return '买入篮子所属轮次已结束'
if controls['halt_all'] or controls['mode'] != 'auto' or controls['control'] == 'pause_all':
return '用户暂停本批执行'
if parent['side']=='buy':
if controls['halt_buy'] or controls['control'] != 'run':
return '用户停止新增买入'
if entry.repo.buy_ban(parent['ts_code']):
return '该股已冻结或列入黑名单'
if parent['ts_code'] not in rotation.get('target',[]) or rotation.get('phase') not in ('micro','entering_micro'):
return '已调出当日买入篮子'
elif not release.get('funding_sales') or rotation.get('phase') != 'entering_micro' or controls['control'] != 'run':
return '本批筹资卖出已停止'
return ''
def execute(work):
from app.services import rotation_execution as trade, rotation_service as service, executor
results, waits = [], []
# 先处理筹资卖出;买入额度始终按QMT实际回款和账户资金保留核验。
for book, iid in sorted(work['parents'], key=lambda item: item[0] != books.ORIGINAL):
code = iid
try:
with store.account_guard(), books.scope(book):
now = entry.local_now()
parent = pms_repo.get_instruction(iid)
if not parent or parent['status'] not in service.LIVE or parent['progress'].get('cancel_requested'):
continue
code = parent['ts_code']
policy = policy_for(parent['progress'])
if not policy or iid not in policy['lines']:
continue
release = entry.read_release(now)
rotation = (store.get('state:live')[0] or {}).get('rotation',{})
reason = cancel_reason(parent, release, rotation, param_store.execution_controls())
if not reason:
reason = work['unavailable'].get(code) if parent['side']=='buy' else None
if reason:
if not executor.cancel_instruction(iid, reason=reason, arbiter='system').get('ok'):
raise RuntimeError('撤单等待确认')
continue
history = qmt_repo.orders_for_parent(iid)
if any(o['status'] not in qmt_repo.FINAL for o in history):
continue
if history and history[-1]['status']=='CANCELLED' and history[-1].get('cancel_state') not in ('REQUESTED','SENT'):
waits.append(code+'下游已撤单,等待重新授权')
continue
if not entry.session_open(now) or now.date().isoformat()!=work['day']:
continue
# 盘口时效不影响保护价;持仓与真实可用资金仍须核实。
if not service.reconcile_books()['ok']:
waits.append(code+'等待策略持仓与QMT对齐')
continue
line = policy['lines'][iid]
limits = work['limits'].get(code,{})
price = protected_price(parent,line,limits)
intent = dict(id=iid,book_id=book,ts_code=code,side=parent['side'],qty=parent['qty'],
reason='盘中篮子保护限价委托',rule_version=release['rule_version'],
quote_basis={'source':'当日授权保护限价','limit_price':price,'source_ref':line['source_ref']},
day_limits=limits,limits_date=work['day'])
result = trade.send_intent(intent,price,now,release['snapshot_version'])
if (result.get('result') or {}).get('ok'):
results.append(result)
elif result.get('state'):
waits.append(code+result['state'])
except Exception as exc:
why = str(exc)[:160] if isinstance(exc, (ValueError,RuntimeError)) else type(exc).__name__
waits.append(code+'等待执行:'+why)
return results, waits

View File

@ -243,14 +243,24 @@ def send_intent(intent, price, now, snapshot_version):
current = intraday_rotation.local_now()
if not intraday_rotation.session_open(current) or current.date() != now.date():
raise ValueError('盘中建仓执行时段已结束')
checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current,
user_limit=(existing or {}).get('limit_price'))
if checked.get('action') != 'FIRE':
raise ValueError(checked.get('reason') or '执行报价已过期')
price = checked['limit_price']
end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57,
second=0, microsecond=0)
until = min(current+dt.timedelta(minutes=10), end, dt.datetime.fromisoformat(progress['expires_at']))
from app.services import rotation_day_orders
policy = rotation_day_orders.policy_for(progress)
line = (policy or {}).get('lines', {}).get(parent)
expiry = dt.datetime.fromisoformat(progress['expires_at'])
if line:
if not existing or intent.get('limits_date') != current.date().isoformat():
raise ValueError('等待核实本交易日的委托价格边界')
price = rotation_day_orders.protected_price(existing,line,intent.get('day_limits') or {})
until = min(expiry, current.replace(hour=15, minute=0, second=0, microsecond=0))
else:
checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current,
user_limit=(existing or {}).get('limit_price'))
if checked.get('action') != 'FIRE':
raise ValueError(checked.get('reason') or '执行报价已过期')
price = checked['limit_price']
end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57,
second=0, microsecond=0)
until = min(current+dt.timedelta(minutes=10), end, expiry)
else:
until = (now.replace(hour=10, minute=0, second=0, microsecond=0) if now.hour < 10 else
min(now+dt.timedelta(minutes=10), now.replace(hour=14, minute=57, second=0, microsecond=0)))
@ -330,6 +340,11 @@ def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable):
continue
if progress.get('cancel_requested'):
continue
if progress.get('ticket'):
from app.services import rotation_day_orders
policy = rotation_day_orders.policy_for(progress)
if policy and parent['instruction_id'] in policy['lines']:
continue # 当日保护限价单由逐笔账户事务接续,不因分钟行情变化撤换。
children = qmt_repo.orders_for_parent(parent['instruction_id'])
live = [c for c in children if c['status'] not in TERMINAL]
quote = quotes.get(code, {})
@ -376,6 +391,8 @@ def cancel_expired(now):
from app.services import executor
with books.scope('all'):
rows = pms_repo.list_instructions(statuses=('PROPOSED', 'DISPATCHED','WAIT_REVIEW'), limit=10000)
policies = {}
release = rotation = controls = None
for row in rows:
p = row.get('progress') or {}
if p.get('execution_profile') != 'rotation':
@ -387,9 +404,22 @@ def cancel_expired(now):
expired = local_now(now) >= 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('轮换委托撤销未确认')

View File

@ -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)

View File

@ -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例)

View File

@ -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')])