diff --git a/DEVLOG.md b/DEVLOG.md index c6240b1..e4796e5 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -2612,3 +2612,56 @@ QMT11:53:36至11:54:04短暂中断,自动重连恢复,外部原因未核实 新增第7图,固定热度0.80及每边30基点,复用已有结果展示1至10日:单日完整41日样本、单日共同池24日和历史至少5次共同池24日。单日41日样本H1/H5/H10平均每批净收益分别为−0.88%/−1.40%/−3.40%;分别标明时间窗口,不将样本变化归因于频次。前六张PNG逐字节不变。保留原图集文件路径,更新开发入口。 开发机macOS核验时间2026-10-30T13:24:29.443371+08:00。全部436行绘图数据、源摘要、引用与Python语法通过;独立Chrome验证7图加载、新旧目录跳转、明细展开及430像素无页面横向溢出,外部请求和页面错误均为0;新增图与说明页面已目视。当前状态见research/strategy_chart_review_20261030/manifest.json。本次补充已完成,没有新回测、数据库访问、参数修改或部署;原有114行DEVLOG和10行复盘台账保持未暂存。 + +## 2026-10-30 跨日买入决策复核 + +- 在独立工作树补齐跨日买入复核,保护主工作树的吸筹研究。旧买单先撤销并等待成交入账,再重新走当日排名、研判、规则和数量;执行价格重新咨询,人工确认按原档位办理。 +- 增加持久复核状态、执行和发送出口守卫、条件更新与同事务审计;保留原父指令及真实成交。页面展示复核状态与真实委托限价。 +- 155两笔旧委托已于09:39请求撤销,09:47确认两笔均撤销且0成交。部署和运行判收另记,详见[跨日复核记录](docs/跨日买入决策复核_2026-10-30.md)。 + +- 10:16:14最终发布pms:daily-review-8f8beba至155的web、worker及唯一ws;155代码提交12b9c22。beat、业务环境和挂载保持。只启用PMS_DAILY_BUY_REVIEW,不改用户暂停及微盘参数。整条命令撤销和策略接管已识别复核等待状态。 +- 本地与155最终候选镜像全量隔离断网回归、36项专项、页面三道护栏通过。1440/390浏览器重放通过、0写请求;最终HTML摘要与验收文件一致。 +- 10:17:39 QMT确认序号1501742较前次1501727推进,序号相等、无缺口及新增拒绝、无待入账与待归属;资金年龄26.3秒,持仓与现金差异0。盛弘旧任务因当日吸筹条件未通过而结束;威胜昨日任务结束,保留今天独立确认的新指令(首批400股、23.30,受理未成交)。不伪称自然覆盖全部恢复分支。证据见docs/evidence/pms_daily_buy_review_20261030.json。 + + +## 2026-10-30 普通限价当日有效与撤单成交边界 + +- 用户给出的威胜D02已核实:10:22:02发出,PMS有效期10:32:00,QMT于10:32:01.896按valid_until到期撤单、零成交,PMS没有主动撤此单。原10分钟分片设置在QMT价格等待模式下造成反复撤挂。 +- 用户确认改为当日有效。新增ParamStore开关PMS_EXEC_QMT_DAY_ORDER,155开启;普通执行器QMT限价单至15:00,微盘、网格和做T窗口及次日完整决策不改。补齐撤单拒绝与下单拒绝区分、累计量防倒退、发送状态不覆盖先到回报、传输不确定时必须向QMT撤单、撤单查询失败仍停止父任务等处理。迟到成交继续归原策略,原有资金占用口径保留。 +- 本机源码64af252、2eaec70;开发机已有全量回归通过,最终新增22专项通过。155最终候选镜像断网、只读、1核512MiB全量ALL SUITES PASS;10:52:39发布pms:day-order-2eaec70至web/worker/唯一ws,服务器源码6702090。worker发布前空闲,beat/监控、实际环境与挂载不变;没有碰188、研究容器、用户暂停和持仓。 +- 真机10:53:05自然发出威胜D05、400股@23.30,QMT ACCEPTED,截止当日15:00。10:54:05连续确认1502309、无新拒绝或额外重连、资金27.8秒、待入账0、孤儿0、数量及现金对账0差异。撤单成交竞争为隔离验证,未制造真实测试成交;收盘到期尚待自然运行。 +- 回退需先停止新增并保留在途回报;已发单期限不能靠关闭参数缩短。详细说明和证据见docs/限价单有效期与撤单成交边界_2026-10-30.md及docs/evidence/pms_day_order_cancel_20261030.json。主工作树吸筹研究未合并,CLAUDE.md不动。 + + +## 2026-10-30 收盘复核与已过期续单修复 + +- 155在16:15至16:25复核:50股快照08:50:08冻结、08:51被PMS自然读取,历史分位10.05%,无信号、微盘空仓;50只均为沪深证券且资格、排序和版本一致。15:20日终记录健康。未查看188,未生成测试信号或交易,未变更用户暂停和策略参数。 +- 威胜D05于10:53受理,15:00:02.787因valid_until自然到期、零成交,确认上午改为当日有效已实际生效。15:00:16多生成的D06仍用15:00期限,随后被本地出口作废,未发QMT。定位到交易时段包含15:00整分钟、执行器缺少截止前检查;本次在QMT价格等待和委托生成前各补检查,14:59行为保持。 +- 源码47f5621、155补丁39d209a;17项专项、本地及155候选镜像全量断网回归通过。16:22:05仅web/worker重建为pms:close-boundary-47f5621,发布前worker空闲,环境、挂载和页面摘要保持;ws仍day-order-2eaec70,beat与监控未动。修复后自然收盘边界尚未再次发生,撤单成交竞争仍为隔离验证,不冒充真机案例。 +- 16:25:45确认1507616较16:15的1507453推进,最新160条连续,无新增拒绝、重连、待入账或孤儿成交;资金年龄6.5秒、冻结0、无活动子委托。四方2700股和汇川200股按原策略归属,总资产1,995,983元,数量及现金对账差异0。今日汇川成交已入账,无归档旧仓回流。费用回报仍null,不补造费用;11月2日快照待今日收盘源数据。 +- 更新自动复核提示和阶段接续,保留16:10日程与无变化静默规则。记录见docs/微盘轮动每日复核_2026-10-30.md及docs/evidence/micro50_daily_20261030.json。主工作树及155私有修改保留,不同步CLAUDE.md。完整微盘自然入退场仍待信号,继续运行复核。 + + +## 2026-11-02 QMT下单策略标识与取消对话定时复核 + +按用户要求,place_order只新增strategy_type:subjective_quant对应主观量化,micro_rotation对应微盘轮动。按持久父指令账本归类,轮换筹资的原策略卖单仍属主观量化;数量、价格、有效期、备注和幂等键不变,撤单与查询报文不变。读取失败保留队列;新字段参与原有完整payload签名,协议文档升V1.0.2而信封与握手版本不改,无DDL或业务参数变更。 + +源码578a2fa,新增8项隔离测试,本地及155候选镜像全量断网回归通过,历史签名向量及页面护栏通过。开发机补齐requirements依赖后使用独立测试环境,生产镜像依赖保持。155首次发布前一致性检查中止且未写配置或重启,随后同样条件重新采样通过;09:07:31只将pms-ws重建为pms:strategy-type-578a2fa,服务器补丁4059b6f。其余容器、实际环境、挂载及用户暂停保持,未触及188。 + +09:08:20确认1569713较发布后1569698推进,最新160条连续,缺口、新拒绝、额外重连、待入账与孤儿0;资金21.2秒,数量和现金对账差异0、无在途。没有生成测试委托,真实QMT接收和保存新字段仍待自然下单,不冒充完成对端验收。说明及证据见docs/QMT下单策略类型_2026-11-02.md和docs/evidence/pms_qmt_strategy_type_20261102.json。 + +通过Codex自动任务工具删除本对话30-pms,返回deleted,配置文件也已不存在;不再进行定时聊天复核,PMS自身业务调度不受影响。阶段接续已更新,主项目研究修改、其他工作树和服务器私有文件保留,CLAUDE.md未修改。 + +## 2026-11-02 交易指令按策略分组 + +用户要求PMS交易指令也区分主观量化和微盘轮动,保持系统风格。交易员与管理视图采用策略标签,保留状态分类;消息显示策略并正确跳转。补齐两账本查询和撤单范围,确认框标明策略,同名股票不混用;轮动哈希指令终态按创建日期保留当日显示,读取失败不冒充空仓。没有调整价格、数量、有效期或执行决策。 + +本地源码716e215;155代码381ddf8,09:39:49仅web完成pms:instruction-books-716e215发布,其他容器与参数不动。开发机14项专项、全量隔离及页面三道护栏通过;155候选镜像断网全量ALL SUITES PASS。Chrome桌面1440和窄屏390以真实只读数据和隔离场景复现分账、计数、终态、消息、错误及撤单确认关闭,错误与写请求均0,部署HTML再次通过。未执行真实撤单或制造委托。 + +09:40:32实机连续确认1570221,缺口、待入账、孤儿及新增拒绝0,资金24.2秒,数量现金对账一致;最新两策略接口归属正确。微盘当前无指令,自然成交和撤单仍待实际发生,不能把回放当真机案例。自动复核仍按上次用户要求取消。详见docs/交易指令策略分组_2026-11-02.md及发布证据。 + +## 2026-11-02 10:13 · 按用户授权再次重置155模拟仓 + +用户确认QMT已清空,初始总规模1,967,927.74元。新增一次性双账本重置脚本及9项隔离测试,本地提交332f008,155补丁36d6ad7,维护镜像pms:sim-reset-332f008断网全量回归ALL SUITES PASS。09:45暂停并温和停止worker/beat,10:08:20将旧持仓、批次、任务、提议、个股策略、流水及净值完整备份后事务清理,实际空仓现金成为新本金,PMS_TOTAL_SCALE同步,净值1.0000。保留规则8%/85%/50只、429条通道委托、1279条逐笔成交及处理标记、操作审计和信号去重;旧轮换资本与收益文档归档,通道序号不动。 + +真机见过:暂停期间两账本持仓与任务清零,回放新增成交和动作均0;10:11:32完成资金与数量对账后仅恢复本次暂停,auto/run继续。10:12:14确认1570706,无缺口、新拒绝、在途或待入账,资金18.9秒,现金及数量差异0;10:13:39健康正常。worker/beat启动原容器,web与唯一ws未重启,镜像环境挂载保持。恢复后新信号和研判是自然调度结果,不再删除。维护首次恢复水位检查未通过时保持暂停,待新采样追平才放开。定时复核保持取消,微盘自然完整成交与费用仍未判收。备份和详细证据见[再次重置与本金基线](docs/模拟仓再次重置与本金基线_2026-11-02.md)。 diff --git a/QMT_WS_PROTOCOL.md b/QMT_WS_PROTOCOL.md index a1586ec..c8f3d17 100644 --- a/QMT_WS_PROTOCOL.md +++ b/QMT_WS_PROTOCOL.md @@ -1,6 +1,6 @@ # PMS ↔ QMT · WebSocket 指令与回报协议 -> 版本:**V1.0.1**(2026-07-30)——V1.0 定稿(2026-07-28)+ 两处澄清,**消息集与状态机一字未动**,V1.0 的实现无需改动即合规。Q1~Q11 与 R1/R2 均已答复回填(见 §10),双方据此实现。 +> 版本:**V1.0.2**(2026-11-02)——`place_order.payload`新增`strategy_type`策略类型,其他业务字段、信封版本及状态机保持。历史变更见§11。 > 后续变更一律版本号递增。**变更记录(§11)按版本号从旧到新排列,读到最后一行才是当前版本**——曾因 V1.0 排在 V0.9.2 之上,对端漏掉了 `ack_seq`(§4.5)。 > 双方:**PMS**(tradingSystem,持仓管理系统,指令发起方)· **QMT**(券商终端侧执行服务,指令执行方) > 本文档取代 `QMT_INTERFACE_REQUIREMENTS.md` 中 B 部分的表通道方案。A 部分(只读数据)与 C 部分(切换约定)继续有效。 @@ -174,6 +174,7 @@ def sign(seed_hex, canon): "limit_price": 12.35, "valid_until": 1769512500000, "intent": "TRIM", + "strategy_type": "subjective_quant", "note": "保垫减仓·垫厚先收" } ``` @@ -187,12 +188,17 @@ def sign(seed_hex, canon): | `limit_price` | number | **必填**,2 位小数。PMS 的择时模块负责定价,QMT 不做价格决策。不接受 null | | `valid_until` | int | 有效期截止,epoch 毫秒。到期仍未全成,QMT **自动撤单**并回 `EXPIRED` 终态 | | `intent` | string | `OPEN`/`FILL`/`ADD`/`DCA`/`TRIM`/`EXIT`/`T0`,仅归类 | +| `strategy_type` | string | `subjective_quant`:主观量化;`micro_rotation`:微盘轮动。用于QMT分类、展示和人工操作,不改变价格、数量或执行规则。新PMS下单必带,历史报文可能没有此字段 | | `note` | string | ≤ 200 字,人工看盘用,QMT 原样落库即可 | `valid_until` 是这套设计里替代「10 秒轮询撤单」的关键:PMS 不必盯着撤,到点 QMT 自己收。 2026-10-28补充:155模拟实例可启用`PMS_EXEC_QMT_PRICE_MONITOR`。已生成的计划由PMS给出限价、数量和有效期,即可提交QMT等待成交,不再等待现价进入区间。买单限价为执行区间上沿,卖单为下沿;买入可在更低价格成交,卖出可在更高价格成交。这不是上下界条件单,协议字段没有增加。用户暂停、资金占用、配额、可卖量和回报入账仍由PMS负责。原执行模式默认保留,不改变其他实例。 +2026-11-02补充:策略类型取自父指令的持久账本归属,适用于买入、卖出、补单及重发。主观量化为微盘筹资的卖单仍为`subjective_quant`,不能按当前轮换阶段或备注判断。内部账本`original`对应`subjective_quant`,`micro30`对应`micro_rotation`,50只版本不改变标识。`note`等原有字段原样保留,撤单与查询报文不加字段。策略来源暂时无法核实时保留队列,不误标为另一策略。 + +QMT需读取并保存该字段,可按上述映射显示中文;兼容既有无此字段的历史订单。验签仍按收到的完整payload规范化,包含新增字段,不能先按旧字段白名单重建payload后验签。信封`v=1`与握手`protocol=1`不变;历史签名测试向量保持原样。 + ### 4.3 `cancel_order` —— 撤单 ```json @@ -201,6 +207,10 @@ def sign(seed_hex, canon): QMT 撤在途部分,已成交部分保留。撤单完成后该指令进入 `CANCELLED` 终态(若撤单前已全成,则回 `reject{code:"ALREADY_FINAL"}` 并附当前状态)。 +2026-10-30补充:155启用`PMS_EXEC_QMT_DAY_ORDER`时,普通QMT限价委托的`valid_until`给到当日15:00;微盘轮换、网格和做T各自的窗口不变。已发送委托不原地改有效期,新委托按新规则生成。次日买入仍须完整决策复核。 + +撤单请求已发送不等于券商撤单成功。`reject`若对应撤单,不能把原委托改成`REJECTED`;`ALREADY_FINAL`也不能替代带累计成交量的终态回报。部分成交后撤单的`cum_qty`必须保留实际累计成交,逐笔`trade`仍须完整推送。PMS停止父任务新增后,仍跟踪子委托、保留在途占用并按原策略接收迟到成交。发送前持久标记可能已发出,重启恢复后的排队单若曾尝试发送,仍向QMT撤单并等终态,不能直接本地作废。 + ### 4.4 查询类 | type | payload | 回应 | @@ -536,3 +546,4 @@ QMT 侧如有本表未覆盖的拒绝场景,请在定稿时补充,**不要 | V0.9.2 | 2026-07-28 | 回填 QMT 侧 Q1~Q11 答复(§10),并据此补齐四处:①新增下行消息 **`ack_seq` 累积确认**(§4.5)——对方的「按最后未 ack 的消息续发」实现依赖它,原协议缺失 ②`trade_no` 定为 `{broker_order_id}#{n}`(§5.5)——券商原生只有委托号,一委托多成交时无法逐笔去重 ③手续费**不摊入持仓成本**、新增 `fee_estimated` 标志(§5.5)——对方明确逐笔费用可能有误差,避免污染安全垫 ④`CANCELLED`/`EXPIRED` 改由 PMS 侧自记(§7.2),不再要求下游区分。另记录 `total_filled` 口径存疑及规避方式(§10.2)。剩余阻塞项收敛为 R1/R2 两条(§10.1) | | **V1.0** | 2026-07-28 | **定稿**。回填 R1/R2:旧通道**即刻停用**、端点定为 `ws://192.168.16.98:8080`;补 §10.1.1 部署前检查清单(白名单、公钥交换、Redis 持久化、密钥只走 `.env`);调整 §9 灰度策略(旧通道已停,无从并行,改为小仓位实跑) | | V1.0.1 | 2026-07-30 | 依 07-30 联调实测澄清两处,**不改消息集与状态机**:①§7.3 `BAD_PARAM` 的含义由「价格精度超限」扩为「价格不合法(精度超限或限价越界)」,并补一段与 `LIMIT_UP`/`LIMIT_DOWN` 的分界说明——原表对「限价超出当日涨跌停区间」没有落点,实测该单既未被拒也未成交,一路挂到 `EXPIRED` ②本表顺序修正:V1.0 那行原排在 V0.9.2 之上,导致对端读到「定稿」即止、漏掉 V0.9.2 引入的 `ack_seq`(§4.5),进而形成 ack→reject 自激循环。**顺序修正不涉及任何条款变更** | +| V1.0.2 | 2026-11-02 | 下单业务体新增`strategy_type`,按父指令账本区分主观量化与微盘轮动;其余下单字段、撤单、信封与握手版本、签名算法及状态机不变。新增字段参与完整payload签名,历史测试向量不变 | diff --git a/app/core/exec_timing.py b/app/core/exec_timing.py index 77c12b5..b90c07e 100644 --- a/app/core/exec_timing.py +++ b/app/core/exec_timing.py @@ -440,8 +440,8 @@ def add_trade_minutes(start_min: int, minutes: int) -> int: def slice_deadline(now, *, ttl_min: int = 10, forced: bool = False) -> int: """单个下发分片的有效期截止 (当日分钟数)。下游到点未成交即自动撤单。 - 普通分片只给 ttl_min 个交易分钟: run_tick 每分钟重评一次, 撤掉重下比挂着更好 - —— 限价是按下发那一刻的价算的, 挂久了价已经不是那个价, 还白占可用资金/持仓。 + 短时分片给 ttl_min 个交易分钟,到期后允许按新依据再评估。 + 普通QMT限价单启用当日有效时,由调用方选择收盘截止。 兜底单 (14:45 之后的 forced) 直接给到收盘: 那是「今天必须走掉」的单, 不能被 TTL 撤回来。 """ diff --git a/app/core/ws_codec.py b/app/core/ws_codec.py index 72e3ee1..a0e4cf9 100644 --- a/app/core/ws_codec.py +++ b/app/core/ws_codec.py @@ -370,7 +370,7 @@ def parse(raw, *, peer_pubkey_b64: str) -> dict: # ================================================================ 各类下行 payload def place_order_payload(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_price, valid_until: int, intent: str = "OPEN", - note: str = "") -> dict: + note: str = "", strategy_type: str = None) -> dict: """§4.2。落地前把易错项一次性校验干净 —— 宁可在本地报错, 不要换 QMT 一个 BAD_PARAM。""" side = str(side or "").lower() if side not in ("buy", "sell"): @@ -395,9 +395,14 @@ def place_order_payload(*, instruction_id: str, ts_code: str, side: str, qty: in intent = "OPEN" if len(str(instruction_id or "")) > 64 or not instruction_id: raise CodecError("BAD_PARAM", f"instruction_id 长度须在 1~64, 收到 {instruction_id!r}") - return {"instruction_id": str(instruction_id), "ts_code": str(ts_code), "side": side, - "qty": qty, "limit_price": px, "valid_until": int(valid_until), - "intent": intent, "note": str(note or "")[:200]} + payload = {"instruction_id": str(instruction_id), "ts_code": str(ts_code), "side": side, + "qty": qty, "limit_price": px, "valid_until": int(valid_until), + "intent": intent, "note": str(note or "")[:200]} + if strategy_type is not None: + if strategy_type not in ("subjective_quant", "micro_rotation"): + raise CodecError("BAD_PARAM", "未知策略类型") + payload["strategy_type"] = strategy_type + return payload def cancel_order_payload(*, cancel_id: str, instruction_id: str) -> dict: diff --git a/app/repo/pms_repo.py b/app/repo/pms_repo.py index c94c31d..1c9bba5 100644 --- a/app/repo/pms_repo.py +++ b/app/repo/pms_repo.py @@ -486,6 +486,17 @@ def add_instruction_exec(instruction_id: str, qty: int) -> int: {"q": int(qty), "iid": instruction_id, "ts": _NOW()}) +def compare_review_instruction(old, progress, status): + """单表条件更新;复核与用户撤销、回放成交互斥,不覆盖并发变化。""" + return execute('UPDATE pms_instruction SET status=:st, progress_json=:pg, ' + 'limit_price=NULL, updated_at=:ts WHERE instruction_id=:iid ' + 'AND status=:old_st AND exec_qty=:eq AND progress_json=:old_pg', + {'st': status, 'pg': _dumps(progress), 'ts': _NOW(), + 'iid': old['instruction_id'], 'old_st': old['status'], + 'eq': int(old.get('exec_qty') or 0), + 'old_pg': old.get('progress_json') or _dumps(old.get('progress') or {})}) + + # ================================================================ pms_proposal def insert_proposal(*, proposal_id, ts_code, action, qty, hard_numbers, expire_at, judge_verdict=None, judge_reason=None, status="WAIT_USER") -> int: diff --git a/app/repo/qmt_repo.py b/app/repo/qmt_repo.py index bd6be52..04b7a9d 100644 --- a/app/repo/qmt_repo.py +++ b/app/repo/qmt_repo.py @@ -417,8 +417,17 @@ def claim_order(instruction_id: str) -> bool: return bool(n) +def mark_send_attempt(instruction_id: str) -> bool: + """发送前持久标记可能已发出;进程崩溃或网络超时后不能按未发单释放占用。""" + return bool(execute("UPDATE pms_qmt_order SET sent_at = :ts, updated_at = :ts " + "WHERE instruction_id = :iid AND status = 'SENDING' " + "AND cancel_state = 'NONE'", {"iid": instruction_id, "ts": _NOW()})) + + def mark_sent(instruction_id: str) -> int: - return execute("UPDATE pms_qmt_order SET status = 'SENT', sent_at = :ts, " + # 回报可能在 send() 返回前已被消费,不能把 ACCEPTED/PARTIAL/终态写回 SENT。 + return execute("UPDATE pms_qmt_order SET status = CASE WHEN status = 'SENDING' " + "THEN 'SENT' ELSE status END, sent_at = :ts, " "send_attempts = send_attempts + 1, updated_at = :ts " "WHERE instruction_id = :iid", {"iid": instruction_id, "ts": _NOW()}) @@ -439,7 +448,7 @@ def requeue_order(instruction_id: str, error: str = "", max_attempts: int = 3, "status = CASE WHEN send_attempts + :inc >= :mx THEN 'SEND_FAILED' " " ELSE 'QUEUED' END, " "send_attempts = send_attempts + :inc, " - "reject_reason = :err, updated_at = :ts WHERE instruction_id = :iid", + "reject_reason = :err, updated_at = :ts WHERE instruction_id = :iid AND status = 'SENDING'", {"iid": instruction_id, "mx": int(max_attempts), "err": str(error)[:300], "inc": 1 if count_attempt else 0, "ts": _NOW()}) @@ -460,7 +469,7 @@ def abort_order(instruction_id: str, note: str) -> int: now = _NOW() return execute("UPDATE pms_qmt_order SET status = 'ABORTED', reject_code = 'LOCAL_ABORT', " "reject_reason = :nt, final_at = :ts, updated_at = :ts " - "WHERE instruction_id = :iid", + "WHERE instruction_id = :iid AND status IN ('QUEUED','SENDING') AND sent_at IS NULL", {"iid": instruction_id, "nt": str(note)[:300], "ts": now}) @@ -488,6 +497,14 @@ def request_cancel(*, parent_id: str, cancel_id: str) -> int: f"AND cancel_state = 'NONE' AND status IN ({_in_clause(list(LIVE), 'lv', p)})", p) +def request_order_cancel(instruction_id: str, cancel_id: str, note: str) -> int: + """只收回这张可能已经发出的委托,不能用本地作废代替QMT确认。""" + p = {'iid': instruction_id, 'cid': cancel_id, 'nt': note[:300], 'ts': _NOW()} + return execute("UPDATE pms_qmt_order SET cancel_state='REQUESTED', cancel_id=:cid, " + "cancel_req_at=:ts, note=:nt, updated_at=:ts WHERE instruction_id=:iid " + f"AND cancel_state='NONE' AND status IN ({_in_clause(list(LIVE), 'lv', p)})", p) + + def next_cancel_requests(limit: int = 20) -> list: p = {"n": int(limit)} return fetch_all( diff --git a/app/scheduler.py b/app/scheduler.py index 4d4f3d2..590a585 100644 --- a/app/scheduler.py +++ b/app/scheduler.py @@ -244,6 +244,8 @@ def intraday_exec(): """ from app.services import executor, proposal_service, strategy_runner r = {"materialized": executor.materialize_plans()} + from app.services import daily_buy_review + r["daily_buy_review"] = daily_buy_review.process() r["proposals"] = proposal_service.scan_and_route() r["strategies"] = strategy_runner.tick() # 个股交易方案: 触发即发短窗口指令, 由下面 run_tick 执行 # 过期收口改为每分钟一次 (原来只在 15:10 日结跑) —— 让过了窗口/deadline 的单当即作废, diff --git a/app/services/command_service.py b/app/services/command_service.py index 35e61ee..92829c3 100644 --- a/app/services/command_service.py +++ b/app/services/command_service.py @@ -27,7 +27,7 @@ from app.services import industry, param_store, portfolio logger = logging.getLogger("pms.command") # 在途 (可被撤销/冲突判定) 的指令状态 -LIVE_INSTR = ("PROPOSED", "RULE_PASSED", "JUDGE_PASSED", "DISPATCHED") +LIVE_INSTR = ("PROPOSED", "RULE_PASSED", "JUDGE_PASSED", "DISPATCHED", "WAIT_REVIEW") STOCK_PARAM_TYPES = ("FREEZE_STOCK", "UNFREEZE_STOCK", "T0_ENABLE", "T0_DISABLE", "SET_STOP_PRICE", "SET_TARGET_PRICE", "BLACKLIST_ADD", "BLACKLIST_REMOVE", diff --git a/app/services/daily_buy_review.py b/app/services/daily_buy_review.py new file mode 100644 index 0000000..cd5d619 --- /dev/null +++ b/app/services/daily_buy_review.py @@ -0,0 +1,312 @@ +"""跨日买入复核:停止旧单、等待真实回报、重走当日决策,再开放当日额度。""" +from copy import deepcopy +from datetime import datetime +import hashlib + +from app.db.session import transaction +from app.repo import pms_repo, qmt_repo +from app.services import param_store + +LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') + + +def _day(value): + try: + return int(str(value)[:10].replace('-', '')) + except (TypeError, ValueError): + return 0 + + +def applies(ins): + return bool(ins and ins.get('side') == 'buy' + and (ins.get('progress') or {}).get('execution_profile') != 'rotation') + + +def _command_blocker(ins): + cid = (ins.get('progress') or {}).get('command_id') + if cid: + cmd = pms_repo.get_command(cid) + if not cmd or cmd['status'] not in ('EXECUTING', 'PARTIAL'): + return '来源命令已经结束,不能恢复旧买入安排' + return None + + +def blocker(ins, *, now=None): + if not applies(ins): + return None + if ins.get('status') == 'WAIT_REVIEW': + return '跨日买入尚未完成当日决策复核' + if not param_store.get_bool('PMS_DAILY_BUY_REVIEW', False): + return None + stopped = _command_blocker(ins) + if stopped: + return stopped + today = _day(now or datetime.now()) + prog = ins.get('progress') or {} + if prog.get('deadline') and _day(prog['deadline']) < today: + return '买入安排已过有效期,不能继续续单' + review = prog.get('daily_review') or {} + if review.get('ymd') == today and review.get('status') == 'approved': + return None + decision_day = prog.get('decision_ymd') or _day(ins.get('created_at')) + if decision_day != today: + return '旧买入安排需按当日候选、研判、数量和价格重新复核' + return None + + +def _orders(ins): + """不把终态当作零成交;出口与账本尚未一致时禁止重开额度。""" + rows = qmt_repo.orders_for_parent(ins['instruction_id']) + if len({r['instruction_id'] for r in rows}) != len(rows): + raise ValueError('出口子单重复,等待核对') + filled = 0 + for row in rows: + qty, done = int(row['qty']), int(row.get('cum_qty') or 0) + if qty <= 0 or not 0 <= done <= qty: + raise ValueError('出口数量无效,等待核对') + filled += qty if row['status'] == qmt_repo.OS_FILLED else done + return rows, filled + + +def allowance(ins, *, now=None): + if not applies(ins): + return max(0, int(ins['qty']) - int(ins.get('exec_qty') or 0)) + if blocker(ins, now=now): + return 0 + review = (ins.get('progress') or {}).get('daily_review') or {} + if review.get('ymd') != _day(now or datetime.now()) or review.get('status') != 'approved': + return max(0, int(ins['qty']) - int(ins.get('exec_qty') or 0)) + rows, filled = _orders(ins) + pending = sum(int(r['qty']) - int(r.get('cum_qty') or 0) + for r in rows if r['status'] not in qmt_repo.FINAL) + consumed = max(filled, int(ins.get('exec_qty') or 0)) - int(review['start_filled']) + return max(0, int(review['qty']) - max(0, consumed) - pending) + + +def _save(old, progress, status, reason, *, proposal=None, decision=None, arbiter='system'): + """所有状态推进均比较旧状态、旧进度及成交量;不能复活用户已撤销的指令。""" + with transaction(): + changed = pms_repo.compare_review_instruction(old, progress, status) + if not changed: + return False + if proposal and decision: + if not pms_repo.decide_proposal(proposal['proposal_id'], decision, + expected_hard=proposal['hard_numbers_json']): + raise RuntimeError('确认建议已变化,本次复核推进已回滚') + recorded = pms_repo.insert_ledger(ts_code=old['ts_code'], action='DAILY_REVIEW', arbiter=arbiter, + verdict='PASS' if status == 'PROPOSED' else 'WAIT' if status == 'WAIT_REVIEW' else 'REJECT', + price_at=0, hard_numbers=progress.get('daily_review'), reason=reason, + ref_id=old['instruction_id']) + if not recorded: + raise RuntimeError('复核留痕失败,状态推进已回滚') + if status == 'PROPOSED' and arbiter == 'system' and (progress['daily_review'].get('self_decide') or {}).get('decision') == 'accept': + counted = pms_repo.insert_ledger(ts_code=old['ts_code'], action=old['action'], arbiter='system', + verdict='PASS', price_at=0, hard_numbers=progress['daily_review'], + reason=pms_repo.SYSTEM_ACCEPT_REASON_PREFIX + '跨日完整复核通过', ref_id=old['instruction_id']) + if not counted: + raise RuntimeError('当日自动采纳计数失败,状态推进已回滚') + return True + + +def _hold(ins, now, reason): + prog = deepcopy(ins.get('progress') or {}) + previous = prog.get('daily_review') or {} + if previous: + prog['daily_review_history'] = (prog.get('daily_review_history', []) + [previous])[-20:] + prog['daily_review'] = {'ymd': _day(now), 'status': 'pending', 'reason': reason} + # 同一日人工维护后重核也不能复用旧执行价。 + for key in ('exec_advice', 'ref_lock', 'last_decision'): + prog.pop(key, None) + if _save(ins, prog, 'WAIT_REVIEW', reason): + return pms_repo.get_instruction(ins['instruction_id']) + return None + + +def _end(ins, reason, now, *, proposal=None, decision=None, arbiter='system'): + prog = deepcopy(ins.get('progress') or {}) + prog['daily_review'] = {'ymd': _day(now), 'status': 'ended', 'reason': reason} + return _save(ins, prog, 'EXPIRED', reason, proposal=proposal, decision=decision, arbiter=arbiter) + + +def _basis(candidate): + h = candidate.get('hard_numbers') or {} + # 价格由执行层重新咨询;成交前仍过实时规则闸。研究/账户变化不能复用人工确认。 + from app.core.plan_revision import fingerprint + return fingerprint({'qty': candidate['qty'], 'action': candidate['action'], + 'code': candidate['ts_code'], 'basis': h.get('plan_basis'), + 'params': h.get('scan_params_hash'), 'portfolio': h.get('portfolio_context_hash'), + 'risk': h.get('risk'), 'consensus': h.get('consensus')}) + + +def _invalidate_confirmation(ins, p, now): + prog = deepcopy(ins.get('progress') or {}) + reason = '当日依据已变化,后台重新准备买入建议' + prog['daily_review'] = {'ymd': _day(now), 'status': 'pending', 'reason': reason} + return _save(ins, prog, 'WAIT_REVIEW', reason, proposal=p, decision='EXPIRED') + + +def _approve(ins, result, now, *, proposal=None, arbiter='system', reason=None): + if _command_blocker(ins): + return False + rows, filled = _orders(ins) + if any(r['status'] not in qmt_repo.FINAL for r in rows) or filled != int(ins.get('exec_qty') or 0): + return False + c = result['candidate'] + qty = min(int(c['qty']), int(ins['qty']) - int(ins.get('exec_qty') or 0)) + if qty <= 0: + return False + prog = deepcopy(ins.get('progress') or {}) + reason = reason or '已通过当日完整决策复核,执行前重新确定限价' + prog['daily_review'] = {'ymd': _day(now), 'status': 'approved', 'qty': qty, + 'start_filled': int(ins.get('exec_qty') or 0), 'at': now.isoformat(), 'reason': reason, + 'basis': _basis(c), 'candidate': c, 'verdict': result['verdict'], + 'self_decide': result.get('self_decide')} + for key in ('exec_advice', 'ref_lock', 'last_decision'): + prog.pop(key, None) + return _save(ins, prog, 'PROPOSED', reason, proposal=proposal, + decision='ACCEPTED' if proposal else None, arbiter=arbiter) + + +def _queue(ins, result, now): + c, verdict = result['candidate'], result['verdict'] + prog = deepcopy(ins.get('progress') or {}) + # 按当次准备内容编号;重启复用,依据变化可以生成新版本。 + digest = hashlib.sha256((ins['instruction_id'] + _basis(c)).encode()).hexdigest()[:18] + pid = f'PRP_DAILY_{_day(now)}_{digest}' + reason = c.get('confirm_why') or verdict.get('reason') or '今日买入需按原确认规则重新确认' + hard = dict(c.get('hard_numbers') or {}, kind='daily_review', daily_parent=ins['instruction_id'], + daily_basis=_basis(c), daily_ymd=_day(now), daily_verdict=verdict, + preparation={'status': 'ready'}, proposal_revision=digest, reason=reason) + prog['daily_review'] = {'ymd': _day(now), 'status': 'confirmation', 'proposal_id': pid, + 'reason': reason} + with transaction(): + if not _save(ins, prog, 'WAIT_REVIEW', reason): + return False + if not pms_repo.get_proposal(pid): + inserted = pms_repo.insert_proposal(proposal_id=pid, ts_code=ins['ts_code'], action=ins['action'], + qty=c['qty'], hard_numbers=hard, expire_at=now.replace(hour=15, minute=0, second=0), + judge_verdict=verdict.get('verdict'), judge_reason=reason[:500]) + if not inserted: + raise RuntimeError('复核确认建议未保存,状态推进已回滚') + return True + + +def process(*, now=None): + from app.services import dispatcher, proposal_service + now = now or datetime.now() + out = {'held': [], 'approved': [], 'queued': [], 'ended': [], 'waiting': [], 'errors': []} + if not param_store.get_bool('PMS_DAILY_BUY_REVIEW', False): + return out + # 先停完所有旧任务,再进行可能耗时的研判;未处理到的也不能从下发出口绕过。 + for row in pms_repo.list_instructions(statuses=list(LIVE), side='buy', limit=500): + if not applies(row) or not blocker(row, now=now): + continue + try: + review = (row.get('progress') or {}).get('daily_review') or {} + if row['status'] != 'WAIT_REVIEW' or review.get('ymd') != _day(now): + held = _hold(row, now, blocker(row, now=now)) + if held: + out['held'].append(row['instruction_id']) + except Exception as e: + out['errors'].append(f"{row['instruction_id']}: {e}") + reviewed = 0 + for row in pms_repo.list_instructions(statuses=['WAIT_REVIEW'], side='buy', limit=500): + if not applies(row): + continue + iid = row['instruction_id'] + try: + orders, filled = _orders(row) + if any(o['status'] not in qmt_repo.FINAL for o in orders): + cancelled = dispatcher.cancel(instruction_id=iid, dispatch_ref=row.get('dispatch_ref')) + if not cancelled.get('ok'): + out['errors'].append(f'{iid}: 旧委托撤销未受理') + out['waiting'].append(iid) + continue + if filled != int(row.get('exec_qty') or 0): + out['waiting'].append(iid) # 等回放,不将通道累计数写成账本成交。 + continue + prog = row.get('progress') or {} + stopped = _command_blocker(row) + if stopped: + if _end(row, stopped, now): + out['ended'].append(iid) + continue + if (prog.get('deadline') and _day(prog['deadline']) < _day(now)) or prog.get('origin') == 'strategy': + if _end(row, '昨日买入安排结束;后续按当日策略重新生成', now): + out['ended'].append(iid) + continue + state = prog.get('daily_review') or {} + if state.get('status') == 'confirmation' and state.get('ymd') == _day(now): + p = pms_repo.get_proposal(state['proposal_id']) + if p and p['status'] == 'WAIT_USER' and not proposal_service.is_expired(p, now): + continue + if _end(row, '当日复核确认未完成,旧买入安排结束', now): + out['ended'].append(iid) + continue + if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False) or param_store.get_bool('PMS_GLOBAL_BUY_HALT', False): + out['waiting'].append(iid) + continue + if reviewed >= 1: + break + reviewed += 1 + result = proposal_service.scan_and_route(now=now, review_instruction=row) + if result.get('errors') or not result.get('ok'): + out['errors'].extend(result.get('errors') or [f'{iid}: 当日决策资料未就绪']) + continue + fresh = result.get('review') + if fresh: + # 模型响应期间上游可能换榜或账户成交。再走同一候选流程,不能只验证旧票仍有报告。 + checked = proposal_service.scan_and_route(now=now, review_instruction=row, + prepared_verdict=fresh['verdict']) + current = checked.get('review') + if checked.get('errors') or not current or _basis(current['candidate']) != _basis(fresh['candidate']): + out['waiting'].append(iid) + continue + fresh = current + changed = _approve(row, fresh, now) if fresh['auto_exec'] else _queue(row, fresh, now) + if changed: + out['approved' if fresh['auto_exec'] else 'queued'].append(iid) + else: + # 未通过不带昨日任务继续。后续条件转好仍由正常扫描产生新建议。 + reasons = [r.get('why') or ';'.join(r.get('failed') or []) + for r in result.get('rejected', []) + result.get('skipped', []) + if r.get('ts_code') in (None, row['ts_code']) and not r.get('informational')] + reason = '当日复核未通过:' + (';'.join(filter(None, reasons)) or '不在当日可执行候选中') + if _end(row, reason[:500], now): + out['ended'].append(iid) + except Exception as e: + out['errors'].append(f'{iid}: {e}') + return out + + +def decide_confirmation(p, decision, reason, revision=None, *, now=None): + """人工入口不调用模型,只在当前候选/账户依据未变时使用当日已准备结论。""" + from app.services import proposal_service + now = now or datetime.now() + h = p.get('hard_numbers') or {} + ins = pms_repo.get_instruction(h.get('daily_parent')) + if decision == 'ACCEPTED' and p['status'] == 'ACCEPTED': + return {'ok': True, 'already_accepted': True, 'instruction_id': h['daily_parent']} + if (not ins or ins['status'] != 'WAIT_REVIEW' or p['status'] != 'WAIT_USER' + or h.get('daily_ymd') != _day(now) or proposal_service.is_expired(p, now) + or revision != h.get('proposal_revision')): + return {'ok': False, 'error': '今日复核建议已变化或过期,请刷新'} + orders, filled = _orders(ins) + if any(o['status'] not in qmt_repo.FINAL for o in orders) or filled != int(ins.get('exec_qty') or 0): + return {'ok': False, 'error': '旧委托或成交尚未核对完成'} + if decision == 'DECLINED': + changed = _end(ins, reason, now, proposal=p, decision=decision, arbiter='user') + else: + if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False) or param_store.get_bool('PMS_GLOBAL_BUY_HALT', False): + return {'ok': False, 'error': '用户已暂停买入或执行'} + result = proposal_service.scan_and_route(now=now, review_instruction=ins, + prepared_verdict=h['daily_verdict']) + fresh = result.get('review') + if result.get('errors'): + return {'ok': False, 'error': '当日资料暂不可用,恢复后再确认'} + if not fresh or _basis(fresh['candidate']) != h['daily_basis']: + pending = _invalidate_confirmation(ins, p, now) + return {'ok': False, 'pending': pending, 'error': '当日依据已变化,后台重新准备买入建议'} + changed = _approve(ins, fresh, now, proposal=p, arbiter='user', reason=reason) + return {'ok': bool(changed), 'decision': decision, 'instruction_id': ins['instruction_id'], + **({} if changed else {'error': '指令已变化,本次未恢复买入'})} diff --git a/app/services/dispatcher.py b/app/services/dispatcher.py index bda206f..8c107c2 100644 --- a/app/services/dispatcher.py +++ b/app/services/dispatcher.py @@ -156,7 +156,9 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr pid = _parent_of(instruction_id, parent_id) parent = pms_repo.get_instruction(pid) stopped = pms_repo.instruction_buy_stop(pid) - blocked = ('清仓已终止原买入安排' if stopped or ((parent or {}).get('progress') or {}).get('stopped_by_exit') else buy_blocker(ts_code)) + from app.services import daily_buy_review + review_block = daily_buy_review.blocker(parent) if parent else None + blocked = review_block or ('清仓已终止原买入安排' if stopped or ((parent or {}).get('progress') or {}).get('stopped_by_exit') else buy_blocker(ts_code)) if parent and parent.get('status') not in ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED'): blocked = '来源买入指令已结束,不再发单' if blocked: @@ -203,6 +205,21 @@ def _parent_of(instruction_id: str, parent_id=None) -> str: return tail[0] if len(tail) == 2 and tail[1].isdigit() else iid +def order_strategy_type(parent_id: str) -> str: + """下单报文按持久父指令的账本归类,不用备注、当前阶段或调用上下文猜测。""" + if not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return "subjective_quant" # 未启用分策略账本的既有实例只有主观量化。 + from app.core import strategy_book as books + from app.repo import pms_repo + with books.scope('all'): + parent = pms_repo.get_instruction(parent_id) + types = {books.ORIGINAL: "subjective_quant", books.MICRO: "micro_rotation"} + book = (parent or {}).get('book_id') + if book not in types: + raise RuntimeError('委托的策略来源无法核实') + return types[book] + + def _ws(*, instruction_id, ts_code, side, qty, limit_price, valid_until, intent=None, parent_id=None, note=None) -> dict: """ws 直连: 落出口队列即返回, 实际发送由 pms-ws 常驻进程完成。 @@ -268,11 +285,21 @@ def cancel(*, instruction_id: str, dispatch_ref=None) -> dict: except Exception as e: logger.exception("撤单请求落表失败 %s", instruction_id) return {"ok": False, "mode": m, "error": f"{type(e).__name__}: {e}"} + pending = bool(n) + if not pending: + try: + pending = any(o.get('status') in qmt_repo.LIVE + for o in qmt_repo.orders_for_parent(instruction_id)) + except Exception: + # 撤销意图已写入。展示核验失败不能使父任务继续新增或恢复续单。 + pending = True + logger.warning('撤单请求已登记,子委托状态暂不可核实 %s', instruction_id) if not n: - return {"ok": True, "mode": m, "cancelled": 0, - "note": "该指令名下没有在途子单, 仅本地置撤销"} + return {"ok": True, "mode": m, "cancelled": 0, "cancel_pending": pending, + "note": "撤单已在处理中,等待QMT终态" if pending else "该指令名下没有在途子单, 仅本地置撤销"} note = f"已标记 {n} 张在途委托待撤 (cancel_id={cancel_id})" ch = channel_status() if not ch["online"]: note += f"; 连接当前 {ch['conn_state']}, 重连后发出" - return {"ok": True, "mode": m, "cancelled": n, "cancel_id": cancel_id, "note": note} + return {"ok": True, "mode": m, "cancelled": n, "cancel_pending": pending, + "cancel_id": cancel_id, "note": note} diff --git a/app/services/exec_advisor.py b/app/services/exec_advisor.py index ce9f7e4..782cfd3 100644 --- a/app/services/exec_advisor.py +++ b/app/services/exec_advisor.py @@ -191,7 +191,10 @@ def _qmt_limit(*, side, action, ts_code, now, day, params, is_last_day, urgent, return result(et.ACT_WAIT, "无有效行情或已停牌,等待核实") if left <= 0: return result(et.ACT_WAIT, et.quota_wait_reason(urgent, is_last_day)) - if not et.in_session(et.hm_to_min(now)): + now_min = et.hm_to_min(now) + if now_min >= et.CLOSE_MIN: + return result(et.ACT_WAIT, "已收盘,今日不再新增委托") + if not et.in_session(now_min): return result(et.ACT_WAIT, "非交易时段") strategy = (prog or {}).get("origin") == "strategy" and (prog or {}).get("stype") in ("GRID", "TRAIL") diff --git a/app/services/execution_conflicts.py b/app/services/execution_conflicts.py index a5da2d8..1ea5a09 100644 --- a/app/services/execution_conflicts.py +++ b/app/services/execution_conflicts.py @@ -1,7 +1,7 @@ """统一执行方向检查。只消解既有指令冲突,不重做研究或择时。""" from app.repo import pms_repo, qmt_repo -LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED') +LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') BUY_ACTIONS = ('OPEN', 'FILL', 'ADD', 'DCA') @@ -51,7 +51,8 @@ def _queued_parent_check(row, parent): return '清仓已终止原买入安排' if parent.get('status') not in LIVE: return '来源买入指令已结束,未发出的委托作废' - return buy_blocker(row['ts_code']) + from app.services import daily_buy_review + return daily_buy_review.blocker(parent) or buy_blocker(row['ts_code']) def enforce_exit(ins): @@ -141,6 +142,14 @@ def instruction_progress(rows): label = '等待买入条件' if row.get('side') == 'buy' else '等待卖出条件' else: label = '等待执行' + review = (row.get('progress') or {}).get('daily_review') or {} + if row.get('status') == 'WAIT_REVIEW' and not active: + 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.get('progress') or {}).get('last_decision') or {}).get('reason')) row['execution_label'] = label row['execution_stage'] = stage except Exception: diff --git a/app/services/executor.py b/app/services/executor.py index 50dc84d..b4135e6 100644 --- a/app/services/executor.py +++ b/app/services/executor.py @@ -36,7 +36,7 @@ logger = logging.getLogger("pms.exec") ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED = "PROPOSED", "RULE_PASSED", "DISPATCHED" ST_CONFIRMED, ST_REJECTED, ST_EXPIRED, ST_CANCELLED = ("CONFIRMED", "REJECTED", "EXPIRED", "CANCELLED") -LIVE = (ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED) +LIVE = (ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED, "WAIT_REVIEW") # 方案状态: GATED = 建仓的补足/加仓批, 等动作引擎按条件解锁 (DDL 注释已同步) PLAN_PENDING, PLAN_GATED, PLAN_EXEC, PLAN_DONE = "PENDING", "GATED", "EXECUTING", "DONE" @@ -104,6 +104,9 @@ def materialize_plans(limit: int = 100) -> dict: or param_store.get_int("PMS_EXEC_WINDOW_TDAYS", 3)) prog0 = {"deadline": str(p.get("deadline") or ""), "command_id": cid, "is_command": True, "children": []} + # 旧方案今天才物化也不能冒充当日决策。 + from app.services.daily_buy_review import _day + prog0['decision_ymd'] = _day(p.get('created_at') or cmd.get('issued_at')) provenance = next((x for x in (cmd.get('progress') or {}).get('plan_provenance', []) if x.get('plan_id') == p['plan_id']), None) if provenance: @@ -209,7 +212,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: if not cancelled.get('ok'): out['errors'].append(cancelled.get('message') or '清仓停止买入尚未完成') continue - blocked = execution_conflicts.buy_blocker(code) + from app.services import daily_buy_review + blocked = daily_buy_review.blocker(ins, now=now) or execution_conflicts.buy_blocker(code) if blocked: prog['last_decision'] = {'at': now.strftime('%H:%M'), 'action': 'WAIT', 'reason': blocked} if not dry_run: @@ -219,6 +223,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: # 回放与下发是两个任务。出口已成交时,exec_qty 可能还没更新, # 不能把「已终态、不在途」误当成「父指令还有额度」。 available = _parent_available(ins, children) + if side == 'buy': + available = min(available, daily_buy_review.allowance(ins, now=now)) if available <= 0: reason = '父指令额度已由成交或在途委托占用,等待回报入账或撤单确认' prog['last_decision'] = {'at': now.strftime('%H:%M'), 'action': 'WAIT', 'reason': reason} @@ -361,13 +367,22 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: pms_repo.update_instruction(ins["instruction_id"], progress=prog) continue + dl_min = order_deadline(now, d, ttl_min=order_ttl) + if dl_min <= et.hm_to_min(now): + # 收盘边界可能刚收到旧单终态,不能因此再生成有效期已到的子单。 + reason = '已到委托截止时间,今日不再新增委托' + prog['last_decision'] = {'at': now.strftime('%H:%M'), 'action': et.ACT_WAIT, 'reason': reason} + if not dry_run: + pms_repo.update_instruction(ins['instruction_id'], progress=prog) + out['waited'].append({'instruction_id': ins['instruction_id'], 'code': code, + 'action': et.ACT_WAIT, 'reason': reason}) + continue if dry_run: out["fired"].append({"instruction_id": ins["instruction_id"], "code": code, "qty": qty, "limit": d["limit_price"], "reason": d["reason"], "dry_run": True}) continue - dl_min = et.slice_deadline(now, ttl_min=order_ttl, forced=d.get("forced", False)) # intent / parent_id / note 是 ws 通道要的 (协议 §4.2): intent 只作归类, # parent_id 让子单能回指父指令, note 原样落到 QMT 侧供人工看盘。 # shadow 模式忽略这三项, 传着不碍事 —— 两种模式共用同一个调用点。 @@ -437,6 +452,8 @@ def sweep_windows(*, now=None) -> dict: pms_repo.update_plan(ins["origin_id"], filled_qty=exec_qty, status=PLAN_DONE if remaining <= 0 else None) out["synced"] += 1 + if ins.get('status') == 'WAIT_REVIEW': + continue # 复核任务自行处理截止日及撤单,不能提前释放在途数量。 if remaining <= 0: pms_repo.update_instruction(ins["instruction_id"], status=ST_CONFIRMED) continue @@ -479,10 +496,8 @@ def cancel_instruction(instruction_id: str, reason: str = "页面人工撤销", return {"ok": False, "error": f"指令处于 {ins['status']}, 不可撤销"} r = dispatcher.cancel(instruction_id=instruction_id, dispatch_ref=ins.get("dispatch_ref")) or {} - # **下游没撤成就不能在本端标 CANCELLED。** 原来 r 拿到手却从不检查, 一律回「已撤销」 - # 并把父指令置终态 —— 而终态之后没有任何东西再跟踪它, 下游那张委托继续挂着、继续成交, - # 成交回来还会因为找不到在途父指令而变成孤儿。撤不掉就保持在途, 让它继续被择时/收口/ - # 对账看见, 由人再处理。 + # ok 只表示撤单意图已落表。父指令停止新增,子委托仍按QMT回报跟踪, + # 在途占用及迟到成交不因父指令 CANCELLED 而清除。 if not r.get("ok"): logger.error("[撤单] 下游未受理 %s: %s —— 指令保持在途, 下游委托可能仍挂着", instruction_id, r.get("error") or r) @@ -500,10 +515,21 @@ def cancel_instruction(instruction_id: str, reason: str = "页面人工撤销", pms_repo.insert_ledger(ts_code=ins["ts_code"], action=ins.get("action"), arbiter=arbiter, verdict="REJECT", price_at=0, ref_id=instruction_id, reason=reason, hard_numbers=(ins.get('progress') or {}).get('plan') or {}) - return {"ok": True, "downstream": r, "message": f"指令 {instruction_id} 已撤销"} + pending = dispatcher.mode() == dispatcher.MODE_WS and bool(r.get('cancel_pending')) + return {"ok": True, "downstream": r, "cancel_pending": pending, + "message": (f"指令 {instruction_id} 已停止新增,撤单处理中,已成交部分仍会入账" + if pending else f"指令 {instruction_id} 已撤销")} # ================================================================ 内部 +def order_deadline(now, decision, *, ttl_min): + # 仅作用于普通执行器的QMT价格监控路径。轮换、网格和做T各自决定有效期。 + day_order = (decision.get('qmt_price_monitor') + and param_store.get_bool('PMS_EXEC_QMT_DAY_ORDER', False)) + return et.slice_deadline(now, ttl_min=ttl_min, + forced=bool(decision.get('forced') or day_order)) + + def _pos_of(view: dict, ts_code: str) -> dict: for x in view["positions"]: if x["ts_code"] == ts_code: diff --git a/app/services/param_store.py b/app/services/param_store.py index b28d42d..2d02e87 100644 --- a/app/services/param_store.py +++ b/app/services/param_store.py @@ -40,6 +40,7 @@ SECRET_KEYS = ("PMS_QMT_SIGN_SEED_HEX", "PMS_QMT_PEER_PUBKEY_B64", "PMS_SESSION_ # 运行态开关: key -> (默认值, 类型, 说明) RUNTIME_EXTRA = { + "PMS_DAILY_BUY_REVIEW": (False, bool, "跨日买入先撤旧委托,再按当日候选、研判、数量和价格完整复核;未通过不得续单"), 'PMS_ROTATION_MODE': ('observe', str, '微盘轮换模式:observe观察、paper独立纸面、auto自动。自动须通过验收门槛'), 'PMS_ROTATION_SIM_DIRECT': (False, bool, '155模拟仓直接启用,取消观察及纸面等待;保留账本、资金、数据、权限和用户控制检查'), 'PMS_ROTATION_MONITOR_URL': ('', str, '微盘监控只读接口根地址,留空停用拉取'), @@ -280,6 +281,7 @@ DESC = { "PMS_DISPATCH_MODE": "下发通道: shadow=只记账待人工 / ws=WebSocket 直连 QMT (需先起 pms-ws)", "PMS_EXEC_SLICES": "当日配额分几笔出手", "PMS_ORDER_TTL_MIN": "单笔挂单有效期 (交易分钟), 到点下游自动撤; 兜底单不受限", + "PMS_EXEC_QMT_DAY_ORDER": "普通QMT限价单当日有效,最晚15:00撤单;不改变微盘和网格的执行窗口", "PMS_SELL_BUCKET_TIMES": "卖出分桶收口时点 (逗号分隔, 如 11:30,14:00): 桶内照旧择价, 桶收口无条件补齐该桶份额, 把跌日的强制卖出从 14:45 一根针分散到多个时点; 留空=不分桶回到旧行为", "PMS_URGENT_SELL_DISCOUNT": "紧急卖出限价系数 (一键清仓/高置信风控清仓直通出手, 比兜底 0.998 更激进, 每分钟按新现价重定)", "PMS_RISK_WARN_ENTRY": "单笔敞口告警线 (占规模)", "PMS_RISK_WARN_PORTFOLIO": "组合敞口告警线", diff --git a/app/services/plan_recheck.py b/app/services/plan_recheck.py index 4ace2e9..29d144b 100644 --- a/app/services/plan_recheck.py +++ b/app/services/plan_recheck.py @@ -193,6 +193,8 @@ def refresh_pending(*, now=None, deadline=None): legacy_on = param_store.get_bool('PMS_PLAN_VERSION_RECHECK', False) rows = pms_repo.list_proposals(statuses=('WAIT_USER',), limit=200) for p in rows: + if (p.get('hard_numbers') or {}).get('kind') == 'daily_review': + continue # 关联旧父指令的当日复核由 daily_buy_review 维护。 if not legacy_on and (p.get('hard_numbers') or {}).get('candidate_source') != 'dividend': continue if p.get('action') != 'OPEN' or (p.get('hard_numbers') or {}).get('kind') == 'strategy' or ps.is_expired(p, now): diff --git a/app/services/proposal_service.py b/app/services/proposal_service.py index 7f7cf2b..2cee9ba 100644 --- a/app/services/proposal_service.py +++ b/app/services/proposal_service.py @@ -63,9 +63,11 @@ def _macro_gate() -> dict: return {} -def scan_and_route(*, now=None, dry_run: bool = False) -> dict: +def scan_and_route(*, now=None, dry_run: bool = False, review_instruction=None, prepared_verdict=None) -> dict: """自主提议扫描一轮。dry_run=True 只出候选与判定, 不落任何表。""" now = now or datetime.now() + if review_instruction is not None: + dry_run = True out = {"ok": True, "autonomy": None, "open_autonomy": None, "candidates": 0, "open_candidates": 0, "executed": [], "queued": [], "rejected": [], "skipped": [], "errors": [], "degraded": False, "dry_run": dry_run, @@ -137,7 +139,8 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: # 「今日系统已判放弃,明日重评」。off 时 _system_declined_today_keys 返回空, 逐字回旧。 skip = {**_jk, **_rejected_today_keys(), **_declined_today_keys(), **_system_declined_today_keys(), - **_inflight_keys()} + **(_inflight_keys(exclude_instruction=review_instruction["instruction_id"]) + if review_instruction else _inflight_keys())} # 挂了 ACTIVE 交易方案(策略)的票交策略层接管, 动作引擎不再对它自动提议 # (读库失败按空集 —— 宁可这轮不排除, 也不能因读不到把全体持仓都排除) try: @@ -210,12 +213,15 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: # ---- 新建仓: 候选池那一路 (取不到候选池不影响上面四类, 反之亦然) ---- open_cands = [] + review_source = (((review_instruction or {}).get('progress') or {}).get('plan') or {}).get('candidate_source') if open_autonomy == AUTONOMY_OFF: out["skipped"].append({"action": ae.A_OPEN, "why": "新建仓档位 off, 不扫描候选池"}) else: try: open_cands = _scan_open(view, params, stock_params, skip, mkt, out, now=now, - record_consumption=not dry_run) + record_consumption=not dry_run, + **({'candidate_source': 'dividend'} if review_source == 'dividend' else {}), + **({'review_instruction': review_instruction} if review_instruction else {})) except Exception as e: logger.exception("新建仓扫描失败") out["errors"].append(f"新建仓扫描失败: {type(e).__name__}: {e}") @@ -235,6 +241,29 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: deadline = time.monotonic() + max( 0, param_store.get_int("PMS_JUDGE_TICK_BUDGET_SEC", 150)) + if review_instruction is not None: + old = review_instruction + fresh = next((c for c in list(scanned['candidates']) + open_cands + if c['ts_code'] == old['ts_code'] and c['action'] == old['action']), None) + if not fresh: + return {**out, 'review': None} + remaining = max(0, int(old['qty']) - int(old.get('exec_qty') or 0)) + fresh['qty'] = min(int(fresh['qty']), remaining) + if fresh['qty'] <= 0: + return {**out, 'review': None} + fresh['_plan_recheck'] = True + fresh['judge_required'] = True + fresh.setdefault('hard_numbers', {}).update(qty=fresh['qty'], daily_parent=old['instruction_id']) + result = _route_one(fresh, view, params, stock_params, brake_active, now, True, out, + deadline=deadline, review_only=True, prepared_verdict=prepared_verdict) + if result: + result['candidate']['qty'] = min(int(result['candidate']['qty']), remaining) + result['candidate']['hard_numbers']['qty'] = result['candidate']['qty'] + if review_source == 'dividend': + # 原人工选定的独立来源不得因跨日复核升级为自主选股。 + result.update(auto_exec=False, force_queue=True) + return {**out, 'review': result} + for group_index, group in enumerate((list(scanned['candidates']), open_cands)): if group_index == 1 and not dry_run: from app.services.plan_recheck import refresh_pending @@ -316,7 +345,8 @@ def _save_tech_exit_done(codes) -> None: # ================================================================ 新建仓的取数与筛选 def _scan_open(view, params, stock_params, skip, mkt, out, now=None, - review_code=None, exclude_proposal=None, record_consumption=True, candidate_source='plan') -> list: + review_code=None, exclude_proposal=None, record_consumption=True, candidate_source='plan', + review_instruction=None) -> list: """候选池 → 新建仓候选。产出的候选数天生不超过剩余名额 (名额与金额在纯逻辑里边走边扣)。 与命令驱动那条路 (command_service._candidates) 有意不同的两点: @@ -359,6 +389,8 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, # 拿不到 ≠ 今天没票可买。显式留痕, 本轮不产新建仓候选, 已有持仓的四类照常。 logger.error("[新建仓] 候选池取数失败, 本轮不建仓: %s", e) out["skipped"].append({"action": ae.A_OPEN, "why": f"候选池取不到, 本轮不建仓: {e}"}) + if review_instruction: + out['errors'].append('当日候选资料未就绪,跨日任务继续等待') return [] # 仅展示的票逐只写跳过原因: disposition_snapshot 复用本函数, 页面「系统在盯的候选」 # 由此显示「选股系统判为仅展示」而不是一个说不清的空白。 @@ -368,6 +400,12 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, out["skipped"].append({"ts_code": row.get("ts_code"), "action": ae.A_OPEN, "why": ae.display_only_why(row)}) items = list(sel.get("items") or []) + if review_instruction: + code = review_instruction['ts_code'] + pending = (sel.get('refresh_status') or {}).get('pending_codes') or [] + if not (sel.get('decision') or {}).get('id') or code in pending or code.replace('.', '') in pending: + out['errors'].append('当前研究资料未就绪,跨日买入继续等待') + return [] if review_code: items = [x for x in items if x['ts_code'] == review_code] if not items: @@ -377,6 +415,9 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, out.setdefault('user_monitor_codes', []).extend(x['ts_code'] for x in items if x.get('user_candidate')) codes = [x["ts_code"] for x in items] prices = market.get_prices(codes) + if review_instruction and review_instruction['ts_code'] in codes and not prices.get(review_instruction['ts_code']): + out['errors'].append('当日有效行情缺失,跨日买入继续等待') + return [] # 行业名一次批量取, 本轮复用。滚动扣减要算行业集中度, 所以必须先有它 —— # caps_ctx 对**从没持仓过**的票带不出行业名, 不显式传的话 sizer.check_caps 遇到 # sector 为空会整段跳过, 行业集中度那道硬拦截就静默失效了。 @@ -399,12 +440,14 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, # 名额与金额都要扣掉**在途的建仓承诺** (2026-08-28 审查修): names_count 只数已成交 # 持仓, 在途 OPEN 指令与等拍板的 OPEN 提议两头都不占 —— 候选没进买入区间时指令滞留 # 在途, 下一跳名额照旧又放两只, 几分钟就把持仓数上限击穿。同票去重挡不住换一只票。 - if candidate_source == 'dividend': + if review_instruction: + inflight = _inflight_open_commitments(view, exclude_proposal=exclude_proposal, + exclude_instruction=review_instruction['instruction_id'], strict=True) + elif candidate_source == 'dividend': inflight = _inflight_open_commitments(view, exclude_proposal=exclude_proposal, strict=True) cands = [c for c in cands if c['ts_code'] not in inflight['names']] else: - inflight = (_inflight_open_commitments(view, exclude_proposal=exclude_proposal) - if exclude_proposal else _inflight_open_commitments(view)) + inflight = _inflight_open_commitments(view, exclude_proposal=exclude_proposal) slots = int(p["max_names"] or 0) - int(t["names_count"] or 0) - len(inflight["names"]) room = float(p["portfolio_cap"] or 0) * float(p["scale"] or 0) \ - float(t["portfolio_mv"] or 0) - inflight["amount"] @@ -420,6 +463,8 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, if str(t.get("cash_source") or "") == portfolio.CASH_WS and t.get("cash_avail") is not None: room = min(room, float(t["cash_avail"])) elif param_store.get_bool("PMS_OPEN_REQUIRE_WS_CASH", True): + if review_instruction: + out['errors'].append('最新账户资金未就绪,跨日买入继续等待') out["skipped"].append({"action": ae.A_OPEN, "why": f"读不到券商账户的可用资金,这一轮不开新仓;" f"已持有的票照常处理。" @@ -616,7 +661,7 @@ def _no_candidate_why(sel) -> str: return head + ":" + ",".join(parts) + "。" -def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dict: +def _inflight_open_commitments(view, exclude_proposal=None, strict=False, exclude_instruction=None) -> dict: """在途的新建仓承诺: names 为代码集合,amount 为预估占用,basis 为稳定核验依据。 口径: 在途 (LIVE) 的 OPEN 指令 + 等拍板 (WAIT_USER) 的 OPEN 提议, 只算**尚未持有** @@ -629,6 +674,8 @@ def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dic rows = [] try: for i in pms_repo.list_instructions(statuses=list(executor.LIVE), limit=300): + if exclude_instruction and i['instruction_id'] == exclude_instruction: + continue if i.get("action") == ae.A_OPEN and i["ts_code"] not in held: rows.append((i["ts_code"], int(i.get("qty") or 0), None)) basis.append(('instruction', str(i.get('instruction_id') or ''), @@ -641,6 +688,8 @@ def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dic for pr in pms_repo.list_proposals(statuses=("WAIT_USER",), limit=200): if exclude_proposal and pr.get('proposal_id') == exclude_proposal: continue + if exclude_instruction and (pr.get('hard_numbers') or {}).get('daily_parent') == exclude_instruction: + continue if pr.get("action") == ae.A_OPEN and pr["ts_code"] not in held: hn = pr.get("hard_numbers") or {} rows.append((pr["ts_code"], int(pr.get("qty") or 0), @@ -1046,7 +1095,8 @@ def _route_one(c, view, params, stock_params, brake_active, now, dry_run, out, c['hard_numbers'].update(judge_verdict=verdict.get('verdict'), judge_conf=verdict.get('confidence'), price=price, reason=c['reason']) - return {'candidate': c, 'verdict': verdict} + return {'candidate': c, 'verdict': verdict, 'auto_exec': auto_exec, 'force_queue': force_queue, + 'self_decide': sd} if dry_run: (out["executed"] if auto_exec else out["queued"]).append( @@ -1665,7 +1715,7 @@ def _declined_today_keys() -> dict: return keys -def _inflight_keys() -> dict: +def _inflight_keys(exclude_instruction=None) -> dict: """已有在途提议或在途指令的 {(代码, 动作): 原因} —— 同一件事不重复提。 提议与指令分开写原因, 并且**指令写在后面覆盖提议**: 一条提议被采纳之后会变成指令, @@ -1685,14 +1735,22 @@ def _inflight_keys() -> dict: keys.setdefault((code, buy), '该股有减持安排待处理,暂不新增买入提议') try: for p in pms_repo.list_proposals(statuses=("WAIT_USER",), limit=200): + if exclude_instruction and (p.get('hard_numbers') or {}).get('daily_parent') == exclude_instruction: + continue _mark(p["ts_code"], p["action"], f"已有在途提议 {p.get('proposal_id')} 在等人确认") except Exception as e: + if exclude_instruction: + raise logger.warning("读提议队列失败: %s", e) try: for i in pms_repo.list_instructions(statuses=list(executor.LIVE), limit=300): + if i['instruction_id'] == exclude_instruction: + continue _mark(i["ts_code"], i.get("action"), f"已有在途指令 {i.get('instruction_id')} ({i.get('status')})") except Exception as e: + if exclude_instruction: + raise logger.warning("读在途指令失败: %s", e) return keys diff --git a/app/services/rotation_service.py b/app/services/rotation_service.py index 1ff77eb..65e6b6c 100644 --- a/app/services/rotation_service.py +++ b/app/services/rotation_service.py @@ -11,7 +11,7 @@ from app.repo import pms_repo, qmt_repo, rotation_repo as store from app.services import param_store, portfolio, market TZ = ZoneInfo('Asia/Shanghai') -LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED') +LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') TERMINAL = qmt_repo.FINAL diff --git a/app/services/strategy_advisor.py b/app/services/strategy_advisor.py index 2dacf3d..43ac1ba 100644 --- a/app/services/strategy_advisor.py +++ b/app/services/strategy_advisor.py @@ -852,7 +852,7 @@ def _has_pending(st) -> bool: ins = pms_repo.get_instruction(iid) except Exception: # noqa: BLE001 return False - return bool(ins and ins.get("status") in ("PROPOSED", "RULE_PASSED", "DISPATCHED")) + return bool(ins and ins.get("status") in ("PROPOSED", "RULE_PASSED", "DISPATCHED", "WAIT_REVIEW")) def _snap(a, hv, p) -> dict: diff --git a/app/services/strategy_runner.py b/app/services/strategy_runner.py index 626d35a..cd37990 100644 --- a/app/services/strategy_runner.py +++ b/app/services/strategy_runner.py @@ -55,7 +55,7 @@ from app.services import market, param_store, portfolio logger = logging.getLogger("pms.strategy") # 指令在途 (未终态) 的状态集 —— 与 executor.LIVE 一致; 本层据此判断「上一笔还没走完, 先别再发」。 -LIVE_INS = ("PROPOSED", "RULE_PASSED", "DISPATCHED") +LIVE_INS = ("PROPOSED", "RULE_PASSED", "DISPATCHED", "WAIT_REVIEW") # 批次动作 (与 recon.ACTION_TO_LOT 对齐) A_T0 = "T0_ROUND" # 做T 买入与卖出 → T0 批次 diff --git a/app/web/main.py b/app/web/main.py index 5044b12..0978652 100644 --- a/app/web/main.py +++ b/app/web/main.py @@ -444,12 +444,17 @@ def api_lots(ts_code: str, status: str = Query("OPEN"), @app.get("/api/instructions") def api_instructions(status: str = Query(None), limit: int = 200, - include_archived: bool = Query(False)): + include_archived: bool = Query(False), + book_id: Literal["original", "micro30"] = Query("original")): statuses = [s for s in (status or "").split(",") if s] or None def _list(): + from app.core import strategy_book as books from app.services.execution_conflicts import instruction_progress - return instruction_progress(pms_repo.list_instructions(statuses=statuses, limit=limit, - include_archived=include_archived)) + if book_id == books.MICRO and not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return [] + with books.scope(book_id): + return instruction_progress(pms_repo.list_instructions(statuses=statuses, limit=limit, + include_archived=include_archived)) return ok(_list) @@ -564,6 +569,9 @@ def api_decide(request: Request, proposal_id: str, payload: dict = Body(default= p = pms_repo.get_proposal(proposal_id) if not p: return {"ok": False, "error": "提议不存在"} + if (p.get('hard_numbers') or {}).get('kind') == 'daily_review': + from app.services.daily_buy_review import decide_confirmation + return decide_confirmation(p, decision, reason, payload.get('proposal_revision')) if (decision == 'ACCEPTED' and p['status'] == 'ACCEPTED' and p['action'] == 'OPEN' and (p.get('hard_numbers') or {}).get('kind') != 'strategy'): existing = pms_repo.accepted_open_instruction(proposal_id) @@ -787,11 +795,18 @@ def api_sweep_windows(): @app.post("/api/instructions/{instruction_id}/cancel") -def api_cancel_instruction(instruction_id: str, payload: dict = Body(default={})): +def api_cancel_instruction(instruction_id: str, payload: dict = Body(default={}), + book_id: Literal["original", "micro30"] = Query("original")): + from app.core import strategy_book as books from app.services import executor - return ok_logged("cancel_instruction", executor.cancel_instruction, instruction_id, + def _cancel(iid, reason): + if book_id == books.MICRO and not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return {"ok": False, "error": "微盘轮动账本尚未启用"} + with books.scope(book_id): + return executor.cancel_instruction(iid, reason) + return ok_logged("cancel_instruction", _cancel, instruction_id, payload.get("reason") or "页面人工撤销", - params={"instruction_id": instruction_id}) + params={"instruction_id": instruction_id, "book_id": book_id}) @app.post("/api/ops/scan-proposals") diff --git a/app/web/static/index.html b/app/web/static/index.html index 6e79b93..3be8af3 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -368,6 +368,10 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} 状态芯片一行、「下一步」短语一行放下, 具体说明进悬停。 */ .position-tabs > .el-tabs__header{margin-bottom:8px;} .position-tabs .tabn{margin-left:6px;} +.instruction-books .el-tabs__item{padding:0 14px;} +.instruction-status > .el-tabs__header{margin-bottom:8px;} +.instruction-status .el-tabs__item{font-size:12px;height:32px;padding:0 9px;} +.instruction-status .el-tabs__nav-wrap::after{height:0;} .book-heading{display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;margin:10px 0;} .book-heading .book-stat{font-size:12px;color:var(--muted);} .postbl .el-scrollbar__wrap{overflow-x:auto;} @@ -1194,19 +1198,25 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} -
+

当日指令

-
今天下发的买卖单,按进展分档
- +
在办买卖安排及今日成交;跨日买入须重新复核
+ + + + + + + - - - + + + @@ -1226,7 +1236,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;} - +
未建仓候选
@@ -2009,11 +2019,17 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}
-
+

在途指令 显示已了结

- + + + + + + +