From 00f72df9b20793600eacadd02240aedc95ac56a1 Mon Sep 17 00:00:00 2001 From: baobao Date: Thu, 19 Nov 2026 11:33:47 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=BE=AE=E7=9B=98=E6=8C=87?= =?UTF-8?q?=E6=A0=87=E3=80=81=E9=80=90=E7=AC=94=E8=BF=9B=E5=B1=95=E4=B8=8E?= =?UTF-8?q?=E6=8C=81=E4=BB=93=E8=A1=A8=E5=B1=95=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 3 +- app/services/execution_conflicts.py | 24 ++++++---- app/services/rotation_display.py | 73 +++++++++++++++++++++++++++++ app/web/main.py | 7 ++- app/web/static/index.html | 47 ++++++++++--------- app/web/static/rotation.html | 4 +- app/web/static/rotation_signal.js | 15 ++++++ scripts/run_tests.py | 2 +- scripts/test_batch41_units.py | 21 +++++++++ 9 files changed, 159 insertions(+), 37 deletions(-) create mode 100644 app/services/rotation_display.py create mode 100644 app/web/static/rotation_signal.js diff --git a/AGENTS.md b/AGENTS.md index 1979f04..1afb49d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ - 主界面优先回答当前结论、关键依据、能否操作及下一步该做什么。已有当前有效结论时,应直接展示该结论,不能用历史“未取得”、缓存状态或内部取数差异替代交易员需要的判断。 - 同一股票的卡片、摘要和详情须使用清晰一致的业务口径。历史决策依据和技术追溯信息按需查看,不抢占主要信息;保留原始审计,不用当前数据改写历史。 - 中性、尚无有效信号、分析未完成、数据不可用须准确区分。异常提示应说明对交易的实际影响和可采取的操作,不把“无读数”“未取得”“版本变化”等内部状态直接当作用户结论,也不把缺失伪装为中性。 -- 沿用现有页面风格、信息密度和交互习惯。优先改善业务表达与功能本身,不靠增加标签、解释段落或开发参数让用户理解内部实现。 +- 设计功能时先核对交易员要完成的操作。等待提示须写明这笔交易到了哪一步、有何限制、由谁继续处理;原因尚未查明时,只展示已核实的进度。 +- 同类页面和表格优先复用已有组件、列顺序、字号、间距、配色和交互。策略之间仅按业务需要增删列。优先改善业务表达与功能本身,不靠增加标签、解释段落或开发参数让用户理解内部实现。 - 验收必须从真实交易员任务检查:是否能迅速理解当前判断、限制原因和操作结果,摘要与详情是否造成矛盾。测试通过、字段准确或程序逻辑自洽,不等于产品设计符合预期。 ## 研究、分析与交易范围 diff --git a/app/services/execution_conflicts.py b/app/services/execution_conflicts.py index ab45acb..351b329 100644 --- a/app/services/execution_conflicts.py +++ b/app/services/execution_conflicts.py @@ -129,6 +129,7 @@ def instruction_progress(rows): """只读展示。父指令发过单,不代表当前还有未成交委托。""" from app.services import dispatcher ws = dispatcher.mode() == 'ws' + rotation_cache = {} for row in rows: if row.get('status') not in LIVE and row.get('status') != 'CANCELLED': continue @@ -140,12 +141,17 @@ def instruction_progress(rows): orders = qmt_repo.orders_for_parent(row['instruction_id']) active = [o for o in orders if o.get('status') in qmt_repo.LIVE] stage = 'waiting' + note = None if any(o.get('cancel_state') in ('REQUESTED', 'SENT') for o in active): label = '撤单处理中' stage = 'cancelling' - elif any(o.get('status') not in ('QUEUED', 'SENDING') for o in active): + elif any(o.get('status') == 'PARTIAL' for o in active): + label, stage = '部分成交,余单待成交', 'submitted' + elif any(o.get('status') in ('ACCEPTED', 'SUBMITTED') for o in active): label = '委托待成交' stage = 'submitted' + elif any(o.get('status') == 'SENT' for o in active): + label, stage = '已发送,待 QMT 确认', 'submitted' elif active: label = '委托待发送' stage = 'sending' if any(o.get('status') == 'SENDING' for o in active) else 'queued' @@ -171,16 +177,16 @@ def instruction_progress(rows): else: label = '等待执行' review = (row.get('progress') or {}).get('daily_review') or {} - if row.get('status') == 'WAIT_REVIEW' and not active: - if (row.get('progress') or {}).get('execution_profile') == 'rotation': - label = '等待篮子执行检查' - stage = 'waiting' - else: - label = '待确认今日买入' if review.get('status') == 'confirmation' else '跨日复核中' - stage = 'review' + rotation = (row.get('progress') or {}).get('execution_profile') == 'rotation' + if rotation and stage == 'waiting' and label == '等待执行': + from app.services.rotation_display import order_wait + label, note = order_wait(row, orders, rotation_cache) + elif not rotation and row.get('status') == 'WAIT_REVIEW' and stage == 'waiting': + label = '待确认今日买入' if review.get('status') == 'confirmation' else '跨日复核中' + stage = 'review' live_prices = {str(o.get('limit_price')) for o in active if o.get('limit_price') is not None} row['execution_limit'] = next(iter(live_prices)) if len(live_prices) == 1 else None - row['execution_note'] = review.get('reason') if stage == 'review' else ( + row['execution_note'] = review.get('reason') if stage == 'review' else note or ( ((row.get('progress') or {}).get('last_decision') or {}).get('reason')) row['execution_label'] = label row['execution_stage'] = stage diff --git a/app/services/rotation_display.py b/app/services/rotation_display.py new file mode 100644 index 0000000..1cbfeac --- /dev/null +++ b/app/services/rotation_display.py @@ -0,0 +1,73 @@ +"""将轮动执行事实转换为交易员可读的进度,只用于展示。""" +import re + +from app.core.execution_policy import local_now, timestamp +from app.repo import rotation_repo + + +def wait_text(reason): + messages = ( + ('账户可用现金或全账户仓位预算不足', '可用现金或剩余仓位额度不足'), + ('资金快照', '等待 QMT 更新可用资金'), + ('可卖数量不足', '等待可卖股数足够'), + ('下游已撤单', '委托已撤,继续交易须重新授权'), + ('已冻结或列入黑名单', '个股已禁止买入'), + ('等待策略持仓与QMT对齐', '等待核对持仓数量'), + ('旧委托尚未核实入账', '等待核对上一笔委托和成交'), + ('行情已过期或时间超前', '等待更新行情'), + ('等待核实本交易日的委托价格边界', '等待确认当日涨跌停价'), + ('pms-ws 常驻进程未在线', '等待恢复 QMT 连接'), + ) + for fragment, label in messages: + if fragment in reason: + return label + if '待重试' in reason or '等待执行:' in reason or '委托未下发' in reason: + return '本次报单未完成,等待下一次执行' + return reason + + +def display_wait(reason): + code = re.match(r'^(\d{6}\.(?:SH|SZ))(.*)$', reason) + if code: + return code[1] + ' ' + wait_text(code[2]) + return wait_text(reason) + + +def order_wait(row, orders, cache): + from app.services import intraday_rotation as entry + + p = row['progress'] + now = local_now() + if p.get('cancel_requested'): + return '正在结束指令', '系统正在核对最后一笔委托。' + end = timestamp(p.get('expires_at')) + if end and now >= end: + return '当日授权已到期', '当日不再新增委托。' + if p.get('ticket') and p.get('deadline') == now.date().isoformat(): + if 'state' not in cache: + cache['state'] = rotation_repo.get('state:live')[0] or {} + state = cache['state'] + tick = timestamp(state.get('last_tick')) + rotation = state.get('rotation') or {} + if (tick and 0 <= (now-tick).total_seconds() <= 180 and p.get('snapshot_version') + and p['snapshot_version'] == rotation.get('consumed_entry') and row.get('side') == 'buy' + and row['ts_code'] in rotation.get('target', [])): + for reason in reversed(state.get('blocked') or []): + if reason.startswith(row['ts_code']+'等待执行:') or reason.startswith(row['ts_code']+'等待策略持仓') or reason.startswith(row['ts_code']+'下游已撤单'): + return wait_text(reason[len(row['ts_code']):]), '最近核对于 '+tick.strftime('%H:%M:%S')+'。当前没有在途委托。' + if row['status'] == 'WAIT_REVIEW': + if 'release' not in cache: + cache['release'] = entry.read_release(now) or {} + if cache['release'].get('ticket') != p['ticket']: + return '等待当日建仓放行', '当日指令已登记,尚未向 QMT 报单。' + if 690 <= now.hour*60+now.minute < 780: + return '午间休市,下午继续', '当前没有在途委托。下午开市后系统继续处理。' + if orders: + state = orders[-1].get('status') + if state == 'CANCELLED': + return '上笔已撤,余量未报单', '当前没有在途委托。' + if state == 'EXPIRED': + return '上笔已到期,余量未报单', '当前没有在途委托。' + if state == 'REJECTED': + return 'QMT 已拒单', '上一笔委托未获受理。' + return '买单尚未报出' if row.get('side') == 'buy' else '卖单尚未报出', '轮动指令已登记,当前没有在途委托。' diff --git a/app/web/main.py b/app/web/main.py index 8b7c647..eb88f81 100644 --- a/app/web/main.py +++ b/app/web/main.py @@ -49,7 +49,12 @@ def rotation_page(): @app.get('/api/rotation') def rotation_status(): from app.services.rotation_service import status - return ok(status) + from app.services.rotation_display import display_wait + result = ok(status) + state = (result.get('data') or {}).get('state') or {} + if state.get('blocked'): + state['display_waits'] = [display_wait(reason) for reason in state['blocked']] + return result @app.get('/api/rotation/history') diff --git a/app/web/static/index.html b/app/web/static/index.html index ad47667..54e42a6 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -8,6 +8,7 @@ + +

策略轮换

主观量化与微盘轮动共用账户,分别记录。
返回工作台
@@ -44,7 +44,7 @@ async function copyMembers(){ function cell(row,value){const td=document.createElement('td');td.textContent=value;row.append(td);return td} function line(table,values){const tr=document.createElement('tr');values.forEach(v=>cell(tr,v));table.append(tr)} async function request(url,options){const r=await fetch(url,options);if(r.status===401)throw Error('请先返回工作台登录');if(r.status===403)throw Error('此操作需要系统管理员权限');const v=await r.json();if(!r.ok||v.ok===false)throw Error(v.error||'请求失败');return v.data||v} -async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=v.mode==='paper'?st.account:null;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(s.basis==='manual_intraday'?'盘中授权 '+String(s.calculated_at).slice(11,19):s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':!s.frozen&&s.basis!=='manual_intraday'?'待冻结':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}} +async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=v.mode==='paper'?st.account:null;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(rotationSignalBasis(v)==='intraday'?'盘中授权 '+String(s.calculated_at).slice(11,19):s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':rotationSignalBasis(v)==='pending'?'等待名单确认':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.display_waits||st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}} function renderDetails(v){ const st=v.state||{},isPaper=v.mode==='paper',a=isPaper?st.account:null,s=v.snapshot||{},p=st.progress||{},rule=s.rule_parameters||v.rule_parameters||{},size=v.basket_size,metrics=isPaper?(st.metrics||{}):((v.accounting||{}).metrics||{}); el('rule-summary').textContent='成长主线瓦解或低于历史'+fmt(rule.entry_percentile==null?null:rule.entry_percentile*100)+'%分位时入场,高于历史'+fmt(rule.exit_percentile==null?null:rule.exit_percentile*100)+'%分位时退出。股汇对冲指标只作用于主观量化。'; diff --git a/app/web/static/rotation_signal.js b/app/web/static/rotation_signal.js new file mode 100644 index 0000000..d6b7a90 --- /dev/null +++ b/app/web/static/rotation_signal.js @@ -0,0 +1,15 @@ +// 工作台与策略详情共用当天的执行依据。盘中采用的名单保留盘前记录。 +function rotationSignalBasis(view) { + const snapshot = view.snapshot || {}; + if (snapshot.frozen === true) return 'frozen'; + const state = view.state || {}; + const morning = view.morning_snapshot || {}; + if (snapshot.basis === 'manual_intraday' && view.mode === 'auto' && + snapshot.effective_date && snapshot.effective_date === state.intraday_date && + morning.frozen === true && morning.effective_date === snapshot.effective_date && + snapshot.morning_version && snapshot.morning_version === morning.snapshot_version && + snapshot.snapshot_version && snapshot.snapshot_version === state.rotation?.consumed_entry) { + return 'intraday'; + } + return 'pending'; +} diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 6d99305..2884688 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -37,7 +37,7 @@ test_batch45_units.py 父指令总量:回放延迟、部分成交、跨日预留、故障守成与影子模式 (16 例) test_batch43_units.py 逐票来源核验、实际API至SQL事务、故障回滚与幂等 (14 例) test_batch42_units.py 提议先准备后采纳、模型复用、并发更新与发布审计 (24 例) - test_batch41_units.py 跨流程买卖互斥、清仓收尾、出口撤单与真实进展及人工清仓T+1 (27 例) + test_batch41_units.py 跨流程买卖互斥、清仓收尾、出口撤单与真实进展及人工清仓T+1、微盘逐股进展 (28 例) test_batch40_units.py 逐笔历史修复、进度暂停、并发与事务回滚与均价失效 (22 例) test_batch39_units.py 成交双来源归属、迟到、部分成交、失败守成与更正挂起摘要 (18 例) test_batch38_units.py 每日计划顺序、版本核验、重新确认、并发采纳、历史保留及采纳失败说明、明确否决撤下 (30 例) diff --git a/scripts/test_batch41_units.py b/scripts/test_batch41_units.py index 8c2288f..267026b 100644 --- a/scripts/test_batch41_units.py +++ b/scripts/test_batch41_units.py @@ -194,6 +194,27 @@ class ConflictsTest(unittest.TestCase): result=c.instruction_progress([row])[0] self.assertEqual((result['execution_label'],result['execution_stage']),('成交待入账','reconciling')) + def test_rotation_wait_uses_current_stock_and_round_and_yields_to_fills(self): + from app.core.execution_policy import local_now + from app.services import execution_conflicts as c, rotation_display as view + now = local_now(datetime(2026, 11, 19, 10, 30)) + row = ins(self.fake, 'micro', 'OPEN', 'buy', 600, 0) + row.update(status='WAIT_REVIEW', progress=dict(execution_profile='rotation', ticket='batch', + deadline='2026-11-19', snapshot_version='basket')) + st = dict(last_tick=now.isoformat(), rotation=dict(consumed_entry='basket', target=[CODE]), + blocked=['600000.SH等待执行:等待策略持仓与QMT对齐', + CODE+'等待执行:轮换委托未下发:ValueError: 账户可用现金或全账户仓位预算不足']) + with patch.object(view, 'local_now', return_value=now), patch.object(view.rotation_repo, 'get', return_value=(st,1)), \ + patch('app.services.intraday_rotation.read_release',return_value=None), patch.object(qmt_repo, 'orders_for_parent') as orders: + orders.return_value = [] + self.assertEqual(c.instruction_progress([row])[0]['execution_label'], '可用现金或剩余仓位额度不足') + st['rotation']['consumed_entry'] = 'previous' + self.assertEqual(c.instruction_progress([row])[0]['execution_label'], '等待当日建仓放行') + orders.return_value = [dict(status='ACCEPTED',cum_qty=0)] + self.assertEqual(c.instruction_progress([row])[0]['execution_label'], '委托待成交') + orders.return_value = [dict(status='FILLED',cum_qty=600)] + self.assertEqual(c.instruction_progress([row])[0]['execution_label'], '成交待入账') + def test_other_stock_not_blocked(self): from app.services import execution_conflicts as c ins(self.fake,'exit','EXIT','sell')