Compare commits
102 Commits
main
...
codex/qmt-
| Author | SHA1 | Date |
|---|---|---|
|
|
47914fede9 | |
|
|
f756344082 | |
|
|
a520fcc426 | |
|
|
67b02779ec | |
|
|
34087b51e8 | |
|
|
6a33bfcf55 | |
|
|
c8634646df | |
|
|
bf5e3edd91 | |
|
|
eef9cb5211 | |
|
|
84eb934295 | |
|
|
017ead5f77 | |
|
|
f50449d0bd | |
|
|
484aa2a879 | |
|
|
af681bbb75 | |
|
|
0b3c50ef34 | |
|
|
76d7043e4c | |
|
|
f4b4f3e62a | |
|
|
ba2745bb98 | |
|
|
a85bc3d70d | |
|
|
56db0fddda | |
|
|
2b1c447b51 | |
|
|
9bc94eb4b3 | |
|
|
ebef980980 | |
|
|
b8037d52b2 | |
|
|
522a46b2b8 | |
|
|
5b75adea85 | |
|
|
bd938b21ae | |
|
|
8dc744da62 | |
|
|
36d6ad7c0d | |
|
|
e033aafabd | |
|
|
381ddf836c | |
|
|
1d73431f04 | |
|
|
4059b6f1ba | |
|
|
7ff397ba22 | |
|
|
39d209a6e4 | |
|
|
b798c1f38e | |
|
|
401b538317 | |
|
|
e62fd606e7 | |
|
|
d1375b111a | |
|
|
15a4f10ddf | |
|
|
6702090264 | |
|
|
c72556901e | |
|
|
da7574eaa1 | |
|
|
12b9c22e2a | |
|
|
5a3d29a2d3 | |
|
|
265bf2871c | |
|
|
5081080b7a | |
|
|
5dd0783640 | |
|
|
d91424a457 | |
|
|
7ecf3a9394 | |
|
|
a0f7f79462 | |
|
|
06570aded8 | |
|
|
b96ce9fba6 | |
|
|
c882819097 | |
|
|
579be3141b | |
|
|
2877c59e9d | |
|
|
4d4663be18 | |
|
|
8c79c4610d | |
|
|
bf2cce4d2c | |
|
|
b2148a1901 | |
|
|
37ceaf6a6c | |
|
|
894da1a6a4 | |
|
|
875a9fc7cb | |
|
|
e337df608d | |
|
|
089e5ec5fb | |
|
|
c57ed900e2 | |
|
|
c51fb7fbd4 | |
|
|
9e14f92834 | |
|
|
cb7edc26f4 | |
|
|
f7c10e36a9 | |
|
|
02837fae94 | |
|
|
40608fd2c3 | |
|
|
596c1ceaa1 | |
|
|
5e1ae075e3 | |
|
|
38cbc19d30 | |
|
|
c9ad9f3d5e | |
|
|
378af8f16d | |
|
|
4500865e42 | |
|
|
b5637b6598 | |
|
|
f1424f3c55 | |
|
|
daee515f8f | |
|
|
316d31d694 | |
|
|
14b79019ad | |
|
|
ce46285d46 | |
|
|
c7ae169030 | |
|
|
966daeef9e | |
|
|
f6ecb206ec | |
|
|
14a22462e6 | |
|
|
dcd21e9dd2 | |
|
|
7a5026a9fc | |
|
|
bdfb608c9f | |
|
|
1d534d95e5 | |
|
|
f0224049bc | |
|
|
49d1a99917 | |
|
|
98a58d165a | |
|
|
9d1e455792 | |
|
|
85b76c2402 | |
|
|
c0f67f7dfa | |
|
|
a7bcd8a28f | |
|
|
c994409e52 | |
|
|
c00df0c139 | |
|
|
e13740e85e |
|
|
@ -0,0 +1,29 @@
|
|||
---
|
||||
name: pms-qmt-diagnose
|
||||
description: 排查PMS与QMT连接、验签拒绝、序号缺口、委托失联或成交对账异常,整理双方联调证据。正常页面开发和策略研究不触发。
|
||||
---
|
||||
|
||||
# PMS与QMT联调排障
|
||||
|
||||
先读[QMT协议](../../../QMT_WS_PROTOCOL.md)及[开发入口](../../../docs/开发入口.md)指向的最新状态。历史地址、空仓、暂停或SIG_INVALID记录只能作线索,不能作为当前故障结论。沿用会话授权,不扩大实例范围。
|
||||
|
||||
## 建立当前事实
|
||||
|
||||
1. 标明采样时间及换算依据,核对实际端点、唯一连接进程、dispatch模式、表前缀、用户暂停和resync。读取连续确认、最高已收、暂存缺口及最近消息;ONLINE只是连接状态。
|
||||
2. 区分PMS验证上行签名失败、QMT发出的SIG_INVALID、旧消息补发和当前新拒绝。记录产生时间、实际收到时间、type、msg_id、seq和关联请求。不能仅凭拒绝文案推断请求来自本PMS。
|
||||
3. 委托问题逐层查命令、父指令、子委托、出口状态、QMT受理号、成交及入账。计划量不等于已发送量,受理不等于成交;先核实最新在途状态,不因页面旧文案补单。
|
||||
4. 查看新账户资金及持仓快照、待处理消息和待归属成交,将两策略合计与QMT核对。发现通道或账本故障按现有守成机制处理,保留证据。
|
||||
|
||||
## 需要双方材料时
|
||||
|
||||
只收集覆盖问题时段的日志和相关函数,不要求对方发整个仓库或完整环境文件。材料包括:实际部署提交与进程入口;连接ID和来源IP;失败请求及其拒绝的生成、入库、入队和发送链路;双方公钥指纹与规范串摘要;消息序列、回放和确认存储的环境隔离方式。
|
||||
|
||||
不要索取私钥。原始签名报文如含敏感业务数据,留在受控位置;共享版脱敏,并注明修改过的报文不能直接用于验签。未经用户明确要求,不向外部发送材料。既有材料结构可参考[10月27日联调包](../../../docs/联调材料/QMT验签与序号缺口_2026-10-27/README.md),只按需要读取。
|
||||
|
||||
若需断连隔离或被动抓包,先完成只读定位,定义最小范围、停止条件和恢复步骤,在已有授权内执行。不能另开竞争WS连接,不能通过忽略签名、重置序号或反复重连消除表面症状。
|
||||
|
||||
## 恢复判定
|
||||
|
||||
连续确认随新消息推进、暂存缺口清零、无新验签拒绝或被动断线后,再核验新资金、在途和待处理回报及账户对账。确认恢复并留痕后才清resync;仅恢复本次维护设置、且未被用户新命令覆盖的暂停。
|
||||
|
||||
交付区分已观察事实、推断、对方自述及待提供证据。保留“旧实例干扰”一类假设,直到来源和部署证据齐全;短时健康不等于历史根因已经查明。
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
---
|
||||
name: pms-release
|
||||
description: 发布PMS代码或策略规则到已授权实例,并核验运行与回退条件。用于部署、升级、重建服务;普通代码编辑、回测和文档整理不触发。
|
||||
---
|
||||
|
||||
# PMS发布与核验
|
||||
|
||||
从仓库[开发入口](../../../docs/开发入口.md)找到当前任务的部署记录。授权沿用根目录规则与会话,不因本技能新增确认,也不把既有155授权扩大到188或无关系统。
|
||||
|
||||
## 发布前
|
||||
|
||||
- 核对目标主机、项目路径、表前缀、dispatch模式、用户暂停、实际镜像与挂载。读取当前服务有效配置,不用旧`.env`替换现用配置;密钥和私有覆盖文件不导出到Git或报告。
|
||||
- 查看本机及服务器差异、拟发布提交和在途任务。先完成代码提交,构建可追溯镜像;需要拉取时检查是否夹带其他未获发布安排的提交。服务器私有修改保留。
|
||||
- 选择受影响服务,不为版本整齐重建无关容器。涉及worker时避开当前任务或温和排空;涉及WS时确保旧进程结束后才启动唯一新连接。
|
||||
- 在开发机完成相应验证,再对服务器候选镜像进行断网、无业务配置的全量回归。不得连接运行库做单测。页面变化按页面目录规则另验收。
|
||||
|
||||
在部署服务器对本次构建的候选镜像执行,替换下列占位名;预期末行为`ALL SUITES PASS`:
|
||||
|
||||
```bash
|
||||
docker run --rm --network none --cpus 1 --memory 512m --read-only --tmpfs /tmp:rw,size=128m CANDIDATE_IMAGE python scripts/run_tests.py
|
||||
```
|
||||
|
||||
## 实施与判收
|
||||
|
||||
- 备份实际配置、镜像和必要数据,记录操作意图及回退条件。迁移先在隔离库演练,再核对实际代理的事务与锁行为;跨策略数量、现金、成本和历史归属不能只验表存在。
|
||||
- 源码在镜像中,更新代码必须构建并force-recreate受影响服务。`make deploy`会拉取、重建和建表,确认整套动作适用后才使用;定向发布沿用该实例私有覆盖配置。`restart`不是代码发布方式。
|
||||
- 策略参数经ParamStore读写。版本、快照、目标数量与在手轮次需匹配;盘中改规则不倒填08:50冻结,不用旧版本快照执行新策略。接入档位遵循用户最新决定,不额外设置观察天数。
|
||||
- 核验实际镜像、启动时间、配置、页面健康、自然调度和实际回执。交易链路还须检查连续确认、缺口、最新资金、在途、待入账及策略合计对账,不能只看容器运行或ONLINE。需要定位异常时再读[pms-qmt-diagnose](../pms-qmt-diagnose/SKILL.md)。
|
||||
- 不注入虚假信号或测试委托制造验收。分开记录隔离回放、本地浏览器复现、真机实际发生与未判收;未出现自然切换就如实保留待办。
|
||||
|
||||
## 回退与交付
|
||||
|
||||
失败时先停止新增风险动作,保留账本和在途回报。回退前检查已产生的成交、数据迁移及绑定规则,不能直接倒退表结构、覆盖新历史或把持仓强行切回旧版本。记录具体阻塞与恢复条件。
|
||||
|
||||
在DEVLOG和本阶段接续中写明提交、镜像、北京时间、实际动作、验证机器和证据、未完成事项。仅文档或离线研究产物更新不因此重启业务容器;已通过的检查不为凑次数重复运行。
|
||||
|
|
@ -3,9 +3,15 @@
|
|||
__pycache__
|
||||
*.pyc
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
backups/
|
||||
logs
|
||||
.DS_Store
|
||||
# 开发代理的本地配置和嵌套工作树不进入运行镜像。
|
||||
.claude
|
||||
.codex
|
||||
.agents
|
||||
|
||||
# 历史实验数据不打进交易运行镜像。
|
||||
research/
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@
|
|||
# 业务参数 (PMS_TOTAL_SCALE 等) 不必写在这里 —— settings.py 有初值,
|
||||
# 上线后经管理页面调整并持久化到 pms_runtime_param 表。
|
||||
|
||||
# 限制价采集密钥PMS_TUSHARE_TOKEN必须仅写入专用.env.market-data,不要放进主.env。
|
||||
# 该专用文件只由pms-market-data服务注入,不提交Git,也不放进镜像。
|
||||
# 缓存消费和采集开关默认关闭,业务运行值经ParamStore维护。
|
||||
|
||||
# ---- 153 代理 (pms_* 全部表 + trading_* + strategy_daily_results, 严格单表访问) ----
|
||||
PROXY_DB_URL=mysql+pymysql://用户:密码@192.168.16.153:3307/my_quant_db
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
# 机密: 数据库/Redis 连接串与密码, 绝不入库 (服务器上手工维护, 参照 .env.example)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
backups/
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
|
|
|||
162
AGENTS.md
162
AGENTS.md
|
|
@ -1,148 +1,38 @@
|
|||
# AGENTS.md
|
||||
# 项目工作规则
|
||||
|
||||
本文件是 Codex 在本仓库工作的项目指令,也是项目开发规则的唯一维护入口。`CLAUDE.md` 保留兼容入口,指向本文件。
|
||||
用可读中文沟通和写文档,句子完整,少用符号和自造缩写。PMS负责命令、数量和账本;bionic负责研判与择时;QMT负责委托成交。
|
||||
|
||||
用可读中文沟通和写文档。写完整句子,一句一事,少用符号,不自造缩写。术语先用白话解释。命令和表格内部不受此限。这些规则直接保存在本文件,不依赖开发机上缺失的输出风格文件。
|
||||
## 研究、分析与交易范围
|
||||
|
||||
## 接续开发从哪里开始
|
||||
北交所证券一律排除在本项目的研究、分析、回测、选股及交易范围之外。“全市场”“全部股票”也不包含北交所,须在沪深范围内按当次资格条件取样。按交易所信息和规范化证券代码在数据读取或样本构建入口排除,不为北交所额外导出数据、补资料、核验异常或生成交易动作。历史材料中已包含的北交所结果仅保留归档,不作为继续开展相关工作的依据。
|
||||
|
||||
当前接续记录是 `docs/开发接续_2026-10-12.md`。接手中断的工作时先读它,再按任务查设计文档。它记录了两个 Claude 修复的整合状态、测试隔离方式、尚未执行的探针和部署判收。
|
||||
## 工作流程
|
||||
|
||||
开工先看 `git status --short`、`git worktree list` 和相关提交。已有的未提交文件与其他工作树属于用户正在进行的工作,不覆盖、不清理。判断是否推送要直接核对远程,不凭过期的 `origin/main` 引用下结论。
|
||||
1. 开工先看`git status --short`、`git worktree list`和相关提交。保护已有未提交文件及其他工作树,不覆盖、不清理。新分支用`codex/`前缀;推送状态直接核对远程。
|
||||
2. 从[开发入口](docs/开发入口.md)选择本任务资料,不通读历史日志。修改前读取目标目录及其父目录的适用规则,包括存在的`AGENTS.override.md`;从仓库根目录启动不能假定子目录规则已经自动加载。
|
||||
3. 按影响范围验证。单测必须隔离配置、禁止联网;部署前用候选镜像完成断网回归。页面改动跑三道护栏,布局与交互另做浏览器验收。纯文档修改检查内容和链接即可。
|
||||
4. 在开发机修改,经Git提交后部署,提交说明用简短中文。交付说明改动、验证机器、实际结果和未完成事项。重要节点追加`DEVLOG.md`;当前状态写接续记录,注明核验时间。历史回执不等于当前健康,本地通过不等于真机判收。
|
||||
|
||||
创建新分支时默认用 `codex/` 前缀。旧的 `claude/` 分支仍是有效的 Git 分支,保留名字和工作树即可接续。合并时核对测试文件是否重名,不能让一批测试覆盖另一批。
|
||||
## 授权边界
|
||||
|
||||
历史交接里的服务器状态只代表记录当天。过期的执行日期不会自动变成今天的执行授权。2026-10-12 用户确认先以当前仓库为准,原定 10-09 的两项探针均未执行。
|
||||
- 按当前任务及会话已有授权推进,不因旧文档或技能重复索要许可。当前155模拟PMS的必要服务器、容器、数据库操作及PMS重启已获授权;不扩展为宿主机重启、新的破坏性清账或其他系统的写操作。
|
||||
- 188真实PMS不在本阶段范围内。执行前核对主机、实例表前缀、运行模式及实际镜像。范围不清或确需超出授权时才询问,并说明具体原因。
|
||||
- 用户新增命令和暂停优先于既有计划。已经取消的观察期、旧参数和历史暂停不能重新套用;运行值到ParamStore及实际回执核实。
|
||||
|
||||
## 这是什么
|
||||
## 关键禁区
|
||||
|
||||
这是一套命令驱动的持仓管理系统,代码里和文档里都简称 PMS(Position Management System,持仓管理系统)。它在整条交易链路里只负责一段:用户在管理页面下达大方向命令,例如设定总规模、调仓位上限、升降仓、对某只股票做 T;PMS 据此把命令拆成分股分批的方案,并管理账本(批次、摊薄成本、安全垫、纪律)。
|
||||
- 命令至上。自动动作不得突破用户约束,命令冲突交用户裁决。研判不可用按既定保守规则和人工确认降级,不自建第二套研判。
|
||||
- 先记账后动作,故障守成。指令落表后才下发,以QMT实际持仓对账;不伪造信号、成交、冻结时间或验收结果,不将研究结论自动上线。
|
||||
- QMT只保留一个`pms-ws`连接。禁止扩副本、忽略验签、归零序号或反复重连掩盖缺口。`ONLINE`不代表确认、资金和账本都正常。
|
||||
- 资金占用不得重复计算。成交按委托和策略归属,不跨策略认领,不回灌已归档旧仓。规则版本、快照与在手轮次必须一致。
|
||||
- 业务参数经ParamStore读取。密钥只由环境注入并登记`SECRET_KEYS`,不入库、不进页面、日志或Git。SQL严格单表,跨表数据在服务层组合。
|
||||
- 测试不得连接真实服务或用真实成交补账。新外部依赖补内存桩,不靠吞异常通过测试。
|
||||
- 改Python后必须构建镜像并重建受影响容器,`restart`不能更新代码。先检查实际挂载和私有覆盖文件,不为追平版本重复重启。
|
||||
|
||||
链路上还有另外两个系统,它们不在本仓库里,但 PMS 时时与它们打交道:
|
||||
## 按需入口
|
||||
|
||||
1. 决策系统,代码里叫 bionic。它负责研判(该不该做)与盘中择时(何时做)。PMS 不自建研判栈,研判和择时都可以委托它。
|
||||
2. 下游系统,即 QMT 侧的执行服务。它只负责挂单成交。PMS 经一条 WebSocket 长连接直连它。
|
||||
- 后端分层与数据约束:[app/AGENTS.md](app/AGENTS.md)。前端另读[app/web/AGENTS.md](app/web/AGENTS.md)。
|
||||
- 测试与脚本:[scripts/AGENTS.md](scripts/AGENTS.md)。历史实验:[research/AGENTS.md](research/AGENTS.md)。
|
||||
- 部署时使用[pms-release](.agents/skills/pms-release/SKILL.md);QMT联调或排障时使用[pms-qmt-diagnose](.agents/skills/pms-qmt-diagnose/SKILL.md)。普通改文档不加载这两个技能。
|
||||
|
||||
一句话概括分工:PMS 管「做什么、多少」,决策系统管「该不该、何时」,下游只管执行。
|
||||
|
||||
## 三条铁律(改任何东西前先读)
|
||||
|
||||
这三条写在 README 开头,是整个系统的设计前提,违反它们的改动一律是错的。
|
||||
|
||||
1. 命令至上。自动决策不得突破用户的命令参数;冲突时命令优先;命令之间的冲突交用户裁决。
|
||||
2. 分工不越权。研判不可用时降级为保守规则加人工确认,绝不自建第二套研判。
|
||||
3. 先记账后动作,故障即守成。指令先落表再下发;出了故障不产生新指令;账本与下游定期对账,以下游为实际持仓的事实源。
|
||||
|
||||
## 常用命令
|
||||
|
||||
日常操作都由 `Makefile` 包了一层,`make help` 看全部目标。下面这些是最常用的。所有 `make` 命令都在部署 PMS 的服务器上跑(源码打进容器镜像,本机直接跑 Python 会因为缺少容器环境而对不上)。
|
||||
|
||||
```bash
|
||||
make deploy # 一句话部署:git pull → 重建镜像 → 重建容器(force-recreate)→ 建表
|
||||
make deploy-local # 同上但跳过 git pull(本地已经改好时用)
|
||||
make test # 跑全部单测(不连库,秒级)。应输出 ALL SUITES PASS
|
||||
make watch # 盯盘看这一个:通道/账户/在途指令/出口委托/账本持仓 一屏看完,只读
|
||||
make health # 页面健康检查(配置装载自证 + 库连通自证)
|
||||
make check # 实机连通性与表结构自检(需要真实 .env)
|
||||
```
|
||||
|
||||
跑单元测试有两种粒度。跑全部用 `make test`,它会先比对容器镜像与工作树的代码指纹,对不上就报警(防「git pull 了没重建,跑的还是旧代码而且照样通过」)。只跑某一批时,直接把那个测试文件当脚本跑:
|
||||
|
||||
```bash
|
||||
# 只跑某一批(例:择时实现B 与规则闸那一批)
|
||||
docker compose run --rm --no-deps pms-web python scripts/unit_test_guard.py scripts/test_batch3_units.py
|
||||
```
|
||||
|
||||
每个 `scripts/test_batch*.py` 都是能独立运行的脚本,`scripts/run_tests.py` 只是把它们逐个 subprocess 起来。测试设计为不连接外部服务,服务层用内存桩(见 `scripts/test_wiring.py` 的 `FakeRepo`)。
|
||||
|
||||
**单测必须隔离配置并禁止联网。** `scripts/run_tests.py` 逐批经 `scripts/unit_test_guard.py` 启动,清除业务环境变量,在没有 `.env` 的临时目录运行。各测试文件直接运行时也先安装联网护栏。Python 套接字调用会在连接前被阻断,即使业务代码吞掉异常,整批仍以失败退出。`install_fakes` 已补齐观察读数仓储与扫描中遗漏的外部依赖。新增服务调用必须补内存桩,不能依赖异常降级让测试通过。
|
||||
|
||||
开发机可以在单独虚拟环境安装 `requirements.txt` 后经隔离入口跑全量回归。服务器部署前仍要用匹配镜像的断网容器验证,不能把本地通过称作服务器验收。2026-09-20 留下的四行历史假数据尚未清理,修测试不会自动删除库里的旧记录。
|
||||
|
||||
## 改代码时最容易踩的坑
|
||||
|
||||
**改了 Python 代码必须重建镜像加 force-recreate,绝不能用 `docker compose restart`。** 源码是打进镜像的,`restart` 只是把老容器停了再起,跑的还是旧镜像里的旧代码,而且一点报错都没有。`make deploy` 和 `make up` 走的都是正确路径。这是本项目头号坑,`Makefile` 顶部、`scripts/deploy.sh`、`run_tests.py` 里都反复写了这一条。
|
||||
|
||||
**模拟仓 155 是个例外,要另记(2026-09-20 实测)。** 155 的项目目录里有一个服务器本地文件 `docker-compose.override.yml`,内容同仓库里的 `docker-compose.dev.yml`,它把整个仓库目录绑定挂载到四个容器的 `/app`。这个文件被 `.gitignore` 忽略,仓库里看不到;真实仓 188 没有它。后果有三条。一,在 155 上 `git pull` 之后,页面静态文件立刻就是新的,后端四个进程仍是旧代码,直到重启或 `make deploy`。二,`make test` 与 `make stale` 起的一次性容器读的也是工作树,所以在 155 上「指纹一致」恒成立,查不出「拉了代码没重启」。三,往 155 拉代码等于把页面先上线了,拉之前先看 `git log` 里有没有别的会话提交的、还没到上线日的改动。`make deploy` 在两台机器上都仍是对的做法。
|
||||
|
||||
**下发模式由参数 `PMS_DISPATCH_MODE` 决定,实际以页面顶部横幅为准,不要拿这段文字当现状。** 设置文件的初值是 `shadow`(影子模式:指令照常生成、过规则闸、记账、置为已下发,但不写下游,需人工在 QMT 侧执行,成交由回放任务按先进先出认领回账本)。但模拟仓 155 运行时已切到 `ws`,指令经 `pms-ws` 真向模拟 QMT 发出、自主动作按档位可自动执行,不再需要人工下单。真实仓 188 的 PMS 尚未追平到最新代码,上线等 QMT 侧,追平部署时按真实仓准备包的初始参数清单先进影子期。切换只是 `PMS_DISPATCH_MODE` 与 `PMS_QMT_WS_ENABLED` 两个开关加一次联调,不是再写代码。改动涉及下单链路时,务必先确认自己面对的是哪一套实例、此刻是哪个模式。
|
||||
|
||||
**业务参数一律走 ParamStore 读,不要直接读 settings。** `config/settings.py` 里的业务参数(`PMS_TOTAL_SCALE`、各种档位阈值等)只是「初值」。运行时以数据库表 `pms_runtime_param` 的值为准,页面改参数即时生效。取业务参数统一经 `app/services/param_store.py`,直接读 settings 会让页面调参失效。基础设施类配置(连接串、密钥)才从 settings 与 `.env` 读。
|
||||
|
||||
**密钥只从 `.env` 注入,不入库、不进 ParamStore、不上页面。** 会话密钥、QMT 通道的两把 Ed25519 密钥都属此类。新增密钥类配置时,要同时登记进 `param_store.py` 的 `SECRET_KEYS`,否则它会被当成可调参数暴露到页面快照里。
|
||||
|
||||
## 架构分层
|
||||
|
||||
代码在 `app/` 下按依赖方向分层,越靠上越纯。
|
||||
|
||||
- `app/core/`:纯逻辑,零外部依赖,可单测。系统的算数与纪律都在这里——批次拆分与组合约束(`sizer.py`)、摊薄成本与安全垫状态机(`cushion.py`)、命令目录与校验(`command_spec.py`)、方案生成(`planner.py`)、规则闸终检(`rule_gate.py`)、择时实现B(`exec_timing.py`)、动作引擎(`action_engine.py`)、QMT 协议编解码与签名(`ws_codec.py`)等。改核心逻辑先在这一层,它有最密的单测覆盖。
|
||||
- `app/db/session.py`:三个数据库的连接,外加一道严格单表访问守卫(下面单列一节)。
|
||||
- `app/repo/`:单表数据访问层。每个函数只碰一张表。
|
||||
- `app/services/`:编排层,把 core 的纯逻辑接上 repo 的取数与落表。命令下达在 `command_service.py`,方案转指令与出手在 `executor.py`,下发通道适配器在 `dispatcher.py`,运行参数中心在 `param_store.py`,组合快照在 `portfolio.py`。
|
||||
- `app/ws/runner.py`:常驻的 QMT 连接进程,容器名 `pms-ws`。它只做通道,不碰账本。
|
||||
- `app/web/`:FastAPI 后端加一个单页前端(`static/index.html`,Vue3 加 ElementPlus,无构建步骤)。
|
||||
- `app/scheduler.py`:Celery beat 调度总表与调度守卫。调度位以代码和 `scripts/test_wiring.py` 中的哨兵清单为准。
|
||||
|
||||
进程边界值得单独理解一下。出手的 `executor` 跑在短命的 Celery worker 任务里,而 QMT 连接必须是一条常驻长连接(协议规定 PMS 只准开一条,多开会让指令乱序)。两者只经数据库耦合:worker 把待发委托写进出口表 `pms_qmt_order`,`pms-ws` 进程亚秒轮询取走并签名发出;QMT 的回报落进 `pms_qmt_inbox`,再由回放任务认领进账本。因此 `pms-ws` 这个服务绝不能扩副本。
|
||||
|
||||
三组容器服务:默认起 `pms-web`(管理页面,端口 38100);`--profile sched` 起 `pms-beat` 和 `pms-worker`(调度与执行);`--profile ws` 起 `pms-ws`(QMT 直连)。
|
||||
|
||||
## 严格单表访问守卫
|
||||
|
||||
153 代理库不支持多表联查,写错了要到线上才报错。为把这条纪律钉死,`app/db/session.py` 在每条 SQL 的执行入口做静态检查,出现 JOIN、逗号连表、跨表子查询一律拒绝抛异常。写数据访问代码时,一条 SQL 只能碰一张表;要联的数据在 service 层分两次查再在内存里拼。`upsert` 语句里的 `ON DUPLICATE KEY UPDATE` 是这道守卫的历史误伤点,改 upsert 时留意。
|
||||
|
||||
## 数据库与外部依赖
|
||||
|
||||
三个 MySQL 库(键名与 bionic 对齐,同一份 `.env` 可服务两个系统):`PROXY_DB_URL` 是 153 代理,放 PMS 全部自有表加决策系统结论表;`SOURCE_DB_EXT_DSN` 是因子库,当前 PMS 不用;`DB_MYSQL_URL` 是大盘指数库,只做页面区制提示。建表脚本是 `scripts/init_db.py`,建表语句在 `ddl_pms_v1.sql`。
|
||||
|
||||
Redis 有几路:决策系统的盘中信号流与风控卖出流、实时行情、PMS 自己的 Celery 总线。**`redis` 依赖必须锁在 5.x**:6.x 默认按 RESP3 握手,而现网的 Redis 版本偏旧会回 `unknown command HELLO`,导致行情与调度总线一起断。`requirements.txt` 已锁版本,升级依赖时别放开。
|
||||
|
||||
## 时区口径(很容易读错)
|
||||
|
||||
不能按「哪个系统」一刀切,要按「哪种时间」分。容器时钟与容器日志正文是北京时间,不要加八小时。数据库里的时间戳列(如各种 `created_at`、`updated_at`)是 UTC,读的时候要加八小时。日期列(如 `trade_date`、`audit_date`)是北京日期,不换算。写记录时一律用北京时间,引用数据库时间列先加八小时并标注已换算。完整依据见 `DEVLOG.md` 开头。
|
||||
|
||||
**待核实的例外。** 上段是历史约定。PMS 自有表的部分列实际是 `DATETIME`,`pms_repo.py` 与 `qmt_repo.py` 用容器内 `datetime.now()` 写值。10-08 的两个探针因此提出先用心跳和快照校准时区。用户已确认探针尚未执行,2026-10-12 部署核对已确认 155 宿主机为 UTC,容器为北京时间,`pms_ws_state.heartbeat_at` 的 DATETIME 原值与容器北京时间同步,该字段不加八小时。其他列仍要核对写入路径和实际时区,并明确标注原值与换算依据,不把两种口径混在同一份读数里。
|
||||
|
||||
## 前端的两个坑
|
||||
|
||||
管理页面是无构建步骤的单页,这两个坑都实际炸过页面,都写在 README 里。
|
||||
|
||||
1. 模板里不能用自闭合的自定义标签。`<el-alert .../>` 这种写法浏览器 HTML 解析器不认,会把后面所有内容当成它的子节点;若它带 `v-if` 且条件为假,整页就跟着消失。一律写成 `<el-xxx ...></el-xxx>`。
|
||||
2. `setup()` 里定义给模板用的东西必须真的 `return` 出去。漏一个函数没接出去,用到它的地方会在渲染时报错并白屏。`scripts/test_page_wiring_guard.py` 就是为这个坑加的护栏(2026-09-10 白屏即漏了十一个显示函数所致)。
|
||||
|
||||
页面有三道静态护栏:`scripts/test_page_enum_guard.py`、`scripts/test_page_wiring_guard.py`、`scripts/test_page_copy_guard.py`。改页面后要一起跑,涉及布局和交互时还要浏览器验收。
|
||||
|
||||
页面措辞要专业,不出现内部设计词,不自造简写。同一概念统一用基本面、技术面、择时三种维度。看多用红色,看空用绿色,中性用灰色,无读数用虚框。说明放在悬停里,表格要能在中栏完整显示。
|
||||
|
||||
## 加测试时的登记纪律
|
||||
|
||||
`scripts/run_tests.py` 把「缺一个测试文件」当失败处理,而不是当「跳过」——因为镜像旧了的时候,新加的那批测试正好全部「不存在」,一条没跑却会报全部通过。所以新增一个 `test_batch*.py`,必须同时登记进 `scripts/run_tests.py` 的 `SUITES` 清单和它上面的例数说明表,否则会被判失败。
|
||||
|
||||
代码里还有若干「哨兵断言」,改了对应的东西就得回到那里改断言,断言不动就是漏了。清单写在 `run_tests.py` 顶部的注释里(DDL 表数、调度位、API 路由、密钥名单、动作求值器次序等)。改这些结构性的东西时先去那份清单对一遍。
|
||||
|
||||
## 部署与运维纪律
|
||||
|
||||
在开发机修改代码,通过git提交,然后在服务器上部署
|
||||
|
||||
部署方式与服务器信息以 `DEVLOG.md` 开头那段为准(PMS 跑在哪台机、决策系统与因子桥各在哪、各自怎么生效)。有模拟仓与真实仓两套实例,靠表名前缀(`PMS_TABLE_PREFIX`)与容器名前缀区分,共用同一套代码。对真实仓做写操作前先确认清楚是哪一套。
|
||||
|
||||
服务器上的容器操作偏敏感:不要随意重启或关停容器,涉及容器与数据库的操作先与用户确认,不碰本仓库以外的项目。登录到哪台机、面对的是哪一套实例,不清楚时先问。
|
||||
|
||||
每次交付写明验证命令在哪台机器上运行,以及预期结果。一个命令块只放一台机器的命令。重要节点及时追加到 `DEVLOG.md`,包含做了什么、动了哪些文件、部署方式、真机判收、还欠着什么。判收只写「真机见过」或「未判收」,本地通过不代替真机判收。
|
||||
|
||||
## 文档地图
|
||||
|
||||
仓库根目录有大量设计与交接文档,需要细节时按主题查这几份:
|
||||
|
||||
- `README.md`:总览,最全。上面各节多是从它摘的。
|
||||
- `DEVLOG.md`:开发节点流水账,每条含「做了什么、动了哪些文件、部署方式、真机判收、还欠什么」五样。查某个改动的来龙去脉看这里。
|
||||
- `docs/开发接续_2026-10-12.md`:Claude 到 Codex 的仓库迁移记录、修复整合、155 部署判收和当前待办入口。
|
||||
- `POSITION_MGMT_DESIGN.md`:总体设计定稿。
|
||||
- `QMT_WS_PROTOCOL.md`:PMS 与 QMT 的 WebSocket 协议,下发通道的唯一实现依据。
|
||||
- `BIONIC_PMS_INTERFACE.md`:PMS 与决策系统的接口契约(研判闸与盘中择时两个接口)。
|
||||
- `UPSTREAM_PLAN_API.md`:上游选股计划接口的接入记录,候选池的事实源。
|
||||
- `docs/复盘决定台账.md`:近期改动按「台账」编号推进,提交信息里的台账号对应到这里。
|
||||
|
||||
## 提交约定
|
||||
|
||||
提交信息用简短中文,描述这次改动的行为而非罗列文件。近期工作按台账编号组织,提交里出现的台账号可回到 `docs/复盘决定台账.md` 对照。
|
||||
规则按上述范围维护,不复制多份。`CLAUDE.md`保留原样,停止同步维护;后续修改和提交不要求附带它。最新参数、镜像、故障与实验结果放接续文档,不继续堆入本文件。
|
||||
|
|
|
|||
|
|
@ -182,6 +182,8 @@ PMS 侧对建议价有一道保护:偏离现价超过 `PMS_EXEC_LIMIT_BAND`(
|
|||
|
||||
### 3.4 下一个迭代(本轮明确不做)
|
||||
|
||||
2026-10-28的155模拟接入修订:启用`PMS_EXEC_QMT_PRICE_MONITOR`时,PMS仍使用本接口给出的执行区间,但不采用“现价尚未进入区间”的等待判断。PMS把买入上沿或卖出下沿作为限价直接交QMT。`observed.today_exit`、昨夜回避结论与参考位漂移仍有效,不能把它们误当价格等待。取数失败或区间缺失时等待补齐,不退回现价追单。旧缓存缺少离场字段时先重新咨询;旧模式行为保持。
|
||||
|
||||
凌晨管线加一步大模型推理,对每只票明示写出买入区间与卖出区间,盘中改为直接读它——届时
|
||||
只换本模块第一步的取数来源和 `advisor` 版本标记,应答结构与 PMS 侧都不动。动凌晨管线
|
||||
属于重大迭代,做之前会先出细方案确认(覆盖范围、存放位置、算不出来怎么办)。
|
||||
|
|
@ -325,3 +327,16 @@ docker compose run --rm --no-deps pms-web python scripts/probe_bionic.py --base
|
|||
- `reanchored`(是否做了除权重锚)、`in_pool`(是否在夜间分析池)、`quality`(数据质量,OK 才用)、`bars_used`、`last_bar_date`、`bars_lag`。
|
||||
|
||||
**持仓管理系统侧怎么用。** 存进 pms_tech_daily 保留 40 个交易日;相位合成与五个阈值见该系统台账 006。四种无读数情形(没有当天行、读数超过两个交易日、未除权重锚、数据质量非 OK)一律弃权,绝不折成看空。本接口不改变研判请求体,研判闸的请求一字不变。
|
||||
|
||||
|
||||
## 2026年11月3日:异步研判与执行依据扩展
|
||||
|
||||
旧接口和字段保留。旧同步研判只有请求显式带`async_compat=true`才复用新服务。新接口必须先在bionic发布,PMS才能打开`PMS_JUDGE_ASYNC_ENABLED`及`PMS_EXEC_REPRICE_ENABLED`。
|
||||
|
||||
- 提交:`POST /api/intraday/pms_judge_submit`。原请求追加`request_id`、带时区的`deadline_at`和可选的`evidence_fingerprint`。
|
||||
- 查询:`GET /api/intraday/pms_judge_result/{request_id}`。返回`PENDING/PASS/REJECT/UNAVAILABLE`,携带请求编号、证据指纹、截止时间、缓存标记及理由。`client_scope`区分实例、策略账本及候选来源,参与证据指纹和新旧任务替代范围。请求编号不可绑定第二份证据。PENDING不表示授权,也不立即建人工提议。
|
||||
- PMS先持久化请求再登记。一次网络请求默认3秒,含排队的总截止默认120秒。短暂传输故障在截止前继续查原编号;超时转既有人工确认路径,同证据失败不自动重新投模。成功结果短期复用前仍过当前规则闸。
|
||||
- `pms_exec.execution_basis`含`version/quality/continuation/reason/generated_at/valid_until/source_date/source`。`CONTINUE`仅说明已有授权机会未撤销,不构成首次准入。`STOP`表示新增买入机会明确撤销,`UNKNOWN`表示缺乏有效事实。已授权卖出不以看空或离场结论作为停止卖出的理由。缺字段、无时区和过期均不能继续授权报价。
|
||||
- 执行依据刷新是独立短任务,已挂委托也检查失效。报价不等待模型重新算区间;每次报价记录实际行情来源及时间。当前确认可用源为分钟行情,盘口和停牌状态未知时不得编造。
|
||||
|
||||
完整状态及验收边界见[实施规格](docs/执行报价与异步研判实施规格_2026-11-03.md)。
|
||||
|
|
|
|||
610
DEVLOG.md
610
DEVLOG.md
|
|
@ -1,5 +1,59 @@
|
|||
# 开发节点记录(三系统量化交易)
|
||||
|
||||
## 2026-11-04 沿用原信息流风格并修复研究恢复
|
||||
|
||||
14:34最终只读确认六条买方评析、六条每日及六条盘中研究全部完成,且均匹配当前报告。最后一条守原一小时冷却,于14:33自然重试并在19.39秒内完成。每日数据日为11月3日,盘中为11月4日,实际盘中结论五条观察、一条风险。没有人为重投、改回执或注入交易。当前跟进完成,不新增长期观察;外部分钟采集的历史回填本次未修改。
|
||||
|
||||
最终1440、390像素实际响应复现逐项核验十二个完成结果,无控制台错误、写请求或外联。14:35从188交叉核对新任务和当前来源一致、旧失败保留,最后一股累计3次、全局盘中登记13次,预算未绕过。上述文档和页面规则提交不重建业务服务,产品版本保持实际发布记录。
|
||||
|
||||
14:06:23仅155网页服务发布pms:watch-flow-67b0277。候选完整断网回归通过,实际HTML与开发机一致,其他17容器和私有配置保持。14:07数量现金对账一致,无待入账或孤儿,最近200条回报连续。14:03原五条已全部取得当前报告对应的日研究和盘中结果,六条买方报告均有效;另一条模型故障仍守原14:33冷却。最新真实响应的1440及390像素复现通过,不是真实登录验收。详细版本、证据及后续结果见下方接续。
|
||||
|
||||
用户提供原信号流截图后,再次明确左栏不区分人工关注。改为沿原单行形式,按真实时间混排原信号和必要的研究入口,去掉关注身份标记、研究胶囊及独立只数。原告警不被研究或等待覆盖,没有结果时保留无假时间、无假级别的普通入口。身份、评析进度和完整理由留在原详情。页面开发规则已记录此偏好。1440、390像素真实响应复现及三道页面护栏通过,页面发布结果另记。
|
||||
|
||||
六份买方评析和每日研究均已自然完成。午后分钟数据一度停在11:30,13:33恢复。随后确认辅助模型的空认证头导致一次调用在本地失败,已修复空密钥请求头,并只为明确模型前的数据等待加入原调度恢复。开发机及188候选16组离线回归通过,含38项关注、74项执行与认证头检查;13:48仅更新三个已授权Bionic目标至a689c8f,其余35容器和共享源码环境保持。13:51已有两条自然盘中结果恢复,旧任务和预算保留;详细时间线和未完成项见[后续跟进](docs/人工关注后续跟进与信号融合_2026-11-04.md)。
|
||||
|
||||
## 2026-11-04 人工关注融入原信号界面
|
||||
|
||||
按用户最新要求取消独立人工关注面板,股票及研究进度并入原信号速览、来源组和个股详情。真实研究回执与买卖信号分别计数;关注入口不被消息条数截断,数据读取失败保留带提示的记录,手动刷新同时更新评析与判断依据。每日固定回执说明不冒充完整模型理由。三道页面护栏和1440、390像素浏览器检查通过,六条实际响应复现无写请求、外联或控制台错误。
|
||||
|
||||
11:39:48剩余五份买方评析全部自然完成,11:44已同步到PMS。受理到完成20至25分钟,实际评析约4至5分钟,主要等待来自原队列;178仅只读核验。午间新研究暂停派发,六条中的原一条已有每日及盘中实际结果,其余五条等待13:00后的自然调度。当前尚未发布新页面,后续部署和真实研究判收见[后续跟进与信号融合](docs/人工关注后续跟进与信号融合_2026-11-04.md)。
|
||||
|
||||
## 2026-11-04 11:16 人工关注与吸筹参考发布核验
|
||||
|
||||
155模拟PMS仅web、worker、beat于11:01:20发布pms:watch-bf5e3ed;桥于11:08:27发布bridge:watch-e5696ee。188只更新三个Bionic目标至bionic:watch-963196a,原共享源码e9681e4与原环境保持,真实PMS未动。各候选断网完整回归通过,目标worker排空后温和重建;WS、采集、微盘监控与无关服务保持。配置和逐服务备份见[发布接续](docs/人工关注与吸筹参考发布接续_2026-11-04.md)。
|
||||
|
||||
11:10自然计划修订取消吸筹独立确认,保持质地排序和其他资格风险条件;候选6增至21、关注11增至27,15个晨版摘要不变。6条人工关注全部进入买方评析目标,实际1条有效报告、5条新请求已受理仍排队;上游队列66项,未强制重跑或改上游队列。已有效的1条自然日研究98秒完成,盘中研究16秒完成,真实数据日分别11-03和11-04;PMS显示有效回执,旧历史清池信号未假造恢复。其余5条尚未完成,按既有调度继续,不增长期观察。
|
||||
|
||||
开发机与候选PMS全量、桥35套、Bionic16组均通过;1440和390浏览器夹具、真实6条响应隔离重放通过,零写请求、外联和控制台错误。后者不是实际登录验收。11:16数量现金对账一致、无待入账孤儿、最近200条确认连续,资金3.1秒新鲜;未改账或制造交易验收。仓库只留聚合记录,原始名单与回执在私有临时目录。
|
||||
|
||||
## 2026-11-04 人工关注分析链与吸筹参考规则实现
|
||||
|
||||
按用户确认沿用当前质地排序、吸筹只作参考、建仓看三源合议。人工关注在信号页独立展示,买方评析完成后通过短期有效的独立名单进入每日和盘中研究;关注被移除、版本变化或超时的结果不能覆盖当前状态。选股桥实际提交缺失评析,保留受理和完成的区别;新准入只发布新的计划修订,历史快照不改。Bionic机械清池改为单独记录覆盖,不再修改历史模型信号。研究观察不扩交易白名单,也不直接产生委托。
|
||||
|
||||
开发机PMS全量隔离通过,最终23项专项与页面三道护栏通过;桌面1440和窄屏390浏览器夹具核验观察展开、真实日期、错误状态及关闭刷新,控制台错误、写请求和外部请求均为零。选股桥35套隔离通过,Bionic16组离线通过。实际候选镜像、定向部署及自然回执仍待下一阶段核实;规格见[修复规格](docs/人工关注分析链修复规格_2026-11-04.md)。
|
||||
|
||||
## 2026-11-04 人工关注与七日选股覆盖只读巡检
|
||||
|
||||
10:05至10:15核对155计划发布、实际消费和188 bionic历史信号。人工关注未过期,机械清池却覆盖信号字段及摘要,旧记录被当作当前风险;关注列表和盘中覆盖又依赖交易筛选。七日计划持续更新,完整主榜稳定,但自动候选有28只不同股票,不是名单停更。前300截断漏过43只去重关注股票,未发现七日自动候选被截断;今日候选均已被消费或按持仓排除。
|
||||
|
||||
已记录关注、覆盖、交易资格分离及完整名单消费方案,并保留模型预算、时效和人工确认边界。本次只读,不改规则、参数、历史信号或模型队列。详见[巡检与调整建议](docs/人工关注与选股覆盖巡检_2026-11-04.md)。原始名单与业务证据仅留本地临时目录,仓库只保存聚合结论。
|
||||
|
||||
## 2026-11-04 一次性自然异步与微盘v3核验完成
|
||||
|
||||
10:07至10:09只读核验155模拟PMS。当前页面和worker仍为pms:funds-cost-017ead5,没有新增部署。今日v3快照在08:50:07自然冻结,采用昨晚已生成的版本,PMS于08:51留存。50首选、100候选的范围和摘要检查通过。限制价在08:57:44已覆盖103个当日目标,含完整候选池,10:07仍全部有效。
|
||||
|
||||
已观察到一条自然异步持久记录。模型约25.4秒完成,PMS约54.8秒消费,早于120秒截止。指纹、请求编号与期限核对一致。模型返回证据不足后,系统生成WAIT_USER人工提议,父指令保持WAIT_REVIEW,没有误授权交易。现金和数量对账一致,QMT连续确认,无待入账、孤儿或缺口;费用仍待真实明细,本次未改账。
|
||||
|
||||
自然超时、迟到结果丢弃、撤单重报价及微盘切换仍未判收。既有网格的自然成交不作为这些项目的证据。一次性v3任务已删除,不增加观察期。两仓仅更新接续文档,脱敏材料见[核验摘要](docs/evidence/pms_v3_natural_check_20261104.json),原始业务材料仅留本地临时目录。本次没有改代码或触发新回归、模型请求及测试委托。
|
||||
|
||||
## 2026-11-04 策略缺行情展示和成本精度修复
|
||||
|
||||
09:25在155确认资金提示的ValueError实际为持仓股票缺少盘前分钟行情,数量对账正常;09:30行情自然恢复后现金差0。修改只读估值为逐策略保留未知值,现金、数量继续独立核对,严格划拨和日结健康判断不放宽。成本均价固定显示三位,导出保留原始加权精度并按金额计算盈亏,补零股保护。用户确认比较的是含费成本,而QMT回传成交成本不含费用、费用仍未知,故不改写成交或猜测手续费。自然执行依据刷新还暴露Decimal无法编码,复用既有JSON类型转换修复。
|
||||
|
||||
独立复核还发现公示导出把负向手续费流水再次相减,误加为平仓收益;已在导出边界修正费用和退款方向,保留原账本符号。导出金额采用十进制累计、半分四舍五入,与Excel公式一致;市值与成本分别到分再相减,缺行情按成本顶价时不制造虚假盈亏。新增估值18、精度及费用14、执行依据编码5项隔离检查,页面与全量验证及实际发布结果见[本次接续](docs/策略估值与成本精度修复_2026-11-04.md)。实际发布及真机核验结果见下段。
|
||||
|
||||
09:53:47实际仅重建155 web/worker至pms:funds-cost-017ead5(sha256:17c80fb323a10e73545cf52ccf5cec9a9629678aadd544d49c7f98651a99daed),旧worker排空后切换。开发机和候选断网全量、37专项、页面护栏及1440/390浏览器夹具均通过。09:54数量/现金对账一致、待入账及孤儿无异常,确认连续;既有策略回报在维护前收到,恢复后正常入账,未注入业务动作。真实xlsx三位均价、两位金额、完整计算精度及费用说明已核验,明细仅留本地。13个其他服务保持,另一项目mtf-etf-155三个服务09:52独立重建;原环境和私有配置保持。费用后补尚无安全入口,不调用旧日总额校准,不推算真实费用。原一次性自然核验保持,不新增长期观察。
|
||||
|
||||
> 这份文件的用途只有一个:**让下一次交接不必重新查一遍**。
|
||||
> 每个重要节点写一条,写完就补,不攒到最后。一条节点包含五样东西:
|
||||
> 做了什么、动了哪些文件、部署方式、真机判收结果、还欠着什么。
|
||||
|
|
@ -11,6 +65,7 @@
|
|||
> **2026-09-20 查实的例外**:155 上有服务器本地文件 `docker-compose.override.yml`,把仓库目录绑定挂载到四个容器的 `/app`,
|
||||
> 所以在 155 上 `git pull` 后页面静态文件立刻是新的、后端进程仍旧,`make stale` 在 155 上恒为一致、查不出「拉了没重启」。
|
||||
> 188 没有这个文件,代码确实在镜像里。`make deploy` 在两台机器上都是对的做法。详见 `docs/交接_2026-09-20.md` 第七节。
|
||||
> **2026-10-27更新**:155四服务已取消`/app`源码挂载,恢复从镜像运行。私有覆盖文件固定各自有效环境和镜像,旧配置已备份。后续以`docker inspect`为准,详见微盘30整体部署判收记录。
|
||||
> - **bionic_trader(决策系统)** 跑在 `192.168.16.188:38000`,挂载卷,
|
||||
> `git pull` 后 `docker compose restart backend-api worker-brain` 即生效;
|
||||
> **新增 env 必须 `docker compose up -d --force-recreate`**,restart 不重读 env。
|
||||
|
|
@ -2198,3 +2253,558 @@ QMT在线、对账无差异。午休任务按原时段跳过,不制造交易
|
|||
本次部署文档更新 docs/账户资金口径核查_2026-10-26.md、docs/开发接续_2026-10-12.md 和本条流水账。私有验收证据在 155 的 /home/factor/pms_logs/funds-fix-20261026。回退分支 codex/pre-funds-20261026、镜像 pms:rollback-before-funds-20261026 已保留;155 回退时须同时处理挂载源码与镜像。开发机原有研究、台账及未跟踪文件未纳入本次提交,服务器已有本地文件保留。
|
||||
|
||||
运行态判收为真机见过。浏览器布局先在本地隔离预览核对,线上实际页面文件和服务读数已核对,本次没有真实登录浏览器验收。QMT 内部估值相差 5,274 元及回笼统计期间仍待下游核实,本次没有通过修改账户数值强行消除差额,也没有为验收发起交易。验证命令、所在机器和预期输出详见资金核查文档。
|
||||
|
||||
|
||||
## 2026-10-27 微盘30股接入PMS观察档
|
||||
|
||||
本阶段按用户要求收口研究,重点转向PMS接入。规则仍为成长主线瓦解或微盘活跃度极低入场、历史高位退出,目标固定30只。用户确认佣金万二及创业板、科创板权限,最低佣金暂按5元假设,未计作已验收。
|
||||
|
||||
完成独立bionic监控、PMS策略轮换页面与接口、分策略账本迁移、四阶段协调、共享资金占用、成交归属及独立纸面账户。代码提交e13740e、c00df0c;页面修正c994409。改动范围与后续入口见docs/微盘30策略PMS接入说明_2026-10-27.md和docs/微盘30观察期接续_2026-10-27.md。保留既有未提交文档和研究资料。
|
||||
|
||||
155部署独立监控bionic-micro30:7a0df88,限制1核和1GiB。13:29只替换pms-web,worker、beat、唯一pms-ws的容器编号及启动时间均未改变。只创建观察文档表,策略交易账本开关保持false。未重启宿主机,未操作188。页面地址http://192.168.16.155:38100/rotation。
|
||||
|
||||
真机见过:155独立内部网络MariaDB迁移演练通过旧字段哈希、重复迁移、同名分账、30股批量委托、幂等、超买及原子回滚检查。两版Python镜像经断网全量回归均为ALL SUITES PASS。新增38项微盘专项通过,最终页面三道静态护栏通过。实际HTTP页面及健康检查200,观察接口有效30股,普通角色控制接口403。实际153代理库的新观察表专用记录通过事务和保存点回滚,未修改交易记录。
|
||||
|
||||
2026-10-26数据对应27日执行的信号和名单都已就绪,但27日08:50后才生成,不能计有效观察日。678日历史信号与20340条成员一致。未判收:正式交易表迁移、跨进程资金竞争、真实开盘窗口成交容量、自动交易及自然观察和纸面期。每日16:10的本聊天复核已创建,先在收盘后更新观察调度,再按至少3日观察和10日独立纸面继续。回退只关闭新策略执行,保留账本和在途回报。
|
||||
|
||||
## 2026-10-27(续)· 155四服务立即部署与持仓按策略展示
|
||||
|
||||
用户明确要求立即部署并允许重启模拟PMS。14:14:12至14:14:33将web、worker、beat和唯一ws统一重建为pms:micro30-c994409,各自保留原有效环境。服务器切至codex/micro30-rotation-20261027分支,私有Compose覆盖文件取消/app源码挂载,保留旧配置和回退镜像。188未操作,宿主机未重启。部署和证据见docs/微盘30整体部署判收_2026-10-27.md。
|
||||
|
||||
真机见过:四服务代码指纹1dbfcdc231d5一致;原调度恢复,pms.rotation_tick每分钟自然完成;页面、健康和30股观察接口正常。微盘命令、指令、出口委托均为零。观察表已启用,策略交易账本保持关闭。3日观察与10日纸面仍按原方案执行,16:10后续任务已改为复核,不重复部署。
|
||||
|
||||
QMT握手超时在部署前已存在,重启后未恢复。用户随后说明QMT正在重启,要求继续其他工作,因此不重复探测或干预下游。14:14:49下游出现600000.SH买入100股的外部成交,原回放于14:15:01入账;单号INS-20261027-4bf193c6,来源待核对,未修改或删除。持仓和批次自然增加,未声称摘要完全不变。
|
||||
|
||||
用户追加要求按策略分开持仓。portfolio新增只读分组与按策略查询批次,positions接口保留原策略既有输入并增加展示分组;交易员和运维持仓页面分开显示原策略与微盘30的数量、市值、持仓综合盈亏及批次。同名股票分别展示;未迁移时微盘为空,读取失败单独报错,缺行情时盈亏不伪装为零。微盘行链接策略轮换页,不显示原策略做T和网格操作。交易计算的默认范围不变。
|
||||
|
||||
改动app/services/portfolio.py、app/web/main.py、app/web/static/index.html,新增test_batch49_units.py八例并登记。开发机全量断网回归ALL SUITES PASS;页面三道护栏、1920与1280宽度浏览器验证通过,同名批次查询分别带original与micro30。补充展示功能尚待155候选镜像断网回归和仅web服务发布,结果在后续判收记录补齐。
|
||||
|
||||
## 2026-10-27(续)· 持仓按策略展示已在155发布
|
||||
|
||||
14:39:35至14:39:40仅重建pms-web为pms:micro30-85b76c2,原有效环境完全不变。worker、beat、ws的容器编号与启动时间不变,保留pms:micro30-c994409。用户已说明QMT正在重启,后续没有干预连接进程。正式交易表和执行档位未改。
|
||||
|
||||
真机见过:14:40认证持仓接口返回原策略5只、微盘空仓;原策略保留26条含平仓记录。同一002050.SZ查询原策略批次62条、微盘零条,非法策略参数422。实际HTTP页面摘要与提交一致。155镜像全量断网回归ALL SUITES PASS,最终页面三道护栏通过;候选、最终镜像和提交归档的Python指纹均为e1bf8e84c3ed。开发机实际页面与真实接口结果隔离渲染通过1440和1280宽度检查,同名股票合成场景通过1920和1280宽度及批次隔离检查。
|
||||
|
||||
补齐docs/微盘30整体部署判收_2026-10-27.md、接入说明和观察期接续;同步开发预览数据。默认Compose只更新web镜像,各服务旧环境和回退配置保留在backups/positions-by-strategy-20261027。每日复核更新为当前发布状态,不重复部署。正式交易迁移、3日观察和10日独立纸面仍未判收,不把页面分组完成视作自动交易验收。
|
||||
|
||||
## 2026-10-27(续)· 策略统一命名并将持仓改为双标签页
|
||||
|
||||
用户将两策略正式命名为主观量化和微盘轮动,要求持仓使用两个标签页节省空间。交易员与运维持仓页面均改为单标签内容显示,标签标明持仓数,刷新保留选择;总览、轮换页和接口名称同步。修改portfolio、index.html、rotation.html及开发预览数据,内部original和micro30账本标识、目标30只、交易规则不变。功能提交98a58d1。
|
||||
|
||||
14:58:22至14:58:27仅重建155的pms-web为pms:micro30-98a58d1。环境保持不变,worker、beat、ws的容器编号和启动时间均不变。没有操作188、写交易记录或干预QMT。备份与回执在backups/position-tabs-20261027,详细命令和预期结果见docs/微盘30整体部署判收_2026-10-27.md末节。
|
||||
|
||||
真机见过:155镜像全量断网回归ALL SUITES PASS,包含页面三道护栏;14:59认证接口返回主观量化5只、微盘轮动空仓。实际HTTP首页与轮换页均匹配提交,web及提交归档指纹e75331009797一致。开发机8项批次隔离专项通过;1920和1280宽度浏览器核验标签切换、刷新保留选择、同名批次和空仓与失败区分。实际页面与真实接口JSON的隔离浏览器核验1440、1280宽度通过,无脚本错误。
|
||||
|
||||
补齐接入说明与观察期接续,每日复核任务名称同步为“微盘轮动策略PMS接入与观察验收”,保持原观察和纸面门槛。本次仅调整展示,正式交易迁移及自动执行仍未判收。
|
||||
|
||||
|
||||
## 2026-10-27 · 按用户授权清理155模拟旧账,建立新的空仓观察基线
|
||||
|
||||
用户明确要求清空原有持仓相关数据,并确认QMT侧已清空。15:15:09已将155模拟仓的26条持仓记录、351条批次、127条指令、1862条动作流水、旧命令方案提议、个股策略及旧日报净值归档后清理;新账本为空仓、净值1.0000、累计盈亏0。保留业务参数、通道委托和逐笔成交去重记录、序号、操作审计及市场数据。详情见docs/模拟仓清账与新观察基线_2026-10-27.md。
|
||||
|
||||
动了scripts/reset_sim_observation_20261027.py以及清账记录、微盘接入说明和观察期接续。一次性脚本提交f022404后在155拉取,以现有web容器临时脚本执行,业务代码和镜像未替换。先经ParamStore暂停买入和执行、限定ws_only,再温和停止beat与worker;备份复制宿主机并核对摘要后,在同一事务清理和重置派生状态。15:16:55恢复原beat与worker,未重启web、WS、QMT或宿主机。
|
||||
|
||||
真机见过:155数据库和认证持仓接口均为主观量化0只、微盘轮动0只;重复回放新增成交及动作均为0;通道364条委托与1275条逐笔成交内容不变;健康检查db_ok=true;观察调度继续,命令轮询受全局暂停拦截。备份和回执在/home/factor/project/tradingSystem/backups/sim-reset-20261027,文件权限600。参数中的规模200万元、仓位上限70%、主观量化最多40只及微盘observe保留。没有改页面和交易逻辑,因此未重跑全量回归或布局验收。
|
||||
|
||||
未判收:QMT实时空仓与资金。15:17仍握手超时,旧trading_position另有11只过期持仓,故保持ws_only,不能用旧表补账。交易继续暂停;已有16:10复核任务已改用新基线,待新空仓及资金快照、序号、在途和待处理成交全部核对通过,并确认用户没有新增暂停指令后,才可恢复清理前暂停状态。微盘仍需原方案观察及纸面验收,188未操作。
|
||||
|
||||
|
||||
## 2026-10-27 · 模拟QMT改连98,空仓资金复测通过但连接仍受替换
|
||||
|
||||
用户指定并确认测试地址ws://192.168.16.98:9443/pms。155在15:29:25经ParamStore切换地址,首次取得14只旧持仓且反复被替换,15:33暂缓本侧连接。用户随后确认QMT方才清空并要求再测,15:35:20重新启用并启动唯一pms-ws。真机见过:新快照持仓0、总资产和可用资金各200万元、冻结0,无在途和待处理成交,PMS空仓对账差异0。未发测试委托,没有导回旧仓或调整序号、密钥。
|
||||
|
||||
未判收:连接稳定性。复测后仍约每30秒出现SIG_INVALID协议拒绝及replaced by new connection;本侧停连时同类拒绝也在产生。155确认只有一个WS进程,具体其他来源需QMT侧查连接日志。15:39通道为OFFLINE并按原规则重连,两个交易暂停与resync_flag=1保留,微盘仍observe。端口已确认,不再重复询问。
|
||||
|
||||
没有修改业务代码或镜像,仅运行参数和原WS进程启停。动了QMT测试地址切换记录、清账基线和观察接续;证据在155 backups/qmt-endpoint-98-20261027,已有16:10复核已更新。详见docs/QMT测试地址切换_2026-10-27.md。恢复交易还欠连接稳定、补发核验和resync对账留痕,188未操作。
|
||||
|
||||
|
||||
## 2026-10-27 · QMT切回182,确认周期性拒绝消息导致序号缺口
|
||||
|
||||
按用户要求,15:47:45将155模拟PMS端点改回ws://192.168.18.182:9443/pms并重启唯一pms-ws。真机见过:握手、心跳正常,观察期间没有再被动踢断,空仓、可用资金和总资产各200万元、冻结0,对账差异0;页面及数据库健康。未发测试委托。
|
||||
|
||||
未判收:连续消息确认。约每30秒出现未实时送达的序号,15:50受控重连后补回1441546、1441553、1441560、1441567,均为SIG_INVALID拒绝,产生于15:48:18至15:49:48。补齐后又出现新缺口。15:52:26已收1441606,确认停在1441576,暂存25条。需QMT侧查其他实例或客户端的共享序列及拒绝消息投递路径,来源尚未确认,不以ONLINE代替完整健康。
|
||||
|
||||
本次只改运行参数与原连接进程启停,没有修改业务代码、镜像或密钥,没有清序号或通道记录。保持两项交易暂停、resync_flag=1、微盘observe与ws_only。动了docs/QMT切回182核验_2026-10-27.md及观察接续;证据在155 backups/qmt-return-182-20261027,已有16:10复核已更新最新地址和缺口判据。188未操作。
|
||||
|
||||
|
||||
## 2026-10-27 · 通过停连与抓包收窄QMT周期拒绝来源,整理双方联调材料
|
||||
|
||||
按用户要求继续排查。155唯一pms-ws于16:07:26停止、16:08:56请求恢复,期间限定182和98的9443端点抓包为0;对端仍在16:07:50、16:08:20、16:08:50生成三条SIG_INVALID,seq为1441798至1441800。恢复连接后补回,表明不是停机期间当前PMS发送触发。来源IP、失败请求及是否98旧环境共用序号仍待QMT侧提供,不据此擅自停其他实例。
|
||||
|
||||
真机见过:恢复后37条PMS下行和84条QMT上行,121条报文签名全部可验证,实时仍有序号缺口;16:11确认停在1441807,已收1441833,暂存22条。保持两项交易暂停、微盘observe、resync=1及唯一182连接,没有测试委托、参数改写、密钥或业务代码变更。仅对原WS停启一次,限0.25核64MiB的被动采集容器已结束并移除,其余业务容器未动,188未操作。
|
||||
|
||||
动了docs/联调材料/QMT验签与序号缺口_2026-10-27及可转交ZIP、182核验和观察接续。材料提供119条原样协议信封、日志、公钥指纹、独立离线验签脚本、摘要,以及QMT侧所需失败帧、连接来源、发布器/验签/回放代码和环境存储配置清单。两条账户快照未加入共享包;原始受限证据保留155 backups/qmt-joint-20261027。开发机离线复核119条全部通过,git diff --check通过;纯文档和材料同步,不重建镜像、不再重启服务。消息链路恢复未判收,不能把现有300秒跳过缺口或ONLINE当作恢复。
|
||||
|
||||
|
||||
## 2026-10-27 · 每日观察复核,今日未冻结且明日日线尚未齐
|
||||
|
||||
16:22至16:25在155只读复核。真机见过:30股名单唯一、排名和市值排序正确,资格标识有效;今日版本13:04生成,未在08:50冻结,因此有效观察0日、纸面0日。明日快照404,监控degraded已定位为10月27日指数日线尚未到齐,现有四条指数及日历源截至10月26日,按原周期等待补算,没有补造日期或有效观察记录。
|
||||
|
||||
QMT仍有序号缺口,16:23确认1441965、最高1442003、暂存32条。16:24账户快照年龄44.8秒,空仓、可用资金200万元、冻结0,对账差异0,页面与数据库健康。保留两项暂停、ws_only、observe和交易账本关闭状态。未重启、迁移、改参数或下单,镜像差异保持,188未操作。
|
||||
|
||||
动了docs/微盘轮动每日复核_2026-10-27.md和观察接续。原始读数保留155 backups/micro30-review-20261027/observation.json。只同步文档,不替换镜像。开发机git diff --check通过;本轮无代码变更,未重复回归和页面验收。通道恢复、自然观察与纸面期及原剩余验收仍未判收。
|
||||
|
||||
|
||||
## 2026-10-27 · 按消息产生时间确认当前QMT仍有周期验签拒绝
|
||||
|
||||
用户说明此前数分钟断线来自QMT系统重启,要求只判断现在是否仍有SIG_INVALID。16:28:38检查仍有新缺口,但PMS最后收到的拒绝属于16:08补发,不能仅凭旧日志作答。确认两项暂停、无在途及待处理成交后,对唯一pms-ws受控重连一次,保留水位1442044。真机见过:补回seq1442045至1442087中的7条SIG_INVALID,产生于16:25:52至16:28:52,间隔约30秒。明确区分产生时间和16:28:58至59的补发接收时间。
|
||||
|
||||
动了docs/QMT验签拒绝即时复核_2026-10-27.md与观察接续,证据在155 backups/qmt-current-reject-20261027。没有业务代码、参数、密钥或委托变更,未重建镜像;交易暂停及resync=1保留,未操作188。开发机git diff --check通过,只同步诊断文档。具体触发来源待QMT日志,验签故障恢复未判收。
|
||||
|
||||
|
||||
## 2026-10-27 · 编写可直接交给QMT研发的验签排查请求
|
||||
|
||||
按用户要求新增docs/QMT侧排查请求_SIG_INVALID_2026-10-27.md,使用16:29复核的7条近期拒绝作为检索入口,明确重启断线不再作为异常依据。文件包含最新报文节选、155停连及签名复核事实、原请求来源与验签/序号投递排查顺序、所需代码范围、结论回填格式和修复后的双方验证标准。保留旧环境干扰为待查假设,不将通用拒绝文案当作当前PMS签名错误的证明。
|
||||
|
||||
本轮只编写交接文件,未操作服务器或改运行状态;引用的诊断证据已在前述节点真机见过,故障恢复仍未判收。开发机核对报文JSON可解析、关键seq及ts一致,git diff --check通过,无业务代码变更。原有未提交文件保持。
|
||||
|
||||
|
||||
## 2026-10-27 · QMT修改后完成连续消息核验,解除本次清账暂停
|
||||
|
||||
用户提供QMT排查回复并确认修改重启。真机见过:16:50自动重连后仍缺1442396、1442403,16:55:29由既有300秒规则跳过。这两条未取得,不能仅凭跳号认定类型或98来源。对唯一pms-ws受控重连一次后,16:55:33至17:06:19连续10分46秒无新SIG_INVALID、PMS本端验签失败、缺口、跳号、确认降级或被动断线;收件表1442461至1442595共135条逐号连续。
|
||||
|
||||
17:06:19使用46.5秒前的新快照,确认空仓、总资产及可用资金各200万元、冻结0,无在途、待处理或孤立成交,对账差异0。旧通道委托364条、逐笔成交1275条及15:15:09回放游标保留,旧持仓、指令、动作均为0,下游成交重叠窗口0。两项暂停仍由sim_reset_20261027设置且没有新增命令,17:06:20在事务中先写操作审计,再清resync并经ParamStore恢复暂停买入和暂停执行为false。首次审计参数含datetime导致序列化失败,未修改状态;转换为字符串后重跑全部检查才完成。微盘保持observe,策略交易账本未启用,ws_only不变。
|
||||
|
||||
动了docs/QMT修复后联调核验_2026-10-27.md、观察接续、182核验、模拟清账基线及DEVLOG,更新既有每日复核提示以避免沿用旧暂停结论。155证据在backups/qmt-postfix-20261027,包括19次状态采样、恢复回执、日志和一次性运维脚本。只重启原pms-ws一次,镜像仍为pms:micro30-c994409;其他业务容器及188未操作,无业务代码、密钥或交易委托变更。文档经Git提交同步,不重建镜像。开发机诊断脚本语法及git diff --check通过,本轮没有代码和页面变更,未重复全量回归。
|
||||
|
||||
通道本轮恢复及新账户对账已真机见过。历史根因、182实际部署提交、两条切换缺口内容和QMT侧ack_seq验签及确认落点仍需对方证据,未判收;不将“98干扰”或“不再发reject”当作根因证明。微盘自然观察、纸面期及其余原方案验收继续。
|
||||
|
||||
|
||||
## 2026-10-28 · 微盘首个自然观察日与轮换故障恢复验收
|
||||
|
||||
用户确认模拟账户每笔最低佣金5元,与既有万二参数及板块权限一致,已写费用确认记录。08:51自然形成10月28日首条观察日,使用10月27日数据,30只名单与信号就绪,快照已冻结,三个宏观触发均为false。继续观察,收盘复核,不提前切纸面或自动档。
|
||||
|
||||
新增scripts/rehearse_micro30_acceptance.py,在155专属内部网络MariaDB演练跨进程资金占用、用户命令冲突、撤单失败、重启恢复和30股独立纸面全周期。初次测试发现撤单失败会回滚退出决定。316d31d将轮换决定先独立提交再执行,并阻止零持仓但下游微盘委托仍未结束时提前完成退出。改动涉及micro_rotation.py、rotation_service.py及第48批测试。7项隔离演练全部通过,9表重复迁移通过;合成样例没有进入运行库或QMT,不抵自然观察及纸面日。
|
||||
|
||||
开发机全量配置隔离、禁止联网回归ALL SUITES PASS。155从Git提交316d31d归档构建pms:micro30-316d31d,候选镜像在network none、无业务配置的一次性容器全量回归ALL SUITES PASS,含页面三道护栏。09:09仅worker温和退出并force-recreate,四服务有效环境未变。web仍为98a58d1,beat与ws仍为c994409,三个容器编号及启动时间未变。没有重启QMT连接、修改页面或迁移运行交易表。
|
||||
|
||||
真机见过:09:10新worker自然完成观察任务,冻结版本和单条观察记录保持一致;费用参数为0.0002及5元。页面及数据库健康,无在途、待入账和待人工成交。09:10:45资金快照年龄37.6秒,空仓、可用资金和总资产各200万元、冻结0,对账差异0。09:11:50核对273条连续消息,无缺失,last_seq与acked_seq同为1454554,缺口和新拒绝为0,resync为0。旧清账暂停保持false,微盘observe及交易账本关闭不变。
|
||||
|
||||
运行库9表只读迁移检查均为空、尚无book_id,旧持仓未回流。实验数据库已在保存证据后停止。部署回执位于155 backups/micro30-acceptance-20261028,隔离及镜像回归位于/home/factor/project/pms-micro30-acceptance-20261028。详情见docs/微盘轮动接入验收_2026-10-28.md,接续和费用说明已同步,每日16:10复核任务更新。
|
||||
|
||||
未判收:正式策略账本迁移及现金初始化、153代理库完整跨进程资金路径、实际开盘容量和实际交易回报,以及至少3个自然观察日和后续10个健康纸面交易日。只读空表检查与隔离演练不替代运行库迁移验收。188不在范围内。
|
||||
|
||||
|
||||
## 2026-10-28 · 按用户要求直接启用155模拟仓微盘自动轮换
|
||||
|
||||
用户明确取消观察及纸面等待,要求模拟仓今天直接上线、运行中继续解决问题。新增PMS_ROTATION_SIM_DIRECT运行参数,授权155跳过历史验收和天数门槛,但仍检查策略账本、实际资金初始化、唯一WS通道、费用及板块权限,执行时继续约束现金、仓位、用户暂停、行情、限制价和对账。页面改为运行控制说明,不伪造观察日或验收证据。188真实PMS未操作。
|
||||
|
||||
代码提交f1424f3涉及param_store.py、rotation_service.py、rotation.html、第48批测试及回归登记。开发机全量断网回归通过;155由干净Git归档构建pms:micro30-f1424f3,在无网络、无业务配置、只读容器全量回归ALL SUITES PASS,含41项微盘专项和页面三道护栏。浏览器使用实际部署页面与真实状态响应检查桌面和390像素窄屏,另用明确测试响应检查缺资金禁止启用和默认策略,均通过;未宣称交易员登录后的实际交易操作验收。
|
||||
|
||||
正式迁移前保存12表数据、DDL和私有配置,设置维护暂停并停止beat、worker、web,保留WS接收回报。9张交易表原来均为空,迁移后原字段哈希与数量一致,增加book_id和分策略持仓唯一键。153实际代理库两个独立连接行锁探针仅允许一方使用80元、100元余额最终20元;没有把该探针冒充全部并发成交链路验收。四服务随后统一force-recreate,旧WS先退出再启动新WS,仅策略账本环境开关由false改为true,其他有效环境不变,无/app源码绑定。
|
||||
|
||||
09:29:06用33.6秒内实际资金快照1454759完成200万元现金初始化并启用auto,初始归属主观量化,微盘本金0、净值为空;本次维护暂停恢复false。09:30开始自然轮换任务完成,今日成长瓦解、微盘低位及高位信号均false,没有注入入场。09:33逐号核对62条新报文连续,无SIG_INVALID或新缺口,09:39连续确认推进至1454904。主观量化09:39自然买单已获QMT接收,尚不能据此判定成交。09:39:47经ParamStore把同一连接的资金和持仓查询间隔从300调至30秒,匹配一分钟资金时效要求,不放宽校验,也没有再次重启。
|
||||
|
||||
真机见过正式迁移、初始资金、auto档、自然任务和QMT委托接收。目标30股实时行情已齐,但今日gp_stk_limit仍0条、最新到10月27日,相关委托继续等待有效限制价。微盘自然成交全周期、实际容量及复杂残余场景未判收,按用户要求运行中继续解决,不恢复旧等待门槛。旧模拟仓和外部测试成交未补回,策略账本不回退。
|
||||
|
||||
证据在155 backups/micro30-direct-20261028,镜像与回归在/home/factor/project/pms-micro30-direct-20261028。新增docs/微盘轮动模拟仓直接上线_2026-10-28.md,更新接续和接入文档,既有16:10任务改为运行复核。后续文档同步不重复重启。其他既有未提交研究与台账文件保留。
|
||||
|
||||
09:43:51追加真机核对:资金快照已按30秒更新,年龄12.1秒;截至1454956共200条新报文逐号连续,无新拒绝。账户与策略资金、数量对账差异为0。主观量化在途买单正确归属original,共享资金占用2954.03元,成交仍0,微盘无委托。完整回执为final-check.json及final-check-2.json,今日限制价缺口仍在。
|
||||
|
||||
|
||||
## 2026-10-28 · 主页展示微盘入场指标并复现股汇漏日差异
|
||||
|
||||
用户要求把微盘入场读数放到现有大盘样式中,并核对发布值-17.8949与页面-20.3。新增主页微盘标签和悬停明细,展示实际执行快照中的8.33%历史分位、0.7266活跃度、0.6940低位线、2.1354高位线、成长瓦解条件和三类分位横向比较。快照过期、未冻结或接口失败显示待核实,不能遗留旧信号;低分位为0仍可正确显示,退出优先于入场。股汇新增只读发布值对照,并把数据日期与扫描日期分开,不修改已有执行信号和下单路径。
|
||||
|
||||
代码4500865涉及macro_repo.py、macro_service.py、index.html及第48批测试和登记。开发机全量断网回归、页面三道护栏和155候选镜像无网络全量回归均ALL SUITES PASS,第48批44项。浏览器使用实际部署页面和实际状态响应检查1440、1280、390像素及明确的异常测试响应,读数、日期、过期和失败状态通过,无脚本错误或控制请求。
|
||||
|
||||
10:01仅pms-web force-recreate至pms:micro30-4500865,镜像从干净Git归档构建;worker、beat、唯一WS容器编号和启动时间不变,保留f1424f3,有效环境不变,页面和数据库健康。首次运维脚本按JSON读YAML私有覆盖文件失败,尚未改配置或服务;改用YAML解析后重新备份完成。真机回执在155 backups/market-readings-20261028-web,构建和回归在/home/factor/project/pms-market-readings-20261028。188未操作。
|
||||
|
||||
用户进一步要求先分析两值差异和科学性,未选择切换交易来源。只读核对发布表、当前完整上证/汇率/利率数据后,以相同公式移除10月8日即可复现10月9日至27日全部13个发布指数,四位小数完全一致,原始价差六位也一致。完整序列最新-20.3242,移除后-17.8949。回看基点从9月21日变为9月18日,40日均值和标准差同时变化。上交所官方公告确认10月8日正常开市,proxy与index两源也有一致日线。发布表DDL的120日、股减汇注释与实际复现不符,不能按注释断定公式。PMS完整日历符合既定计算口径,盈利预测能力仍须另验,不因本次复现宣称有效。
|
||||
|
||||
新增docs/微盘指标展示与股汇差异核验_2026-10-28.md及离线复现材料,更新接续和既有每日复核。源表任务代码、输入日志与具体漏日原因未判收,未改上游表、既有2%升仓命令或交易口径。先前研究、台账及其他工作树保持。验证命令在开发机为python3 docs/联调材料/股汇差异_2026-10-28/reproduce.py,预期13/13;实际通过。
|
||||
|
||||
|
||||
## 2026-10-28 · 两个指标悬浮框改为趋势图并回溯股汇接入依据
|
||||
|
||||
用户要求图形为主、最少文字。股汇保留22条已有执行历史,显示正负刻度、冷热线和退出带;微盘显示60日活跃度及三品类历史分位两图。缺数断线,接口失败清旧图,保留当前值、日期和触发状态。监控在同一计算中保存独立历史缓存,PMS只读转发,不复制计算,不改变冻结快照与执行流程。
|
||||
|
||||
原方案与最初提交证实,8月18日就选定PMS原料计算、标定同口径、ParamStore参数及逐日信号留痕,并非本次新建替代指数。原文没有明确比较读取已发布表的取舍,今天的漏日发现不能冒充当初理由。详见docs/指标悬浮趋势与股汇接入回溯_2026-10-28.md。
|
||||
|
||||
代码为PMS c9ad9f3、监控ba663ed。10:33在155更新web和独立监控,保留各自有效环境;worker、beat、ws容器编号及启动时间不变,188未操作。首次构建参数不支持,由部署守卫在容器操作前拦下,修正后通过隔离镜像检查才部署。监控回执在/home/factor/project/pms-trend-popovers-20261028/monitor-backup-verified,web回执在backups/trend-popovers-20261028-web。
|
||||
|
||||
真机见过:股汇执行-20.3242、发布-17.8949,60日微盘趋势最新记录等于今日冻结信号,冻结文件摘要完全不变。开发机与155待发布镜像全量断网回归均ALL SUITES PASS,第48批47项,页面三道护栏通过。监控9项隔离测试通过。实际部署页面与服务数据的1440、1280、390宽度浏览器渲染通过,无脚本错误、无写请求。上游股汇生成任务具体漏日原因未判收。既有未提交研究、DEVLOG及台账内容保留。
|
||||
|
||||
|
||||
## 2026-10-28 · 恢复阈值变色柱图并区分计划指令与真实委托
|
||||
|
||||
用户要求柱状趋势并核查盛弘600股在QMT不可见。精确关联父指令、出口与收件回报,10:59真机见过盛弘仍未生成子委托,最新择时价格31.10高于锁定上沿30.02,正常等待买入条件。四方100股第三个子委托09:59:40以28.92成交,10:00是父指令进度更新时间。两者均来自主观量化宏观升仓命令,没有补发、强制买入或修改价格条件。
|
||||
|
||||
修改index.html、execution_conflicts.py、第41批测试及登记。两个悬浮框改为柱状图,以颜色提示越界;消息栏使用实际执行阶段,计划量不再称为下单量,等待条件展示具体原因。仍在途子委托优先于父指令终态显示,读取失败不声称已发送,出站成交尚未回账显示待入账。交易规则与原始状态不变。代码提交5e1ae07、596c1ce。
|
||||
|
||||
开发机全量断网回归ALL SUITES PASS,第41批27项,页面三道护栏通过。155干净归档镜像断网全量回归ALL SUITES PASS,10:59仅web重建为pms:micro30-596c1ce,worker、beat、ws容器与启动时间不变,有效环境不变,页面及数据库健康。真实部署HTML与服务响应在隔离浏览器重放检查1440、1280、390宽度,通过且无脚本错误、无写请求;真实登录会话人工操作未判收。188未操作。
|
||||
|
||||
部署回执为155 backups/bars-orders-20261028-web/receipt.json,构建与回归日志位于/home/factor/project/pms-bars-orders-20261028。完整证据与后续接续见docs/柱状趋势与盛弘待执行核验_2026-10-28.md及接续文档。已有DEVLOG、研究、台账与服务器私有改动保留。
|
||||
|
||||
|
||||
## 2026-10-28 · 限价交QMT等待并精简微盘历史分位展示
|
||||
|
||||
用户要求PMS提供价格和数量,把成交价格等待交QMT。新增按实例启用的PMS_EXEC_QMT_PRICE_MONITOR,默认关闭,155通过ParamStore开启。已生成主观量化指令按执行区间上沿买入、下沿卖出,不等现价入区间,不叠加涨幅和MA5价格等待,不在普通单尾盘追价。买单可以更低成交,卖单可以更高成交。策略触发、每日配额、资金和数量、用户暂停、离场否决及数据有效性保持。区间不可用不改成现价单。
|
||||
|
||||
代码02837fa修改exec_advisor、executor、rule_gate、参数与接口说明,新增第50批14项隔离测试。页面恢复蓝金灰柱色,只保留微盘历史百分位,详情及顶栏入口新标签页。开发机与155干净候选镜像全量断网回归均ALL SUITES PASS,三道页面护栏通过。实际部署HTML及服务响应在隔离浏览器检查1440、1280、390宽度,实际点击和关闭新标签页后主页面仍保留,无脚本错误,无写请求。真实登录会话人工操作未判收。
|
||||
|
||||
11:20:08完成155 web与worker镜像更新,beat短停后恢复原容器,beat与唯一ws仍为f1424f3,ws连接未重启,监控仍为ba663ed。有效环境和用户暂停值保持。首次参数记录updated_by过长导致写入失败并自动回退,缩短运维标识后二次通过。部署回执在backups/qmt-price-20261028-verified。188未操作。
|
||||
|
||||
真机见过:盛弘计划的首笔200股、30.02元于11:20:16由自然调度发出,QMT回执1456511确认受理,编号DESK-bffb6ade07。核查时成交0,页面显示委托待成交,不能把受理当成交。QMT序号连续,无新拒绝或重连,待入账0。没有手动执行真实tick或测试单。完整证据、命令及边界见docs/QMT限价等待与微盘分位展示_2026-10-28.md,接续与既有16:10运行复核已更新。其他工作树、研究、既有DEVLOG及台账改动保留。
|
||||
|
||||
|
||||
## 2026-10-28 微盘轮动三个参数离线标定
|
||||
|
||||
用户要求利用既有历史数据标定入场分位、退出分位及目标持股只数。本轮固定成长瓦解、历史资格、次日执行、每日成员轮换及费用口径,只研究三个参数,不修改155模拟PMS参数,不涉及188。
|
||||
|
||||
新增 `research/micro_calibration_20261028/`,含运行前冻结口径、数据摘要、独立研究引擎、378组参数在单边30和60基点下的结果、按时间顺序选参、独立复核、三幅研究图及完整报告。入口为 `docs/微盘轮动三参数标定_2026-10-28.md`。原始数据及生成缓存不提交,旧研究目录保留原状。
|
||||
|
||||
原30只和100只5/95账户全部678日净值复现。偏重回撤与分散度的研究候选5/85/50,累计+73.62%、最大回撤−21.07%,对比原5/95/30的+31.54%、−32.78%。全历史最高10/97.5/75累计+143.29%,但两轮中只有一轮结束。按前序年份选参的2025至2026检验期仅+9.29%,原参数+9.56%,未验证稳定超越,不能把历史冠军直接写入线上。完整报告同时披露已见过数据、少量轮次、可分割单位、历史覆盖与容量限制。
|
||||
|
||||
验证均在开发机经 `scripts/unit_test_guard.py` 隔离配置并禁止联网执行。6项研究测试通过;378组在2024年末和2025年末分别截断重跑,过去净值完全一致;10个详细账户独立复算现金、持仓及估值,误差低于1e-14。图表已逐张视觉检查。没有生产代码变更,未部署,155真机判收为未判收;不能将研究测试称为PMS全量回归。
|
||||
|
||||
|
||||
## 2026-10-28 12:48 · 按用户决定发布8%入场、85%退出与50股微盘规则
|
||||
|
||||
做了什么:用户明确要求直接部署155模拟仓。新规则micro50-v2-20261028已由ParamStore选定,成长瓦解仍保留其95%过热条件。页面阈值、变色、目标数量和容量同步,详情新标签页。内部micro30账本保留。
|
||||
|
||||
动了哪些文件:micro_rotation、rotation_service、param_store、两页HTML、batch48及测试清单;独立监控calculation、server、监控测试、README与双方台账021/006。完整记录见docs/微盘轮动50股参数发布_2026-10-28.md。
|
||||
|
||||
部署方式:PMS提交9e14f92和监控3e2a584分别构建镜像,通过155候选镜像全量断网回归后重建web、worker和独立监控。beat短停后恢复原容器,唯一ws完全未动。运行档auto,两项全局暂停false,价格监控交QMT保持。188未操作。
|
||||
|
||||
真机判收:50只名单与60条历史就绪,页面8%/85%/50正确;最新分位8.33%,三项触发均false。新规则盘中未冻结,旧冻结文件摘要不变。实际连续确认继续推进,无新增验签拒绝或重连,对账与现金差异0。三宽度浏览器复现通过。开发机及155断网全量回归通过,微盘55项、监控12项通过。
|
||||
|
||||
还欠着:新版本完整自然入退场和成交尚未判收。10月29日08:50按既有流程冻结,09:30至10:00按信号执行;不增加观察和纸面等待。日常复核任务已改为50股规则。没有改原策略持仓或在途委托。
|
||||
|
||||
|
||||
## 2026-10-28 · 微盘轮动入退场分位的多日平滑实验
|
||||
|
||||
做了什么:以已部署8%入场、85%退出、50只为基线,冻结3/5/10/20交易日均值和中位数,分别只平滑入场、只平滑退出、两侧平滑,共24种。只平滑每日历史百分位,成长瓦解和账户方法不变,使用2024年前数据预热。另做单日分位桥接,678天信号及账户与基线一致。
|
||||
|
||||
动了哪些文件:新增research/micro_smoothing_20261028中的协议、离线实验、测试、独立复算、报告、完整结果与两张图。原标定脚本和线上代码没有修改。
|
||||
|
||||
结果:2024-01-02至2026-10-23基线累计79.44%、最大回撤21.07%。双侧3日均值51.69%,3日中位数61.97%,最大回撤均未改善。双侧10/20日平滑漏掉2026年初高位退出,回撤扩大到31.73%。24种平滑在30与60基点费用下收益均低于基线。结论仅限固定阈值下的历史比较,宏观轮次稀少,不声称统计显著。
|
||||
|
||||
部署方式:未部署,155与188未访问或修改,现有8%/85%/50只自动运行规则保持。研究文件经Git保存,不把离线实验自动升级为生产策略。
|
||||
|
||||
判收:开发机断网隔离9项测试通过;独立审核27个账户、52次前缀重跑、17628条指标,最大现金净值误差4.22e-15。两张图已检查。线上交易效果未判收。完整报告为research/micro_smoothing_20261028/微盘轮动多日平滑实验.md。
|
||||
|
||||
还欠着:真实策略自然轮次仍需模拟运行。历史退市与简称覆盖、复权单位和开盘成交假设沿用前次局限。本实验不要求再调参或部署。
|
||||
|
||||
|
||||
## 2026-10-28 · 汇总微盘轮动阶段接续与实验意见
|
||||
|
||||
做了什么:按用户要求收口当前上下文,新增docs/微盘轮动阶段接续_2026-10-28.md,并在通用接续与旧微盘观察期记录顶部加入入口。明确现行8%入场、85%退出、50只、155自动运行,以及不额外平滑的实验意见。旧参数和观察期保留为历史,不能再覆盖最新决定。
|
||||
|
||||
动了哪些文件:新阶段摘要、两个接续入口与本日志。既有30-pms每日复核说明改为读取简明摘要,删除相互覆盖的历史说明;名称、北京时间16:10计划、ACTIVE状态及目标会话不变。
|
||||
|
||||
部署方式:仅文档与复核说明更新,没有访问155或188,没有变更交易参数、代码、容器或数据库。保留既有未提交日志、台账、研究材料和其他工作树。
|
||||
|
||||
判收:开发机核对Git、部署记录、标定及平滑报告,摘要本地链接均存在,git diff --check通过;复核任务更新成功并回读确认。运行状态引用10月28日12:49:37的既有真机证据,不声称本次重新核验。无代码修改,不重复运行全量测试。
|
||||
|
||||
还欠着:新版本自然冻结、完整微盘入退场和实际成交仍需按最新运行证据判收。股汇上游漏日生成原因尚待核实。不会因汇总自动新增研究或策略变更。
|
||||
|
||||
|
||||
## 2026-10-28 · 精简Codex规则并拆分目录与按需技能
|
||||
|
||||
做了什么:按用户要求,先核对官方目录指令和技能加载机制,再将根AGENTS.md由150行、17174字节缩至34行、3720字节,减少约78%。主文件保留工作流程、已有授权和关键禁区;明确155授权内不反复确认,188不在本阶段范围内。
|
||||
|
||||
动了哪些文件:新增app、app/web、scripts、research四份目录规则,新增pms-release与pms-qmt-diagnose两个仓库技能,以及docs/开发入口.md。README的重复开发约定改为指向统一入口,旧迁移记录中的双文件同步提交要求标为历史。CLAUDE.md内容完全未改,停止同步维护。
|
||||
|
||||
验证:开发机核对官方文档,本机Codex CLI版本为0.163.0-alpha.10.2。调用skills/list只读接口,在仓库根目录和app/web均实际发现两个enabled技能,无本仓库加载错误,未启动模型回合。两个技能通过Skill Creator校验,35个本地链接有效,项目目录规则组合未超过默认32KiB限制,git diff --check通过。校验所需PyYAML仅安装到/tmp专用目录,不改应用依赖。
|
||||
|
||||
部署方式与判收:仅文档和技能,经Git提交保存,没有访问155、188或QMT,没有改应用代码、业务参数或运行容器。未重新跑无关业务回归,不声称完成新的交易真机判收。新会话实际目录指令链尚未另外启动验证,官方机制、手工路径检查与本机技能发现分别记录在开发入口。
|
||||
|
||||
还欠着:无本次文档重整阻塞。运行接入待办继续按微盘阶段接续,不因本次改规则而重启或重做历史实验。已有DEVLOG的114行、复盘台账的10行及未跟踪研究材料保留。
|
||||
|
||||
|
||||
## 2026-10-28 · 全市场热度、涨跌幅与持有期四维标定
|
||||
|
||||
做了什么:按微盘三参数报告形式建立新研究,用户确认比较1至10个交易日。冻结热度下限、当日涨跌幅上下限、持有期,共3,510组含对照;主样本与含回填历史分别计算,补充118条费用分支账户。
|
||||
|
||||
数据发现:stock_fund_heat_scores导出636,116行,但4月27日至8月3日数据于8月4日集中回填。按入库可用时间筛选后,共同信号样本只有8月4日至10月8日41个日期,行情观察至10月23日。热度只覆盖沪深,无北交所;时间列两种时区假设在共同区间信号一致,尚未完成上游写入语义核查。
|
||||
|
||||
结果:基线0.80热度、涨幅0至5%、5日账户累计−9.18%。事后候选0.75热度、涨幅0至2%、4日累计+1.59%,最大回撤−4.82%;每边费用从30增加到60基点后累计−4.30%。训练规则选出的0.80、0至2%、1日验证账户累计−0.22%。2,770组样本量达标热度组合只有15组平均每批净收益在30基点下为正,60基点下为0组。不能认定稳健最优或直接上线。
|
||||
|
||||
动了哪些文件:新增research/heat_calibration_20261028的冻结协议、独立只读取数、离线引擎、测试、复算、结果、完整中文报告及三张图;新增docs/全市场热度四维标定接续_2026-10-28.md并更新开发入口。现有未提交日志、台账及研究材料保留。
|
||||
|
||||
验证与机器:开发机8项隔离断网测试通过,24条账户逐笔重建的最大误差1.50e-13,118条账户现金收支通过,3次日期前缀重跑一致,3组事件均值从成交独立复算一致。三张图已目视检查,本地链接及git diff --check通过。
|
||||
|
||||
部署方式与判收:155仅以模拟实例空前缀、实际pms:micro50-9e14f92镜像运行一次性只读导出,源容器只有logs挂载;不含下单凭证,没有业务表写入或服务重启。未修改应用代码,无业务容器需要重建。188未访问,线上交易效果本轮未判收。
|
||||
|
||||
还欠着:更长且当时可用的热度历史、源算法版本与时间语义、退市覆盖、整手和最低佣金、单股权重与开盘容量。当前研究已完成,未创建后台任务或自动上线安排。具体结果、核验时间和复现入口见新接续文档。
|
||||
|
||||
|
||||
## 2026-10-28 16:12 · 微盘轮动收盘只读复核
|
||||
|
||||
做了什么:按既有每日复核,读取155实际镜像、挂载、运行参数、两次QMT回执、资金持仓和日终记录。现行8%/85%/50只auto规则保持,不重启、不改暂停、不手动下单。
|
||||
|
||||
真机见过:16:10:04至16:12:22连续确认1461183推进到1461221,两次最近160条消息连续;无新验签拒绝、重连或丢弃,待处理及待归属成交0,数量及现金对账0。主观量化四方100股,微盘空仓。盛弘13个子单到期、1个排队过期作废,成交0,无活动子委托,父计划仍未完成。15:20自然日终记录已生成。
|
||||
|
||||
当前缺项:四个指数最新10月27日;当日股票、风险、限制价及辅助市值也均未到齐。监控在收盘计算时返回ValueError,10月29日快照404,不能把旧8.33%读数作为明日信号。保留15分钟自然补算与次日08:50冻结流程,不倒填数据。
|
||||
|
||||
动了哪些文件:新增docs/微盘轮动每日复核_2026-10-28.md及evidence/micro50_daily_20261028.json,阶段接续追加最新入口。验证在155运行容器中只读完成,开发机核对证据关系、链接和git diff --check;无代码变更,不跑无关业务回归。
|
||||
|
||||
部署方式与边界:未部署,155镜像及私有工作树保留,188未操作。本地已进入用户的另一研究分支,其他提交和既有未提交改动均保留。未判收项仍是新版本自然冻结、完整微盘入退场及实际成交容量;本轮数据未齐已留痕,既有复核继续。
|
||||
|
||||
|
||||
## 2026-10-28 综合分与聪明资金分分阶段标定
|
||||
|
||||
北京时间16:45,完成用户指定150/factordb评分表的只读导出与离线研究。按三参数标定形式冻结9档总分、9档聪明资金分及1至10交易日,合计810组;共同信号区间2025年1月2日至2026年9月30日,行情截至10月23日。报告与完整结果在`research/signal_scores_20261028/`,接续见`docs/综合分与聪明资金分标定接续_2026-10-28.md`。
|
||||
|
||||
每边30基点下,810组2026年平均单批净收益均为负。预设0.8/0.7/5日账户2026收益−21.77%、最大回撤−25.73%;只筛smart≥0.7为−21.12%。2025训练选出的smart≥0.8、2日方案为−38.66%,分阶段方案为−35.24%。阶段判断对沪深300或中证2000分类敏感;没有将任何研究参数写入运行系统。
|
||||
|
||||
开发机9项配置隔离、断网测试通过;3个逐笔账户重建最大误差5.22e-14,36条账户现金守恒通过,10种持有期训练截断复算一致,旧热度基线全路径复现。4幅研究图已检查。源表没有历史入库时刻或版本号,支持覆盖旧值,因此只称现存历史评分回放;缺评分日、缺历史资格和期末残仓已披露。待补不可覆盖快照、历史可用时间、完整退市与实际成交容量证据。未改应用代码、未部署或重建线上容器。
|
||||
|
||||
|
||||
## 2026-10-29 反复活跃股票频次与持有期矩阵
|
||||
|
||||
北京时间09:36,按用户要求完成单分数、市场阶段、收益指数及此前20日达标次数隔离。协议09:10冻结,total和smart分别扫描6档门槛、0至20次、1至10交易日及3种当天/历史条件,共5160组;交付201,240行分组结果、42条预设账户、自包含矩阵浏览器及6幅PNG。入口为`docs/反复活跃矩阵研究接续_2026-10-29.md`,报告与代码在`research/score_recurrence_20261029/`。
|
||||
|
||||
缺评分不记0次,统一完整20日观察池后有389个可用信号日。每边30基点下,2026有94组最低展示样本要求内的平均批次净收益为正,60基点下剩44组;高频次正格多为少数股票,不能当独立验证或账户盈利。固定smart≥0.8、K≥5、H5的2026批次净收益−0.84%,相对K0改善0.062个百分点;加当天达标未延续改善。固定H5、两年皆正的仅历史频次条件有5组,但2026日均入选仅1.7至4.2只。
|
||||
|
||||
开发机9项配置隔离、断网测试通过;1200次直接历史窗口计数、6项旧基线和36项指数区间核验通过;3个账户逐笔独立重建、42条账户现金守恒及21条30基点前缀核验通过。本地Chrome完成矩阵与表格联动、独立阶段/指数切片、CSV/PNG导出及手机布局验收,外部请求0。沿用历史可覆盖快照,首次可用时间、完整退市覆盖及实际成交容量仍未解决。未改应用、运行参数、持仓或容器,未部署。
|
||||
|
||||
|
||||
## 2026-10-29 完成系统热度反复活跃矩阵研究
|
||||
|
||||
核验时间:2026年10月29日10:14,北京时间。新增`research/heat_recurrence_20261029/`,沿用评分矩阵的阈值、前20交易日次数、持有1至10日及阶段和指数隔离逻辑。协议先冻结;直接使用`stock_fund_heat_scores.score`,每种数据口径3440组、三口径共10320次评估,生成536640行结果、72个预设账户、六张图和可离线交互HTML。
|
||||
|
||||
155模拟PMS只读核对实际镜像`pms:micro50-9e14f92`、空前缀与仅日志挂载;运行读源仍为该表,ParamStore热度阈值0.80。最新10月28日5208只中341只达0.80。回测未追加新数据,仍沿用原缓存、行情截至10月23日,共同信号末日10月8日;没有业务写入、部署、重启、委托或188操作。
|
||||
|
||||
数据质量是主要边界:选股截止前已入库的完整20日观察池只有24日;要求历史逐日及时入库仅4日;忽略入库时间的含回填诊断71日。9月7日缺数使其后20日无完整窗口。固定热度0.80、历史至少5次、H5平均每批净收益−1.42%,60bp−2.01%;所有H1至10均负。主口径1240个达标格中38格30bp正收益(含16个重复K0对照),60bp正收益0;各阶段样本不足,未选上线参数。
|
||||
|
||||
开发机12项断网隔离测试、2400个原始窗口、36项实际买卖日指数比较、三种逐笔账本独立重建、72账户现金守恒及36账户样本内截断前缀通过;原H1/5/10热度事件基线和H5现金基线精确复现。四指数阶段加总、费用顺序、缺值、43个本地链接和源摘要通过;本机Chrome10项验收,外部请求0,六图目视核验。研究代码不属于业务运行镜像,无受影响容器。接续见`docs/热度反复活跃矩阵研究接续_2026-10-29.md`。原有未提交日志、台账、文档及研究目录保持原样。
|
||||
|
||||
|
||||
## 2026-10-29 宏观价量网格与三因素首轮实验
|
||||
|
||||
核验时间:2026-10-29 11:50,北京时间。用户要求先固定口径,用既有数据比较同步形成、进入方向和价格推进效率,并交付热力图、各风格结果及当前区间。协议11时10分冻结并提交2877c59;新增研究目录research/macro_grid_20261029,报告和接续均已保存。行情截至10月23日,没有新取数。
|
||||
|
||||
五完整年训练、下一年检验,2024至2026年六个主要或扩展目标各657个日期。四个主目标的三项合用Brier误差分别增加8.48%、9.77%、13.05%、9.60%,28项主比较没有正增量通过综合标准。原有信息基线优于当前网格表示。同步高位停滞21日实为5段相连行情,保留衰减条件线索;不据负结果修改协议或重选参数。
|
||||
|
||||
当前是10月23日快照:沪深300所在层4016至4370,创业板2553至3128,中证2000为2521至2944;上方同步候选分别4576至4661、无(3128至3324仅几何参考)、2944至3042。三个风格均在最低层,没有完整下方相邻格;层下沿不称验证支撑,双侧首达有效分母为零。模型概率校准表现不佳,微盘50.7%原始上涨分数不当可信胜率。下一轮建议减少逐格交互、区分同步形成与停滞,并增加尾部固定ATR细格。
|
||||
|
||||
开发机12项配置隔离、断网测试通过;独立复核600个特征窗口、18次QRS、3942条未来收益与分类、39420行概率、18个训练边界、3285条路径风险、393条首达记录,14个截断对比、36次模型重放及12次当前概率重放通过。八幅PNG已目视检查,链接与摘要校验通过。研究计算不导入业务配置,不访问服务器;只在准备本地环境时安装研究依赖。未改应用、运行参数、数据库、持仓或容器,无受影响业务镜像,155和188均未操作。
|
||||
|
||||
接续见docs/宏观网格研究接续_2026-10-29.md。现有未提交日志、台账、旧研究材料、探针与其他工作树保留;仅提交本轮新增内容。
|
||||
|
||||
|
||||
## 2026-10-29 微盘轮动自然冻结与收盘复核
|
||||
|
||||
核验时间16:16:42至16:18:38,北京时间,155模拟PMS只读检查。50股micro50-v2-20261028于08:50:12自然冻结,08:51被PMS读取;数据10月28日,历史分位9.39%,三个信号均未触发。09:30持仓行情缺失守成,09:31恢复,后29次窗口任务无阻断、无交易意图;微盘继续空仓。
|
||||
|
||||
QMT11:53:36至11:54:04短暂中断,自动重连恢复,外部原因未核实;当前确认1484434推进到1484463,无序号缺口、新reject、待处理或待归属成交,resync=false,资金快照5秒内。主观量化四方2700股;今日买2700、卖100均有实际成交并按委托入账,账户数量及现金对账差异0、活动子委托0。QMT费用字段为null且未扣费,费用验收仍保留,未补造费用。
|
||||
|
||||
明日快照等待10月29日收盘源数据,当前最新数据10月28日;既有监控继续自动补算。镜像、运行参数、暂停、数据库及服务均未改,不访问188。自然冻结与无信号流程已有真机证据,完整微盘入退场仍未判收。文档与证据断言、链接及差异检查通过,无业务代码变更,不重复全量回归。详见docs/微盘轮动每日复核_2026-10-29.md及docs/evidence/micro50_daily_20261029.json,阶段接续已更新。保留本地已有114行DEVLOG、10行复盘台账及其他研究修改;当前研究分支未见远程同名分支,本次记录仅本地提交,不推送其他研究历史。
|
||||
|
||||
|
||||
## 2026-10-29 历史风控提醒修复与质地排名核验
|
||||
|
||||
用户指出check_qmt_connection长期出现在风控提醒,并要求检查排名规则切换后的选股计划。155只读定位到日志295:10月27日15:52旧故障,17:06日志296已有修复对账通过。页面未按日期过滤操作日志、只显示时分,并将所有BLOCKED泛称合规拦截。修复仅涉及index.html:当前消息按服务端北京日期过滤,历史保留完整日期,补连接检查中文名称,通用失败显示未完成。没有删除或改写日志,今日失败操作实际为0。
|
||||
|
||||
主观量化排序运行态为桥quality、PMS upstream、空传导白名单。14:32真实消费记录219在同一不可变版本、同一参数及持仓上下文内存回放,7只顺序完全一致;最新15:05版本名单相同,强/弱/无传导各2/2/3。上游前300只、默认同主题5只仍生效:现行7只候选;扩范围并保留主题限额为7候选加7关注;完整561只取消主题限额的对照为8候选加16关注。汇川技术研究第49、质地中、判为候选,却因模组主题前五只占满被裁;额外16只关注均质地差。仅作范围对照,没有调整参数或生成测试委托。当前人工确认的威胜信息为池首位,并纠正早先复核文档对688100.SH的简称误写。
|
||||
|
||||
代码提交b96ce9f,155单独应用补丁为06570ad;web于16:43发布pms:alerts-b96ce9f,其余交易服务保持原容器。开发机和155候选镜像全量隔离断网回归及三道页面护栏通过;Chrome 1440/390宽度、当日与历史日志、跨日及未知日期、美国浏览器时区下北京日期验证通过,实际部署HTML摘要一致并重放通过,零控制台错误、零外部或写请求。不是交易员真实登录判收。
|
||||
|
||||
部署前Git身份缺失在业务动作前中止,随后用单次命令提交身份处理;一次发布校验把环境变量顺序误判为变更,web自动回退,核实键值一致并改成映射比较后重发。16:43:46核验参数、暂停、资金、持仓未变;QMT确认1484807推进到1484864,无新增重连或拒绝、无待入账及归属待核,resync=false,资金快照11.4秒,数量和现金对账差异0。未访问188。详情及长期证据见docs/风控历史提醒修复与选股排名核验_2026-10-29.md,阶段接续已更新。保留原有114行DEVLOG、10行复盘台账及研究文件。
|
||||
|
||||
|
||||
## 2026-10-29 17:09|取消主题配额并发布微盘名单复制
|
||||
|
||||
- 用户要求选股取消主题限额、按现有排名筛选,同时在策略轮换页提供简洁的代码名称复制按钮。修正上游参数0原先被省略、导致默认每主题5只的语义;现在明确传theme_cap=0,本地主题限额也为0,运行参数无需改值。保留原排名、资格和交易约束。
|
||||
- 代码7ecf3a9,155补丁提交d91424a;web和worker已重建为pms:theme-copy-7ecf3a9,17:08:40核验。beat和唯一ws保持原进程,私有配置、环境和挂载保留,未触及188。首次核验误以匿名请求访问受保护的/rotation,401触发web和worker自动回退;改用公开静态路径校验后重新发布成功,QMT未重连。
|
||||
- 155 worker实际请求和上游回报均确认theme_cap=0。固定同一发布版只读对照,候选7变8,新增原研究排名49的汇川技术,原7只顺序不变。未制造真实委托或消费记录,后续自然调度消费仍待观察。
|
||||
- 本地及155候选镜像全量隔离回归通过,页面三道护栏通过。实际部署HTML与只读数据在Chrome重放,1440/390宽度、HTTP复制后粘贴50行、HTTPS剪贴板、空名单/故障禁用、失败反馈、刷新和排除残余持仓均通过;无控制台错误或业务写请求,不冒充真实登录验收。
|
||||
- 17:09:03 QMT连续确认1485267、待处理0、待归属0,无新增拒绝或重连;资金年龄28.2秒、冻结0、四方2700股及微盘空仓,数量和现金对账均无差异。17:09:54确认继续推进1485281。微盘规则、模式及全局暂停保持原值。
|
||||
- 记录见docs/选股取消主题限额与微盘名单复制_2026-10-29.md及docs/evidence/pms_theme_copy_20261029.json,当前状态已更新阶段接续。原有114行DEVLOG未提交内容与其他研究改动保留,CLAUDE.md未修改。
|
||||
|
||||
|
||||
## 2026-10-30 筹码断档与吸筹次数首轮实验
|
||||
|
||||
按用户认可的方案,将现价上方稀疏与双峰断档分别研究,协议与参数在收益计算前冻结。155独立只读研究容器导出阶段快照、筹码分档和压力表,所有SQL单表,未继承业务挂载及交易凭证。行情截止10月29日,09:43核验本任务容器均已回收。无部署、参数调整或交易动作,未接触188真实PMS。
|
||||
|
||||
共14595个预定观察,10231个成熟,只有31个信号日和3个60日时间块。费用每边0.3%,成熟配对中上方稀疏21组胜率33.33%对19.05%,但平均净收益仍为负6.33%;上方双峰6组两边50%;下跌中至少2次独立吸筹14组两边57.14%。多次吸筹原始组54笔胜率46.30%,高于零次组38.57%,优势未在匹配后保留。15%拉升路径、组合条件与费用敏感性另列,未据小样本进行正式显著性判定。
|
||||
|
||||
套牢盘压力表只有26个数据日,较长历史依赖回填筹码与252日阶段回放。2286条分档核实ocr_above为严格高于现价的原始占比,ocr_115为成本达到现价115%及以上的远端占比。吸筹次数与固定价格门槛下套牢变化的描述性相关约负0.016,未证实清楚线性关系。粗分档、历史证券及行业覆盖、交易日历表为空等限制写入报告。
|
||||
|
||||
开发机10项配置隔离、断网专项测试通过;500条观察独立复算,97组配对逐项核对,98项源摘要一致;原始缓存重建筹码特征后摘要不变,四幅研究图检查通过。协议、代码、结果、审计和文件摘要位于research/chip_accumulation_20261030,当前状态见docs/筹码断档与吸筹研究接续_2026-10-30.md。研究原始数据和中间缓存留在开发机,不入Git。
|
||||
|
||||
尚未完成冻结后新样本的前瞻60日验证,也未完成真实交易链路验收;没有创建新的定时任务。保留原有114行DEVLOG未提交修改、复盘台账及其他未跟踪研究材料,仅提交本轮研究文件与本条记录。
|
||||
|
||||
## 2026-10-30 全量股票筹码与吸筹绝对收益实验
|
||||
|
||||
按用户最新要求取消匹配及相对胜率,取消股票代码十四分之一和周度抽样,覆盖现有5604只沪深北股票。5405只曾满足资格或资料不足观察门槛,5356只触发至少一个条件,合计467623个股票日。206天完整筹码共114000514条分档。保留首轮阈值,分别统计两类断档、吸筹轮次与明确吸筹天数、下跌联合条件;筹码单独条件不依赖阶段窗口。
|
||||
|
||||
每边成本0.3%,同股持仓期间不重复买入,复权争议单列后:上方稀疏9264笔,胜率33.03%,均值负3.60%;上方双峰1702笔,34.96%,负2.64%;下跌多次吸筹297笔,41.41%,负1.08%;下跌稀疏多次22笔,18.18%,负8.98%;下跌双峰多次12笔,16.67%,负12.42%。全部触发日的多次吸筹3802次,胜率48.21%、均值正0.90%,中位负0.82%;它与不重叠入场回答不同问题,两份结果同时保留,没有把重复观察当独立交易,也没有构造账户年化收益。
|
||||
|
||||
极端值核验发现33只股票40个股票日存在复权与日线昨收及公布涨跌幅口径争议,包括11只北交所股票10月27日因子大幅缩小。没有擅改因子,保留原始结果与全部争议行,固定双向审计规则给出争议单列结果和胜率边界,原始买卖选择不变。上方稀疏6笔、上方双峰2笔完成交易受影响,吸筹主条件不受影响。事后触发的质量审计明确披露,不能冒充预注册新策略或外部权益事件核验。
|
||||
|
||||
开发机17项配置隔离且断网专项测试通过;独立复算1000条真实观察,回放48个条件与资格范围,核对242项源摘要和三个实际历史前缀;25606个新旧重合股票日的筹码标记一致,96组质量结果与原始总数、争议数量及边界一致。两幅最终图已检查。155仅用于独立只读容器,208次实际镜像回执已登记,11:02确认本任务容器剩余0;没有部署、参数变更或交易动作,未接触188。期间业务镜像由其他工作更新,本任务没有参与。
|
||||
|
||||
结果、协议、代码、覆盖、质量审计和摘要清单位于research/chip_absolute_all_20261030,当前状态已更新研究接续和开发入口。只有3至4个60日时间块,联合条件仍小样本,阶段回放及筹码回填不等于历史真实可得。证券与退市历史、独立交易日历和复权争议的外部逐股核验未完成;没有创建定时观察或上线。原始快照和中间缓存不入Git;保留原有114行DEVLOG、复盘台账及其他未跟踪研究材料,仅提交本轮文件和本条日志。
|
||||
|
||||
## 2026-10-30 结束筹码吸筹研究并明确北交所范围禁区
|
||||
|
||||
11:13按用户最新决定结束筹码断档、套牢盘及吸筹次数研究,已有结果归档,不再扩样、调参、补前瞻观察或继续本研究遗留核验。开发入口和研究接续已标为结束,历史未来计划不再列为待办。
|
||||
|
||||
根AGENTS.md明确北交所不属于任何研究、分析、回测、选股和交易范围,“全市场”“全部股票”限定在沪深范围内。要求在数据读取或样本构建入口按交易所及规范化代码排除,不额外导出、补资料、核验或生成交易动作;研究目录仅引用根规则,避免复制多套约束。历史含北交所的实验保留原样,不重新计算。
|
||||
|
||||
本次仅改规则及状态文档,开发机内容、链接和差异检查通过;没有运行数据分析、调整运行参数、修改交易代码或部署。保留原有114行DEVLOG、复盘台账及其他研究文件,仅提交本条日志和本轮文档。
|
||||
|
||||
|
||||
## 2026-10-30 热度与评分四轮实验核心图汇总
|
||||
|
||||
按用户要求只整理本对话已有的单日热度、双评分阈值、评分频次及热度频次四轮实验,不追加回测、不重新优化参数。固定六张图:双评分年度门槛、评分次数与持有期、热度门槛与次数、四指数阶段、费用敏感性和热度样本覆盖。所有收益图明确平均每批口径与同日配对差,保留加费后仍为正的既有观察点,区分局部改善、绝对收益及独立验证。
|
||||
|
||||
交付research/strategy_chart_review_20261030/热度与评分实验六图汇总.html,附六张PNG、六张SVG、六份绘图数据、复现程序及源摘要。现有来源证券索引核实仅含沪深;未追加数据库读取、改变股票范围或涉及已结束的筹码研究。开发入口已增加图集链接。
|
||||
|
||||
开发机macOS核验406行绘图数据与原聚合结果一致,源摘要及本地引用通过。独立无头Chrome在1440及430像素下验证六图加载、目录跳转、数据展开和无页面横向溢出,外部请求及页面错误均为0;六张图、桌面与窄屏截图已目视。核验时刻:2026-10-30T13:14:00.910872+08:00,状态与证据见manifest.json及visual_review.json。
|
||||
|
||||
本次图表整理已完成。评分历史版本及首次可用时间、热度短样本和历史回填、真实费用与成交容量的原有限制保留,没有将事后正格升格为上线参数。无运行策略、服务、参数或账本变更。保留原有114行DEVLOG、10行复盘台账及其他未跟踪研究材料,仅提交本轮图集、入口和本条记录。
|
||||
|
||||
|
||||
## 2026-10-30 补充当前热度说明与单日选股图
|
||||
|
||||
按用户指出的缺项,在原图集开头补充热度字段、最大批次读取方式、0.80数值门槛及持仓策略挂载用途;明确运行值依据10月29日09:58回执,本次没有重新核验服务器开关或参数。现有代码中高热度与浮盈是跟踪止盈条件之一,不能把固定持有期选股实验等同于PMS整体收益;上游公式权重与不可改写历史版本仍未取得。
|
||||
|
||||
新增第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-11-03 执行报价与异步研判实现
|
||||
|
||||
用户确认实施。使用独立codex工作树,保留原工作树未提交文件。新增异步研判持久化、共同撤单确认后重挂、原始执行依据追溯及微盘v3冻结备选。取消、过期和部分成交均按实际出口回报及入账收尾;逐单释放已核实的未成交占用。已授权卖出不因看空依据被反向阻断。
|
||||
|
||||
实现与启用条件见docs/执行报价与异步研判实施规格_2026-11-03.md。首次本地全量发现一处旧取消测试预期,与新pending/confirmed语义不符,已交专项修正。后续将合并155已发布源并重新全量验证。当前没有新功能启用、没有测试下单,也未操作188真实PMS。
|
||||
## 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)。
|
||||
|
||||
## 2026-11-03 选股计划用户候选同步发布(12:17核验)
|
||||
|
||||
用户随后明确回复“允许同步发布到155”,上条待授权记录已成为历史。11:57完成首次同步发布;进一步补齐旧调用方隔离,12:16:14将PMS web、worker更新为 `pms:plan-user-934d46f`,上游12:16:09更新为 `bridge:plan-user-04339be`。开发提交分别为934d46f、04339be,均已推送同名功能分支并直接核对远程;155应用提交分别为5b75ade、36b9e08。仅新增来源入口,未改变基本面、技术面、盘中研判、排序、资金及执行限制。旧调用方默认不取用户独有候选,新版PMS显式声明取用,逐票核验和缓存同步隔离。
|
||||
|
||||
开发机与155最终候选镜像的全量隔离检查均通过,PMS末行为 `ALL SUITES PASS`,上游60项 `OK`;PMS用户候选专项9项,页面三道护栏及1440/390像素固定示例浏览器验收通过。最终补丁只涉及取用接口与兼容过滤,页面摘要保持 `88d0fe421e558b2628f362f754a5bbc9805d3fe3ac43e218aef60d3afd1d654d`;开发机、155源码、web及worker代码指纹均为 `e3e8dbb38c36`。155列表及搜索接口可用、写入配置就绪,worker自然调度已成功完成10项任务,访问日志确认新版显式请求,最终三个服务无错误日志。
|
||||
|
||||
12:17:27真机只读核验:QMT确认与接收序号同为1595743,最新160条连续,缺口、待入账、待归属及新增拒绝均为0,重连累计8保持;资金年龄21.5秒,数量及现金对账0差异。原有2笔受理委托保持,不创建测试委托或登记示例股票。主观新开仓仍为 `propose_only`,版本复核开启,轮换auto/run、两项全局暂停false;唯一WS和beat保持原容器与启动时间,188未操作。
|
||||
|
||||
配置与发布文件备份位于155的 `backups/plan-user-20261103-035319`,最终补丁覆盖配置备份位于 `backups/plan-optin-20261103-041529`。私有部署脚本、环境与上游data保留,写入凭据只进入私有环境配置。首次发布的备份权限及Git身份问题在恢复前解决;web一次冷启动高股息读取超时随后恢复。最终补丁温和结束上游服务进程后收尾其等待包装进程;发布后环境列表顺序比较触发误报,按配置键值及Compose美元符转义核对相符,未因此再次重建。
|
||||
|
||||
12:20:39追加核验:上游自然刷新健康时间已推进到12:20:15,无错误、待评估代码为空;输入未变,正确沿用12:15发布的既有决策版本。未制造首次真实添加、到期移除或交易案例,这些行为的边界通过隔离测试和固定示例浏览器验证。回退前须停止新增来源消费,并核对仍有效的用户来源及在途指令;不可直接让旧PMS消费含用户独有候选的发布文件,不覆盖已发布历史、持仓或成交。证据见[155用户候选发布核验](docs/evidence/pms_plan_user_candidates_20261103.json)。
|
||||
|
||||
## 2026-11-03 批量股票名称修复(12:41核验)
|
||||
|
||||
用户反馈华策影视、中文在线、捷成股份、掌阅科技、百纳千成、果麦文化被误报为不支持的证券。已复现两个缺陷:直接粘贴的名称虽在提交时拆分,却直接进入代码校验;搜索又只读行业池,遗漏其中四只。改为从现有上市证券基础表读取沪深A股名单,名称精确映射代码,混合输入及各种分隔符整批校验后保存;未知或重名输入明确提示,不部分写入。前端粘贴即拆成独立标签,接口去除面向用户的异常类名。完整证券名称作为真实修订输入录制,重放不回源;风险名称和既有基本面、技术面、择时、评分及执行限制继续生效。
|
||||
|
||||
开发机及155最终候选镜像均通过隔离回归:PMS `ALL SUITES PASS`,上游64项 `OK`;页面三道护栏、1440和390像素浏览器复现通过,六个名称保存为六代码,未知名称整批拒绝,控制台错误和警告0。12:39:42仅web发布 `pms:plan-names-8e6ce09`,上游12:39:38发布 `bridge:plan-names-c11ae65`;开发提交8e6ce09/c11ae65已推送并核对远程,155代码b8037d5/d9c4b92。worker、beat、唯一WS保持原容器,环境、挂载、用户参数、私有脚本和上游data保持。
|
||||
|
||||
12:40:19真机只读核验:六只均可经PMS搜索且唯一映射,批量解析结果与证券基础表一致;登记仍为0条、revision=0,没有代替用户添加。确认序号1596110与接收相等,最新160条无缺口,资金13.1秒,数量现金对账0差异,无新增拒绝和重连。12:40:24上游自然刷新完成,无错误或待评估积压。web启动后高股息接口一次超时,随后只读调用恢复182行;新增搜索与解析正常。代码指纹 `1d92e659f123`,页面摘要 `adbd12d451f62a1ebdbf9463ec3db1080b9dd1e5c157198b85da630bc3c71fee` 与本机一致。备份及证据见[批量股票名称修复核验](docs/evidence/pms_plan_candidate_names_20261103.json)。首次真实登记与自然评估仍由用户正常操作,不制造测试委托。
|
||||
|
||||
|
||||
### 2026-11-03 14:14 自然调度补修
|
||||
|
||||
155首轮发布后,页面、QMT回放和对账正常,但自然调度暴露scheduler新增入口缺少模块级ParamStore导入,执行扫描按守成中止。原测试只核对调度注册,未直接调用此入口。已补导入和五项真实任务入口隔离测试,覆盖新旧扫描、独立刷新与全局暂停下撤单收尾。按候选镜像断网回归后仅重建受影响worker,其他服务不为追平版本重建。最终结果另记。
|
||||
|
||||
|
||||
## 2026-11-03 14:37 执行链路发布准备与实际边界
|
||||
|
||||
PMS最终代码56db0fd已推送,155 web/WS/beat为execution-2b1c447,worker为execution-56db0fd;14:19仅重建worker修复自然调度发现的入口导入缺失,五项入口测试及本地、候选全量通过。微盘监控已换00f6785代码但保持v2,既有冻结文件不变。实际资金快照2.8秒、数量及现金对账无差异、待入账与孤儿均0。新改价与异步消费仍关闭,当天沪深限制价缺失,不能提前切v3。
|
||||
|
||||
188最初候选构建被自动审批拒绝后,用户明确授权仅API、brain、pms三个bionic服务收盘后发布。现已完成候选15组断网检查、私有回退备份、独立持久源码工作树及仅三服务覆盖配置核对;首次打包遗漏公开配置样例已修正并完整重跑。运行容器尚未改变,不操作188真实PMS,也不变更其他服务共享的源码或环境。具体提交、镜像、证据和后续动作见docs/执行报价与异步研判发布接续_2026-11-03.md。
|
||||
|
||||
14:38已在Codex应用安排本对话15:10一次性收盘后续作,ID为bionic,次数1。提示明确三个获授权服务、候选证据、独立源码、回退、155后续开关及真实数据缺口。安排成功不等于发布完成,不恢复旧定期观察。
|
||||
|
||||
|
||||
## 2026-11-03 15:17 收盘后完成三个bionic服务发布
|
||||
|
||||
用户授权的188 API、brain、pms于15:12:01完成定向重建,两个worker先停消费并确认无在途。镜像execution-00f6785及独立挂载源码一致,15组候选断网回归、实际配置、API根路径、异步结果只读GET和任务注册均通过。原共享源码e9681e4及.env保持,188真实PMS未操作;其他容器45个保持,quant_ml_trainer在本次操作之前15:08发生外部重建,不能把该基线差异归成本次或隐去。现用.env中已有ACCUM_PHASE等配置随重建注入,未修改既有值。
|
||||
|
||||
155于15:16:06经ParamStore开启异步消费。15:17自然任务正确遵守收盘守卫,撤单收尾无错误;15:16:53确认1598615、160条连续、资金23.5秒、现金数量无差异、无在途待入账孤儿。当前异步请求0条,未制造请求、信号或委托,模型完成及超时仍待自然判收。当天沪深限制价记录0,新报价与微盘v3仍关闭,不能称为全部执行能力已启用。一次性bionic续作已通过应用删除,不恢复旧观察。详细配置、证据和可运行只读验证见docs/执行报价与异步研判发布接续_2026-11-03.md。
|
||||
|
||||
|
||||
## 2026-11-03 15:40 按用户指令开启改价与微盘v3
|
||||
|
||||
用户新指令明确开启,并评估用收盘日线计算次日限制价。15:37:30仅重建155微盘监控注入v3及100候选,沿用已验证镜像与挂载,16个v2文件未变、旧容器停止保留。15:37:53经ParamStore开启改价并同步v3,异步保持true;首个审计标签超长导致写入失败,未生效,缩短后逐项核对成功。没有Python变更或额外重建PMS容器。
|
||||
|
||||
15:38新v3快照50首选100候选、信号与名单就绪,数据11-02/执行11-03,frozen=false;11-04版待夜间数据,不回填早盘冻结。15:40确认1598996、最近160条连续、资金10.3秒、数量现金一致,无待入账和孤儿。已安排11-04 10:00一次性任务v3核验自然请求,未恢复长期观察。
|
||||
|
||||
现行交易所规则与源表核实后,日线计算评估为普通情形可行,但缺完整目标日公司行为与证券状态,不能作为唯一精确兜底。发现11-04已有明确除息个例,报价与名称资料陈旧,故本轮未将推算接入下单;保留正式当日限制价及逐票等待。该评估和真实数据日期、回退备份、当前参数及验证安排已写发布接续和决策台账。
|
||||
|
||||
## 2026-11-03 当日限制价独立采集代码完成
|
||||
|
||||
按用户批准方案实现155模拟PMS的独立采集、本地当日缓存和两个执行消费入口。实际Tushare单证券HTTPS可取得11月3日记录,逗号批量代码返回空,故采用逐票限速。目标覆盖原策略全部持仓、活动指令、在途、计划和建议,以及微盘完整100候选;入口排除北交所。查询共享gp_stk_limit的pre_close列存在,但11月2日实际样本为空,因此该票需要Tushare补全证据,不能冒充已完整校验。
|
||||
|
||||
新增缓存及采集开关默认关闭,密钥仅专用采集容器注入。价格严格校验、跨日失效、逐票隔离、重试退避、租约防并发、来源版本留痕均已实现;日线推算不进入下单。只读复核确认本次不需重建WS或beat,待发布目标为worker、web和新增采集进程。
|
||||
|
||||
开发机新增121项隔离检查通过,最终全量末行ALL SUITES PASS,日志/private/tmp/pms-limits-local-tests-release-20261103.log。审查补齐共享坏值重复退避、超时票饥饿、单票脏元数据及开关损坏四类边界。后续以已提交代码构建候选并完成155断网全量,再启动采集和核对实际覆盖;本条不代表已部署或自然交易判收。
|
||||
|
||||
|
||||
## 2026-11-03 16:47 限制价补齐发布完成及雷赛智能迟报处理
|
||||
|
||||
155候选pms:limits-0b3c50e完成断网全量ALL SUITES PASS。16:31:49仅重建web和worker、增加独立采集,先排空原worker;唯一WS、beat和微盘监控未动,其他12个运行服务不变。原.env保持,专用凭据权限600、只进采集容器,数据库5秒读写超时仅作用于采集。16:38在103/103当日目标及完整100候选就绪后开启缓存。16:47采集COMPLETE、错误0,两个执行消费入口真实取到来源及版本,报价仍遵从分钟行情新鲜度。
|
||||
|
||||
核验发现16:16盘后回补导致雷赛智能100股缺账,早于本次发布。用户确认盘中实际成交48.29元,沿既有回放当天入original,现金和数量归零差异。另按seq1599512原始FILLED回执对同一子单作审计更正,保留seq1598347原EXPIRED,不改通用终态保护。父目标300、累计100、剩余200;费用仍未知。没有新委托、伪造回报或自动跨策略认领。
|
||||
|
||||
16:47确认1600016、160条连续、资金16.9秒,待入账/孤儿/在途均0,账实一致。自然异步仍0,明日快照尚待夜间生成;已更新11-04 10:00一次性v3核验,加入当日缓存及迟报防重检查。实际配置、备份、测试日志和回退见发布接续及docs/evidence/pms_price_limits_release_20261103.json。后续仅文档推送不重建镜像。
|
||||
|
||||
|
||||
## 2026-11-05 QMT工作台成交修正接入
|
||||
|
||||
按用户提供的trade_correction协议实现原成交号不变、修正编号幂等及配套amended委托回报。修正与累计回报先收存并等待连续水位,原成交先入账;后续按原策略归属、当前有效版本和完整批次证据核验后,在同账户事务内调整本金、数量、成本、父子进度及网格档位,原始成交与费用事实保留。终态不恢复,数量下降不自动补单;缺失新持仓快照只等待,身份冲突、跨旧仓轮次或无法证明现账时挂起审计。
|
||||
|
||||
补齐普通成交的批次来源凭据、终态累计数量审计、资金快照截止、旧委托状态并发写回和网格旧任务/旧提议版本保护。挂起结果沿回放与日终摘要显示,不以ok=true遮蔽待核实。普通amended=false报文兼容,无关坏回执不污染其它修正。新专项覆盖批次投影、报文乱序重复、资金事务、普通入账凭据及网格并发;开发机全量ALL SUITES PASS,最后坏行隔离另做定向验证,最终提交仍需候选断网全量。
|
||||
|
||||
155发布前数量、现金一致,无待入账、孤儿或真实修正报文。计划仅重建web、worker和唯一WS,保留配置、其他服务及188。实际镜像和自然判收将在本次[成交修正接续](docs/QMT成交修正接入与发布_2026-11-05.md)追加,本条不代表已发布。
|
||||
|
||||
|
||||
## 2026-11-05 09:36 成交修正发布核验
|
||||
|
||||
155候选f756344断网全量ALL SUITES PASS后,09:32:42仅更新web、worker、唯一WS为pms:trade-correction-f756344。先暂停目标worker消费并核对在途为0,未强杀任务。其余15个容器完整基线不变,私有配置和挂载保持,188未操作。09:33:46确认1639151、近200条连续,资金0.5秒、现金数量一致,待入账与孤儿0。09:36新worker自然完成三轮关键任务,WS容器/进程均唯一,三个服务无Traceback,代码指纹97764c9aeff1。
|
||||
|
||||
实际修正报文0,未伪造测试验收。134项专项及候选全量均通过,原链路健康与真实修正尚未发生分别记录。发布镜像、配置备份及修正已入账后不能直接降回不兼容旧版本的边界见[成交修正接续](docs/QMT成交修正接入与发布_2026-11-05.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,10 +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
|
||||
|
|
@ -199,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 | 回应 |
|
||||
|
|
@ -256,7 +268,7 @@ QMT 撤在途部分,已成交部分保留。撤单完成后该指令进入 `CA
|
|||
|
||||
### 5.4 `order_update` —— 委托状态变更
|
||||
|
||||
每次状态发生变化推一条,**终态必须推且只推一次**。
|
||||
每次状态发生变化推一条,普通执行终态必须推送。终态后的成交修正另按§5.5.1处理,不表示重新开放执行。
|
||||
|
||||
```json
|
||||
{
|
||||
|
|
@ -272,7 +284,7 @@ QMT 撤在途部分,已成交部分保留。撤单完成后该指令进入 `CA
|
|||
| `cum_qty` | **本委托**累计成交股数。口径明确为本委托,不是当日、不是该股票持仓 |
|
||||
| `cum_avg_price` | **本委托**累计成交均价,2 位小数 |
|
||||
| `leaves_qty` | 未成交剩余 = `qty - cum_qty`。撤单/过期后应为 0 |
|
||||
| `final` | 是否终态。终态后该 `instruction_id` 不再有任何 `order_update` |
|
||||
| `final` | 是否执行终态。普通状态不能使终态回退;终态后的修正配套回报须带§5.5.1标记 |
|
||||
|
||||
> 这三个字段是为了消灭原 `trading_log` 示例里 `total_filled=5000` 而 `order_quantity=600` 那种口径歧义。凡是累计量,一律以「本委托」为准。
|
||||
|
||||
|
|
@ -292,17 +304,42 @@ QMT 撤在途部分,已成交部分保留。撤单完成后该指令进入 `CA
|
|||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `trade_no` | 该笔成交的唯一编号。**格式固定为 `{broker_order_id}#{n}`**,`n` 为该委托内成交序号,从 1 起递增。券商原生只提供委托号(`order_id`),一次委托多次成交时委托号相同、无法区分,故由 QMT 按此规则拼出笔号。跨重启唯一性由「委托号唯一 + n 从该委托已回报笔数续接」保证 |
|
||||
| `trade_no` | 该笔成交的稳定唯一编号。普通券商成交沿用`{broker_order_id}#{n}`,工作台可使用`T-DESK-…`。PMS将其作为不透明标识,不根据格式推断策略。修正时不换号,跨重启仍须唯一 |
|
||||
| `qty` / `price` | **本笔**成交股数与价格 |
|
||||
| `amount` | `price × qty`,QMT 给出,PMS 会校验一致性(差异 > 0.01 元告警) |
|
||||
| `fee` | 本笔手续费(佣金 + 印花税 + 过户费合计)。QMT 侧按费率**估算**,与实际扣费可能有误差 |
|
||||
| `fee_estimated` | `true` 表示 `fee` 为估算值。PMS 据此决定是否把它计入成本 |
|
||||
| `fee_estimated` | `true`表示`fee`为估算值,用于费用追溯;不改变费用与成交成本分开记录的口径 |
|
||||
|
||||
**关于手续费的处理口径**(QMT 侧已说明逐笔费用未必精确):PMS **不把 `fee` 摊进持仓成本**,成本价只由 `price × qty` 决定;费用单独记为一笔现金流出。这样估算误差不会污染摊薄成本,进而不会污染安全垫(cushion)与保垫减仓的判断——这是 PMS 里最不能被噪声干扰的一条计算链。真实费用在日终用资金快照反推校准(总资产变动 − 成交净额 = 当日实际费用),只入现金账,不回溯改成本。
|
||||
**关于手续费的处理口径**:PMS不把`fee`摊进成交成本,费用单独记为现金流出。费用为空表示未知。双策略场景不能用账户总资产变化倒推并分摊逐笔费用;真实费用须按实际明细另行核对。历史日总额校准接口不能替代安全的分策略费用后补流程,成交修正也不承担费用后补。
|
||||
|
||||
**PMS 的账本以 `trade` 为唯一入账依据**,`order_update` 只用于状态跟踪与最终核对(用终态的 `cum_qty` 校验逐笔加总是否相等,不等则告警)。这样即使某条 `order_update` 丢失也不会记错账。
|
||||
**普通成交只以 `trade` 入账**。`order_update`不能产生新成交。已成交事实的更正只经§5.5.1的独立审计流程,原`trade`保留;有效逐笔合计仍须与对应委托累计量核对。
|
||||
|
||||
去重是双层的:**第一层按 `seq`**(补发时同一条消息 `seq` 不变,见 §6.1),**第二层按 `trade_no`**。任一层命中即丢弃。第二层的意义是防住 `seq` 实现出 bug 的场景,两层都命中才入账。
|
||||
普通成交去重是双层的:**第一层按 `seq`**(补发时同一条消息 `seq` 不变,见 §6.1),**第二层按 `trade_no`**。任一层命中均不重复入账,两层都未命中才处理。新序号的重复消息仍留占位记录,保证连续确认不产生缺口。
|
||||
|
||||
### 5.5.1 `trade_correction` —— 成交修正(工作台)
|
||||
|
||||
交易员纠正已推送成交的价量时,不改变`trade_no`。QMT发送一条修正,并发送配套的`order_update`。
|
||||
|
||||
```json
|
||||
{
|
||||
"correction_id": "AMD-20261104-a1b2c3d4e5f6",
|
||||
"instruction_id": "INS-...", "broker_order_id": "DESK-...",
|
||||
"trade_no": "T-DESK-abc123",
|
||||
"ts_code": "600000.SH", "side": "buy",
|
||||
"before": { "qty": 100, "price": 10.50, "amount": 1050.00 },
|
||||
"after": { "qty": 100, "price": 10.48, "amount": 1048.00 },
|
||||
"reason": "desk_trader_fix",
|
||||
"correct_time": 1769500200000
|
||||
}
|
||||
```
|
||||
|
||||
配套`order_update`包含`amended: true`、`reason: "trade_correction"`和相同`correction_id`。原信封、签名、序号与连续确认规则不变。两种消息均先持久化,PMS在worker中配对核验,收到顺序不构成业务依赖。
|
||||
|
||||
`correction_id`是幂等键。同编号同内容只处理一次;同编号异内容保留冲突,不能覆盖先前事实。原成交、修正前后及每次处理结果均留存。再次修正同一成交,`before`必须对应前次已应用的有效版本,而非最初原文。
|
||||
|
||||
累计成交可能减少,但QMT保证不超过原指令数量。PMS还会核验子委托和父指令总量。终态保留,已终结的委托剩余量保持零。数量修正不自动授权补差或重新执行原父指令;相关执行须待复核。普通`order_update`不能绕过修正链改变已审计的终态累计事实。
|
||||
|
||||
修正只能改变已核实的成交本金、数量及相关账本派生值。费用另按真实明细处理,缺少费用仍表示未知;不能用含费持仓成本覆盖成交价格,也不能由价差推算手续费。完整可核验的处理边界、事务及发布状态见[成交修正接入说明](docs/QMT成交修正接入与发布_2026-11-05.md)。
|
||||
|
||||
### 5.6 `persist_result` —— 落库结果
|
||||
|
||||
|
|
@ -408,7 +445,7 @@ QMT 侧为每条上行消息分配单调递增 `seq` 并**持久化到 Redis**
|
|||
└──────────┘
|
||||
```
|
||||
|
||||
**终态**:`FILLED` / `CANCELLED` / `EXPIRED` / `REJECTED`。终态唯一、不可再变、必须推送一次 `order_update{final:true}`。
|
||||
**终态**:`FILLED` / `CANCELLED` / `EXPIRED` / `REJECTED`。普通执行状态不可从终态回退,必须推送`order_update{final:true}`。之后纠正已成交事实时使用§5.5.1,不恢复委托执行。
|
||||
|
||||
`CANCELLED` 与 `EXPIRED` 均可能带部分成交(`cum_qty > 0`),这是正常情况,PMS 会如实入账。
|
||||
|
||||
|
|
@ -534,3 +571,5 @@ 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签名,历史测试向量不变 |
|
||||
| V1.0.3 | 2026-11-05 | 接入工作台`trade_correction`及带修正标记的配套委托回报,按修正编号幂等并保留原成交,终态不恢复执行;信封版本与签名算法不变 |
|
||||
|
|
|
|||
30
README.md
30
README.md
|
|
@ -8,10 +8,17 @@
|
|||
|
||||
## 文档与交付物
|
||||
|
||||
当前工作从[AGENTS.md](AGENTS.md)和[开发入口](docs/开发入口.md)开始。本文保留系统说明及历史初始化、联调步骤,涉及旧参数、影子模式、测试委托和回退的内容须结合最新接续与会话授权判断。
|
||||
|
||||
2026年11月5日成交修正接入:QMT的 `trade_correction` 与配套修正委托回报成对核验,按原策略归属调整本金、持仓及批次,同时保留原成交和审计。数量修正不恢复自动续单;缺少完整证据时挂起核实,费用未知仍保留未知。实现、发布和自然判收分别见[成交修正接续](docs/QMT成交修正接入与发布_2026-11-05.md)。
|
||||
|
||||
2026年11月4日开发补充:信号页独立保留有效人工关注,并提供已有信号、买方评析和每日、盘中观察分析入口。真实评析完成后,独立分钟任务发布研究名单;研究覆盖不从交易筛选结果提取。用户确认沿用公司质地排序,吸筹作为参考,建仓继续由基本面、技术面、择时三源合议及原研判、风险和资金约束决定。实现与边界见[修复规格](docs/人工关注分析链修复规格_2026-11-04.md),字段见[上游接口契约](UPSTREAM_PLAN_API.md)。开发验证通过不等于已发布或自然分析已经完成。
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `AGENTS.md` | Codex 项目指令与统一开发规则。`CLAUDE.md` 保留兼容入口 |
|
||||
| `docs/开发接续_2026-10-12.md` | 中断后的工作接续:两个未合入修复、未执行探针、待确认事项与本地验证边界 |
|
||||
| `AGENTS.md` | 工作流程、授权边界和关键禁区。目录规则与按需技能见 `docs/开发入口.md`;`CLAUDE.md` 保留原样,不再同步维护 |
|
||||
| `docs/开发入口.md` | 按任务查找目录规则、部署与QMT排障技能、当前接续和历史证据 |
|
||||
| `docs/开发接续_2026-10-12.md` | 通用迁移、修复整合与历史判收。当前专题状态由开发入口指向最新接续 |
|
||||
| `POSITION_MGMT_DESIGN.md` | 总体设计 **V0.4(定稿,开发启动)**:命令系统与管理页面/账本/仓位框架/动作引擎/两道关口/择时执行/下游通道。功能一次性开发,上线按依赖分三步切换 |
|
||||
| `QMT_WS_PROTOCOL.md` | **PMS ↔ QMT WebSocket 指令与回报协议 V1.0(定稿)**:传输与重连、Ed25519 签名与幂等、消息集、状态机、断线补发与对账兜底、部署前检查清单。**这是下发通道的唯一实现依据** |
|
||||
| `QMT_INTERFACE_REQUIREMENTS.md` | 与 QMT 侧的数据与接口需求清单 **V2.0**:A 部分(只读数据)与 C 部分(切换约定)有效;**B 部分的表通道已废止**,改由上面的 ws 协议承担 |
|
||||
|
|
@ -57,6 +64,8 @@ app/
|
|||
market.py 行情 (Redis db13) 与参考位 (决策系统主口径 + 兜底自算)
|
||||
plan_feed.py **上游选股计划 /plan 接入**: 解析 / 交易日龄校验 / 候选筛选
|
||||
/ 名册快照与榜单变化 (上游 changes 恒为 null, PMS 自己算)
|
||||
plan_candidates.py 人工关注登记代理;保存或移除后刷新独立研究名单
|
||||
monitor_watch.py 人工关注研究名单发布、版本核验及只读分析回执,不生成交易动作
|
||||
industry.py 行业划分可插拔适配器 (gp_hybk / custom_table / 停用; 带实探不靠参数)
|
||||
ws/runner.py **常驻连接进程 (pms-ws)**: 握手/心跳/重连/补发 + 出口出栈 + 上行落库确认
|
||||
web/ FastAPI + 单页 (Vue3 + ElementPlus),页面四块 + 运维/日报抽屉
|
||||
|
|
@ -495,12 +504,11 @@ docker compose --profile ws up -d pms-ws && docker compose logs -f pms-ws
|
|||
|
||||
## 开发约定
|
||||
|
||||
- 开发机与服务器经 git 同步代码;**构建与运行统一走 Docker**(`docker compose build` → 容器内 `python scripts/run_tests.py` → `up -d`),测试结果回传后迭代。
|
||||
- 153 代理侧数据库严格单表访问;该纪律已落到 `app/db/session.py` 的静态守卫,违规 SQL 在执行前抛 `MultiTableSQL`。持仓系统内部代码统一 Tushare 点式(`600000.SH`),读决策系统结论表时转前缀式。
|
||||
> 2026-07-28 修了守卫本身的一个误判:`ON DUPLICATE KEY UPDATE` 后面跟的是列名不是表名,原来会被当成第二张表,于是**所有 upsert 一执行就抛 `MultiTableSQL`**——页面改参数、`ensure_position`、日报落库、行业映射导入四条路径全中。单测走内存桩不经过该函数,所以一直没暴露。回归用例在 `test_batch6_units.py` 的 [G] 组。
|
||||
- 配置分两层:基础设施连接串在 `.env`(服务器手工维护,不入库,模板见 `.env.example`);业务参数在 `config/settings.py` 只是初值,上线后经管理页面修改并持久化到 `pms_runtime_param` 表。**业务代码禁止直接读 settings 取业务参数**,一律走 `services/param_store.py`。
|
||||
> 例外是**密钥**:`PMS_QMT_SIGN_SEED_HEX` / `PMS_QMT_PEER_PUBKEY_B64` 只走 `.env`(协议 §10.1.1),已列入 `param_store.SECRET_KEYS`——页面读不到、改不了、快照里也不出现。新增密钥类配置记得同步加进那个元组,否则它会被当成普通业务参数显示在参数设置页上。
|
||||
- 新增纯逻辑一律进 `app/core/`(零外部依赖 + 配套单测);需要连库的编排进 `app/services/`,并保证连库失败时降级而非崩页。ws 通道的协议编解码在 `app/core/ws_codec.py`,改动后**必须先跑通协议 §2.1.1 的测试向量**(`test_batch6_units.py` 的 [A] 组)——规范化串两边写不一致的话,联调只会告诉你"签名验不过",看不出差在哪一段。
|
||||
- **关键路径禁止丢弃返回值。** 本系统里大量写入函数失败时不抛异常,只回 `{"ok": False, ...}` 或影响 0 行——`param_store.set_param`、`dispatcher.dispatch/cancel`、`executor.cancel_instruction`、`proposal_service.bump_once_guards`、`portfolio.save_neg_streak`、`qmt_repo.update_order` 都是。**写这类调用时返回值必须接住并处理**,否则写入没发生而调用方照常报成功。`test_batch10_units.py` 的 [A] 组 AST 扫全库守着这条;新加一个软失败函数,记得同时加进它的 `SOFT_FAIL` 名单。
|
||||
- 里程碑(设计定稿、建表、各期上线)及时 git 提交。
|
||||
- **接手前先读三份**:本文件 → `POSITION_MGMT_DESIGN.md`(V0.4 定稿,**勿改设计**)→ `QMT_WS_PROTOCOL.md`(V1.0 定稿,下发通道的唯一依据)。三份读完即可开工,不需要额外的口头背景。
|
||||
工作流程和授权边界统一维护在[AGENTS.md](AGENTS.md),技术限制在[后端目录规则](app/AGENTS.md)及相应子目录中。部署、QMT联调和测试按[开发入口](docs/开发入口.md)选择资料,不在本节重复维护,也不再要求每次通读三份设计文档。
|
||||
|
||||
|
||||
### 执行报价与异步研判(2026年11月3日)
|
||||
|
||||
新增可独立开启的异步研判和限价撤换流程。bionic负责机会判断,PMS按新鲜行情报价。撤单确认、累计成交入账之前,旧单继续占用数量和资金。微盘v3将首选与有序备选一并冻结;单股受阻不会中止其他成员。旧v2快照与规则保持兼容。
|
||||
|
||||
新开关默认关闭,运行值通过ParamStore读取。接口、开启条件和验证记录见[实施规格](docs/执行报价与异步研判实施规格_2026-11-03.md)。没有实时盘口时明确使用分钟行情降级,不承诺即时成交。
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
# 上游选股计划接口 · 接入记录与待确认口径
|
||||
|
||||
2026年10月29日补充:`PMS_PLAN_THEME_CAP=0`现在明确发送`theme_cap=0`,表示上游不按主题限额截断;PMS本地主题限额也可用`PMS_PLAN_THEME_CAP_LOCAL=0`取消。155已按用户要求采用两个0,候选仍按既有排名、资格和数量范围筛选。旧文中“0=不传”及早期每主题5只均为历史行为。`top`、`obs_top`为0时仍使用上游默认。
|
||||
|
||||
当前开发契约见本文末尾“2026-10-15 补充:完整决策版本契约”;下文早期接入实测保留历史语义。
|
||||
|
||||
> 2026-07-30 建。上游「选股系统」提供 HTTP 计划接口, PMS 的升仓/建仓候选池自此改吃它,
|
||||
|
|
@ -688,3 +690,61 @@ make changes # 页面同款结论
|
|||
- PMS meta.kind 区分 received、consumed、rechecked;消费记录包括真实顺序、有效参数和过滤原因。
|
||||
- 采纳核验由 PMS_PLAN_VERSION_RECHECK 控制,默认关闭;内容更新时接口返回 ok=false、原因及更新后的 proposal,页面必须重新确认其 proposal_revision。
|
||||
- 旧消费者可忽略新增字段,新消费者接受旧字段为空;无版本旧数据不能通过已启用的自主采纳核验。
|
||||
|
||||
## 2026-11-03 补充:在选股计划中添加关注股票
|
||||
|
||||
PMS 在原选股计划抽屉提供“添加股票”。支持按名称或代码搜索、批量输入沪深 A 股完整名称或代码、填写理由和关注截止日。名称来自上市证券基础表,精确匹配后统一保存代码;模糊或重名输入需先选择搜索结果或改用代码,整批校验通过后才保存。北交所在资料读取和登记入口排除。同一股票的有效登记不重复创建,移除和到期保留历史;不会由此生成卖出或撤单命令。
|
||||
|
||||
| 上游接口 | 用途 |
|
||||
| --- | --- |
|
||||
| `GET /plan/user-candidates/search?q=名称或代码` | 返回最多 30 个匹配的沪深 A 股名称和前缀代码 |
|
||||
| `GET /plan/user-candidates` | 返回登记及其等待评估、已评估、已到期、已移除状态 |
|
||||
| `POST /plan/user-candidates` | 登记 `codes`、`reason`、`expires_on` 和服务端提供的 `actor` |
|
||||
| `POST /plan/user-candidates/{id}/remove` | 停止该条人工关注,保留原记录 |
|
||||
|
||||
PMS 对应路径统一为 `/api/plan/user-candidates`,沿用交易员登录权限并记操作日志。写请求以环境变量 `PMS_PLAN_WRITE_KEY` 作为 `X-Job-Key` 调用上游;值须与上游既有 `XXL_TRIGGER_KEY` 一致,仅通过环境注入,禁止进入 ParamStore、页面和日志。未配置或上游未升级时明确提示不可用。
|
||||
|
||||
登记先持久化,再由上游计划修订任务评估。每次最多 30 只,理由最多 300 字,截止日为北京当天至未来 90 个自然日,页面默认未来 7 日。登记成功表示已保存,不等于候选合格或已下单。非修订时段等待后续有效生成或修订,不倒填晨版。
|
||||
|
||||
人工来源仅补充原有发现条件,`pointed` 继续表示真实产业传导状态。券商覆盖、估值空间、风险、吸筹、基本面、技术面、择时及资金约束仍走原逻辑;不加分、不插队、不放大仓位,也不绕过当前前列数量和档位配置。没有原分数时返回 `score=null`,不生成虚构档位。证券名称资料缺失时仅展示。
|
||||
|
||||
完整计划顶层 `user_candidates` 保存本版采用的登记;对应行带 `user_candidate` 和 `user_required`。后者表示候选需要人工来源才能成立。移除、到期及重新登记但尚未发布时,最新计划和逐票核验的 `pending_codes` 阻止旧来源继续被采纳。来源信息进入 PMS 依据指纹、提议与评审材料,既有版本核验和跨日复核继续生效。
|
||||
|
||||
新版PMS读取 `/plan` 和 `/plan/check` 时显式发送 `include_user_candidates=1`。未声明支持的调用方只获得系统来源:在前列数量及主题裁剪前剔除仅依靠人工来源的行,缓存也按此选项分开;逐票核验不返回人工专属候选。未升级的PMS和其他既有调用方不会自动吸收新增来源。归档完整版本保留,普通请求的来源过滤不重写历史。
|
||||
|
||||
人工来源只接入自主建仓候选链。资金投放命令不会额外吸收仅靠人工来源新增的股票;已有系统来源仍正常参与。盘中加入的合格基础候选可补读已有技术面数据,并进入现有盘中扫描关注范围,不自行生成技术面或择时结论。到期或移除不改变已经建立的持仓管理规则。
|
||||
|
||||
## 2026-11-04 补充:人工关注独立研究与吸筹参考
|
||||
|
||||
本节记录当前开发契约,覆盖上一节有关人工关注研究范围的旧描述。发布与自然任务完成情况另记接续,不能由本地实现推定。
|
||||
|
||||
用户确认沿用当前公司质地排序。吸筹用于提供研究参考,非明确、缺失或陈旧吸筹不再单独构成候选确认条件;真实且有效的高位派发风险仍保留。桥侧规则变化发布新的计划版本,PMS继续读取当前版本的判决、风险及依据,不关闭`PMS_PLAN_ROUTE_BY_VERDICT`。人工来源不加分、不插队、不放大仓位。建仓仍经过基本面、技术面、择时三源合议,以及研判、用户命令、资金与执行限制。
|
||||
|
||||
“关注”不是固定的人工确认档位。PMS自决为`full`且允许试探仓时,合议、真实研判应答、风险、数量和每日限额等条件满足后,可以自动采纳试探仓。自决关闭或其他条件不成立时,仍按对应分支等待、交人或放弃;不能只凭关注登记或上游“关注”二字下结论。
|
||||
|
||||
### 登记与买方评析状态
|
||||
|
||||
`GET /plan/user-candidates`保留顶层`ok`、`revision`和`rows`。`revision`是非负整数。每行保留原登记状态,并新增以下字段。GET只读查询,不提交评析或模型任务。
|
||||
|
||||
| 字段 | 语义 |
|
||||
| --- | --- |
|
||||
| `status` | 原登记与计划状态:`pending`、`evaluated`、`expired`、`removed`。`evaluated`不表示买方评析完成 |
|
||||
| `review_status` | `missing`、`pending`、`queued`、`completed`、`failed`。只有`completed`满足研究名单的评析前提 |
|
||||
| `review_ref` | 真实报告的64位十六进制版本标识,不用当前计划版本代替 |
|
||||
| `company_review`、`company_review_text` | 已有结构化评析与摘要;缺失不能由PMS生成或猜补 |
|
||||
| `company_review.report_ran_at` | 报告实际生成时间,带时区。PMS据此发布`review_completed_at` |
|
||||
| `review_data_date` | 报告实际生成时间对应的北京日期,不是计划数据日或本次核对日期 |
|
||||
| `review_updated_at` | 最近真实核对时间,可能晚于报告生成时间;不能改写报告日期 |
|
||||
| `review_error` | 评析未完成的可读原因,不能把失败显示为空结果或完成 |
|
||||
|
||||
上游只有在有效报告版本、真实买方评议成功(`brain_used=true`且`brain_status=ok`)、必要研究内容及非未来生成时间均可核实后,才返回`completed`。已入计划、已有任务编号或已受理均不等于完成。排队、失败与报告缺失独立于原登记状态,过期和移除不删除历史。
|
||||
|
||||
### 独立研究名单与结果展示
|
||||
|
||||
PMS每分钟执行`pms.monitor_watch_sync`。来源是完整有效人工登记中评析已完成的沪深A股,不依赖交易候选、排名截断或自主提议是否产生。该步骤不受交易暂停及交易时段限制,也不产生交易命令。`PMS_MONITOR_WATCH_SCOPE`默认空,仅155模拟实例明确配置`pms-sim-155`;`PMS_MONITOR_WATCH_TTL_SEC`默认600秒。
|
||||
|
||||
研究名单写入共享行情Redis的db2独立键`pms:monitor_watch:v1:pms-sim-155`。登记读取成功后全量替换,包括确认有效的空名单;读取失败不伪造空成功。新增或移除成功后立即尝试刷新,失败向页面报告并等待下一轮。旧登记版本和更早生成的同步结果不能覆盖新快照。时间戳带时区,快照过期后消费者停止新增研究。
|
||||
|
||||
Bionic回执保存在`bionic:monitor_watch:status:v1:pms-sim-155`。PMS核对来源、关注编号、登记版本、报告版本、名单有效期和任务截止时间。`QUEUED`、`RUNNING`表示等待或在途,只有有效的`COMPLETE`表示已有结果;`UNAVAILABLE`和`EXPIRED`保留原因。调度日`analysis_date`、真实行情日`data_date`及完成时间`completed_at`分别展示,盘前使用上一交易日日线时不能强行改成同一天。
|
||||
|
||||
信号页的人工关注入口持续保留至到期或主动移除。单票已有信号沿用点击触发的只读接口,不加入全流轮询。独立观察分析展开后显示真实结论、原因、行情数据日和完成时间,并注明研究结论不是交易授权。页面GET不派模型任务;覆盖回执不作为买卖信号进入交易消费链。旧`DROPPED`标为历史停止覆盖,既不恢复旧`BUY/WATCH`,也不冒充今天的新看空结论。完整快照与回执结构见[修复规格](docs/人工关注分析链修复规格_2026-11-04.md)。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
# 后端目录规则
|
||||
|
||||
本文件适用于`app/`及其子目录;根目录规则继续适用。
|
||||
|
||||
## 分层与契约
|
||||
|
||||
- `core/`只放纯逻辑,不接数据库或网络。`repo/`负责单表访问,`services/`编排取数、判断、落表和动作。跨表数据分次读取,在服务层组合。
|
||||
- `db/session.py`会拒绝JOIN、逗号连表和跨表子查询。不要绕过守卫;修改upsert时检查`ON DUPLICATE KEY UPDATE`兼容性。
|
||||
- `executor`在worker中把委托写入出口表,`ws/runner.py`只负责传输与回报落库,不直接改策略账本。回放服务按委托归属记账,兼顾重复、迟到和部分成交。
|
||||
- 业务参数走`services/param_store.py`;`config/settings.py`只是业务初值和基础设施配置。新密钥同时登记`SECRET_KEYS`和相应测试,不进入参数快照。
|
||||
- 资金冻结、在途买入、卖出释放及策略划拨使用既有统一占用口径。新增执行路径不能另算一份余额;划拨不是盈利。
|
||||
- 关键写入和下发函数可能返回`ok=False`或影响0行而不抛异常,必须检查返回值并处理失败。新软失败函数同步登记`test_batch10_units.py`的`SOFT_FAIL`。
|
||||
- 内部股票代码使用Tushare点式,例如`600000.SH`;访问上游时在边界转换。改`core/ws_codec.py`后验证协议签名向量,不能只看连接成功。
|
||||
- 修改接口先查对应契约:QMT用[协议](../QMT_WS_PROTOCOL.md),bionic用[接口说明](../BIONIC_PMS_INTERFACE.md),上游选股用[计划接口](../UPSTREAM_PLAN_API.md)。架构定位见[README](../README.md)。
|
||||
|
||||
## 数据与时间
|
||||
|
||||
- 数据源由`db/session.py`选择,表前缀区分实例。不要硬编码生产前缀,也不要凭旧文档判断某库“当前不用”。
|
||||
- 交易日期按北京日期处理。时间戳先核对列类型、写入代码、会话时区及实际读数,不能统一加八小时。容器日志使用北京时间;已核验的`pms_ws_state.heartbeat_at`为北京时间DATETIME原值。
|
||||
- 区分数据日期、计算时间、冻结时间和执行日期。修订另存版本,空结果不解释为退出,展示重算结果不冒充历史执行记录。
|
||||
- Redis客户端保持`redis` 5.x约束。升级前须验证现网服务端协议兼容性,不能直接放开到默认RESP3的版本。
|
||||
|
||||
## 验证入口
|
||||
|
||||
后端、DDL、路由或调度变化,按[scripts目录规则](../scripts/AGENTS.md)检查测试桩和哨兵。改`web/`时还要读该目录的规则。临时日志不得输出密钥、完整连接串或登录凭据。
|
||||
|
|
@ -882,6 +882,7 @@ def eval_open(c: dict, params: dict, caps: dict, room_amt: float):
|
|||
"valuation_text": c.get("valuation_text"),
|
||||
# 催化事件与定价状态 (2026-09-08 量价研判链 3.5): 原值进账本与提议卡; 两句整句另送研判
|
||||
# (它们是事件与量价, 不是产业逻辑, 见 judge.OPEN_JUDGE_KEYS)。不参与任何判定。
|
||||
'user_candidate': c.get('user_candidate'), 'user_required': c.get('user_required'),
|
||||
"events": c.get("events"), "events_text": c.get("events_text"),
|
||||
"pricing_state": c.get("pricing_state"), "pricing_text": c.get("pricing_text"),
|
||||
# 相关快讯 (2026-09-08 台账 050): 原值进账本与提议卡, 整句另送研判。只是上下文, 不进判定。
|
||||
|
|
|
|||
|
|
@ -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 撤回来。
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -0,0 +1,115 @@
|
|||
"""执行依据与报价的纯规则。未知事实不能授权买入,不推测盘口。"""
|
||||
from datetime import datetime, timezone, timedelta, date
|
||||
from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR
|
||||
import math
|
||||
import re
|
||||
|
||||
BEIJING = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def supported_code(code):
|
||||
return bool(re.fullmatch(r'(?:60\d{4}\.SH|68\d{4}\.SH|00\d{4}\.SZ|30\d{4}\.SZ)', str(code or '').upper()))
|
||||
|
||||
|
||||
def local_now(now=None):
|
||||
value = now or datetime.now(BEIJING)
|
||||
return value.replace(tzinfo=BEIJING) if value.tzinfo is None else value.astimezone(BEIJING)
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
return parsed.astimezone(BEIJING) if parsed.tzinfo is not None else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def positive(value):
|
||||
try:
|
||||
number = float(value)
|
||||
return number if math.isfinite(number) and number > 0 else 0.
|
||||
except (TypeError, ValueError):
|
||||
return 0.
|
||||
|
||||
|
||||
def basis_reason(basis, now=None, max_source_days=7):
|
||||
"""空串表示依据有效;拒绝无来源、无版本、无时区和过期事实。"""
|
||||
if not isinstance(basis, dict):
|
||||
return '执行依据缺失'
|
||||
if basis.get('continuation') == 'STOP':
|
||||
return '机会已撤销:' + str(basis.get('reason') or '上游明确停止')
|
||||
if basis.get('quality') != 'VALID' or basis.get('continuation') != 'CONTINUE':
|
||||
return '执行依据不可用或机会状态未知:' + str(basis.get('reason') or '')
|
||||
if not str(basis.get('version') or '').strip() or not str(basis.get('source') or '').strip():
|
||||
return '执行依据缺少版本或来源'
|
||||
generated, until = timestamp(basis.get('generated_at')), timestamp(basis.get('valid_until'))
|
||||
current = local_now(now)
|
||||
if not generated or not until or not generated <= current < until:
|
||||
return '执行依据时间无效或已过期'
|
||||
try:
|
||||
source_day = date.fromisoformat(str(basis.get('source_date')))
|
||||
except (ValueError, TypeError):
|
||||
return '执行依据缺少有效数据日期'
|
||||
if source_day > generated.date() or not 0 <= (current.date()-source_day).days <= max_source_days:
|
||||
return '执行依据数据日期超出有效范围'
|
||||
return ''
|
||||
|
||||
|
||||
def price_order(*, side, quote, now=None, user_limit=None, anchor_price=None, params=None):
|
||||
"""按对手盘报价;分钟行情只能显式降级,并始终遵守用户价格边界。"""
|
||||
prm, current = params or {}, local_now(now)
|
||||
def wait(why):
|
||||
return {'action': 'WAIT', 'limit_price': None, 'reason': why, 'degraded': False}
|
||||
if side not in ('buy', 'sell') or not isinstance(quote, dict):
|
||||
return wait('委托方向或行情无效')
|
||||
if quote.get('halted'):
|
||||
return wait('证券停牌,不报价')
|
||||
kind, source = quote.get('kind'), str(quote.get('source') or '')
|
||||
at = timestamp(quote.get('as_of'))
|
||||
if not source or not at or at.date() != current.date():
|
||||
return wait('行情缺少当日来源或明确时间')
|
||||
age = (current-at).total_seconds()
|
||||
minute = kind == 'minute'
|
||||
max_age = float(prm.get('minute_max_age_sec', 90) if minute else prm.get('quote_max_age_sec', 15))
|
||||
if age < 0 or age > max_age:
|
||||
return wait('行情已过期或时间超前')
|
||||
low, high, last = (positive(quote.get(k)) for k in ('limit_down', 'limit_up', 'last'))
|
||||
if not low or not high or low > high or not last:
|
||||
return wait('行情价格或当日价格上下限不可核实')
|
||||
tick = .01
|
||||
if minute:
|
||||
if not prm.get('allow_minute', True):
|
||||
return wait('没有实时盘口,分钟行情降级未启用')
|
||||
offset = max(0., float(prm.get('minute_slippage_pct', .002)))
|
||||
proposed = last*(1+offset if side == 'buy' else 1-offset)
|
||||
note = '分钟行情降级报价(无实时盘口)'
|
||||
elif kind == 'level1':
|
||||
counter = positive(quote.get('ask' if side == 'buy' else 'bid'))
|
||||
bid, ask = positive(quote.get('bid')), positive(quote.get('ask'))
|
||||
if not counter or (bid and ask and bid > ask):
|
||||
return wait('对手盘口缺失或买卖价异常')
|
||||
proposed = counter + (1 if side == 'buy' else -1)*tick*max(0, int(prm.get('offset_ticks', 1)))
|
||||
note = '实时对手盘口报价'
|
||||
else:
|
||||
return wait('行情种类未经核实')
|
||||
anchor = positive(anchor_price) or last
|
||||
slippage = max(0., float(prm.get('max_slippage_pct', .01)))
|
||||
boundary = positive(user_limit)
|
||||
if user_limit is not None and not boundary:
|
||||
return wait('用户价格边界无效')
|
||||
if side == 'buy':
|
||||
ceiling = min(high, last*(1+slippage), boundary or high)
|
||||
price = Decimal(str(min(proposed, ceiling))).quantize(Decimal('.01'), rounding=ROUND_FLOOR)
|
||||
else:
|
||||
floor = max(low, last*(1-slippage), boundary or low)
|
||||
price = Decimal(str(max(proposed, floor))).quantize(Decimal('.01'), rounding=ROUND_CEILING)
|
||||
value = float(price)
|
||||
if not low <= value <= high:
|
||||
return wait('用户边界或报价超出当日合法价格范围')
|
||||
result = {'action': 'FIRE', 'limit_price': value, 'reason': note,
|
||||
'degraded': minute, 'quote_source': source, 'quote_as_of': at.isoformat(),
|
||||
'quote_age_sec': age, 'anchor_price': anchor, 'user_limit': boundary or None}
|
||||
if quote.get('limit_version'):
|
||||
result.update(limit_source=quote.get('limit_source'), limit_version=quote['limit_version'],
|
||||
limit_fetched_at=quote.get('limit_fetched_at'))
|
||||
return result
|
||||
|
|
@ -0,0 +1,344 @@
|
|||
"""微盘轮换状态与订单计算。纯函数,无行情、数据库或下单依赖。"""
|
||||
import copy
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
|
||||
LEGACY_RULE = 'micro30-v1-20261027'
|
||||
RULE = 'micro50-v2-20261028'
|
||||
EXECUTION_RULE = 'micro50-v3-20261103'
|
||||
SUPPORTED_RULES = (RULE, EXECUTION_RULE)
|
||||
# 参数组成不可拆分的规则版本。运行版本由服务层经ParamStore选择并核对。
|
||||
SIZE = 50
|
||||
ENTRY_PERCENTILE = .08
|
||||
EXIT_PERCENTILE = .85
|
||||
RULE_PARAMETERS = {'entry_percentile': ENTRY_PERCENTILE, 'exit_percentile': EXIT_PERCENTILE,
|
||||
'basket_size': SIZE}
|
||||
PHASES = ('original', 'entering_micro', 'micro', 'returning_original')
|
||||
|
||||
|
||||
def rule_parameters(rule=RULE, candidate_pool_size=100):
|
||||
if rule not in SUPPORTED_RULES:
|
||||
raise ValueError('未知微盘规则版本')
|
||||
result = dict(RULE_PARAMETERS)
|
||||
if rule == EXECUTION_RULE:
|
||||
if not SIZE <= candidate_pool_size <= 500:
|
||||
raise ValueError('冻结候选数量须在50至500之间')
|
||||
result.update(candidate_pool_size=candidate_pool_size,
|
||||
substitution='zero_fill_only', pricing='marketable_limit')
|
||||
return result
|
||||
|
||||
|
||||
def mainland_code(code):
|
||||
return bool(isinstance(code, str) and re.fullmatch(r'(?:60\d{4}|68\d{4})\.SH|(?:00\d{4}|30\d{4})\.SZ', code))
|
||||
|
||||
|
||||
def initial_state():
|
||||
return {'phase': 'original', 'rule_version': RULE, 'cycle': 0, 'last_snapshot': None, 'entry_date': None,
|
||||
'exit_date': None, 'reason': None, 'target': [], 'entry_budget': 0., 'disabled': False,
|
||||
'entry_quantities': {}, 'consumed_entry': None, 'closed_date': None}
|
||||
|
||||
|
||||
def snapshot_check(value, execution_date, *, require_frozen=True, expected_rule=None, candidate_pool_size=100):
|
||||
errors = []
|
||||
if not isinstance(value, dict):
|
||||
return ['没有监控快照']
|
||||
rule = value.get('rule_version')
|
||||
if rule not in SUPPORTED_RULES or (expected_rule and rule != expected_rule) or value.get('basket_size') != SIZE or value.get('rule_parameters') != rule_parameters(rule if rule in SUPPORTED_RULES else RULE, candidate_pool_size):
|
||||
errors.append('策略规则版本不一致')
|
||||
if value.get('effective_date') != execution_date or str(value.get('data_date', '')) >= execution_date:
|
||||
errors.append('快照日期不适用于本次执行')
|
||||
if require_frozen and value.get('frozen') is not True:
|
||||
errors.append('执行快照尚未冻结')
|
||||
keys = ('rule_version', 'rule_parameters', 'basket_size', 'data_date', 'effective_date', 'signal_ready',
|
||||
'basket_ready', 'signal', 'members', 'source_hashes', 'errors')
|
||||
if rule == EXECUTION_RULE:
|
||||
keys += ('candidates', 'candidate_count')
|
||||
try:
|
||||
body = {k: value[k] for k in keys}
|
||||
digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':'), allow_nan=False).encode()).hexdigest()
|
||||
if digest != value.get('snapshot_version'):
|
||||
errors.append('快照摘要不一致')
|
||||
signal = value['signal']
|
||||
if signal.get('date') != value['data_date'] or signal.get('ready') is not value['signal_ready']:
|
||||
errors.append('信号就绪或日期字段冲突')
|
||||
if any(type(signal.get(k)) is not bool for k in ('growth_break', 'low', 'high')):
|
||||
errors.append('信号必须是明确的布尔值')
|
||||
if value['basket_ready']:
|
||||
members = value['members']
|
||||
if len(members) != SIZE or len({m['code'] for m in members}) != SIZE:
|
||||
errors.append(f'目标名单不是{SIZE}只唯一股票')
|
||||
if any(m.get('eligible') is not True or m.get('rank') != i+1 for i, m in enumerate(members)):
|
||||
errors.append('名单资格或排名不完整')
|
||||
if any(not mainland_code(m.get('code')) for m in members):
|
||||
errors.append('名单包含沪深范围外证券')
|
||||
if rule == EXECUTION_RULE:
|
||||
pool = value['candidates']
|
||||
if (not SIZE <= len(pool) <= candidate_pool_size or value['candidate_count'] != len(pool)
|
||||
or pool[:SIZE] != members or len({m['code'] for m in pool}) != len(pool)
|
||||
or any(m.get('eligible') is not True or m.get('rank') != i+1 or not mainland_code(m.get('code')) for i, m in enumerate(pool))):
|
||||
errors.append('冻结候选池数量、资格或顺序不完整')
|
||||
except (KeyError, ValueError, TypeError):
|
||||
errors.append('快照字段不完整或数字非法')
|
||||
return errors
|
||||
|
||||
|
||||
def transition(state, snapshot, *, micro_qty, original_qty, budget, control='run', micro_pending=False):
|
||||
s = copy.deepcopy(state)
|
||||
if s['phase'] not in PHASES:
|
||||
raise ValueError('未知轮换阶段')
|
||||
ready = bool(snapshot and snapshot.get('signal_ready'))
|
||||
signal = snapshot['signal'] if ready else {}
|
||||
if control == 'pause_all':
|
||||
return s
|
||||
if control != 'exit_disable' and snapshot and s['phase'] in ('entering_micro', 'micro') and s.get('rule_version', LEGACY_RULE) != snapshot.get('rule_version'):
|
||||
raise ValueError('持仓轮次规则与新快照不一致,不能隐式更换策略')
|
||||
if control == 'exit_disable':
|
||||
s['disabled'] = True
|
||||
if s['phase'] != 'original' or micro_qty:
|
||||
s['phase'], s['reason'] = 'returning_original', '用户退出并停用'
|
||||
if ready and signal.get('high') and s['phase'] in ('entering_micro', 'micro'):
|
||||
s.update(phase='returning_original', exit_date=snapshot['effective_date'], reason='微盘活跃度高位')
|
||||
if s['phase'] == 'returning_original' and micro_qty == 0 and not micro_pending:
|
||||
s.update(phase='original', target=[], entry_budget=0., entry_quantities={}, buy_targets={}, execution_day=None,
|
||||
closed_date=(snapshot or {}).get('effective_date') or s.get('exit_date'))
|
||||
return s # 清完当天不立即重开下一轮。
|
||||
fresh_entry = snapshot and snapshot.get('snapshot_version') != s.get('consumed_entry') and snapshot.get('effective_date') != s.get('closed_date')
|
||||
if s['phase'] == 'original' and fresh_entry and not s['disabled'] and control == 'run' and ready and snapshot.get('basket_ready') and not signal.get('high') and (signal.get('growth_break') or signal.get('low')):
|
||||
if micro_qty:
|
||||
raise ValueError('旧微盘持仓未清完,不能再次入场')
|
||||
s.update(phase='entering_micro', cycle=s['cycle']+1, entry_date=snapshot['effective_date'],
|
||||
rule_version=snapshot['rule_version'],
|
||||
entry_budget=max(0., budget), entry_quantities={}, buy_targets={}, execution_day=None, consumed_entry=snapshot['snapshot_version'],
|
||||
reason='成长主线瓦解' if signal['growth_break'] else '微盘活跃度极低')
|
||||
if snapshot and snapshot.get('basket_ready') and s['phase'] in ('entering_micro', 'micro'):
|
||||
if s.get('rule_version') != EXECUTION_RULE or s.get('execution_day') != snapshot['effective_date']:
|
||||
s['target'] = [r['code'] for r in snapshot['members']]
|
||||
if snapshot:
|
||||
s['last_snapshot'] = snapshot['snapshot_version']
|
||||
return s
|
||||
|
||||
|
||||
def resolve_targets(state, snapshot, *, micro=(), pending=(), unavailable=None):
|
||||
"""每日冻结排名只作确定性递补。已成交或尚有在途的成员始终占原席位。"""
|
||||
if state.get('rule_version') != EXECUTION_RULE or state['phase'] not in ('entering_micro', 'micro') or not snapshot.get('basket_ready'):
|
||||
return []
|
||||
day = snapshot['effective_date']
|
||||
if state.get('execution_day') != day:
|
||||
state.update(execution_day=day, target=[m['code'] for m in snapshot['members']],
|
||||
skipped_candidates={}, substitutions=[])
|
||||
owned = {r['ts_code'] for r in micro if int(r.get('total_qty') or 0) > 0}
|
||||
active = {r['ts_code'] for r in pending}
|
||||
blocked = unavailable or {}
|
||||
skipped = state.setdefault('skipped_candidates', {})
|
||||
target = list(state['target'])
|
||||
waits = []
|
||||
for code in target:
|
||||
if code in blocked:
|
||||
if code in owned or code in active:
|
||||
waits.append(code+'已成交或委托未结清,保留席位')
|
||||
else:
|
||||
skipped.setdefault(code, str(blocked[code]))
|
||||
# 同一天不恢复已经跳过的成员。候选也须确认无持仓、无在途才可跳过。
|
||||
kept = [c for c in target if c not in skipped or c in owned or c in active]
|
||||
removed = [c for c in target if c not in kept]
|
||||
pool = snapshot['candidates']
|
||||
for member in pool:
|
||||
if len(kept) >= SIZE:
|
||||
break
|
||||
code = member['code']
|
||||
if code in kept or code in skipped:
|
||||
continue
|
||||
if code in blocked and code not in owned and code not in active:
|
||||
skipped[code] = str(blocked[code])
|
||||
continue
|
||||
kept.append(code)
|
||||
previous = removed.pop(0) if removed else None
|
||||
state.setdefault('substitutions', []).append({'from': previous, 'to': code,
|
||||
'rank': member['rank'], 'reason': skipped.get(previous, '补充未完成席位'),
|
||||
'snapshot_version': snapshot['snapshot_version']})
|
||||
state['target'] = kept
|
||||
state['target_shortfall'] = max(0, SIZE-len(kept))
|
||||
state['buy_targets'] = {c: t for c, t in state.get('buy_targets', {}).items() if c in kept}
|
||||
if len(kept) < SIZE:
|
||||
waits.append('候选已用尽,未完成席位'+str(SIZE-len(kept)))
|
||||
return waits
|
||||
|
||||
|
||||
def board(code):
|
||||
if code.startswith('68'):
|
||||
return 'STAR'
|
||||
if code.startswith('30'):
|
||||
return 'CHINEXT'
|
||||
return 'MAIN'
|
||||
|
||||
|
||||
def min_qty(code):
|
||||
return 200 if board(code) == 'STAR' else 100
|
||||
|
||||
|
||||
def fee(value, side, *, rate=.0003, minimum=5., sell_tax=.0005, transfer_rate=.00001):
|
||||
return round(max(minimum, value*rate)+value*transfer_rate+(value*sell_tax if side == 'sell' else 0), 2)
|
||||
|
||||
|
||||
def buy_qty(code, price, budget, costs):
|
||||
if not math.isfinite(price) or price <= 0 or not math.isfinite(budget) or budget <= 0:
|
||||
return 0
|
||||
qty = int(budget/price)//100*100
|
||||
while qty >= min_qty(code) and qty*price+fee(qty*price, 'buy', **costs) > budget:
|
||||
qty -= 100
|
||||
return qty if qty >= min_qty(code) else 0
|
||||
|
||||
|
||||
def preflight(members, budget, allowed_boards, costs):
|
||||
issues = []
|
||||
if len(members) != SIZE:
|
||||
return [f'目标名单数量不是{SIZE}只']
|
||||
for m in members:
|
||||
if board(m['code']) not in allowed_boards:
|
||||
issues.append(m['code']+'板块权限未确认')
|
||||
if not buy_qty(m['code'], float(m['close']), budget/SIZE, costs):
|
||||
issues.append(m['code']+'等资金份额不足最小交易单位及费用')
|
||||
return issues
|
||||
|
||||
|
||||
def orders(state, snapshot, *, original, micro, quotes, cash, account_mv, cap_amount,
|
||||
reserve_cash=0., pending=(), control='run', blacklisted=(), costs=None):
|
||||
"""只形成意图,不把计划卖出计入现金。调用者落表后再执行。"""
|
||||
from app.core.planner import plan_reduce_exposure
|
||||
costs = costs or {}
|
||||
result, waits = [], []
|
||||
if control == 'pause_all':
|
||||
return result, ['用户暂停全部执行']
|
||||
active_codes = {r['ts_code'] for r in pending}
|
||||
original_by = {r['ts_code']: r for r in original if r.get('total_qty', 0) > 0}
|
||||
micro_by = {r['ts_code']: r for r in micro if r.get('total_qty', 0) > 0}
|
||||
phase = state['phase']
|
||||
if phase == 'entering_micro':
|
||||
positions = [{**p, 'price': quotes.get(c, {}).get('price')} for c, p in original_by.items()]
|
||||
release = sum(p['total_qty']*p['price'] for p in positions if p.get('price'))
|
||||
plan = plan_reduce_exposure(release_amount=release, positions=positions)
|
||||
seen = set()
|
||||
for item in plan['items']:
|
||||
if item['side'] != 'sell':
|
||||
continue
|
||||
c = item['ts_code']
|
||||
if c in seen:
|
||||
continue
|
||||
seen.add(c)
|
||||
# 同股先完成加仓部分,再由下一跳重算剩余批次;不能提前整股清仓。
|
||||
result.append({'book_id': 'original', 'ts_code': c, 'side': 'sell',
|
||||
'qty': min(int(item['qty']), original_by[c]['total_qty']), 'reason': item['reason']})
|
||||
for c, p in original_by.items():
|
||||
if c not in seen and p.get('total_qty'):
|
||||
result.append({'book_id': 'original', 'ts_code': c, 'side': 'sell', 'qty': p['total_qty'], 'reason': '轮换剩余持仓退出'})
|
||||
target = set(state['target']) if phase in ('entering_micro', 'micro') else set()
|
||||
for c, p in micro_by.items():
|
||||
if phase == 'returning_original' or (snapshot and snapshot.get('basket_ready') and c not in target):
|
||||
result.append({'book_id': 'micro30', 'ts_code': c, 'side': 'sell', 'qty': p['total_qty'], 'reason': '高位清仓或成员调出'})
|
||||
result = [r for r in result if r['ts_code'] not in active_codes]
|
||||
if phase not in ('entering_micro', 'micro') or control != 'run' or not snapshot or not snapshot.get('basket_ready'):
|
||||
return result, waits
|
||||
available = max(0., min(cash-reserve_cash, cap_amount-account_mv))
|
||||
# 入场期间保留既定每股资金目标,以便原策略分批回款后继续完成建仓。
|
||||
missing = sorted(c for c in target if c not in micro_by)
|
||||
objectives = state.setdefault('buy_targets', {})
|
||||
objectives = {c: t for c, t in objectives.items() if c in target}
|
||||
state['buy_targets'] = objectives
|
||||
candidates = sorted(target) if phase == 'entering_micro' else sorted(set(missing)|{
|
||||
c for c, t in objectives.items() if int(t['qty']) > int(micro_by.get(c, {}).get('total_qty') or 0)})
|
||||
per_new = available/len(missing) if missing else 0.
|
||||
for c in candidates:
|
||||
if c in original_by or c in active_codes or c in blacklisted:
|
||||
waits.append(c+'旧仓、在途委托或黑名单阻止买入')
|
||||
continue
|
||||
q = quotes.get(c, {})
|
||||
price = q.get('price')
|
||||
if not price or price <= 0:
|
||||
waits.append(c+'没有有效行情')
|
||||
continue
|
||||
owned_qty = micro_by.get(c, {}).get('total_qty', 0)
|
||||
if phase == 'entering_micro':
|
||||
quantities = state.setdefault('entry_quantities', {})
|
||||
# 首次有行情时固定数量,部分成交只补剩余,不随价格下跌重新等权。
|
||||
if c not in quantities:
|
||||
target_qty = buy_qty(c, price, state['entry_budget']/SIZE, costs)
|
||||
if target_qty:
|
||||
quantities[c] = target_qty
|
||||
if c not in quantities:
|
||||
waits.append(c+'份额不足最小交易单位及费用')
|
||||
continue
|
||||
remaining_qty = max(0, quantities[c]-owned_qty)
|
||||
desired = remaining_qty*price+fee(remaining_qty*price, 'buy', **costs) if remaining_qty else 0.
|
||||
else:
|
||||
if c not in objectives:
|
||||
target_qty = buy_qty(c, price, per_new, costs)
|
||||
if not target_qty:
|
||||
waits.append(c+'可用资金不足最小交易单位及费用')
|
||||
continue
|
||||
objectives[c] = {'qty': target_qty, 'snapshot_version': snapshot['snapshot_version'],
|
||||
'effective_date': snapshot['effective_date']}
|
||||
remaining_qty = max(0, int(objectives[c]['qty'])-owned_qty)
|
||||
desired = remaining_qty*price+fee(remaining_qty*price, 'buy', **costs) if remaining_qty else 0.
|
||||
budget = min(available, desired)
|
||||
qty = buy_qty(c, price, budget, costs)
|
||||
qty = min(qty, remaining_qty)
|
||||
if qty:
|
||||
result.append({'book_id': 'micro30', 'ts_code': c, 'side': 'buy', 'qty': qty, 'reason': '初始建仓补齐' if phase == 'entering_micro' else '名单调入'})
|
||||
available -= qty*price+fee(qty*price, 'buy', **costs)
|
||||
return result, waits
|
||||
|
||||
|
||||
def apply_paper_fill(account, order, price, trade_date, costs, prices=None):
|
||||
"""独立纸面现金账,不接真实成交。相同成交键只记一次,T+1按买入日约束。"""
|
||||
key = order['id']
|
||||
if key in account['fills']:
|
||||
return False
|
||||
book, code, side, qty = order['book_id'], order['ts_code'], order['side'], order['qty']
|
||||
positions = account['books'][book]
|
||||
position = positions.setdefault(code, {'qty': 0, 'cost': 0., 'lots': []})
|
||||
amount = qty*price
|
||||
fees = fee(amount, side, **costs)
|
||||
from app.core import rotation_account as capital
|
||||
values = {}
|
||||
prices = prices or {code: price}
|
||||
for b in ('original', 'micro30'):
|
||||
if any(c not in prices for c, p in account['books'][b].items() if p['qty']):
|
||||
raise ValueError('纸面划拨前需要完整持仓估值')
|
||||
values[b] = sum(p['qty']*prices.get(c, 0) for c, p in account['books'][b].items())
|
||||
if 'capital' not in account:
|
||||
account['capital'] = capital.seed(account['cash'], values)
|
||||
cashbook = account['capital']
|
||||
if side == 'buy':
|
||||
if account['cash']+1e-8 < amount+fees:
|
||||
raise ValueError('纸面账户现金不足')
|
||||
need = max(0., amount+fees-cashbook['cash'][book])
|
||||
if need:
|
||||
capital.transfer(cashbook, 'original' if book == 'micro30' else 'micro30', book, need, values, 'fund:'+key)
|
||||
capital.fill(cashbook, book, side, amount, fees, key)
|
||||
account['cash'] -= amount+fees
|
||||
position['qty'] += qty
|
||||
position['cost'] += amount+fees
|
||||
position['lots'].append({'date': trade_date, 'qty': qty})
|
||||
else:
|
||||
available = sum(r['qty'] for r in position['lots'] if r['date'] < trade_date)
|
||||
if qty > available or qty > position['qty']:
|
||||
raise ValueError('纸面账本可卖数量不足')
|
||||
capital.fill(cashbook, book, side, amount, fees, key)
|
||||
old_qty = position['qty']
|
||||
position['qty'] -= qty
|
||||
released_cost = position['cost']*qty/old_qty
|
||||
position['cost'] -= released_cost
|
||||
account['cash'] += amount-fees
|
||||
account['realized'][book] += amount-fees-released_cost
|
||||
remaining = qty
|
||||
for lot in position['lots']:
|
||||
taken = min(remaining, lot['qty']) if lot['date'] < trade_date else 0
|
||||
lot['qty'] -= taken
|
||||
remaining -= taken
|
||||
account['fees'][book] += fees
|
||||
account['fills'][key] = {**order, 'price': price, 'date': trade_date, 'fee': fees}
|
||||
return True
|
||||
|
|
@ -13,6 +13,8 @@ def basis(row):
|
|||
result = {k: row.get(k) for k in ('score', 'tier', 'upside', 'heat', 'theme',
|
||||
'verdict', 'risk', 'missing', 'reasons', 'logic_state', 'company_gate',
|
||||
'company_review', 'company_review_text', 'events', 'pricing_state', 'news')}
|
||||
if row.get('user_candidate'):
|
||||
result.update(user_candidate=row['user_candidate'], user_required=bool(row.get('user_required')))
|
||||
if row.get('candidate_source') == 'dividend':
|
||||
result.update({k: row.get(k) for k in ('candidate_source', 'dividend_ref', 'dividend_policy_version')})
|
||||
# 资料年龄不是研究变化;固定报告引用和研究内容才是。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,153 @@
|
|||
"""限制价主源的纯校验。只接受目标日沪深A股事实,不计算或补造价格。"""
|
||||
from collections.abc import Mapping
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation, localcontext
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
|
||||
MAX_ROWS = 6000
|
||||
REQUIRED_FIELDS = ('trade_date', 'ts_code', 'pre_close', 'up_limit', 'down_limit')
|
||||
_CENT = Decimal('0.01')
|
||||
_SUPPORTED = re.compile(r'(?:60[0-9]{4}\.SH|68[0-9]{4}\.SH|00[0-9]{4}\.SZ|30[0-9]{4}\.SZ)')
|
||||
_IDENTIFIABLE = re.compile(r'[0-9]{6}\.(?:SH|SZ|BJ)')
|
||||
|
||||
|
||||
def supported(code):
|
||||
"""仅规范化大小写与首尾空白,不猜测交易所,不包含北交所。"""
|
||||
return isinstance(code, str) and _SUPPORTED.fullmatch(code.strip().upper()) is not None
|
||||
|
||||
|
||||
def _result(error=None):
|
||||
return {'records': {}, 'invalid': {}, 'errors': [error] if error else []}
|
||||
|
||||
|
||||
def _day(value):
|
||||
if isinstance(value, datetime):
|
||||
return value.date().isoformat()
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int)):
|
||||
raise ValueError('INVALID_DATE')
|
||||
value = str(value).strip()
|
||||
if re.fullmatch(r'[0-9]{8}', value):
|
||||
value = value[:4]+'-'+value[4:6]+'-'+value[6:]
|
||||
elif not re.fullmatch(r'[0-9]{4}-[0-9]{2}-[0-9]{2}', value):
|
||||
raise ValueError('INVALID_DATE')
|
||||
try:
|
||||
return date.fromisoformat(value).isoformat()
|
||||
except ValueError:
|
||||
raise ValueError('INVALID_DATE') from None
|
||||
|
||||
|
||||
def _price(value):
|
||||
if isinstance(value, bool) or not isinstance(value, (str, int, float, Decimal)):
|
||||
raise ValueError('INVALID_PRICE')
|
||||
text = str(value).strip()
|
||||
if not text or len(text) > 128:
|
||||
raise ValueError('INVALID_PRICE')
|
||||
try:
|
||||
number = Decimal(text)
|
||||
if not number.is_finite() or number < 0:
|
||||
raise ValueError('INVALID_PRICE')
|
||||
with localcontext() as context:
|
||||
context.prec = 28
|
||||
context.traps[InvalidOperation] = True
|
||||
cents = number.quantize(_CENT)
|
||||
if cents != number:
|
||||
raise ValueError('INVALID_PRECISION')
|
||||
return cents
|
||||
except InvalidOperation:
|
||||
raise ValueError('INVALID_PRICE') from None
|
||||
|
||||
|
||||
def normalize_rows(rows, day, requested_codes=None):
|
||||
"""返回可JSON序列化记录;坏票隔离,结构错误拒绝整批。
|
||||
|
||||
日期输出ISO格式,价格输出精确两位字符串。同票任何坏行都会隔离该票,
|
||||
不能用另一条正确日期或正确价格的行掩盖。错误仅返回固定原因码。
|
||||
"""
|
||||
try:
|
||||
target = _day(day)
|
||||
except ValueError:
|
||||
return _result('INVALID_TARGET_DATE')
|
||||
if not isinstance(rows, (list, tuple)):
|
||||
return _result('INVALID_ROWS')
|
||||
if len(rows) > MAX_ROWS:
|
||||
return _result('TOO_MANY_ROWS')
|
||||
if any(not isinstance(row, Mapping) for row in rows):
|
||||
return _result('INVALID_ROW_STRUCTURE')
|
||||
allowed = None
|
||||
if requested_codes is not None:
|
||||
if not isinstance(requested_codes, (list, tuple, set, frozenset)):
|
||||
return _result('INVALID_REQUESTED_CODES')
|
||||
if any(not supported(code) for code in requested_codes):
|
||||
return _result('INVALID_REQUESTED_CODES')
|
||||
allowed = {code.strip().upper() for code in requested_codes} or None
|
||||
result = _result()
|
||||
records, invalid = result['records'], result['invalid']
|
||||
for index, row in enumerate(rows):
|
||||
raw_code = row.get('ts_code')
|
||||
code = raw_code.strip().upper() if isinstance(raw_code, str) else ''
|
||||
# 不回显任意上游文本;无法识别为证券代码时只记录行号。
|
||||
key = code if _IDENTIFIABLE.fullmatch(code) else f'row:{index+1}'
|
||||
reason = None
|
||||
if not supported(code):
|
||||
reason = 'OUT_OF_SCOPE' if _IDENTIFIABLE.fullmatch(code) else 'INVALID_CODE'
|
||||
elif allowed is not None and code not in allowed:
|
||||
reason = 'NOT_REQUESTED'
|
||||
elif any(field not in row for field in REQUIRED_FIELDS):
|
||||
reason = 'MISSING_FIELD'
|
||||
else:
|
||||
try:
|
||||
if _day(row['trade_date']) != target:
|
||||
raise ValueError('DATE_MISMATCH')
|
||||
close, high, low = (_price(row[field]) for field in ('pre_close', 'up_limit', 'down_limit'))
|
||||
if high == 0 or low == 0:
|
||||
raise ValueError('UNSUPPORTED')
|
||||
if close <= 0:
|
||||
raise ValueError('INVALID_PRE_CLOSE')
|
||||
if low >= high:
|
||||
raise ValueError('INVALID_RANGE')
|
||||
if not low <= close <= high:
|
||||
raise ValueError('PRE_CLOSE_OUTSIDE_LIMITS')
|
||||
record = {'trade_date': target, 'ts_code': code, 'pre_close': format(close, '.2f'),
|
||||
'up_limit': format(high, '.2f'), 'down_limit': format(low, '.2f')}
|
||||
digest = hashlib.sha256(json.dumps(record, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':')).encode('utf-8')).hexdigest()
|
||||
record['version'] = digest
|
||||
if code in records and records[code] != record:
|
||||
raise ValueError('DUPLICATE_CONFLICT')
|
||||
if code not in invalid:
|
||||
records[code] = record
|
||||
except ValueError as exc:
|
||||
reason = str(exc)
|
||||
if reason:
|
||||
records.pop(code, None)
|
||||
invalid.setdefault(key, reason)
|
||||
return result
|
||||
|
||||
|
||||
def provider_decode(body, day, requested_codes=None):
|
||||
"""校验Tushare JSON封套。HTTP状态由调用层检查,不输出msg或响应正文。"""
|
||||
if not isinstance(body, Mapping) or type(body.get('code')) is not int:
|
||||
return _result('INVALID_PROVIDER_RESPONSE')
|
||||
if body['code'] != 0:
|
||||
return _result('PROVIDER_ERROR')
|
||||
data = body.get('data')
|
||||
if not isinstance(data, Mapping):
|
||||
return _result('INVALID_PROVIDER_DATA')
|
||||
fields, items = data.get('fields'), data.get('items')
|
||||
if (not isinstance(fields, list) or not fields
|
||||
or any(not isinstance(field, str) or not field for field in fields)
|
||||
or len(set(fields)) != len(fields)):
|
||||
return _result('INVALID_PROVIDER_FIELDS')
|
||||
if any(field not in fields for field in REQUIRED_FIELDS):
|
||||
return _result('MISSING_PROVIDER_FIELDS')
|
||||
if not isinstance(items, list):
|
||||
return _result('INVALID_PROVIDER_ITEMS')
|
||||
if len(items) > MAX_ROWS:
|
||||
return _result('TOO_MANY_ROWS')
|
||||
if any(not isinstance(item, (list, tuple)) or len(item) != len(fields) for item in items):
|
||||
return _result('INVALID_PROVIDER_ITEM_STRUCTURE')
|
||||
return normalize_rows([dict(zip(fields, item)) for item in items], day, requested_codes)
|
||||
|
|
@ -223,7 +223,8 @@ def map_trades_to_book(trades: list, parent_actions=None) -> dict:
|
|||
"lot_type": (ACTION_TO_LOT.get(str(action or "").upper(), "BASE")
|
||||
if side == "buy" else None),
|
||||
"instruction_id": parent if action else None,
|
||||
"order_id": pl.get("trade_no"), "seq": seq, "alerts": []})
|
||||
"order_id": pl.get("trade_no"), "seq": seq, "alerts": [],
|
||||
"source_payload": dict(pl), "child_instruction_id": iid})
|
||||
|
||||
fee = pl.get("fee")
|
||||
if fee is not None and float(fee) != 0:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,78 @@
|
|||
"""分策略现金、内部划拨和单位净值。划拨只改变本金和份额,不产生利润。"""
|
||||
import math
|
||||
|
||||
BOOKS = ('original', 'micro30')
|
||||
|
||||
|
||||
def seed(cash, values):
|
||||
if cash < 0 or any(v < 0 or not math.isfinite(v) for v in [cash, *values.values()]):
|
||||
raise ValueError('初始资产非法')
|
||||
return {'cash': {'original': cash, 'micro30': 0.},
|
||||
'units': {b: values.get(b, 0)+(cash if b == 'original' else 0) for b in BOOKS},
|
||||
'net_capital': {b: values.get(b, 0)+(cash if b == 'original' else 0) for b in BOOKS},
|
||||
'fees': {b: 0. for b in BOOKS}, 'transfers': {}, 'fills': {}}
|
||||
|
||||
|
||||
def metrics(account, values):
|
||||
"""缺少市值时保留现金和本金,不把未知市值算成零。"""
|
||||
result = {}
|
||||
for b in BOOKS:
|
||||
market_value = values.get(b, 0.)
|
||||
equity = account['cash'][b]+market_value if market_value is not None else None
|
||||
units = account['units'][b]
|
||||
result[b] = {'cash': account['cash'][b], 'market_value': market_value, 'equity': equity,
|
||||
'net_capital': account['net_capital'][b],
|
||||
'profit': equity-account['net_capital'][b] if equity is not None else None,
|
||||
'nav': equity/units if equity is not None and units > 1e-8 else None, 'fees': account['fees'][b]}
|
||||
complete = all(r['market_value'] is not None for r in result.values())
|
||||
result['account'] = {'cash': sum(account['cash'].values()),
|
||||
'market_value': sum(r['market_value'] for r in result.values()) if complete else None,
|
||||
'equity': sum(r['equity'] for r in result.values()) if complete else None,
|
||||
'profit': sum(r['profit'] for r in result.values()) if complete else None,
|
||||
'fees': sum(account['fees'].values())}
|
||||
return result
|
||||
|
||||
|
||||
def transfer(account, source, target, amount, values, key):
|
||||
if key in account['transfers']:
|
||||
old = account['transfers'][key]
|
||||
if (old['source'], old['target'], old['amount']) != (source, target, amount):
|
||||
raise ValueError('划拨幂等键内容不一致')
|
||||
return False
|
||||
if source == target or source not in BOOKS or target not in BOOKS or amount <= 0 or not math.isfinite(amount):
|
||||
raise ValueError('划拨参数非法')
|
||||
if account['cash'][source]+1e-6 < amount:
|
||||
raise ValueError('策略可划拨现金不足')
|
||||
if any(v is None or not math.isfinite(v) for v in values.values()):
|
||||
raise ValueError('策略估值不完整,不能划拨现金')
|
||||
before = metrics(account, values)
|
||||
for b, change in ((source, -amount), (target, amount)):
|
||||
nav = before[b]['nav']
|
||||
if nav is None:
|
||||
if abs(before[b]['equity']) > 1e-6:
|
||||
raise ValueError('策略有资产但没有可核实份额')
|
||||
nav = 1.
|
||||
if nav <= 0:
|
||||
raise ValueError('非正净值不能自动划拨')
|
||||
account['cash'][b] += change
|
||||
account['net_capital'][b] += change
|
||||
account['units'][b] += change/nav
|
||||
account['transfers'][key] = {'source': source, 'target': target, 'amount': amount,
|
||||
'source_nav': before[source]['nav'], 'target_nav': before[target]['nav']}
|
||||
return True
|
||||
|
||||
|
||||
def fill(account, book, side, amount, fee_amount, key):
|
||||
if key in account['fills']:
|
||||
if account['fills'][key] != {'book': book, 'side': side, 'amount': amount, 'fee': fee_amount}:
|
||||
raise ValueError('成交资金幂等键冲突')
|
||||
return False
|
||||
if book not in BOOKS or side not in ('buy', 'sell') or amount <= 0 or fee_amount < 0:
|
||||
raise ValueError('成交资金参数非法')
|
||||
change = (amount if side == 'sell' else -amount)-fee_amount
|
||||
if account['cash'][book]+change < -1e-6:
|
||||
raise ValueError('策略现金不足,不能跨账本透支')
|
||||
account['cash'][book] += change
|
||||
account['fees'][book] += fee_amount
|
||||
account['fills'][key] = {'book': book, 'side': side, 'amount': amount, 'fee': fee_amount}
|
||||
return True
|
||||
|
|
@ -192,6 +192,8 @@ def _check_buy(failed, warns, qty, price, ctx, pos, day, prm, flg, is_cmd, hard,
|
|||
else:
|
||||
failed.append("BRAKE_ACTIVE: 组合刹车中, 自主增持暂停")
|
||||
|
||||
hard["qmt_price_monitor"] = bool(flg.get("qmt_price_monitor"))
|
||||
if not flg.get("qmt_price_monitor"):
|
||||
if day.get("limit_up"):
|
||||
failed.append("LIMIT_UP: 涨停封板, 不追买")
|
||||
elif day.get("limit_down"):
|
||||
|
|
|
|||
|
|
@ -0,0 +1,60 @@
|
|||
"""策略账本范围。默认原策略,全账户范围只允许读取。"""
|
||||
import contextlib
|
||||
import contextvars
|
||||
import re
|
||||
|
||||
ORIGINAL = 'original'
|
||||
MICRO = 'micro30'
|
||||
CURRENT = contextvars.ContextVar('strategy_book', default=ORIGINAL)
|
||||
TABLES = frozenset({'pms_command', 'pms_plan', 'pms_position', 'pms_lot',
|
||||
'pms_instruction', 'pms_proposal', 'pms_action_ledger', 'pms_cash_flow', 'pms_strategy'})
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def scope(book):
|
||||
if book not in (ORIGINAL, MICRO, 'all'):
|
||||
raise ValueError('未知策略账本')
|
||||
token = CURRENT.set(book)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
CURRENT.reset(token)
|
||||
|
||||
|
||||
def scoped_sql(sql, book=None):
|
||||
"""只改既有单表语句的顶层条件,字符串与括号内部不参与定位。"""
|
||||
book = book or CURRENT.get()
|
||||
if book not in (ORIGINAL, MICRO, 'all'):
|
||||
raise ValueError('未知策略账本')
|
||||
match = re.search(r'\b(?:FROM|UPDATE|INTO)\s+(pms_\w+)\b', sql, re.I)
|
||||
if not match or match.group(1) not in TABLES:
|
||||
return sql
|
||||
verb = sql.lstrip().split()[0].upper()
|
||||
if verb not in ('SELECT', 'INSERT', 'UPDATE', 'DELETE'):
|
||||
return sql
|
||||
if book == 'all':
|
||||
if verb != 'SELECT':
|
||||
raise ValueError('全账户范围禁止直接写入策略账本')
|
||||
return sql
|
||||
if verb == 'INSERT':
|
||||
m = re.match(r'(\s*INSERT\s+INTO\s+pms_\w+\s*\()([^)]*)(\)\s*VALUES\s*\()', sql, re.I)
|
||||
if not m or re.search(r'\bbook_id\b', m.group(2), re.I):
|
||||
raise ValueError('策略账本INSERT形状不受支持或重复指定归属')
|
||||
return m.group(1)+'book_id, '+m.group(2)+m.group(3)+"'"+book+"', "+sql[m.end():]
|
||||
# 屏蔽引号,不改变字符下标。顶层WHERE整体包裹,避免OR越过账本条件。
|
||||
masked = re.sub(r"'(?:''|\\.|[^'])*'|\"(?:\\.|[^\"])*\"", lambda m: ' '*len(m.group()), sql)
|
||||
depth, tokens = 0, []
|
||||
for m in re.finditer(r'\(|\)|\b(?:WHERE|GROUP\s+BY|ORDER\s+BY|LIMIT|FOR\s+UPDATE)\b', masked, re.I):
|
||||
if m.group() == '(':
|
||||
depth += 1
|
||||
elif m.group() == ')':
|
||||
depth -= 1
|
||||
elif depth == 0:
|
||||
tokens.append((m.group().upper(), m.start(), m.end()))
|
||||
where = next((t for t in tokens if t[0] == 'WHERE'), None)
|
||||
tail = next((t for t in tokens if t[0] != 'WHERE'), None)
|
||||
end = tail[1] if tail else len(sql)
|
||||
condition = "book_id = '"+book+"'"
|
||||
if where:
|
||||
return sql[:where[1]]+'WHERE '+condition+' AND ('+sql[where[2]:end].strip()+') '+sql[end:]
|
||||
return sql[:end].rstrip()+' WHERE '+condition+' '+sql[end:]
|
||||
|
|
@ -0,0 +1,330 @@
|
|||
"""成交更正的纯投影器。原账可完整重演时才返回修改计划,不访问数据库或发出动作。"""
|
||||
from copy import deepcopy
|
||||
from datetime import date, datetime, timezone, timedelta
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
import re
|
||||
|
||||
from app.core.cushion import sell_allocation
|
||||
from app.core.recon import parent_instruction_id
|
||||
|
||||
TZ = timezone(timedelta(hours=8))
|
||||
PRICE_UNIT, MONEY_UNIT = Decimal('0.001'), Decimal('0.01')
|
||||
LOT_TYPES = {'BASE', 'FILL', 'ADD', 'DCA', 'T0'}
|
||||
LOT_FIELDS = ('qty', 'closed_qty', 'open_price', 'close_avg_price', 'realized_pnl', 'status')
|
||||
MAX_QTY = 2147483647
|
||||
|
||||
|
||||
def _need(value, reason):
|
||||
if not value:
|
||||
raise ValueError(reason)
|
||||
|
||||
|
||||
def _decimal(value, label):
|
||||
_need(value is not None and not isinstance(value, bool), label+'缺失或格式错误')
|
||||
try:
|
||||
number = Decimal(str(value))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
raise ValueError(label+'不是有效数字') from None
|
||||
_need(number.is_finite(), label+'必须为有限数字')
|
||||
return number
|
||||
|
||||
|
||||
def _quantize(value, unit):
|
||||
try:
|
||||
return value.quantize(unit, rounding=ROUND_HALF_UP)
|
||||
except InvalidOperation:
|
||||
raise ValueError('成交数字超出可核验精度') from None
|
||||
|
||||
|
||||
def _qty(value, label='成交数量'):
|
||||
number = _decimal(value, label)
|
||||
_need(0 <= number <= MAX_QTY and number == number.to_integral_value(), label+'须为非负整数')
|
||||
return int(number)
|
||||
|
||||
|
||||
def _identity(value, label):
|
||||
number = _decimal(value, label)
|
||||
_need(0 < number < 2 ** 63 and number == number.to_integral_value(), label+'须为正整数')
|
||||
return int(number)
|
||||
|
||||
|
||||
def _price(value):
|
||||
number = _decimal(value, '成交价格')
|
||||
_need(0 <= number < Decimal('10000000') and number == _quantize(number, PRICE_UNIT),
|
||||
'成交价格须非负且不超过三位小数')
|
||||
return number
|
||||
|
||||
|
||||
def _money(value):
|
||||
number = _quantize(value, MONEY_UNIT)
|
||||
_need(abs(number) < Decimal('1000000000000'), '成交金额超出账本范围')
|
||||
return number
|
||||
|
||||
|
||||
def _economic(payload):
|
||||
_need(isinstance(payload, dict), '成交字段须为对象')
|
||||
qty, price = _qty(payload.get('qty')), _price(payload.get('price'))
|
||||
amount = _decimal(payload.get('amount'), '成交金额')
|
||||
_need(amount >= 0 and amount == _money(amount), '成交金额须非负且不超过两位小数')
|
||||
_need(qty == 0 or price > 0, '非零成交数量必须有正价格')
|
||||
_need(amount == _money(price * qty), '成交数量、价格与金额不一致')
|
||||
return {'qty': qty, 'price': price, 'amount': amount}
|
||||
|
||||
|
||||
def _day(value, label):
|
||||
try:
|
||||
if isinstance(value, datetime):
|
||||
return _stamp(value).date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
return date.fromisoformat(str(value))
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(label+'缺失或格式错误') from None
|
||||
|
||||
|
||||
def _stamp(value):
|
||||
try:
|
||||
stamp = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
return stamp.replace(tzinfo=TZ) if stamp.tzinfo is None else stamp.astimezone(TZ)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError('入账时间缺失或格式错误') from None
|
||||
|
||||
|
||||
def _trade_day(row):
|
||||
raw = row['original_payload'].get('trade_time')
|
||||
if raw is None:
|
||||
# 只有服务层显式提供的真实交易日可替代原时间,不拿接收日猜交易日。
|
||||
return _day(row.get('trade_day'), '真实交易日期')
|
||||
try:
|
||||
value = _decimal(raw, '成交时间')
|
||||
_need(value > 0 and value == value.to_integral_value(), '成交时间须为正毫秒整数')
|
||||
return datetime.fromtimestamp(int(value) / 1000, TZ).date()
|
||||
except (OverflowError, OSError, ValueError):
|
||||
raise ValueError('真实成交时间不可核验') from None
|
||||
|
||||
|
||||
def _code(value):
|
||||
value = str(value or '').strip().upper()
|
||||
_need(re.fullmatch(r'(?:60\d{4}\.SH|68\d{4}\.SH|00\d{4}\.SZ|30\d{4}\.SZ)', value),
|
||||
'更正范围须为沪深股票')
|
||||
return value
|
||||
|
||||
|
||||
def _parent(payload):
|
||||
value = payload.get('parent_id') or parent_instruction_id(payload.get('instruction_id'))
|
||||
_need(isinstance(value, str) and value, '成交缺少父指令归属')
|
||||
return value
|
||||
|
||||
|
||||
def _fields(lot):
|
||||
qty, closed = _qty(lot.get('qty'), '批次剩余数量'), _qty(lot.get('closed_qty'), '批次已平数量')
|
||||
close = lot.get('close_avg_price')
|
||||
close = _price(close) if close is not None else None
|
||||
pnl = _decimal(lot.get('realized_pnl'), '批次已实现盈亏')
|
||||
_need(pnl == _money(pnl), '批次盈亏金额精度不可核验')
|
||||
status = str(lot.get('status') or '')
|
||||
_need(status in ('OPEN', 'CLOSED'), '批次状态不可核验')
|
||||
return {'qty': qty, 'closed_qty': closed, 'open_price': _price(lot.get('open_price')),
|
||||
'close_avg_price': close, 'realized_pnl': pnl, 'status': status}
|
||||
|
||||
|
||||
def _export(fields):
|
||||
out = dict(fields)
|
||||
for key in ('open_price', 'close_avg_price'):
|
||||
if out.get(key) is not None:
|
||||
out[key] = format(_quantize(out[key], PRICE_UNIT), 'f')
|
||||
if 'realized_pnl' in out:
|
||||
out['realized_pnl'] = format(_money(out['realized_pnl']), 'f')
|
||||
return out
|
||||
|
||||
|
||||
def _export_trade(value):
|
||||
return {'qty': value['qty'], 'price': format(_quantize(value['price'], PRICE_UNIT), 'f'),
|
||||
'amount': format(_money(value['amount']), 'f')}
|
||||
|
||||
|
||||
def _prepare(lots, trades, lot_links):
|
||||
_need(isinstance(lots, list) and lots and isinstance(trades, list) and trades,
|
||||
'缺少完整批次或逐笔成交')
|
||||
codes, books, by_lot = set(), set(), {}
|
||||
for lot in lots:
|
||||
_need(isinstance(lot, dict), '批次格式错误')
|
||||
lid = _identity(lot.get('id'), '批次编号')
|
||||
_need(lid > 0 and lid not in by_lot, '批次编号缺失或重复')
|
||||
_need(lot.get('lot_type') in LOT_TYPES, '存在RECON或未知批次,不能自动更正')
|
||||
_need(lot.get('instruction_id'), '存在外部批次,不能自动更正')
|
||||
_need(not lot.get('archived_at'), '已归档批次不能自动更正')
|
||||
_fields(lot)
|
||||
_day(lot.get('open_date'), '批次开仓日期')
|
||||
codes.add(_code(lot.get('ts_code')))
|
||||
if 'book_id' in lot:
|
||||
_need(lot['book_id'] in ('original', 'micro30'), '批次策略归属不可核验')
|
||||
books.add(lot['book_id'])
|
||||
by_lot[lid] = lot
|
||||
rows, seqs, numbers = [], set(), set()
|
||||
for source in trades:
|
||||
_need(isinstance(source, dict), '逐笔记录格式错误')
|
||||
row = deepcopy(source)
|
||||
payload = row.get('payload')
|
||||
original = row.get('original_payload', payload)
|
||||
_need(isinstance(payload, dict) and isinstance(original, dict), '缺少原始或有效成交')
|
||||
_economic(payload)
|
||||
_need(_economic(original)['qty'] > 0, '原始成交数量必须为正数')
|
||||
seq = _identity(row.get('seq'), '入账序号')
|
||||
no = payload.get('trade_no')
|
||||
_need(seq > 0 and seq not in seqs and isinstance(no, str) and no and no not in numbers,
|
||||
'成交序号或成交号缺失、重复')
|
||||
_need(payload.get('side') in ('buy', 'sell'), '成交方向不可核验')
|
||||
_need(all(payload.get(k) == original.get(k) for k in
|
||||
('trade_no', 'ts_code', 'side', 'instruction_id', 'broker_order_id'))
|
||||
and _parent(payload) == _parent(original), '有效成交与原成交身份冲突')
|
||||
_need(not row.get('archived_at') and not payload.get('archived_at'), '已归档成交不能自动更正')
|
||||
codes.add(_code(payload.get('ts_code')))
|
||||
for owner in (row, payload, original):
|
||||
if 'book_id' in owner:
|
||||
_need(owner['book_id'] in ('original', 'micro30'), '成交策略归属不可核验')
|
||||
books.add(owner['book_id'])
|
||||
seqs.add(seq); numbers.add(no)
|
||||
row.update(seq=seq, payload=payload, original_payload=original)
|
||||
rows.append(row)
|
||||
_need(len(codes) == 1, '更正输入混有不同证券')
|
||||
_need(len(books) <= 1 and books <= {'original', 'micro30'}, '更正输入混有不同或未知策略账本')
|
||||
links = dict(lot_links or {})
|
||||
buy_numbers = {r['payload']['trade_no'] for r in rows if r['payload']['side'] == 'buy'}
|
||||
_need(set(links) <= buy_numbers, '批次映射包含不属于本次证据的成交')
|
||||
used, mapped = set(), {}
|
||||
for row in rows:
|
||||
current, original = row['payload'], row['original_payload']
|
||||
if current['side'] != 'buy':
|
||||
continue
|
||||
no = current['trade_no']
|
||||
if no in links:
|
||||
lid = _identity(links[no], '映射批次编号')
|
||||
candidates = [by_lot[lid]] if lid in by_lot else []
|
||||
else:
|
||||
value = _economic(original)
|
||||
stamp = _stamp(row.get('processed_at'))
|
||||
candidates = [l for l in lots if l['instruction_id'] == _parent(original)
|
||||
and _qty(l['qty']) + _qty(l['closed_qty']) == value['qty']
|
||||
and _price(l['open_price']) == value['price']
|
||||
and _stamp(l.get('created_at')) == stamp]
|
||||
_need(len(candidates) == 1, '原始买入成交不能唯一映射批次')
|
||||
lot = candidates[0]
|
||||
lid = int(lot['id'])
|
||||
_need(lid not in used and lot['instruction_id'] == _parent(current), '成交批次重复使用或父指令不符')
|
||||
used.add(lid); mapped[no] = lid
|
||||
_need(used == set(by_lot), '批次缺少完整逐笔来源,不能假设零基线')
|
||||
return sorted(rows, key=lambda r: r['seq']), by_lot, mapped
|
||||
|
||||
|
||||
def _project(rows, by_lot, mapped):
|
||||
state = {lid: {'qty': 0, 'closed_qty': 0, 'open_price': Decimal(0),
|
||||
'close_avg_price': None, 'realized_pnl': Decimal(0), 'status': 'CLOSED'} for lid in by_lot}
|
||||
allocations, t_profit = [], Decimal(0)
|
||||
for row in rows:
|
||||
p = row['payload']; value = _economic(p)
|
||||
qty, price = value['qty'], value['price']
|
||||
if p['side'] == 'buy':
|
||||
state[mapped[p['trade_no']]].update(qty=qty, open_price=price, status='OPEN' if qty else 'CLOSED')
|
||||
_need(sum(l['qty'] for l in state.values()) <= MAX_QTY, '逐笔持仓数量超出账本范围')
|
||||
continue
|
||||
candidates = [{'lot_id': lid, 'lot_type': by_lot[lid]['lot_type'], 'qty': l['qty'],
|
||||
'open_date': int(_day(by_lot[lid]['open_date'], '批次开仓日期').strftime('%Y%m%d'))}
|
||||
for lid, l in sorted(state.items(), key=lambda pair: (str(by_lot[pair[0]]['open_date']), pair[0]))
|
||||
if l['qty'] > 0]
|
||||
trade_t_profit = Decimal(0)
|
||||
for allocation in sell_allocation(candidates, qty):
|
||||
lid, take = allocation['lot_id'], allocation['qty']
|
||||
lot = state[lid]
|
||||
old_pnl = lot['realized_pnl']
|
||||
if by_lot[lid]['lot_type'] == 'T0':
|
||||
trade_t_profit += (price - lot['open_price']) * take
|
||||
closed = lot['closed_qty'] + take
|
||||
# MySQL逐笔UPDATE会把均价写入三位列、盈亏写入两位列,下一笔使用这些已落库值。
|
||||
lot['close_avg_price'] = _quantize(((lot['close_avg_price'] or Decimal(0)) * lot['closed_qty']
|
||||
+ price * take) / closed, PRICE_UNIT)
|
||||
lot['realized_pnl'] = _money(old_pnl + (price - lot['open_price']) * take)
|
||||
lot.update(qty=lot['qty'] - take, closed_qty=closed)
|
||||
lot['status'] = 'OPEN' if lot['qty'] else 'CLOSED'
|
||||
allocations.append({'seq': row['seq'], 'trade_no': p['trade_no'], 'lot_id': lid, 'qty': take,
|
||||
'price': format(_quantize(price, PRICE_UNIT), 'f'),
|
||||
'realized_pnl_delta': format(lot['realized_pnl'] - old_pnl, '.2f')})
|
||||
# 持仓T收益是在一笔卖出全部T批核销后合计写入两位列,与逐批盈亏分别舍入不同。
|
||||
t_profit = _money(t_profit + trade_t_profit)
|
||||
_need(sum(l['qty'] for l in state.values()) <= MAX_QTY, '更正后持仓数量超出账本范围')
|
||||
return state, allocations, t_profit
|
||||
|
||||
|
||||
def _round_boundaries(rows):
|
||||
"""记录清零后再次买入的真实仓次边界;零量更正也保留原买入身份。"""
|
||||
balance, bought = 0, False
|
||||
boundaries, before = [], {}
|
||||
for row in rows:
|
||||
p, seq = row['payload'], row['seq']
|
||||
qty = _qty(p['qty'])
|
||||
before[seq] = balance
|
||||
if p['side'] == 'buy':
|
||||
if bought and balance == 0 and qty > 0:
|
||||
boundaries.append(seq)
|
||||
bought = True
|
||||
balance += qty
|
||||
else:
|
||||
balance -= qty
|
||||
return boundaries, before
|
||||
|
||||
|
||||
def compile_correction(*, lots, trades, target_trade_no, after, today, lot_links=None):
|
||||
"""证明当前有效逐笔与批次一致,再替换一笔并重演;费用与策略资金由服务层另行核验。
|
||||
|
||||
trades中的payload为已应用既有更正后的有效成交,original_payload保留原始trade。
|
||||
lot_links为{trade_no: lot_id};没有明确映射的旧数据须按原父指令、数量、价格、时间唯一配对。
|
||||
原始trade_time为毫秒;缺失时只接受服务层显式提供的真实trade_day,不用接收时间猜测。
|
||||
"""
|
||||
rows, by_lot, mapped = _prepare(lots, trades, lot_links)
|
||||
current, allocations_before, t_before = _project(rows, by_lot, mapped)
|
||||
for lid, lot in by_lot.items():
|
||||
_need(_fields(lot) == current[lid], '当前批次与有效逐笔重演不一致,拒绝更正')
|
||||
targets = [r for r in rows if r['payload']['trade_no'] == target_trade_no]
|
||||
_need(len(targets) == 1, '目标成交缺失或不唯一')
|
||||
target = targets[0]
|
||||
boundaries, _ = _round_boundaries(rows)
|
||||
_need(not any(target['seq'] < boundary for boundary in boundaries),
|
||||
'目标成交之后已清零并建立新仓,旧轮次更正须人工核对,不能回灌当前仓次')
|
||||
_need(isinstance(after, dict) and set(after) == {'qty', 'price', 'amount'},
|
||||
'更正仅接受数量、价格和金额,不能修改成交身份或费用')
|
||||
old, new = _economic(target['payload']), _economic(after)
|
||||
current_day, actual_day = _day(today, '核验日期'), _trade_day(target)
|
||||
_need(actual_day <= current_day, '成交日期在未来,拒绝更正')
|
||||
quantity_delta = new['qty'] - old['qty']
|
||||
if quantity_delta:
|
||||
book_day = (_day(by_lot[mapped[target_trade_no]]['open_date'], '批次开仓日期')
|
||||
if target['payload']['side'] == 'buy' else
|
||||
_day(target['book_day'], '原入账日期') if target.get('book_day') else
|
||||
_stamp(target.get('processed_at')).date())
|
||||
_need(book_day == actual_day, '原成交跨日入账,数量更正的T+1基线待核实')
|
||||
target['payload'].update(after)
|
||||
projected, allocations, t_after = _project(rows, by_lot, mapped)
|
||||
_, revised_before = _round_boundaries(rows)
|
||||
_need(all(revised_before[boundary] == 0 for boundary in boundaries),
|
||||
'更正会使旧清零边界带库存进入新仓,须人工核对')
|
||||
changed, exported = [], []
|
||||
for lid in sorted(by_lot):
|
||||
old_fields, new_fields = _export(current[lid]), _export(projected[lid])
|
||||
exported.append(dict(deepcopy(by_lot[lid]), **new_fields))
|
||||
if old_fields != new_fields:
|
||||
changed.append({'id': lid, 'before': old_fields, 'after': new_fields})
|
||||
def net(state):
|
||||
return sum((l['qty'] * l['open_price'] - l['realized_pnl'] for l in state.values()), Decimal(0))
|
||||
side = target['payload']['side']
|
||||
avail_delta = -quantity_delta if side == 'sell' else quantity_delta if actual_day < current_day else 0
|
||||
cash_delta = (new['amount'] - old['amount']) * (1 if side == 'sell' else -1)
|
||||
return {'lots': exported, 'changes': changed, 'lot_links': mapped,
|
||||
'allocations': allocations, 'allocations_before': allocations_before,
|
||||
'qty_before': sum(l['qty'] for l in current.values()),
|
||||
'qty_after': sum(l['qty'] for l in projected.values()),
|
||||
'amount_before': format(old['amount'], '.2f'), 'amount_after': format(new['amount'], '.2f'),
|
||||
'cash_delta': format(cash_delta, '.2f'), 'avail_delta': avail_delta,
|
||||
't_profit_delta': format(t_after - t_before, '.2f'),
|
||||
't_profit_before': format(t_before, '.2f'), 't_profit_after': format(t_after, '.2f'),
|
||||
'net_cost_before': format(net(current), 'f'), 'net_cost_after': format(net(projected), 'f'),
|
||||
'trade_before': _export_trade(old), 'trade_after': _export_trade(new)}
|
||||
|
|
@ -60,14 +60,14 @@ DOWNSTREAM_TYPES = (T_HELLO, T_PLACE, T_CANCEL, T_Q_POS, T_Q_FUNDS, T_Q_ORDERS,
|
|||
|
||||
T_HELLO_ACK, T_ACK, T_REJECT = "hello_ack", "ack", "reject"
|
||||
T_ORDER_UPDATE, T_TRADE, T_PERSIST = "order_update", "trade", "persist_result"
|
||||
T_TRADE_CORRECTION = "trade_correction"
|
||||
T_SNAPSHOT, T_POS_UPDATE, T_FUNDS_UPDATE, T_PONG = ("snapshot", "position_update",
|
||||
"funds_update", "pong")
|
||||
UPSTREAM_TYPES = (T_HELLO_ACK, T_ACK, T_REJECT, T_ORDER_UPDATE, T_TRADE, T_PERSIST,
|
||||
UPSTREAM_TYPES = (T_HELLO_ACK, T_ACK, T_REJECT, T_ORDER_UPDATE, T_TRADE, T_TRADE_CORRECTION, T_PERSIST,
|
||||
T_SNAPSHOT, T_POS_UPDATE, T_FUNDS_UPDATE, T_PONG)
|
||||
|
||||
# 只有 trade 需要 worker 入账 (§5.5「账本以 trade 为唯一入账依据」), 其余上行消息
|
||||
# 由常驻进程自己消化完就落库存档。这个集合是 inbox 里 processed 初值的判据。
|
||||
NEEDS_LEDGER = (T_TRADE,)
|
||||
# 成交与成交修正由worker入账。修正型order_update还须按payload分类,见needs_ledger。
|
||||
NEEDS_LEDGER = (T_TRADE, T_TRADE_CORRECTION)
|
||||
|
||||
# 指令状态 (§7.1)。终态唯一、不可再变。
|
||||
ST_ACCEPTED, ST_SUBMITTED, ST_PARTIAL = "ACCEPTED", "SUBMITTED", "PARTIAL"
|
||||
|
|
@ -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,
|
||||
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:
|
||||
|
|
@ -414,11 +419,29 @@ def ack_seq_payload(seq: int) -> dict:
|
|||
|
||||
|
||||
# ================================================================ 上行 payload 读取
|
||||
def is_correction(type_: str, payload: dict) -> bool:
|
||||
"""单独 amended=false 是普通回报;修正编号或其它修正标记必须核验。"""
|
||||
payload = payload or {}
|
||||
return type_ == T_TRADE_CORRECTION or (type_ == T_ORDER_UPDATE and
|
||||
(('amended' in payload and payload['amended'] is not False) or
|
||||
'correction_id' in payload or payload.get('reason') == T_TRADE_CORRECTION))
|
||||
|
||||
|
||||
def needs_ledger(type_: str, payload: dict) -> bool:
|
||||
return type_ in NEEDS_LEDGER or is_correction(type_, payload)
|
||||
|
||||
|
||||
def dedup_key(type_: str, payload: dict):
|
||||
"""第二层去重键 (§5.5)。目前只有 trade 有 —— trade_no 唯一, 命中即丢弃。
|
||||
"""第二层业务键:原成交按trade_no,修正两类证据各按correction_id。
|
||||
|
||||
第一层是 seq (补发时同一条消息 seq 不变)。两层都设是为了防住 seq 实现出 bug 的场景。
|
||||
"""
|
||||
if is_correction(type_, payload):
|
||||
cid = (payload or {}).get('correction_id')
|
||||
if not isinstance(cid, str) or not cid.strip():
|
||||
return None
|
||||
prefix = 'correction:' if type_ == T_TRADE_CORRECTION else 'amendment:'
|
||||
return prefix + hashlib.sha256(cid.encode('utf-8')).hexdigest()
|
||||
if type_ == T_TRADE:
|
||||
tn = (payload or {}).get("trade_no")
|
||||
return f"trade:{tn}" if tn else None
|
||||
|
|
|
|||
|
|
@ -19,6 +19,8 @@ import logging
|
|||
import re
|
||||
import time
|
||||
import threading
|
||||
import contextlib
|
||||
import contextvars
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
|
@ -29,6 +31,30 @@ logger = logging.getLogger("pms.db")
|
|||
|
||||
_engines = {}
|
||||
_lock = threading.Lock()
|
||||
_TRANSACTION = contextvars.ContextVar('pms_transaction', default=None)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def transaction():
|
||||
"""跨多条单表语句的原子事务。只在显式业务编排中启用。"""
|
||||
existing = _TRANSACTION.get()
|
||||
if existing is not None:
|
||||
yield existing
|
||||
return
|
||||
with get_engine('proxy').begin() as connection:
|
||||
token = _TRANSACTION.set(connection)
|
||||
try:
|
||||
yield connection
|
||||
finally:
|
||||
_TRANSACTION.reset(token)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def savepoint():
|
||||
"""一个子委托失败只回滚自身,已规划的退出阶段仍可提交。"""
|
||||
with transaction() as connection:
|
||||
with connection.begin_nested():
|
||||
yield connection
|
||||
|
||||
|
||||
# 短路冷却: 库刚连挂过就直接快速失败, 不再逐次等 TCP 超时。
|
||||
# 目的 —— 库不可达时页面仍能秒开 (每个接口只吃一次超时), 调度任务也不会被拖死。
|
||||
|
|
@ -114,6 +140,9 @@ TABLE_PREFIX = _load_prefix()
|
|||
|
||||
def map_tables(sql: str) -> str:
|
||||
"""按实例表名前缀改写 SQL 里的 pms_* 表名; 前缀为空原样返回。"""
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.core.strategy_book import scoped_sql
|
||||
sql = scoped_sql(str(sql))
|
||||
if not TABLE_PREFIX:
|
||||
return str(sql)
|
||||
return _PMS_TBL_RE.sub(TABLE_PREFIX + r"\1", str(sql))
|
||||
|
|
@ -170,6 +199,9 @@ def ping(name: str = "proxy") -> dict:
|
|||
def fetch_all(sql: str, params=None, source: str = "proxy") -> list:
|
||||
sql = map_tables(sql)
|
||||
assert_single_table(sql)
|
||||
connection = _TRANSACTION.get()
|
||||
if connection is not None and source == 'proxy':
|
||||
return [dict(r) for r in connection.execute(text(sql), params or {}).mappings().fetchall()]
|
||||
_check_cooldown(source)
|
||||
try:
|
||||
with get_engine(source).connect() as c:
|
||||
|
|
@ -203,6 +235,9 @@ def execute(sql: str, params=None, source: str = "proxy") -> int:
|
|||
"""写操作 (INSERT/UPDATE/DELETE)。返回受影响行数。"""
|
||||
sql = map_tables(sql)
|
||||
assert_single_table(sql)
|
||||
connection = _TRANSACTION.get()
|
||||
if connection is not None and source == 'proxy':
|
||||
return int(connection.execute(text(sql), params or {}).rowcount or 0)
|
||||
_check_cooldown(source)
|
||||
try:
|
||||
with get_engine(source).begin() as c:
|
||||
|
|
@ -224,6 +259,9 @@ def execute_many(sql: str, seq_params: list, source: str = "proxy") -> int:
|
|||
assert_single_table(sql)
|
||||
if not seq_params:
|
||||
return 0
|
||||
connection = _TRANSACTION.get()
|
||||
if connection is not None and source == 'proxy':
|
||||
return int(connection.execute(text(sql), seq_params).rowcount or 0)
|
||||
_check_cooldown(source)
|
||||
try:
|
||||
with get_engine(source).begin() as c:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
"""当日限制价的独立采集入口,不启动Celery或QMT连接。"""
|
||||
import logging
|
||||
import re
|
||||
import signal
|
||||
from threading import Event
|
||||
|
||||
|
||||
logger = logging.getLogger('pms.market_data_worker')
|
||||
|
||||
|
||||
def _summary(result):
|
||||
"""只保留固定摘要字段,源响应及异常正文不得进入进程日志。"""
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError('采集摘要格式无效')
|
||||
status = result.get('status')
|
||||
status = status if isinstance(status, str) and re.fullmatch(r'[A-Za-z0-9_-]{1,48}', status) else 'unknown'
|
||||
day = result.get('day')
|
||||
day = day if isinstance(day, str) and re.fullmatch(r'\d{4}-\d{2}-\d{2}', day) else '-'
|
||||
counts = []
|
||||
for key in ('target_count', 'valid_count', 'missing_count', 'error_count'):
|
||||
value = result.get(key)
|
||||
counts.append(value if type(value) is int and value >= 0 else 0)
|
||||
return status, day, *counts
|
||||
|
||||
|
||||
def main():
|
||||
from app.services import price_limit_collector
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s %(message)s')
|
||||
stopping = Event()
|
||||
|
||||
def stop(_signum, _frame):
|
||||
stopping.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
while not stopping.is_set():
|
||||
try:
|
||||
result = price_limit_collector.run_once()
|
||||
logger.info('限制价采集 status=%s day=%s target_count=%s valid_count=%s missing_count=%s error_count=%s',
|
||||
*_summary(result))
|
||||
except Exception as exc:
|
||||
logger.warning('限制价采集失败:%s', type(exc).__name__)
|
||||
stopping.wait(10)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
"""执行依据只更新独立JSON字段,避免刷新任务覆盖委托进度。"""
|
||||
import json
|
||||
from app.db import session as db
|
||||
|
||||
|
||||
def save_basis(instruction_id, value):
|
||||
affected = db.execute("UPDATE pms_instruction SET progress_json=JSON_SET("
|
||||
"COALESCE(progress_json,JSON_OBJECT()),'$.execution_basis_cache',JSON_EXTRACT(:body,'$')) "
|
||||
"WHERE instruction_id=:iid", {'iid': instruction_id, 'body': json.dumps(value, ensure_ascii=False)})
|
||||
if not affected:
|
||||
raise RuntimeError('执行依据缓存没有写入父指令')
|
||||
|
||||
|
||||
def pending_trades(child_ids):
|
||||
if not child_ids:
|
||||
return 0
|
||||
args = {'p': 0, 'orphan': 3}
|
||||
keys = []
|
||||
for index, iid in enumerate(child_ids):
|
||||
key = 'c'+str(index)
|
||||
args[key] = iid
|
||||
keys.append(':'+key)
|
||||
ids = ','.join(keys)
|
||||
row = db.fetch_one("SELECT COUNT(*) AS n FROM pms_qmt_inbox WHERE ((msg_type='trade' "
|
||||
"AND processed IN (:p,:orphan)) OR ("+_correction_sql()+" AND "+_pending_correction_sql()+")) AND (corr_id IN ("+ids+
|
||||
") OR JSON_UNQUOTE(JSON_EXTRACT(payload_json,'$.instruction_id')) IN ("+ids+'))', args)
|
||||
return int((row or {}).get('n') or 0)
|
||||
|
||||
|
||||
def _correction_sql():
|
||||
return ("(msg_type='trade_correction' OR (msg_type='order_update' AND "
|
||||
"((JSON_CONTAINS_PATH(payload_json,'one','$.amended') AND "
|
||||
"NOT COALESCE(JSON_CONTAINS(payload_json,'false','$.amended'),0)) OR "
|
||||
"JSON_CONTAINS_PATH(payload_json,'one','$.correction_id') OR "
|
||||
"JSON_UNQUOTE(JSON_EXTRACT(payload_json,'$.reason'))='trade_correction')))")
|
||||
|
||||
|
||||
def _pending_correction_sql():
|
||||
# 升级前未知类型或amended被通道存成2,不等于修正已经入账;重复占位的note不同。
|
||||
return ("(processed IN (0,3) OR (processed=2 AND process_note IN "
|
||||
"('trade_correction 由通道进程消化, 不入账','order_update 由通道进程消化, 不入账')))")
|
||||
|
||||
|
||||
def pending_corrections(ts_code=None, child_ids=None):
|
||||
"""账户买入读全部未核实修正;按证券或子单查询供卖出及已有父指令守卫。"""
|
||||
args = {}
|
||||
where = [_correction_sql(), _pending_correction_sql()]
|
||||
identity = []
|
||||
if ts_code:
|
||||
args['code'] = ts_code
|
||||
identity.append("JSON_UNQUOTE(JSON_EXTRACT(payload_json,'$.ts_code'))=:code")
|
||||
if child_ids:
|
||||
keys = []
|
||||
for index, iid in enumerate(child_ids):
|
||||
key = 'c'+str(index)
|
||||
args[key] = iid
|
||||
keys.append(':'+key)
|
||||
ids = ','.join(keys)
|
||||
identity.append("(corr_id IN ("+ids+") OR JSON_UNQUOTE(JSON_EXTRACT(payload_json,'$.instruction_id')) IN ("+ids+'))')
|
||||
if identity:
|
||||
where.append('('+' OR '.join(identity)+')')
|
||||
row = db.fetch_one('SELECT COUNT(*) AS n FROM pms_qmt_inbox WHERE '+' AND '.join(where), args)
|
||||
return int((row or {}).get('n') or 0)
|
||||
|
|
@ -41,6 +41,14 @@ def _loads(v):
|
|||
|
||||
|
||||
# ================================================================ 行情源表 (只读)
|
||||
def latest_published_hedge():
|
||||
"""现有指标表的最新发布记录,仅用于核对,不替换PMS执行信号。"""
|
||||
return fetch_one(
|
||||
'SELECT id,trade_date,hedge_index,spread,zone,create_time '
|
||||
'FROM gp_stock_fx_hedge_index ORDER BY trade_date DESC,id DESC LIMIT 1',
|
||||
source="proxy")
|
||||
|
||||
|
||||
def fetch_hedge_inputs(limit_days: int = 140) -> dict:
|
||||
"""股汇对冲指数的三条原始序列, 各取最近 N 条, 返回升序 (ymd, value) 列表。
|
||||
|
||||
|
|
|
|||
|
|
@ -470,7 +470,19 @@ def update_instruction(instruction_id: str, *, status=None, exec_qty=None, exec_
|
|||
sets.append("dispatch_ref = :dr")
|
||||
p["dr"] = dispatch_ref
|
||||
if progress is not None:
|
||||
sets.append("progress_json = :pg")
|
||||
# 独立刷新任务仅通过 execution_repo 写缓存;旧的整份进度不能覆盖新依据。
|
||||
# 同理,异步撤单/撤换标记不能被不知情的执行回写抹掉。显式传键可更新标记。
|
||||
body = ':pg'
|
||||
for key in ('cancel_requested', 'replacement_requested', 'trade_correction_hold'):
|
||||
if key not in progress:
|
||||
body = ("CASE WHEN JSON_CONTAINS_PATH(COALESCE(progress_json,JSON_OBJECT()),"
|
||||
f"'one','$.{key}') THEN JSON_SET(JSON_EXTRACT({body},'$'),"
|
||||
f"'$.{key}',JSON_EXTRACT(progress_json,'$.{key}')) ELSE {body} END")
|
||||
body = ("CASE WHEN JSON_CONTAINS_PATH(COALESCE(progress_json,JSON_OBJECT()),"
|
||||
"'one','$.execution_basis_cache') THEN JSON_SET(JSON_EXTRACT("+body+",'$'),"
|
||||
"'$.execution_basis_cache',JSON_EXTRACT(progress_json,'$.execution_basis_cache')) "
|
||||
'ELSE '+body+' END')
|
||||
sets.append('progress_json = '+body)
|
||||
p["pg"] = _dumps(progress)
|
||||
guard = " AND status IN ('PROPOSED','RULE_PASSED','JUDGE_PASSED','DISPATCHED')" if status == 'DISPATCHED' else ''
|
||||
# 下发后的旧进度回写不能把已撤销指令复活。真实迟到成交仍由成交入口记账。
|
||||
|
|
@ -486,6 +498,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:
|
||||
|
|
@ -1002,19 +1025,46 @@ def insert_strategy(*, strategy_id, ts_code, stype, autonomy="auto", params=None
|
|||
|
||||
|
||||
def update_strategy(strategy_id: str, **fields) -> int:
|
||||
"""更新策略。params/state 传 dict 会自动 json 化到 *_json 列。"""
|
||||
"""更新策略;state 按成交更正版本比较后写入,旧运行任务不得覆盖新状态。"""
|
||||
upd = dict(fields)
|
||||
unset = object()
|
||||
expected = upd.pop("correction_expected", unset)
|
||||
if "params" in upd:
|
||||
upd["params_json"] = _dumps(upd.pop("params"))
|
||||
if "state" in upd:
|
||||
upd["state_json"] = _dumps(upd.pop("state"))
|
||||
state_write = "state_json" in upd
|
||||
if state_write:
|
||||
state = _loads(upd["state_json"])
|
||||
if not isinstance(state, dict):
|
||||
raise ValueError("策略状态必须是对象")
|
||||
correction = state.get("trade_correction") or {}
|
||||
if not isinstance(correction, dict):
|
||||
raise ValueError("策略成交更正版本异常")
|
||||
if expected is unset:
|
||||
expected = correction.get("correction_id")
|
||||
if expected is not None and (not isinstance(expected, str) or not expected):
|
||||
raise ValueError("策略成交更正版本异常")
|
||||
elif expected is not unset:
|
||||
raise ValueError("成交更正版本比较必须同时保存策略状态")
|
||||
clause, p = _set_clause(upd, STRATEGY_COLS)
|
||||
if not clause:
|
||||
return 0
|
||||
p["sid"] = strategy_id
|
||||
p["ts"] = _NOW()
|
||||
return execute(
|
||||
f"UPDATE pms_strategy SET {clause}, updated_at = :ts WHERE strategy_id = :sid", p)
|
||||
where = "strategy_id = :sid"
|
||||
if state_write:
|
||||
epoch = "JSON_EXTRACT(state_json, '$.trade_correction.correction_id')"
|
||||
if expected is None:
|
||||
where += f" AND ({epoch} IS NULL OR {epoch} = JSON_EXTRACT('null', '$'))"
|
||||
else:
|
||||
where += f" AND {epoch} = JSON_EXTRACT(:correction_expected, '$')"
|
||||
p["correction_expected"] = json.dumps(expected, ensure_ascii=False)
|
||||
changed = execute(
|
||||
f"UPDATE pms_strategy SET {clause}, updated_at = :ts WHERE {where}", p)
|
||||
if state_write and changed != 1:
|
||||
raise RuntimeError("策略成交更正版本已变化或策略不存在,拒绝覆盖旧状态")
|
||||
return changed
|
||||
|
||||
|
||||
# ================================================================ 软归档 (从在办/在途视图移除)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ from __future__ import annotations
|
|||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from app.core import ws_codec
|
||||
|
||||
from app.db.session import execute, fetch_all, fetch_one
|
||||
|
||||
|
|
@ -48,10 +49,10 @@ def is_smoke(parent_id) -> bool:
|
|||
|
||||
|
||||
# pms_qmt_inbox.processed 的取值。0/1/2 是原有语义; 3 是 2026-07-30 新增的「挂起待人工」。
|
||||
# 0 待入账 只有 trade 会是这个值 (见 ws_codec 的 NEEDS_LEDGER)
|
||||
# 0 待入账 trade、trade_correction及修正型order_update。
|
||||
# 1 已入账 成交已落进批次账本
|
||||
# 2 已消化 通道自处理完毕、无需入账 (含联调单跳过、重复 trade_no 占位行)
|
||||
# 3 挂起待人工 该入账但**不敢入**: 出口表反查不到这笔成交对应的委托。
|
||||
# 3 挂起待人工 归属未知、修正身份或内容冲突,不能安全入账。
|
||||
# 绝不能顺手当成 2 —— 2 的语义是「确认过不用管」, 3 是「有账没记, 等人看」。
|
||||
# 混在一起, 事后翻 inbox 就分不出哪些是真丢账。
|
||||
PROC_PENDING, PROC_BOOKED, PROC_DIGESTED, PROC_ORPHAN = 0, 1, 2, 3
|
||||
|
|
@ -166,10 +167,23 @@ def beat(stat=None) -> int:
|
|||
|
||||
# ================================================================ pms_qmt_inbox
|
||||
PUT_NEW, PUT_DUP_SEQ, PUT_DUP_KEY = "NEW", "DUP_SEQ", "DUP_KEY"
|
||||
PUT_CONFLICT = "CONFLICT"
|
||||
|
||||
|
||||
def inbox_put(*, seq: int, msg_id: str, msg_type: str, payload: dict, msg_ts: int,
|
||||
corr_id=None, dedup_key=None, processed: int = 2, note=None) -> str:
|
||||
"""修正消息的持久化与委托发送占用同一账户锁,先落库再推进确认水位。"""
|
||||
from config.settings import settings
|
||||
from contextlib import nullcontext
|
||||
from app.repo import rotation_repo
|
||||
guard = rotation_repo.account_guard() if settings.INFRA_STRATEGY_BOOK_SCHEMA and ws_codec.is_correction(msg_type, payload) else nullcontext()
|
||||
with guard:
|
||||
return _inbox_put(seq=seq, msg_id=msg_id, msg_type=msg_type, payload=payload,
|
||||
msg_ts=msg_ts, corr_id=corr_id, dedup_key=dedup_key, processed=processed, note=note)
|
||||
|
||||
|
||||
def _inbox_put(*, seq, msg_id, msg_type, payload, msg_ts, corr_id=None, dedup_key=None,
|
||||
processed=2, note=None):
|
||||
"""落一条上行消息。返回 NEW / DUP_SEQ / DUP_KEY。
|
||||
|
||||
双层去重 (§6.1 + §5.5): 主键 seq 是第一层, 唯一索引 dedup_key (trade_no) 是第二层。
|
||||
|
|
@ -193,11 +207,28 @@ def inbox_put(*, seq: int, msg_id: str, msg_type: str, payload: dict, msg_ts: in
|
|||
return PUT_DUP_SEQ
|
||||
|
||||
verdict = PUT_NEW
|
||||
correction = ws_codec.is_correction(msg_type, payload)
|
||||
if correction:
|
||||
# 仓储也计算业务键,避免调用方遗漏后将修正当普通存档静默消化。
|
||||
corr_id = payload.get('instruction_id')
|
||||
dedup_key = ws_codec.dedup_key(msg_type, payload)
|
||||
processed = PROC_PENDING
|
||||
if dedup_key is None:
|
||||
processed, verdict = PROC_ORPHAN, PUT_CONFLICT
|
||||
note = '成交修正缺少有效 correction_id,挂起核对,不改变委托和账本'
|
||||
if dedup_key and fetch_one("SELECT seq FROM pms_qmt_inbox WHERE dedup_key = :k",
|
||||
{"k": str(dedup_key)[:80]}):
|
||||
verdict = PUT_DUP_KEY
|
||||
note = f"重复成交 (dedup_key={dedup_key}), 不入账, 仅占位以推进 seq 水位"
|
||||
if correction:
|
||||
old = fetch_one('SELECT msg_type, payload_json FROM pms_qmt_inbox WHERE dedup_key=:k',
|
||||
{'k': dedup_key})
|
||||
if not old or old['msg_type'] != msg_type or _loads(old['payload_json'], None) != payload:
|
||||
verdict = PUT_CONFLICT
|
||||
note = '同一 correction_id 对应不同修正内容,挂起核对,原回执保留'
|
||||
dedup_key, processed = None, 2
|
||||
if verdict == PUT_CONFLICT:
|
||||
processed = PROC_ORPHAN
|
||||
|
||||
p = {"s": seq, "mi": str(msg_id)[:64], "mt": str(msg_type)[:24],
|
||||
"ci": (str(corr_id)[:64] if corr_id else None),
|
||||
|
|
@ -213,6 +244,26 @@ def inbox_put(*, seq: int, msg_id: str, msg_type: str, payload: dict, msg_ts: in
|
|||
return verdict
|
||||
|
||||
|
||||
def inbox_by_key(key):
|
||||
row = fetch_one('SELECT * FROM pms_qmt_inbox WHERE dedup_key=:key', {'key': key})
|
||||
if row:
|
||||
row['payload'] = _loads(row.get('payload_json'), {})
|
||||
return row
|
||||
|
||||
|
||||
def inbox_for_order(iid, msg_type=None, limit=10000):
|
||||
"""按原始 payload 身份兼容旧 corr_id;达到上限由调用方拒绝不完整核验。"""
|
||||
params = {'iid': iid, 'n': int(limit)}
|
||||
condition = "(corr_id=:iid OR JSON_UNQUOTE(JSON_EXTRACT(payload_json,'$.instruction_id'))=:iid)"
|
||||
if msg_type:
|
||||
condition += ' AND msg_type=:type'
|
||||
params['type'] = msg_type
|
||||
rows = fetch_all('SELECT * FROM pms_qmt_inbox WHERE '+condition+' ORDER BY seq LIMIT :n', params)
|
||||
for row in rows:
|
||||
row['payload'] = _loads(row.get('payload_json'), {})
|
||||
return rows
|
||||
|
||||
|
||||
def inbox_recover_watermark(stored_last_seq: int, limit: int = 20000) -> int:
|
||||
"""用 inbox 重算真正的连续水位。
|
||||
|
||||
|
|
@ -231,9 +282,12 @@ def inbox_recover_watermark(stored_last_seq: int, limit: int = 20000) -> int:
|
|||
return cur
|
||||
|
||||
|
||||
def inbox_pending(limit: int = 500) -> list:
|
||||
rows = fetch_all("SELECT * FROM pms_qmt_inbox WHERE processed = 0 ORDER BY seq ASC "
|
||||
"LIMIT :n", {"n": int(limit)})
|
||||
def inbox_pending(limit: int = 500, msg_type=None) -> list:
|
||||
condition, params = 'processed = 0', {'n': int(limit)}
|
||||
if msg_type:
|
||||
condition += ' AND msg_type=:type'
|
||||
params['type'] = msg_type
|
||||
rows = fetch_all('SELECT * FROM pms_qmt_inbox WHERE '+condition+' ORDER BY seq ASC LIMIT :n', params)
|
||||
for r in rows:
|
||||
r["payload"] = _loads(r.get("payload_json"), {})
|
||||
return rows
|
||||
|
|
@ -417,8 +471,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 +502,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 +523,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 +551,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(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
"""轮换文档仓储。快照、纸面账本、控制、验收证据分别保存,单条SQL单表。"""
|
||||
import contextlib
|
||||
import datetime as dt
|
||||
import json
|
||||
from sqlalchemy import text
|
||||
from app.db import session as db
|
||||
|
||||
|
||||
def encode(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str, allow_nan=False)
|
||||
|
||||
|
||||
def get(key):
|
||||
row = db.fetch_one('SELECT payload_json, revision FROM pms_rotation_document WHERE doc_id=:key', {'key': key})
|
||||
if row:
|
||||
return json.loads(row['payload_json']), int(row['revision'])
|
||||
return None, 0
|
||||
|
||||
|
||||
def put_once(key, kind, value):
|
||||
"""同键只能保存相同内容;重复快照可重试,历史版本不可覆盖。"""
|
||||
body = encode(value)
|
||||
db.execute('INSERT INTO pms_rotation_document (doc_id,kind,payload_json,revision,updated_at) '
|
||||
'VALUES (:key,:kind,:body,1,:now) ON DUPLICATE KEY UPDATE doc_id=VALUES(doc_id)',
|
||||
{'key': key, 'kind': kind, 'body': body, 'now': dt.datetime.now()})
|
||||
old, _ = get(key)
|
||||
if encode(old) != body:
|
||||
raise ValueError('同一幂等键出现不同内容')
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def locked(key, kind, initial):
|
||||
"""行锁内读、修改、保存同一文档;异常整体回滚。"""
|
||||
db.execute('INSERT INTO pms_rotation_document (doc_id,kind,payload_json,revision,updated_at) '
|
||||
'VALUES (:key,:kind,:body,0,:now) ON DUPLICATE KEY UPDATE doc_id=VALUES(doc_id)',
|
||||
{'key': key, 'kind': kind, 'body': encode(initial), 'now': dt.datetime.now()})
|
||||
with db.transaction():
|
||||
row = db.fetch_one('SELECT payload_json,revision FROM pms_rotation_document WHERE doc_id=:key FOR UPDATE', {'key': key})
|
||||
value = json.loads(row['payload_json'])
|
||||
yield value
|
||||
db.execute('UPDATE pms_rotation_document SET payload_json=:body,revision=:revision,updated_at=:now WHERE doc_id=:key',
|
||||
{'key': key, 'body': encode(value), 'revision': int(row['revision'])+1, 'now': dt.datetime.now()})
|
||||
|
||||
|
||||
def recent(kind, limit=100):
|
||||
rows = db.fetch_all('SELECT doc_id,payload_json,updated_at FROM pms_rotation_document '
|
||||
'WHERE kind=:kind ORDER BY updated_at DESC LIMIT :n', {'kind': kind, 'n': min(1000, int(limit))})
|
||||
return [{'id': r['doc_id'], 'value': json.loads(r['payload_json']), 'updated_at': str(r['updated_at'])} for r in rows]
|
||||
|
||||
|
||||
def stage_locked(key, value):
|
||||
"""在既有行锁事务内先发布阶段,供同事务的下发闸读取;外部仍不可见。"""
|
||||
if db._TRANSACTION.get() is None:
|
||||
raise RuntimeError('阶段写入必须处于持锁事务')
|
||||
db.execute('UPDATE pms_rotation_document SET payload_json=:body WHERE doc_id=:key',
|
||||
{'key': key, 'body': encode(value)})
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def account_guard():
|
||||
"""只获取账户锁,不在退出时覆盖内层更新的资金保留文档。"""
|
||||
db.execute('INSERT INTO pms_rotation_document (doc_id,kind,payload_json,revision,updated_at) '
|
||||
"VALUES ('account-execution','funds_reservation',:body,0,:now) ON DUPLICATE KEY UPDATE doc_id=VALUES(doc_id)",
|
||||
{'body': encode({'epoch_seq': 0, 'available': 0., 'orders': {}}), 'now': dt.datetime.now()})
|
||||
with db.transaction():
|
||||
db.fetch_one("SELECT doc_id FROM pms_rotation_document WHERE doc_id='account-execution' FOR UPDATE")
|
||||
yield
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
"""成交修正的只读取证。单次查询只访问一张表,满上限不得冒充完整历史。"""
|
||||
import json
|
||||
|
||||
from app.db import session as db
|
||||
from app.core import ws_codec
|
||||
|
||||
|
||||
def _rows(rows, limit=None, *, strict=True):
|
||||
if limit is not None and len(rows) >= limit:
|
||||
raise ValueError('成交修正证据超过核验上限,需人工核对')
|
||||
for row in rows:
|
||||
try:
|
||||
row['payload'] = json.loads(row.get('payload_json') or '{}')
|
||||
if not isinstance(row['payload'], dict):
|
||||
raise ValueError('成交回执不是对象')
|
||||
except (TypeError, ValueError):
|
||||
if strict:
|
||||
raise
|
||||
# 保留原文和seq,让worker只挂起坏行,不让它阻塞本批其它更正。
|
||||
row['payload'] = None
|
||||
return rows
|
||||
|
||||
|
||||
def pending(limit=100):
|
||||
# 兼容升级前旧WS将未知类型存成2的原消息,不扫描已消化的重复占位行。
|
||||
return _rows(db.fetch_all(
|
||||
"SELECT * FROM pms_qmt_inbox WHERE msg_type='trade_correction' "
|
||||
"AND (processed=0 OR (processed=2 AND process_note="
|
||||
"'trade_correction 由通道进程消化, 不入账')) ORDER BY seq ASC LIMIT :n",
|
||||
{'n': max(1, min(int(limit), 500))}), strict=False)
|
||||
|
||||
|
||||
def get_inbox(seq, lock=False):
|
||||
row = db.fetch_one('SELECT * FROM pms_qmt_inbox WHERE seq=:seq'+
|
||||
(' FOR UPDATE' if lock else ''), {'seq': int(seq)})
|
||||
return _rows([row], strict=False)[0] if row else None
|
||||
|
||||
|
||||
def get_trade(trade_no):
|
||||
key = ws_codec.dedup_key('trade', {'trade_no': trade_no})
|
||||
row = db.fetch_one('SELECT * FROM pms_qmt_inbox WHERE dedup_key=:key',
|
||||
{'key': key[:80] if key else None})
|
||||
if row:
|
||||
row = _rows([row])[0]
|
||||
if row['msg_type'] != 'trade' or row['payload'].get('trade_no') != trade_no:
|
||||
raise ValueError('成交编号与原回执去重键冲突')
|
||||
return row
|
||||
|
||||
|
||||
def _matches_correction(row, correction_id, kind):
|
||||
payload = row.get('payload')
|
||||
key = ws_codec.dedup_key(kind, {'correction_id': correction_id, 'amended': True})
|
||||
# 原文坏损但业务键仍指向本编号时也是冲突证据,不可默默筛掉。
|
||||
return (isinstance(payload, dict) and payload.get('correction_id') == correction_id
|
||||
or bool(key) and row.get('dedup_key') == key)
|
||||
|
||||
|
||||
def _correction_rows(kind, correction_id, iid):
|
||||
# 同编号不同正文不能因主去重行存在而被忽略;也读取空dedup的冲突占位。
|
||||
limit = 10001
|
||||
rows = _rows(db.fetch_all(
|
||||
'SELECT * FROM pms_qmt_inbox WHERE msg_type=:kind ORDER BY seq ASC LIMIT :n',
|
||||
{'kind': kind, 'n': limit}), limit, strict=False)
|
||||
return [r for r in rows if _matches_correction(r, correction_id, kind)]
|
||||
|
||||
|
||||
def amendments(correction_id, iid):
|
||||
# 正常order_update量大,先走child corr_id索引;新类型收包强制corr_id=iid。
|
||||
limit = 2001
|
||||
rows = _rows(db.fetch_all(
|
||||
"SELECT * FROM pms_qmt_inbox WHERE msg_type='order_update' AND corr_id=:iid "
|
||||
'ORDER BY seq ASC LIMIT :n', {'iid': iid, 'n': limit}), limit, strict=False)
|
||||
# 冲突占位可能篡改instruction_id,不能只在正常child范围内找冲突。
|
||||
conflicts = _rows(db.fetch_all(
|
||||
"SELECT * FROM pms_qmt_inbox WHERE msg_type='order_update' AND processed=3 "
|
||||
'ORDER BY seq ASC LIMIT :n', {'n': limit}), limit, strict=False)
|
||||
by_seq = {r['seq']: r for r in [*rows, *conflicts]
|
||||
if _matches_correction(r, correction_id, 'order_update')}
|
||||
return sorted(by_seq.values(), key=lambda r: int(r['seq']))
|
||||
|
||||
|
||||
def corrections(correction_id, iid):
|
||||
return _correction_rows('trade_correction', correction_id, iid)
|
||||
|
||||
|
||||
def pending_for_trade(trade_no, before_seq):
|
||||
limit = 10001
|
||||
rows = _rows(db.fetch_all(
|
||||
"SELECT * FROM pms_qmt_inbox WHERE msg_type='trade_correction' AND seq<:seq "
|
||||
"AND (processed IN (0,3) OR (processed=2 AND process_note="
|
||||
"'trade_correction 由通道进程消化, 不入账')) ORDER BY seq ASC LIMIT :n",
|
||||
{'seq': int(before_seq), 'n': limit}), limit, strict=False)
|
||||
return [r for r in rows if (r.get('payload') or {}).get('trade_no') == trade_no]
|
||||
|
||||
|
||||
def orders_for_code(code, limit=10001):
|
||||
rows = db.fetch_all('SELECT * FROM pms_qmt_order WHERE ts_code=:code '
|
||||
'ORDER BY id ASC LIMIT :n', {'code': code, 'n': int(limit)})
|
||||
if len(rows) >= limit:
|
||||
raise ValueError('该股委托历史超过核验上限')
|
||||
return rows
|
||||
|
||||
|
||||
def trades_for_orders(child_ids, limit=20001):
|
||||
# 历史信封的corr_id可能不是子委托;以持久原文instruction_id核对,不猜所属策略。
|
||||
ids = set(child_ids)
|
||||
rows = _rows(db.fetch_all("SELECT * FROM pms_qmt_inbox WHERE msg_type='trade' "
|
||||
'ORDER BY seq ASC LIMIT :n', {'n': int(limit)}), int(limit))
|
||||
return [r for r in rows if r['payload'].get('instruction_id') in ids
|
||||
and r.get('dedup_key') is not None]
|
||||
|
|
@ -34,6 +34,7 @@ from celery import Celery
|
|||
from celery.schedules import crontab
|
||||
|
||||
from config.settings import settings
|
||||
from app.services import param_store
|
||||
from app.core import tradedays as td
|
||||
|
||||
logging.basicConfig(level=logging.INFO,
|
||||
|
|
@ -147,6 +148,14 @@ def _brief(r):
|
|||
|
||||
|
||||
# ================================================================ 任务
|
||||
@celery_app.task(name="pms.monitor_watch_sync")
|
||||
@guard(trade_day=False, respect_exec_halt=False)
|
||||
def monitor_watch_sync():
|
||||
"""独立刷新人工关注研究范围,交易暂停和选股筛选不影响此只读研究步骤。"""
|
||||
from app.services import monitor_watch
|
||||
return monitor_watch.sync()
|
||||
|
||||
|
||||
@celery_app.task(name="pms.tech_pull")
|
||||
@guard(trade_day=True, respect_exec_halt=False) # 取数动作, 暂停执行照跑 (只落读数更新映射, 不产生指令)
|
||||
def tech_pull():
|
||||
|
|
@ -197,7 +206,11 @@ def plan_pull():
|
|||
@guard(trade_day=True)
|
||||
def premarket():
|
||||
from app.services import ledger_service
|
||||
return ledger_service.premarket()
|
||||
result = ledger_service.premarket()
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.services.rotation_service import reset_micro_available
|
||||
result['micro_available'] = reset_micro_available()
|
||||
return result
|
||||
|
||||
|
||||
@celery_app.task(name="pms.command_poll")
|
||||
|
|
@ -240,7 +253,13 @@ def intraday_exec():
|
|||
"""
|
||||
from app.services import executor, proposal_service, strategy_runner
|
||||
r = {"materialized": executor.materialize_plans()}
|
||||
if not param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False):
|
||||
from app.services import daily_buy_review
|
||||
r["daily_buy_review"] = daily_buy_review.process()
|
||||
r["proposals"] = proposal_service.scan_and_route()
|
||||
if param_store.get_bool('PMS_EXEC_REPRICE_ENABLED', False):
|
||||
from app.services import execution_basis
|
||||
r['execution_basis'] = execution_basis.monitor()
|
||||
r["strategies"] = strategy_runner.tick() # 个股交易方案: 触发即发短窗口指令, 由下面 run_tick 执行
|
||||
# 过期收口改为每分钟一次 (原来只在 15:10 日结跑) —— 让过了窗口/deadline 的单当即作废,
|
||||
# 不再多活一整天堵在「今日在办」、也不会隔天还替它试单 (2026-08-12 用户定的"实时"口径)。
|
||||
|
|
@ -250,6 +269,38 @@ def intraday_exec():
|
|||
return r
|
||||
|
||||
|
||||
@celery_app.task(name="pms.execution_cancel_confirm")
|
||||
@guard(trade_day=False, session=False, respect_exec_halt=False)
|
||||
@_exclusive("INFRA_LOCK_EXEC_CANCEL_CONFIRM", ttl_sec=55)
|
||||
def execution_cancel_confirm():
|
||||
"""暂停或收盘后继续核实既有撤单;此任务绝不报价或发新单。"""
|
||||
from app.services import execution_basis
|
||||
return execution_basis.monitor(cancel_only=True)
|
||||
|
||||
|
||||
@celery_app.task(name="pms.proposal_scan")
|
||||
@guard(trade_day=True, session=True)
|
||||
@_exclusive("INFRA_LOCK_PROPOSAL_SCAN", ttl_sec=230)
|
||||
def proposal_scan():
|
||||
if not param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False):
|
||||
return {'skipped': '异步研判未开启'}
|
||||
from app.services import proposal_service, daily_buy_review
|
||||
review = daily_buy_review.process()
|
||||
result = proposal_service.scan_and_route()
|
||||
result['daily_buy_review'] = review
|
||||
return result
|
||||
|
||||
|
||||
@celery_app.task(name="pms.execution_basis_refresh")
|
||||
@guard(trade_day=True, session=True)
|
||||
@_exclusive("INFRA_LOCK_EXEC_BASIS_REFRESH", ttl_sec=115)
|
||||
def execution_basis_refresh():
|
||||
if not param_store.get_bool('PMS_EXEC_REPRICE_ENABLED', False):
|
||||
return {'skipped': '独立执行依据刷新未开启'}
|
||||
from app.services import execution_basis
|
||||
return execution_basis.refresh()
|
||||
|
||||
|
||||
@celery_app.task(name="pms.signal_digest")
|
||||
@guard(trade_day=True, session=True)
|
||||
@_exclusive("INFRA_LOCK_SIGNAL_DIGEST", ttl_sec=115)
|
||||
|
|
@ -319,11 +370,21 @@ def daily_settle():
|
|||
pre = ledger_service.replay_fills()
|
||||
except Exception as e:
|
||||
logger.error("[daily_settle] 尾窗成交入账失败 (对账将按差异吸收): %s", e)
|
||||
pre = {"ok": False, "errors": ["尾窗成交入账失败:"+type(e).__name__]}
|
||||
out = ledger_service.daily_settle()
|
||||
out.setdefault("steps", {})["pre_replay"] = {
|
||||
"ok": pre.get("ok"), "actions": pre.get("actions"),
|
||||
"ws_actions": (pre.get("ws") or {}).get("actions"),
|
||||
"errors": (pre.get("errors") or [])[:3]}
|
||||
"errors": (pre.get("errors") or [])[:3],
|
||||
"corrections": {key: (pre.get("corrections") or {}).get(key, 0)
|
||||
for key in ("applied", "waiting", "held")},
|
||||
"alerts": (pre.get("alerts") or [])[:3]}
|
||||
# 业务挂起不混成程序错误;但不能把尾窗待核实的更正报成日终健康。
|
||||
if pre.get("ok") is False:
|
||||
out["ok"] = False
|
||||
out.setdefault("errors", []).extend(pre.get("errors") or [])
|
||||
if pre.get("alerts"):
|
||||
out.setdefault("alerts", []).extend(pre["alerts"])
|
||||
try:
|
||||
out["steps"]["windows"] = executor.sweep_windows() # 窗口耗尽收口 + 方案成交回写
|
||||
except Exception as e:
|
||||
|
|
@ -344,7 +405,11 @@ def nav_snapshot():
|
|||
在运营日报 (15:30) 之前。同日重跑覆盖, 以最后一次为准。历史不回填
|
||||
(2026-08-28 拍板: 启用日之前的净值继续查人工表格)。"""
|
||||
from app.services import publish_export
|
||||
return publish_export.record_nav_snapshot()
|
||||
result = publish_export.record_nav_snapshot()
|
||||
if settings.INFRA_ROTATION_DOCUMENT_SCHEMA or settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.services.rotation_service import settle_day
|
||||
result['rotation'] = settle_day()
|
||||
return result
|
||||
|
||||
|
||||
@celery_app.task(name="pms.daily_report")
|
||||
|
|
@ -356,7 +421,19 @@ def daily_report():
|
|||
|
||||
|
||||
# ================================================================ beat 调度表
|
||||
@celery_app.task(name='pms.rotation_tick')
|
||||
@guard(trade_day=True, respect_exec_halt=False)
|
||||
def rotation_tick():
|
||||
from app.services.rotation_service import tick
|
||||
return tick()
|
||||
|
||||
|
||||
celery_app.conf.beat_schedule = {
|
||||
'monitor_watch_sync': {'task': 'pms.monitor_watch_sync', 'schedule': crontab(minute='*'), 'options': {'expires': 50}},
|
||||
'execution_cancel_confirm': {'task': 'pms.execution_cancel_confirm', 'schedule': crontab(minute='*'), 'options': {'expires': 50}},
|
||||
'proposal_scan': {'task': 'pms.proposal_scan', 'schedule': crontab(minute='*'), 'options': {'expires': 50}},
|
||||
'execution_basis_refresh': {'task': 'pms.execution_basis_refresh', 'schedule': crontab(minute='*'), 'options': {'expires': 50}},
|
||||
'rotation_tick': {'task': 'pms.rotation_tick', 'schedule': crontab(minute='*'), 'options': {'expires': 50}},
|
||||
# 技术面取数 (2026-09-11): 决策系统夜扫实测 00:38 完, 06:30 留足余量; 在计划拉取 (08:40) 之前。
|
||||
"tech_pull": {"task": "pms.tech_pull", "schedule": crontab(hour=6, minute=30)},
|
||||
"plan_pull": {"task": "pms.plan_pull", "schedule": crontab(hour=8, minute=40)},
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
@ -173,6 +173,10 @@ def issue(cmd_type: str, params: dict, *, note=None, issued_by="user",
|
|||
res = plan_command(pms_repo.get_command(command_id))
|
||||
res.setdefault("command_id", command_id)
|
||||
res["conflicts"] = conflicts
|
||||
from config.settings import settings as infrastructure
|
||||
if infrastructure.INFRA_STRATEGY_BOOK_SCHEMA and res.get('ok'):
|
||||
from app.services.rotation_service import on_user_command
|
||||
on_user_command(cmd_type, command_id, issued_by)
|
||||
return res
|
||||
|
||||
|
||||
|
|
@ -305,6 +309,7 @@ def plan_command(cmd: dict) -> dict:
|
|||
cancel_r = _cancel_marked_instructions(items)
|
||||
cancelled = cancel_r["cancelled"]
|
||||
cancel_failed = cancel_r["failed"]
|
||||
cancel_pending = cancel_r.get('pending') or []
|
||||
|
||||
# 命令覆盖冲突 (设计铁律「命令至上」): 全额清仓类命令一下达, 立刻停掉这些票的**买入侧**
|
||||
# —— 撤活跃策略 (网格/做T/跟踪) 与待你确认的买入提议, 别再边卖边买。在途买单已由上面
|
||||
|
|
@ -341,6 +346,8 @@ def plan_command(cmd: dict) -> dict:
|
|||
if cancel_failed:
|
||||
notes.insert(0, f"⚠ {len(cancel_failed)} 条在途指令**没撤掉, 仍在下游挂着**: "
|
||||
+ "; ".join(f"{x['instruction_id']}({x['why']})" for x in cancel_failed[:5]))
|
||||
if cancel_pending:
|
||||
notes.insert(0, f'{len(cancel_pending)} 条委托已请求撤单,等待QMT终态及成交入账确认')
|
||||
if stop_r.get("strategies") or stop_r.get("proposals") or stop_r.get("instructions"):
|
||||
notes.insert(0, f"清仓覆盖冲突: 已撤策略 {len(stop_r['strategies'])} 条、"
|
||||
f"驳回买入提议 {len(stop_r['proposals'])} 条、"
|
||||
|
|
@ -361,6 +368,7 @@ def plan_command(cmd: dict) -> dict:
|
|||
# 有一堆候选、全被同一道闸拒了。不聚合出来就得去翻 rejects 原始清单。
|
||||
"reject_summary": pl.summarize_rejects(rejects),
|
||||
"cancelled_instructions": cancelled,
|
||||
'cancel_pending': cancel_pending,
|
||||
"cancel_failed": cancel_failed,
|
||||
"stopped_buyside": stop_r or {}}
|
||||
|
||||
|
|
@ -525,11 +533,15 @@ def cancel(command_id: str) -> dict:
|
|||
if cmd["status"] not in cs.ACTIVE_TASK_STATES:
|
||||
return {"ok": False, "message": f"命令处于 {cmd['status']}, 不可撤销"}
|
||||
|
||||
progress = dict(cmd.get('progress') or {})
|
||||
progress['cancel_requested'] = True
|
||||
if not pms_repo.update_command(command_id, progress=progress):
|
||||
return {'ok': False, 'message': '命令停止执行标记写入失败'}
|
||||
n_plan = pms_repo.cancel_plans_of_command(command_id)
|
||||
# 匹配在途指令用**全部**方案 (不带状态过滤): 上一次撤销若只撤了一半, 方案已进
|
||||
# CANCELLED, 按状态过滤会把剩下的在途指令漏成孤儿。
|
||||
plan_ids = {p["plan_id"] for p in pms_repo.list_plans(command_id=command_id)}
|
||||
cancelled, failed = [], []
|
||||
cancelled, failed, pending = [], [], []
|
||||
for ins in pms_repo.list_instructions(statuses=list(LIVE_INSTR), limit=500):
|
||||
if ins.get("origin_type") == "plan" and ins.get("origin_id") in plan_ids:
|
||||
try:
|
||||
|
|
@ -537,7 +549,9 @@ def cancel(command_id: str) -> dict:
|
|||
ins["instruction_id"], reason=f"撤销命令 {command_id}") or {}
|
||||
except Exception as e:
|
||||
r = {"ok": False, "error": f"{type(e).__name__}: {e}"}
|
||||
if r.get("ok"):
|
||||
if r.get('ok') and r.get('pending'):
|
||||
pending.append(ins['instruction_id'])
|
||||
elif r.get("ok"):
|
||||
cancelled.append(ins["instruction_id"])
|
||||
else:
|
||||
failed.append({"instruction_id": ins["instruction_id"],
|
||||
|
|
@ -551,6 +565,9 @@ def cancel(command_id: str) -> dict:
|
|||
f"仍在下游挂着**: "
|
||||
+ "; ".join(f"{x['instruction_id']}({x['why']})" for x in failed[:5])
|
||||
+ " —— 命令保持在途继续跟踪, 处理后可再次撤销")}
|
||||
if pending:
|
||||
return {'ok': True, 'pending': pending, 'cancelled': cancelled,
|
||||
'message': f'命令 {command_id} 已停止新下发,{len(pending)} 条委托等待撤单确认'}
|
||||
pms_repo.update_command(command_id, status=cs.ST_CANCELLED, done_at=datetime.now())
|
||||
return {"ok": True, "cancelled": cancelled,
|
||||
"message": f"命令 {command_id} 已撤销 (作废方案 {n_plan} 条, "
|
||||
|
|
@ -603,6 +620,10 @@ def refresh_progress(command_id=None) -> dict:
|
|||
out = []
|
||||
today = datetime.now().date()
|
||||
for c in [x for x in cmds if x]:
|
||||
if (c.get('progress') or {}).get('cancel_requested'):
|
||||
result = cancel(c['command_id'])
|
||||
out.append({'command_id': c['command_id'], 'cancellation': result})
|
||||
continue
|
||||
plans = pms_repo.list_plans(command_id=c["command_id"])
|
||||
done_amt = 0.0
|
||||
for p in plans:
|
||||
|
|
@ -707,14 +728,16 @@ def _cancel_marked_instructions(items: list) -> dict:
|
|||
命令点名的条数, 不是真撤掉的条数。
|
||||
"""
|
||||
from app.services import executor
|
||||
ok, failed = [], []
|
||||
ok, failed, pending = [], [], []
|
||||
for it in items or []:
|
||||
iid = it.get("cancel_instruction_id")
|
||||
if not iid:
|
||||
continue
|
||||
try:
|
||||
r = executor.cancel_instruction(iid, reason="命令撤销在途指令") or {}
|
||||
if r.get("ok"):
|
||||
if r.get('ok') and r.get('pending'):
|
||||
pending.append(iid)
|
||||
elif r.get("ok"):
|
||||
ok.append(iid)
|
||||
else:
|
||||
failed.append({"instruction_id": iid,
|
||||
|
|
@ -724,7 +747,7 @@ def _cancel_marked_instructions(items: list) -> dict:
|
|||
failed.append({"instruction_id": iid, "why": f"{type(e).__name__}: {e}"})
|
||||
if failed:
|
||||
logger.error("[命令] %s 条在途指令没撤掉, **它们仍在下游挂着**: %s", len(failed), failed)
|
||||
return {"cancelled": ok, "failed": failed}
|
||||
return {"cancelled": ok, "failed": failed, 'pending': pending}
|
||||
|
||||
|
||||
def _codes_with_live_plans() -> list:
|
||||
|
|
@ -793,7 +816,7 @@ def _candidates(view: dict) -> list:
|
|||
|
||||
if src in (plan_feed.SRC_PLAN_API, plan_feed.SRC_BOTH):
|
||||
try:
|
||||
sel = plan_feed.candidates(held=held, black=black)
|
||||
sel = plan_feed.candidates(held=held, black=black, allow_user=False)
|
||||
for r in sel["items"]:
|
||||
_push(r["ts_code"], r["score"], "plan_api", theme=r.get("theme"),
|
||||
plan_provenance={k: r.get(k) for k in ('decision', 'consumption_id',
|
||||
|
|
@ -913,7 +936,9 @@ def _stop_buyside_for_exit(codes: list, command_id: str) -> dict:
|
|||
iid = i.get("instruction_id")
|
||||
try:
|
||||
r = executor.cancel_instruction(iid, reason="清仓命令下达: 撤该票在途买入 (命令覆盖冲突)") or {}
|
||||
if r.get("ok"):
|
||||
if r.get('ok') and r.get('pending'):
|
||||
out.setdefault('pending_instructions', []).append(iid)
|
||||
elif r.get("ok"):
|
||||
out["instructions"].append(iid)
|
||||
else:
|
||||
# 下游没撤成: 指令仍在途, 单独列出来别吞 (与 _cancel_marked_instructions 同纪律)
|
||||
|
|
@ -1042,7 +1067,10 @@ def cleanup_exited_positions(limit: int = 500) -> dict:
|
|||
for ins in buys:
|
||||
try:
|
||||
r = executor.cancel_instruction(ins["instruction_id"], reason="清仓完成清场: 撤在途建仓") or {}
|
||||
if r.get("ok"):
|
||||
if r.get('ok') and r.get('pending'):
|
||||
err_codes.add(ins.get('ts_code'))
|
||||
out.setdefault('pending_instructions', []).append(ins['instruction_id'])
|
||||
elif r.get("ok"):
|
||||
per_code[ins["ts_code"]]["instructions"].append(ins["instruction_id"])
|
||||
else:
|
||||
err_codes.add(ins.get("ts_code"))
|
||||
|
|
|
|||
|
|
@ -70,6 +70,14 @@ def report_url_for(code: str, *, state_map=None, plan=None) -> tuple[str | None,
|
|||
u = _url_of(r.get("company_review"))
|
||||
if u:
|
||||
return u, SRC_CAND
|
||||
try:
|
||||
from app.services import monitor_watch
|
||||
row = monitor_watch.research_row(code)
|
||||
u = _url_of((row or {}).get('company_review'))
|
||||
if u:
|
||||
return u, 'watch'
|
||||
except Exception as e:
|
||||
logger.warning("[评析报告] 人工关注来源暂不可用 %s: %s", code, type(e).__name__)
|
||||
return None, SRC_NONE
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,325 @@
|
|||
"""跨日买入复核:停止旧单、等待真实回报、重走当日决策,再开放当日额度。"""
|
||||
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):
|
||||
from app.services import execution_orders
|
||||
correction = execution_orders.correction_blocker(ins) if ins else ''
|
||||
if correction:
|
||||
return correction
|
||||
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('出口子单重复,等待核对')
|
||||
from app.services import execution_orders
|
||||
filled = 0
|
||||
for row in rows:
|
||||
filled += execution_orders.effective_filled(row)
|
||||
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, execution_orders
|
||||
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:
|
||||
if execution_orders.correction_blocker(row):
|
||||
out['waiting'].append(iid)
|
||||
continue
|
||||
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
|
||||
if any(x.get('by') == 'judge_pending' for x in result.get('skipped', [])):
|
||||
out['waiting'].append(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'))
|
||||
from app.services import execution_orders
|
||||
if decision == 'ACCEPTED' and ins:
|
||||
blocked = execution_orders.correction_blocker(ins)
|
||||
if blocked:
|
||||
return {'ok': False, 'error': blocked}
|
||||
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': '指令已变化,本次未恢复买入'})}
|
||||
|
|
@ -48,6 +48,7 @@ from __future__ import annotations
|
|||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from config.settings import settings
|
||||
|
||||
from app.core import ws_codec as wsc
|
||||
from app.repo import qmt_repo
|
||||
|
|
@ -140,18 +141,70 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr
|
|||
"""递一手给下游。返回 {ok, ref, mode, note, error}; ok=False 时 executor 不改指令状态。"""
|
||||
m = mode()
|
||||
try:
|
||||
from app.repo import pms_repo
|
||||
from app.services import execution_orders, execution_basis
|
||||
pid = _parent_of(instruction_id, parent_id)
|
||||
parent = pms_repo.get_instruction(pid)
|
||||
correction = execution_orders.correction_blocker(parent, ts_code=ts_code, side=str(side).lower())
|
||||
if correction:
|
||||
return {'ok': False, 'ref': None, 'mode': m, 'note': '', 'error': correction}
|
||||
if parent and (parent.get('progress') or {}).get('cancel_requested'):
|
||||
return {'ok': False, 'ref': None, 'mode': m, 'note': '', 'error': '父指令撤销处理中,禁止继续下发'}
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and str(side).lower() == 'buy':
|
||||
from app.core import strategy_book
|
||||
from app.services.rotation_service import strategy_buy_blocker
|
||||
if strategy_book.CURRENT.get() == strategy_book.ORIGINAL:
|
||||
from app.repo import pms_repo
|
||||
parent = pms_repo.get_instruction(_parent_of(instruction_id, parent_id))
|
||||
blocked = strategy_buy_blocker(strategy_book.ORIGINAL, parent)
|
||||
if blocked:
|
||||
return {'ok': False, 'ref': None, 'mode': m, 'note': '', 'error': blocked}
|
||||
if str(side).lower() == 'buy':
|
||||
from app.services.execution_conflicts import buy_blocker
|
||||
from app.repo import pms_repo
|
||||
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:
|
||||
return {'ok': False, 'ref': None, 'mode': m, 'note': '', 'error': blocked}
|
||||
if m == MODE_WS:
|
||||
with execution_orders.account_guard():
|
||||
parent = pms_repo.get_instruction(pid)
|
||||
blocked = execution_orders.correction_blocker(parent, ts_code=ts_code, side=str(side).lower())
|
||||
if blocked:
|
||||
raise ValueError(blocked)
|
||||
if execution_orders.enabled() and not qmt_repo.get_order(instruction_id):
|
||||
from app.core.execution_policy import supported_code
|
||||
if not supported_code(ts_code):
|
||||
raise ValueError('执行范围仅限沪深合资格证券')
|
||||
parent = pms_repo.get_instruction(pid)
|
||||
if not parent or parent.get('status') not in ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED'):
|
||||
raise ValueError('父指令未获准或已结束')
|
||||
progress = parent.get('progress') or {}
|
||||
if progress.get('cancel_requested'):
|
||||
raise ValueError('父指令正在撤销')
|
||||
state = execution_orders.replacement_state(pid)
|
||||
if not state['ready'] or qty > state['remaining']:
|
||||
raise ValueError('旧子单未确认结束、成交未入账或数量超过剩余目标')
|
||||
retry_wait = execution_orders.retry_reason(pid)
|
||||
if retry_wait:
|
||||
raise ValueError(retry_wait)
|
||||
if execution_basis.uses_basis(parent):
|
||||
reason = execution_basis.cache_reason(progress)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
reason = execution_orders.code_settlement_blocker(ts_code)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
boundary = progress.get('user_limit_price', parent.get('limit_price'))
|
||||
if boundary is not None and ((side == 'buy' and float(limit_price) > float(boundary)) or
|
||||
(side == 'sell' and float(limit_price) < float(boundary))):
|
||||
raise ValueError('报价突破用户指定价格边界')
|
||||
return _ws(instruction_id=instruction_id, ts_code=ts_code, side=side, qty=qty,
|
||||
limit_price=limit_price, valid_until=valid_until,
|
||||
intent=intent, parent_id=parent_id, note=note)
|
||||
|
|
@ -193,6 +246,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 常驻进程完成。
|
||||
|
|
@ -222,6 +290,10 @@ def _ws(*, instruction_id, ts_code, side, qty, limit_price, valid_until, intent=
|
|||
return {"ok": False, "ref": None, "mode": MODE_WS, "note": "",
|
||||
"error": f"指令不合协议要求 ({e.code}): {e.message}"}
|
||||
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.services.rotation_execution import enqueue_with_reservation
|
||||
enqueue_with_reservation(payload, _parent_of(instruction_id, parent_id))
|
||||
else:
|
||||
qmt_repo.enqueue_order(
|
||||
instruction_id=payload["instruction_id"],
|
||||
parent_id=_parent_of(instruction_id, parent_id),
|
||||
|
|
@ -254,11 +326,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}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,11 @@
|
|||
卖出区间, 盘中只回答「现价在不在区间内 + 限价挂哪里」, 不做任何新的盘中判断
|
||||
(2026-08-03 用户定的原则: 提前计算为主、盘中监控为辅, 可以接受买不上)。
|
||||
|
||||
分工与降级 (三条, 都是纪律不是实现细节):
|
||||
以下分工与降级描述兼容模式。开启 PMS_EXEC_REPRICE_ENABLED 后,独立任务刷新
|
||||
版本化执行依据,本模块只读取缓存与行情报价;依据未知或过期时等待,不退本地研判。
|
||||
PMS_EXEC_QMT_PRICE_MONITOR 模式则维持指定区间边缘限价,接口故障时等待补齐。
|
||||
|
||||
兼容模式的分工与降级:
|
||||
1. **本地检查先行**: 配额/兜底/停牌/一字板/不追高(当日涨幅) 由 core.exec_timing 的
|
||||
hard_gate 先判, 命中就不咨询 —— 这些检查始终留在 PMS 本地。尤其 14:45 兜底:
|
||||
到点必须完成, 决策系统说什么都不算。
|
||||
|
|
@ -23,6 +27,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
|
||||
from app.core import exec_timing as et
|
||||
from app.core import tradedays as td
|
||||
|
|
@ -52,6 +57,9 @@ def available() -> bool:
|
|||
|
||||
def status() -> dict:
|
||||
"""页面/排查用的一句话状态。"""
|
||||
if param_store.get_bool("PMS_EXEC_QMT_PRICE_MONITOR", False):
|
||||
return {"impl": impl(), "available": available(), "price_monitor": "qmt",
|
||||
"note": "PMS确定限价和数量,QMT等待成交;执行区间缺失时等待补齐"}
|
||||
if impl() != IMPL_A:
|
||||
return {"impl": IMPL_B, "available": False,
|
||||
"note": "内置保守择时 (PMS_EXEC_IMPL=B)。切实现A: 页面改 PMS_EXEC_IMPL=A"}
|
||||
|
|
@ -65,9 +73,11 @@ def status() -> dict:
|
|||
|
||||
|
||||
def _post(url: str, payload: dict, timeout: int) -> dict:
|
||||
"""HTTP 一跳, 单测在这里打桩。"""
|
||||
"""HTTP 一跳;数据库数值保持 JSON 数值,不转成展示用字符串。"""
|
||||
import requests
|
||||
r = requests.post(url, json=payload, timeout=timeout)
|
||||
# 独立执行依据刷新直接读取仓储,成本与参考位可能仍为 Decimal。
|
||||
# 复用研判接口的明确类型转换,未知类型和非有限数仍由 JSON 编码拒绝。
|
||||
r = requests.post(url, json=judge.jsonable(payload), timeout=timeout)
|
||||
r.raise_for_status()
|
||||
return r.json() or {}
|
||||
|
||||
|
|
@ -107,7 +117,7 @@ def _strategy_immediate(*, side, now, day, quota, fired_today,
|
|||
def decide(*, side: str, action: str, ts_code: str, now, day: dict, params: dict,
|
||||
is_last_day: bool, is_command: bool = True, urgent: bool = False,
|
||||
fired_today: int = 0, quota: int = 0,
|
||||
pos: dict = None, tdays_left=None, prog: dict = None) -> dict:
|
||||
pos: dict = None, tdays_left=None, prog: dict = None, instruction_limit=None) -> dict:
|
||||
"""择时判定统一入口 (executor.run_tick 的唯一调用点)。
|
||||
|
||||
返回结构与 exec_timing.decide 相同, 另带 source 字段标明这条决定是谁做的:
|
||||
|
|
@ -118,6 +128,16 @@ def decide(*, side: str, action: str, ts_code: str, now, day: dict, params: dict
|
|||
prog 由调用方传入指令的 progress dict, 咨询结果/失败冷却会写进 prog["exec_advice"],
|
||||
随调用方既有的落表动作持久化; 传 None 则本轮结论不缓存 (dry_run 语义)。
|
||||
"""
|
||||
if param_store.get_bool('PMS_EXEC_REPRICE_ENABLED', False):
|
||||
return _execution_quote(side=side, action=action, ts_code=ts_code, now=now,
|
||||
quota=quota, fired_today=fired_today, prog=prog or {},
|
||||
instruction_limit=instruction_limit, urgent=urgent)
|
||||
if param_store.get_bool("PMS_EXEC_QMT_PRICE_MONITOR", False):
|
||||
return _qmt_limit(side=side, action=action, ts_code=ts_code, now=now, day=day,
|
||||
params=params, is_last_day=is_last_day, urgent=urgent,
|
||||
fired_today=fired_today, quota=quota, pos=pos or {},
|
||||
tdays_left=tdays_left, prog=prog, instruction_limit=instruction_limit)
|
||||
|
||||
# 网格/跟踪止盈: 策略层已按档位触发, 这里不做择时博弈, 到价即时成交、收盘不强制。
|
||||
# 只识别策略来源且类型为 GRID/TRAIL 的指令; 做T(T0)与其余来源一律走原有逻辑, 不受影响。
|
||||
if (prog or {}).get("origin") == "strategy" and str((prog or {}).get("stype")) in ("GRID", "TRAIL"):
|
||||
|
|
@ -164,6 +184,95 @@ def decide(*, side: str, action: str, ts_code: str, now, day: dict, params: dict
|
|||
return d
|
||||
|
||||
|
||||
def _execution_quote(*, side, action, ts_code, now, quota, fired_today, prog,
|
||||
instruction_limit, urgent):
|
||||
"""新执行环只读取版本化缓存和行情,绝不在这里同步咨询。"""
|
||||
from app.services import execution_basis, execution_orders, market
|
||||
left = max(0, int(quota)-int(fired_today))
|
||||
def wait(why):
|
||||
return {'action': et.ACT_WAIT, 'qty_hint': left, 'limit_price': None,
|
||||
'reason': why, 'forced': False, 'source': '执行报价', 'qmt_price_monitor': True}
|
||||
if prog.get('cancel_requested'):
|
||||
return wait('父指令撤单处理中')
|
||||
if not left or not et.in_session(et.hm_to_min(now)):
|
||||
return wait('本轮没有可发数量或不在执行时段')
|
||||
parent = {'progress': {**prog, 'urgent': urgent}, 'side': side}
|
||||
if execution_basis.uses_basis(parent):
|
||||
why = execution_basis.cache_reason(prog, now)
|
||||
if why:
|
||||
return wait(why)
|
||||
quote = market.execution_quote(ts_code, now=now)
|
||||
result = execution_orders.quote_order(side, quote, now,
|
||||
user_limit=prog.get('user_limit_price', instruction_limit),
|
||||
anchor_price=prog.get('execution_anchor_price'))
|
||||
prog['execution_quote'] = result
|
||||
if result.get('action') == et.ACT_FIRE:
|
||||
prog.setdefault('execution_anchor_price', result['anchor_price'])
|
||||
result.update(qty_hint=left, forced=False, source='执行报价', qmt_price_monitor=True,
|
||||
basis_version=((prog.get('execution_basis_cache') or {}).get('basis') or {}).get('version'))
|
||||
return result
|
||||
|
||||
|
||||
def _qmt_limit(*, side, action, ts_code, now, day, params, is_last_day, urgent,
|
||||
fired_today, quota, pos, tdays_left, prog, instruction_limit):
|
||||
"""计划已确定后只定限价,不等现价进入区间;数据故障不能转成追价买入。"""
|
||||
left = max(0, int(quota) - int(fired_today))
|
||||
|
||||
def result(action, reason, limit=None, **extra):
|
||||
return {"action": action, "qty_hint": left, "limit_price": limit,
|
||||
"reason": reason, "forced": False, "source": "QMT限价",
|
||||
"qmt_price_monitor": True, **extra}
|
||||
|
||||
price = _f(day.get("price"))
|
||||
if side not in ("buy", "sell"):
|
||||
return result(et.ACT_SKIP, "委托方向无效")
|
||||
if not price or day.get("halted"):
|
||||
return result(et.ACT_WAIT, "无有效行情或已停牌,等待核实")
|
||||
if left <= 0:
|
||||
return result(et.ACT_WAIT, et.quota_wait_reason(urgent, is_last_day))
|
||||
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")
|
||||
if (urgent and side == "sell") or strategy:
|
||||
# 已触发的网格、跟踪止盈和紧急退出沿用自己的定价,不再附加价格到位检查。
|
||||
limit = _f(instruction_limit)
|
||||
if not limit:
|
||||
ratio = (params.get("urgent_sell_discount", 0.995) if urgent and side == "sell"
|
||||
else 1.002 if side == "buy" else 0.998)
|
||||
limit = round(price * float(ratio), 2)
|
||||
return result(et.ACT_FIRE, "按策略限价提交QMT等待成交", round(limit, 2))
|
||||
|
||||
if not available():
|
||||
return result(et.ACT_WAIT, "未配置有效执行区间来源,暂不提交限价")
|
||||
advice, note = _advice(ts_code=ts_code, side=side, action=action, now=now, day=day,
|
||||
pos=pos, left=left, is_last_day=is_last_day,
|
||||
tdays_left=tdays_left, prog=prog)
|
||||
if advice is None:
|
||||
return result(et.ACT_WAIT, "执行价格暂不可用:" + note)
|
||||
if advice.get("ref_drift"):
|
||||
return result(et.ACT_WAIT, advice["ref_drift"], ref_drift=advice["ref_drift"])
|
||||
if side == "buy" and (advice.get("today_exit") or
|
||||
str(advice.get("y_signal") or "").upper() in ("SELL", "AVOID", "DROPPED")):
|
||||
return result(et.ACT_WAIT, "已有离场或回避结论,暂停买入", y_signal=advice.get("y_signal"))
|
||||
band = advice.get("buy_band" if side == "buy" else "sell_band")
|
||||
if not isinstance(band, (list, tuple)) or len(band) != 2:
|
||||
return result(et.ACT_WAIT, "执行区间缺失,暂不提交限价")
|
||||
lo, hi = (_f(x) for x in band)
|
||||
if not lo or not hi or lo > hi:
|
||||
return result(et.ACT_WAIT, "执行区间无效,暂不提交限价")
|
||||
limit = round(hi if side == "buy" else lo, 2)
|
||||
if limit <= 0:
|
||||
return result(et.ACT_WAIT, "执行限价无效,暂不提交")
|
||||
# WAIT只表示当前价格未进区间。限价买单允许更低成交,卖单允许更高成交。
|
||||
# 不因距离现价较远而改价,也不在尾盘把锁定买价改成追价。
|
||||
return result(et.ACT_FIRE, f"限价{limit:.2f}提交QMT等待成交", limit,
|
||||
y_signal=advice.get("y_signal"))
|
||||
|
||||
|
||||
def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_left, prog):
|
||||
"""取一份有效研判: 缓存命中 → 直接用; 冷却中 → (None, 原因); 否则咨询一次。
|
||||
返回 (advice|None, 不可用原因)。advice 带 _source 标明 A / A缓存。"""
|
||||
|
|
@ -174,6 +283,8 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
|
||||
if int(cached.get("ymd") or 0) == today:
|
||||
if (cached.get("verdict") in (FIRE, WAIT)
|
||||
and (not param_store.get_bool("PMS_EXEC_QMT_PRICE_MONITOR", False)
|
||||
or cached.get("price_facts_version") == 1)
|
||||
and now_min <= int(cached.get("valid_until_min") or -1)):
|
||||
c = dict(cached)
|
||||
c["_source"] = "A缓存"
|
||||
|
|
@ -195,6 +306,8 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
}
|
||||
to = max(1, param_store.get_int("PMS_EXEC_TIMEOUT_SEC", 8))
|
||||
url = base_url() + (param_store.get("PMS_EXEC_PATH", "/api/intraday/pms_exec") or "")
|
||||
fallback_note = ("等待有效执行价格" if param_store.get_bool("PMS_EXEC_QMT_PRICE_MONITOR", False)
|
||||
else "本轮退实现B")
|
||||
|
||||
def _cool(err: str):
|
||||
cool = max(1, param_store.get_int("PMS_EXEC_FAIL_COOLDOWN_MIN", 5))
|
||||
|
|
@ -207,7 +320,7 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
data = _post(url, payload, to)
|
||||
except Exception as e:
|
||||
err = f"{type(e).__name__}: {e}"
|
||||
logger.error("[择时A] 咨询失败, 本轮退实现B (%s %s): %s", ts_code, side, err)
|
||||
logger.error("[择时A] 咨询失败, %s (%s %s): %s", fallback_note, ts_code, side, err)
|
||||
_cool(err)
|
||||
return None, err
|
||||
|
||||
|
|
@ -215,8 +328,8 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
if verdict not in (FIRE, WAIT):
|
||||
# 对端明说给不出结论 (UNAVAILABLE), 或答复不认识 —— 都按拿不到处理, 退实现B
|
||||
reason = str(data.get("reason") or f"verdict={verdict or '空'}")[:200]
|
||||
logger.warning("[择时A] 决策系统给不出结论 (%s %s): %s —— 本轮退实现B",
|
||||
ts_code, side, reason)
|
||||
logger.warning("[择时A] 决策系统给不出结论 (%s %s): %s —— %s",
|
||||
ts_code, side, reason, fallback_note)
|
||||
_cool(f"UNAVAILABLE: {reason}")
|
||||
return None, f"UNAVAILABLE: {reason}"
|
||||
|
||||
|
|
@ -235,6 +348,8 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
# 支撑/压力/买入区间也一并存下来 —— 新建仓的漂移比对要用 (见 _check_ref_drift)
|
||||
"support": obs.get("support"), "pressure": obs.get("pressure"),
|
||||
"buy_band": obs.get("buy_band"),
|
||||
"sell_band": obs.get("sell_band"), "today_exit": obs.get("today_exit"),
|
||||
"price_facts_version": 1,
|
||||
"valid_until_min": et.add_trade_minutes(now_min, valid_min),
|
||||
"consulted_at": et._fmt(now_min)}
|
||||
drift = _check_ref_drift(action=action, prog=prog, adv=adv, today=today)
|
||||
|
|
@ -253,7 +368,7 @@ def _advice(*, ts_code, side, action, now, day, pos, left, is_last_day, tdays_le
|
|||
def _f(v):
|
||||
try:
|
||||
x = float(v)
|
||||
return x if x > 0 else 0.0
|
||||
return x if math.isfinite(x) and x > 0 else 0.0
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,132 @@
|
|||
"""独立刷新执行依据;在途监控不做HTTP,也不因配额已占用而跳过。"""
|
||||
import time
|
||||
from datetime import timedelta
|
||||
from app.core import execution_policy as policy, strategy_book as books
|
||||
from app.repo import pms_repo, execution_repo
|
||||
from app.services import param_store, execution_orders
|
||||
|
||||
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
||||
|
||||
|
||||
def uses_basis(parent):
|
||||
progress = parent.get('progress') or {}
|
||||
# STOP 表达看空或离场,不能反向禁止已经获准的减仓和退出。
|
||||
return (parent.get('side') == 'buy'
|
||||
and progress.get('execution_profile') != 'rotation'
|
||||
and not (progress.get('origin') == 'strategy' and progress.get('stype') in ('GRID', 'TRAIL')))
|
||||
|
||||
|
||||
def cache_reason(progress, now=None):
|
||||
cache = (progress or {}).get('execution_basis_cache') or {}
|
||||
return policy.basis_reason(cache.get('basis'), now,
|
||||
max_source_days=max(0, param_store.get_int('PMS_EXEC_BASIS_SOURCE_MAX_DAYS', 7)))
|
||||
|
||||
|
||||
def refresh(now=None):
|
||||
"""短请求有整轮预算。失败留痕,但不会把旧依据时间重新延长。"""
|
||||
from app.services import exec_advisor, market
|
||||
current = policy.local_now(now)
|
||||
out = {'enabled': execution_orders.enabled(), 'refreshed': [], 'errors': [], 'skipped': []}
|
||||
if not out['enabled']:
|
||||
return out
|
||||
deadline = time.monotonic()+max(1, param_store.get_int('PMS_EXEC_BASIS_REFRESH_BUDGET_SEC', 20))
|
||||
with books.scope('all'):
|
||||
parents = pms_repo.list_instructions(statuses=list(LIVE), limit=10000)
|
||||
parents.sort(key=lambda p: ((p.get('progress') or {}).get('execution_basis_cache') or {}).get('fetched_at', ''))
|
||||
for parent in parents:
|
||||
if not policy.supported_code(parent.get('ts_code')) or not uses_basis(parent) or (parent.get('progress') or {}).get('cancel_requested'):
|
||||
continue
|
||||
cache = dict((parent.get('progress') or {}).get('execution_basis_cache') or {})
|
||||
due = policy.timestamp(cache.get('refresh_after'))
|
||||
if due and current < due:
|
||||
continue
|
||||
left = deadline-time.monotonic()
|
||||
if left < 1:
|
||||
out['skipped'].append('本轮执行依据刷新预算用尽')
|
||||
break
|
||||
fresh = dict(cache)
|
||||
try:
|
||||
if not exec_advisor.available():
|
||||
raise ValueError('执行依据来源未配置')
|
||||
with books.scope(parent.get('book_id') or books.ORIGINAL):
|
||||
position = pms_repo.get_position(parent['ts_code']) or {}
|
||||
day = market.day_snapshot(parent['ts_code'])
|
||||
payload = {'direction': 'PMS_EXEC', 'ts_code': parent['ts_code'],
|
||||
'side': parent['side'], 'action': parent.get('action'),
|
||||
'qty_left': max(0, int(parent['qty'])-int(parent.get('exec_qty') or 0)),
|
||||
'now': current.strftime('%H:%M'), 'day': day,
|
||||
'refs': {k: position.get(k+'_ref') for k in ('support', 'pressure', 'stop')},
|
||||
'position': {k: position.get(k) for k in ('total_qty', 'avail_qty', 'avg_cost')},
|
||||
'is_last_day': False, 'tdays_left': None}
|
||||
response = exec_advisor._post(exec_advisor.base_url()+param_store.get('PMS_EXEC_PATH', '/api/intraday/pms_exec'),
|
||||
payload, max(1, min(param_store.get_int('PMS_EXEC_TIMEOUT_SEC', 8), int(left))))
|
||||
if not isinstance(response, dict):
|
||||
raise ValueError('执行依据响应格式无效')
|
||||
basis = response.get('execution_basis')
|
||||
# 明确未知或停止立即覆盖旧事实。只有传输失败可保留尚在有效期内的旧依据。
|
||||
fresh = {'basis': basis if isinstance(basis, dict) else {},
|
||||
'observed': response.get('observed') or {}, 'error': ''}
|
||||
reason = policy.basis_reason(fresh['basis'], current,
|
||||
max_source_days=max(0, param_store.get_int('PMS_EXEC_BASIS_SOURCE_MAX_DAYS', 7)))
|
||||
if reason:
|
||||
fresh['error'] = reason
|
||||
except Exception as exc:
|
||||
fresh['error'] = str(exc)[:300]
|
||||
out['errors'].append({'instruction_id': parent['instruction_id'], 'error': fresh['error']})
|
||||
fresh['fetched_at'] = current.isoformat()
|
||||
fresh['refresh_after'] = (current+timedelta(seconds=max(1,
|
||||
param_store.get_int('PMS_EXEC_BASIS_REFRESH_SEC', 60)))).isoformat()
|
||||
with books.scope(parent.get('book_id') or books.ORIGINAL):
|
||||
execution_repo.save_basis(parent['instruction_id'], fresh)
|
||||
out['refreshed'].append(parent['instruction_id'])
|
||||
return out
|
||||
|
||||
|
||||
def monitor(now=None, cancel_only=False):
|
||||
from app.services import executor, market
|
||||
current = policy.local_now(now)
|
||||
out = {'cancelled': [], 'replacing': [], 'errors': []}
|
||||
with books.scope('all'):
|
||||
parents = pms_repo.list_instructions(statuses=list(LIVE)+['CANCELLED', 'EXPIRED'], limit=10000)
|
||||
for parent in parents:
|
||||
if not policy.supported_code(parent.get('ts_code')):
|
||||
continue
|
||||
try:
|
||||
with books.scope(parent.get('book_id') or books.ORIGINAL):
|
||||
progress = parent.get('progress') or {}
|
||||
if progress.get('cancel_requested') or parent.get('status') in ('CANCELLED', 'EXPIRED'):
|
||||
result = executor.cancel_instruction(parent['instruction_id'],
|
||||
reason=(progress.get('cancel_requested') or {}).get('reason', '继续确认撤单'), arbiter='system')
|
||||
if not result.get('ok'):
|
||||
raise ValueError(result.get('error') or result.get('message'))
|
||||
out['cancelled'].append(result)
|
||||
continue
|
||||
if cancel_only:
|
||||
continue
|
||||
if not execution_orders.enabled() or progress.get('execution_profile') == 'rotation':
|
||||
continue
|
||||
state = execution_orders.replacement_state(parent['instruction_id'])
|
||||
if not state['active']:
|
||||
continue
|
||||
reason = cache_reason(progress, current) if uses_basis(parent) else ''
|
||||
if reason:
|
||||
result = execution_orders.request_replace(parent['instruction_id'], reason, current)
|
||||
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': reason, 'pending': result['pending']})
|
||||
continue
|
||||
try:
|
||||
quote = market.execution_quote(parent['ts_code'], now=current)
|
||||
desired = execution_orders.quote_order(parent['side'], quote, current,
|
||||
user_limit=progress.get('user_limit_price', parent.get('limit_price')),
|
||||
anchor_price=progress.get('execution_anchor_price'))
|
||||
except Exception as exc:
|
||||
desired = {'action': 'WAIT', 'reason': '行情读取失败,等待恢复:'+str(exc)[:200]}
|
||||
if desired.get('action') != 'FIRE':
|
||||
result = execution_orders.request_replace(parent['instruction_id'], desired['reason'], current)
|
||||
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': desired['reason'], 'pending': result['pending']})
|
||||
continue
|
||||
if execution_orders.should_replace(parent, desired, current):
|
||||
result = execution_orders.request_replace(parent['instruction_id'], desired['reason'], current)
|
||||
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': desired['reason'], 'pending': result['pending']})
|
||||
except Exception as exc:
|
||||
out['errors'].append({'instruction_id': parent['instruction_id'], 'error': str(exc)[:300]})
|
||||
return out
|
||||
|
|
@ -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')
|
||||
|
||||
|
||||
|
|
@ -17,16 +17,66 @@ def buy_blocker(ts_code):
|
|||
|
||||
def queued_buy_blocker(row):
|
||||
"""发出前再次检查。异常由通道保留队列等待,不按无冲突继续。"""
|
||||
from config.settings import settings
|
||||
from app.services import execution_orders
|
||||
from app.core import strategy_book as books
|
||||
with books.scope('all'):
|
||||
correction_parent = pms_repo.get_instruction(row.get('parent_id'))
|
||||
correction = execution_orders.correction_blocker(correction_parent,
|
||||
ts_code=row.get('ts_code'), side=row.get('side'))
|
||||
if correction:
|
||||
return correction
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.core import strategy_book as books
|
||||
from app.services import param_store, rotation_service
|
||||
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
||||
return '用户暂停全部执行'
|
||||
with books.scope('all'):
|
||||
parent = pms_repo.get_instruction(row.get('parent_id'))
|
||||
if not parent or parent.get('book_id') not in (books.ORIGINAL, books.MICRO):
|
||||
raise RuntimeError('委托的策略来源无法核实')
|
||||
reason = _queued_basis_check(parent)
|
||||
if reason:
|
||||
return reason
|
||||
if (parent.get('progress') or {}).get('execution_profile') == 'rotation' and param_store.get('PMS_ROTATION_CONTROL', 'run') == 'pause_all':
|
||||
return '用户暂停轮换全部执行'
|
||||
if row.get('side') != 'buy':
|
||||
return None
|
||||
if param_store.get_bool('PMS_GLOBAL_BUY_HALT', False):
|
||||
return '用户暂停买入'
|
||||
reason = rotation_service.strategy_buy_blocker(parent['book_id'], parent)
|
||||
if reason:
|
||||
return reason
|
||||
with books.scope(parent['book_id']):
|
||||
return _queued_parent_check(row, parent)
|
||||
parent = pms_repo.get_instruction(row.get('parent_id'))
|
||||
reason = _queued_basis_check(parent) if parent else None
|
||||
if reason or row.get('side') != 'buy':
|
||||
return reason
|
||||
return _queued_parent_check(row, parent)
|
||||
|
||||
|
||||
def _queued_basis_check(parent):
|
||||
if (parent.get('progress') or {}).get('cancel_requested'):
|
||||
return '父指令已请求撤销,未发出的委托作废'
|
||||
from app.services import execution_orders, execution_basis
|
||||
if execution_orders.enabled() and execution_basis.uses_basis(parent):
|
||||
return execution_basis.cache_reason(parent.get('progress') or {}) or None
|
||||
return None
|
||||
|
||||
|
||||
def _queued_parent_check(row, parent):
|
||||
if not parent:
|
||||
raise RuntimeError('买入来源指令无法核实,暂不发送')
|
||||
if pms_repo.instruction_buy_stop(row.get('parent_id')) or (parent.get('progress') or {}).get('stopped_by_exit'):
|
||||
return '清仓已终止原买入安排'
|
||||
if parent.get('status') not in LIVE:
|
||||
return '来源买入指令已结束,未发出的委托作废'
|
||||
return buy_blocker(row['ts_code'])
|
||||
reason = _queued_basis_check(parent)
|
||||
if reason:
|
||||
return reason
|
||||
from app.services import daily_buy_review
|
||||
return daily_buy_review.blocker(parent) or buy_blocker(row['ts_code'])
|
||||
|
||||
|
||||
def enforce_exit(ins):
|
||||
|
|
@ -80,29 +130,53 @@ def instruction_progress(rows):
|
|||
continue
|
||||
if not ws:
|
||||
row['execution_label'] = '影子执行待核对'
|
||||
row['execution_stage'] = 'shadow'
|
||||
continue
|
||||
try:
|
||||
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'
|
||||
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):
|
||||
label = '委托待成交'
|
||||
stage = 'submitted'
|
||||
elif active:
|
||||
label = '委托待发送'
|
||||
stage = 'sending' if any(o.get('status') == 'SENDING' for o in active) else 'queued'
|
||||
else:
|
||||
reason = ((row.get('progress') or {}).get('last_decision') or {}).get('reason') or ''
|
||||
decision = (row.get('progress') or {}).get('last_decision') or {}
|
||||
reason = decision.get('reason') or ''
|
||||
if row.get('status') == 'CANCELLED':
|
||||
label = '已撤销'
|
||||
stage = 'ended'
|
||||
elif sum(int(o.get('cum_qty') or 0) for o in orders) >= int(row.get('qty') or 1):
|
||||
label = '成交待入账'
|
||||
stage = 'reconciling'
|
||||
elif '可卖量不足' in reason:
|
||||
label = '等待可卖'
|
||||
elif '当日配额' in reason:
|
||||
label = '等待下一批'
|
||||
elif '暂停买入' in reason:
|
||||
label = '买入已暂停'
|
||||
elif decision.get('action') == 'REJECT':
|
||||
label = '执行检查未通过'
|
||||
elif decision.get('action') in ('WAIT', 'SKIP', 'STOP'):
|
||||
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:
|
||||
row['execution_label'] = '委托状态待核实'
|
||||
row['execution_stage'] = 'unknown'
|
||||
return rows
|
||||
|
|
|
|||
|
|
@ -0,0 +1,244 @@
|
|||
"""共用报价及撤换。撤单请求不释放数量,实际终态及成交入账后才可重报。"""
|
||||
from contextlib import nullcontext
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from app.core import execution_policy as policy, strategy_book as books
|
||||
from app.repo import pms_repo, qmt_repo, execution_repo
|
||||
from app.services import param_store
|
||||
from config.settings import settings
|
||||
|
||||
|
||||
def enabled():
|
||||
return param_store.get_bool('PMS_EXEC_REPRICE_ENABLED', False)
|
||||
|
||||
|
||||
def account_guard():
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.repo import rotation_repo
|
||||
return rotation_repo.account_guard()
|
||||
return nullcontext()
|
||||
|
||||
|
||||
def _receipt_time(value):
|
||||
try:
|
||||
parsed = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
return policy.local_now(parsed) # 本端数据库 DATETIME 按已核实的北京时间解释。
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def order_correction(order, *, require_current=False):
|
||||
"""只接受修正事务已保存且与出口累计数一致的审计投影。"""
|
||||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
return None
|
||||
from app.repo import rotation_repo
|
||||
iid = order['instruction_id']
|
||||
value, _ = rotation_repo.get('order-correction:'+hashlib.sha256(iid.encode()).hexdigest())
|
||||
if value is None:
|
||||
return None
|
||||
if (not isinstance(value, dict) or value.get('instruction_id') != iid or
|
||||
not 0 <= int(value.get('cum_qty', -1)) <= int(order['qty']) or
|
||||
(require_current and int(value['cum_qty']) != int(order.get('cum_qty') or 0)) or
|
||||
int(value.get('correction_seq') or 0) <= 0 or _receipt_time(value.get('received_at')) is None):
|
||||
raise ValueError('委托成交修正审计与当前累计量不一致,等待核对')
|
||||
return value
|
||||
|
||||
|
||||
def effective_filled(order):
|
||||
qty, done = int(order['qty']), int(order.get('cum_qty') or 0)
|
||||
if qty <= 0 or not 0 <= done <= qty:
|
||||
raise ValueError('子单累计成交数量异常')
|
||||
if order.get('status') == 'FILLED' and done != qty and not order_correction(order, require_current=True):
|
||||
raise ValueError('全成子单累计成交不完整,且没有已核实的成交修正')
|
||||
return done
|
||||
|
||||
|
||||
def settlement_cutoff(order):
|
||||
"""释放资金必须使用修正消息之后的快照,不能沿用早于修正的原终态时间。"""
|
||||
final = _receipt_time(order.get('final_at'))
|
||||
if final is None:
|
||||
return None
|
||||
audit = order_correction(order)
|
||||
if audit:
|
||||
return max(final, _receipt_time(audit['received_at']))
|
||||
return final
|
||||
|
||||
|
||||
def correction_blocker(parent=None, *, ts_code=None, side=None):
|
||||
parent = parent or {}
|
||||
if (parent.get('progress') or {}).get('trade_correction_hold'):
|
||||
return '父指令成交数量已修正,停止自动续单和改价;后续须另行明确安排'
|
||||
progress = parent.get('progress') or {}
|
||||
if parent.get('origin_type') == 'strategy' and parent.get('origin_id'):
|
||||
with books.scope('all'):
|
||||
strategy = pms_repo.get_strategy(parent['origin_id'])
|
||||
if progress.get('stype') == 'GRID' or (strategy or {}).get('type') == 'GRID':
|
||||
if not strategy or strategy.get('status') != 'ACTIVE' or strategy.get('archived_at'):
|
||||
return '来源网格策略已停止或不可核实,旧指令不再下发'
|
||||
state = strategy.get('state') or {}
|
||||
if state.get('correction_hold'):
|
||||
return '来源网格正在核实成交修正,停止旧指令下发'
|
||||
epoch = (state.get('trade_correction') or {}).get('correction_id')
|
||||
if epoch != progress.get('strategy_correction_id'):
|
||||
return '来源网格的成交已修正,旧版本指令不能继续下发'
|
||||
side = side or parent.get('side')
|
||||
code = ts_code or parent.get('ts_code')
|
||||
if not execution_repo.pending_corrections():
|
||||
return ''
|
||||
if side == 'buy':
|
||||
return '账户存在待核实成交修正,暂停新增买入和释放资金占用'
|
||||
else:
|
||||
if not code:
|
||||
return '成交修正涉及证券无法核实,暂停新增委托'
|
||||
# 修正原文证券字段缺失或冲突时,仍按本端出口身份拦住该股的新父指令。
|
||||
children = qmt_repo.list_orders(ts_code=code, limit=10001)
|
||||
if len(children) >= 10001:
|
||||
return '该股出口历史超过核验上限,等待成交修正核对'
|
||||
if execution_repo.pending_corrections(ts_code=code, child_ids=[r['instruction_id'] for r in children]):
|
||||
return '该证券存在待核实成交修正,暂停新增委托和改价'
|
||||
return ''
|
||||
|
||||
|
||||
def prepare_send(instruction_id):
|
||||
"""与修正收件串行检查,成功标记之后才允许WS实际发送。"""
|
||||
with account_guard(), books.scope('all'):
|
||||
order = qmt_repo.get_order(instruction_id)
|
||||
if not order:
|
||||
return {'marked': False, 'blocked': '委托不存在'}
|
||||
parent = pms_repo.get_instruction(order['parent_id'])
|
||||
blocked = correction_blocker(parent, ts_code=order['ts_code'], side=order['side'])
|
||||
if blocked:
|
||||
return {'marked': False, 'blocked': blocked}
|
||||
return {'marked': qmt_repo.mark_send_attempt(instruction_id), 'blocked': ''}
|
||||
|
||||
|
||||
def quote_order(side, quote, now=None, user_limit=None, anchor_price=None):
|
||||
return policy.price_order(side=side, quote=quote, now=now, user_limit=user_limit,
|
||||
anchor_price=anchor_price, params={
|
||||
'allow_minute': param_store.get_bool('PMS_EXEC_ALLOW_MINUTE_QUOTE', True),
|
||||
'quote_max_age_sec': param_store.get_int('PMS_EXEC_QUOTE_MAX_AGE_SEC', 15),
|
||||
'minute_max_age_sec': param_store.get_int('PMS_EXEC_MINUTE_MAX_AGE_SEC', 90),
|
||||
'offset_ticks': param_store.get_int('PMS_EXEC_PRICE_OFFSET_TICKS', 1),
|
||||
'max_slippage_pct': param_store.get_float('PMS_EXEC_MAX_SLIPPAGE_PCT', .01),
|
||||
'minute_slippage_pct': param_store.get_float('PMS_EXEC_MINUTE_SLIPPAGE_PCT', .002)})
|
||||
|
||||
|
||||
def replacement_state(parent_id):
|
||||
with books.scope('all'):
|
||||
parent = pms_repo.get_instruction(parent_id)
|
||||
if not parent:
|
||||
raise ValueError('父指令不存在')
|
||||
orders = qmt_repo.orders_for_parent(parent_id)
|
||||
filled, live, seen = 0, [], set()
|
||||
for order in orders:
|
||||
iid = order['instruction_id']
|
||||
if iid in seen:
|
||||
raise ValueError('重复子单编号')
|
||||
seen.add(iid)
|
||||
done = effective_filled(order)
|
||||
filled += done
|
||||
if order.get('status') not in qmt_repo.FINAL:
|
||||
live.append(order)
|
||||
booked, target = int(parent.get('exec_qty') or 0), int(parent['qty'])
|
||||
if max(booked, filled) > target:
|
||||
raise ValueError('已成交数量超出父指令,等待核对')
|
||||
pending_trades = execution_repo.pending_trades(list(seen))
|
||||
remaining = max(0, target-max(booked, filled))
|
||||
missing = [c.get('ref') for c in (parent.get('progress') or {}).get('children', [])
|
||||
if c.get('ref') and c.get('ref') not in seen]
|
||||
ready = not live and booked >= filled and not pending_trades and not missing
|
||||
return {'ready': ready, 'pending': not ready, 'confirmed_filled': max(booked, filled),
|
||||
'remaining': remaining, 'active': live, 'orders': orders,
|
||||
'pending_trades': pending_trades, 'booked': booked, 'missing_orders': missing}
|
||||
|
||||
|
||||
def code_settlement_blocker(ts_code):
|
||||
"""跨父指令与策略检查迟到成交,不因旧父指令本地终态而再次建仓。"""
|
||||
with books.scope('all'):
|
||||
parents = pms_repo.list_instructions(ts_code=ts_code, limit=10001, include_archived=True)
|
||||
if len(parents) >= 10001:
|
||||
return '该股历史指令超过核验上限,等待核对'
|
||||
for parent in parents:
|
||||
state = replacement_state(parent['instruction_id'])
|
||||
if state['pending_trades'] or state['booked'] < state['confirmed_filled'] or state['missing_orders']:
|
||||
return '该股已有成交或旧委托尚未核实入账'
|
||||
return ''
|
||||
|
||||
|
||||
def next_child_id(parent_id):
|
||||
numbers = [0]
|
||||
prefix = parent_id+'_D'
|
||||
for row in qmt_repo.orders_for_parent(parent_id):
|
||||
iid = row['instruction_id']
|
||||
if not iid.startswith(prefix) or not iid[len(prefix):].isdigit():
|
||||
raise ValueError('父指令存在无法核实序号的子单')
|
||||
numbers.append(int(iid[len(prefix):]))
|
||||
return prefix+str(max(numbers)+1).zfill(2)
|
||||
|
||||
|
||||
def retry_reason(parent_id, now=None):
|
||||
"""拒单和发送失败退避;普通到期及正常撤换不消耗此预算。"""
|
||||
history = qmt_repo.orders_for_parent(parent_id)
|
||||
if not history or history[-1].get('status') not in ('REJECTED', 'SEND_FAILED'):
|
||||
return ''
|
||||
last = history[-1]
|
||||
code, count = last.get('reject_code'), 0
|
||||
for row in reversed(history):
|
||||
if row.get('status') not in ('REJECTED', 'SEND_FAILED') or row.get('reject_code') != code:
|
||||
break
|
||||
count += 1
|
||||
at = last.get('final_at') or last.get('sent_at') or last.get('created_at')
|
||||
if not hasattr(at, 'tzinfo'):
|
||||
at = policy.timestamp(at)
|
||||
if at is None:
|
||||
return '拒单时间不可核实,等待核对'
|
||||
base = max(1, param_store.get_int('PMS_EXEC_REJECT_COOLDOWN_SEC', 60))
|
||||
cap = max(base, param_store.get_int('PMS_EXEC_REJECT_MAX_COOLDOWN_SEC', 900))
|
||||
wait = min(cap, base*2**min(max(0, count-1), 8))
|
||||
left = wait-(policy.local_now(now)-policy.local_now(at)).total_seconds()
|
||||
return f'委托连续拒绝或发送失败,退避等待 {max(0, int(left))} 秒:{code or "原因见回执"}' if left > 0 else ''
|
||||
|
||||
|
||||
def request_replace(parent_id, reason, now=None):
|
||||
from app.services import dispatcher
|
||||
with account_guard(), books.scope('all'):
|
||||
parent = pms_repo.get_instruction(parent_id)
|
||||
if not parent:
|
||||
raise ValueError('父指令不存在')
|
||||
progress = dict(parent.get('progress') or {})
|
||||
if not progress.get('replacement_requested'):
|
||||
progress['replacement_requested'] = {'at': policy.local_now(now).isoformat(), 'reason': reason}
|
||||
if not pms_repo.update_instruction(parent_id, progress=progress):
|
||||
raise RuntimeError('撤换请求没有写入父指令')
|
||||
result = dispatcher.cancel(instruction_id=parent_id, dispatch_ref=parent.get('dispatch_ref'))
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('撤换请求未成功落表:'+str(result.get('error')))
|
||||
state = replacement_state(parent_id)
|
||||
return {'requested': True, **state}
|
||||
|
||||
|
||||
def should_replace(parent, desired, now=None):
|
||||
"""仅比较同轮报价;失败重试次数和间隔由实际子单历史决定。"""
|
||||
if desired.get('action') != 'FIRE':
|
||||
return False
|
||||
if correction_blocker(parent):
|
||||
return False
|
||||
orders = qmt_repo.orders_for_parent(parent['instruction_id'])
|
||||
live = [o for o in orders if o.get('status') not in qmt_repo.FINAL]
|
||||
if not live or any(o.get('cancel_state') in ('REQUESTED', 'SENT') for o in live):
|
||||
return False
|
||||
cap = max(0, param_store.get_int('PMS_EXEC_REPRICE_MAX_ATTEMPTS', 0))
|
||||
if cap and len(orders) >= cap:
|
||||
return False
|
||||
gap = max(1, param_store.get_int('PMS_EXEC_REPRICE_TICKS', 2))*.01
|
||||
min_age = max(0, param_store.get_int('PMS_EXEC_REPRICE_MIN_SEC', 60))
|
||||
current = policy.local_now(now)
|
||||
for order in live:
|
||||
at = order.get('sent_at') or order.get('created_at')
|
||||
if at is None:
|
||||
return False
|
||||
if not hasattr(at, 'tzinfo'):
|
||||
at = policy.timestamp(at)
|
||||
if at is None or (current-policy.local_now(at)).total_seconds() < min_age:
|
||||
return False
|
||||
return any(abs(float(o['limit_price'])-desired['limit_price'])+1e-8 >= gap for o in live)
|
||||
|
|
@ -16,6 +16,7 @@ progress_json.children[]; exec_qty 由回放认领回填 (账本以下游成交
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
import hashlib
|
||||
|
|
@ -35,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"
|
||||
|
|
@ -103,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:
|
||||
|
|
@ -154,7 +158,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
"errors": [], "mode": dispatcher.mode(), "dry_run": dry_run}
|
||||
|
||||
instrs = [i for i in pms_repo.list_instructions(statuses=list(LIVE), limit=200)
|
||||
if int(i.get("qty") or 0) > int(i.get("exec_qty") or 0)]
|
||||
if int(i.get("qty") or 0) > int(i.get("exec_qty") or 0)
|
||||
and (i.get('progress') or {}).get('execution_profile') != 'rotation']
|
||||
if not instrs:
|
||||
return out
|
||||
|
||||
|
|
@ -188,6 +193,30 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
is_last = tdays_left <= 1
|
||||
|
||||
try:
|
||||
if prog.get('cancel_requested'):
|
||||
if not dry_run:
|
||||
cancelled = cancel_instruction(ins['instruction_id'],
|
||||
reason=prog['cancel_requested'].get('reason', '继续确认撤单'), arbiter='system')
|
||||
if not cancelled.get('ok'):
|
||||
out['errors'].append(cancelled.get('error') or cancelled.get('message'))
|
||||
continue
|
||||
from app.services import execution_orders
|
||||
correction_wait = execution_orders.correction_blocker(ins)
|
||||
if correction_wait:
|
||||
out['waited'].append({'instruction_id': ins['instruction_id'], 'code': code,
|
||||
'reason': correction_wait})
|
||||
continue
|
||||
if execution_orders.enabled() and dispatcher.mode() == dispatcher.MODE_WS:
|
||||
replacement = execution_orders.replacement_state(ins['instruction_id'])
|
||||
if not replacement['ready']:
|
||||
out['waited'].append({'instruction_id': ins['instruction_id'], 'code': code,
|
||||
'reason': '等待旧子单终态及实际成交入账'})
|
||||
continue
|
||||
retry_wait = execution_orders.retry_reason(ins['instruction_id'], now)
|
||||
if retry_wait:
|
||||
out['waited'].append({'instruction_id': ins['instruction_id'], 'code': code,
|
||||
'reason': retry_wait})
|
||||
continue
|
||||
from app.services import execution_conflicts
|
||||
if ins.get('action') == 'EXIT' and side == 'sell' and not dry_run:
|
||||
cleanup = execution_conflicts.enforce_exit(ins)
|
||||
|
|
@ -207,7 +236,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:
|
||||
|
|
@ -217,6 +247,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}
|
||||
|
|
@ -250,7 +282,7 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
# 择时判定统一走 exec_advisor: PMS_EXEC_IMPL=B (默认) 时它就是 et.decide 原样;
|
||||
# =A 时先过硬闸 (配额/兜底等 PMS 自留地), 再委托决策系统, 不可用退实现B。
|
||||
# 咨询结论会写进 prog["exec_advice"], 随下面既有的 update_instruction 落表;
|
||||
# dry_run 传 None —— 只算不落库, 试算不该占用/刷新研判缓存。
|
||||
# dry_run 传进度副本,保留参考位锁定,但不落库或刷新真实缓存。
|
||||
# is_command 必须一路传到 hard_gate: 窗口末日的强制完成只对命令驱动生效,
|
||||
# 自主买入到期作废 (与 window_verdict 的口径对齐, 见 exec_timing 里那段说明)。
|
||||
d = exec_advisor.decide(side=side, action=ins.get("action"), ts_code=code,
|
||||
|
|
@ -260,7 +292,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
urgent=bool(prog.get("urgent")),
|
||||
fired_today=fired_today,
|
||||
quota=quota, pos=pos, tdays_left=tdays_left,
|
||||
prog=(None if dry_run else prog))
|
||||
prog=(deepcopy(prog) if dry_run else prog),
|
||||
instruction_limit=ins.get("limit_price"))
|
||||
|
||||
if d["action"] != et.ACT_FIRE:
|
||||
prog["last_decision"] = {"at": now.strftime("%H:%M"), **d}
|
||||
|
|
@ -301,7 +334,7 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
"action": et.ACT_WAIT, "reason": "可卖量不足, 顺延"})
|
||||
continue
|
||||
|
||||
ma5 = market.get_ma5(code) if side == "buy" else None
|
||||
ma5 = market.get_ma5(code) if side == "buy" and not d.get("qmt_price_monitor") else None
|
||||
# 新建仓 (从没持仓过的票) 的组合上下文必须显式带 is_new_name 与行业名:
|
||||
# caps_ctx 在 view 里找不到该票时带不出行业, 行业集中度终检会静默跳过
|
||||
# (与 proposal_service._route_one 已修过的同一个洞, 2026-08-28 补齐执行终检侧)
|
||||
|
|
@ -317,7 +350,9 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
caps = portfolio.caps_ctx(view, ts_code=code, is_new_name=is_new, sector=sec) \
|
||||
if is_new else portfolio.caps_ctx(view, ts_code=code)
|
||||
gate = rule_gate.check(
|
||||
side=side, action=ins.get("action"), qty=qty, price=day_ctx.get("price"),
|
||||
side=side, action=ins.get("action"), qty=qty,
|
||||
price=(max(float(day_ctx.get("price") or 0), float(d["limit_price"]))
|
||||
if side == "buy" and d.get("qmt_price_monitor") else day_ctx.get("price")),
|
||||
ctx={"ts_code": code, "position": pos, "day": {**day_ctx, "ma5": ma5},
|
||||
"params": {**exec_prm, "sector_source_ready": view["sector_ready"]},
|
||||
"caps": caps,
|
||||
|
|
@ -328,6 +363,7 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
# 只告警不拦截, 告警随 hard_numbers 落进评审账本。
|
||||
"stop_price": stock_params.get(code, {}).get("stop_price"),
|
||||
"is_command": bool(prog.get("is_command")),
|
||||
"qmt_price_monitor": bool(d.get("qmt_price_monitor")),
|
||||
# 决策系统昨夜对该股的定性, 由择时应答带回 (退实现B 时为 None)
|
||||
"y_signal": d.get("y_signal")}})
|
||||
|
||||
|
|
@ -355,18 +391,29 @@ 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 模式忽略这三项, 传着不碍事 —— 两种模式共用同一个调用点。
|
||||
res = dispatcher.dispatch(
|
||||
instruction_id=_child_id(ins["instruction_id"], len(children) + 1),
|
||||
instruction_id=(execution_orders.next_child_id(ins['instruction_id'])
|
||||
if execution_orders.enabled() and dispatcher.mode() == dispatcher.MODE_WS
|
||||
else _child_id(ins["instruction_id"], len(children) + 1)),
|
||||
parent_id=ins["instruction_id"], intent=ins.get("action"),
|
||||
ts_code=code, side=side, qty=qty, limit_price=d["limit_price"],
|
||||
note=d.get("reason"),
|
||||
|
|
@ -381,6 +428,7 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
"valid_until": et._fmt(dl_min),
|
||||
"forced": d.get("forced", False), "reason": d["reason"]})
|
||||
prog["children"] = children
|
||||
prog['replacement_requested'] = None
|
||||
prog.setdefault("dispatched_at", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
prog["last_decision"] = {"at": now.strftime("%H:%M"), "action": et.ACT_FIRE,
|
||||
"reason": d["reason"], "source": d.get("source")}
|
||||
|
|
@ -425,12 +473,22 @@ def sweep_windows(*, now=None) -> dict:
|
|||
for ins in pms_repo.list_instructions(statuses=list(LIVE), limit=300):
|
||||
try:
|
||||
prog = dict(ins.get("progress") or {})
|
||||
if prog.get('cancel_requested'):
|
||||
cancellation = cancel_instruction(ins['instruction_id'],
|
||||
reason=prog['cancel_requested'].get('reason', '继续确认撤单'), arbiter='system')
|
||||
if not cancellation.get('ok'):
|
||||
out['errors'].append(cancellation.get('error') or cancellation.get('message'))
|
||||
elif cancellation.get('confirmed') and cancellation.get('status') == ST_EXPIRED:
|
||||
out['expired'].append(ins['instruction_id'])
|
||||
continue
|
||||
exec_qty = int(ins.get("exec_qty") or 0)
|
||||
remaining = int(ins["qty"]) - exec_qty
|
||||
if ins.get("origin_type") == "plan" and ins.get("origin_id"):
|
||||
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
|
||||
|
|
@ -447,9 +505,14 @@ def sweep_windows(*, now=None) -> dict:
|
|||
continue
|
||||
prog["window_verdict"] = v
|
||||
if v["verdict"] == "EXPIRED":
|
||||
pms_repo.update_instruction(ins["instruction_id"], status=ST_EXPIRED,
|
||||
progress=prog)
|
||||
out["expired"].append(ins["instruction_id"])
|
||||
if not pms_repo.update_instruction(ins["instruction_id"], progress=prog):
|
||||
raise RuntimeError('窗口到期状态未写入')
|
||||
cancellation = cancel_instruction(ins['instruction_id'], reason=v['note'],
|
||||
arbiter='system', final_status=ST_EXPIRED)
|
||||
if not cancellation.get('ok'):
|
||||
out['errors'].append(cancellation.get('error') or cancellation.get('message'))
|
||||
elif cancellation.get('confirmed') and cancellation.get('status') == ST_EXPIRED:
|
||||
out['expired'].append(ins['instruction_id'])
|
||||
else:
|
||||
pms_repo.update_instruction(ins["instruction_id"], progress=prog)
|
||||
out["partial"].append({"instruction_id": ins["instruction_id"],
|
||||
|
|
@ -465,39 +528,73 @@ def sweep_windows(*, now=None) -> dict:
|
|||
return out
|
||||
|
||||
|
||||
def cancel_instruction(instruction_id: str, reason: str = "页面人工撤销", *, arbiter="user") -> dict:
|
||||
def cancel_instruction(instruction_id: str, reason: str = "页面人工撤销", *, arbiter="user",
|
||||
final_status=ST_CANCELLED) -> dict:
|
||||
"""先停止新下发,再请求撤子单;只有实际终态和入账确认后结束父指令。"""
|
||||
from app.services import execution_orders
|
||||
try:
|
||||
if final_status not in (ST_CANCELLED, ST_EXPIRED):
|
||||
raise ValueError('撤单后的父指令终态无效')
|
||||
with execution_orders.account_guard():
|
||||
ins = pms_repo.get_instruction(instruction_id)
|
||||
if not ins:
|
||||
return {"ok": False, "error": "指令不存在"}
|
||||
if ins["status"] not in LIVE:
|
||||
if ins['status'] in (ST_CANCELLED, ST_CONFIRMED, ST_EXPIRED):
|
||||
if dispatcher.mode() != dispatcher.MODE_WS or execution_orders.replacement_state(instruction_id)['ready']:
|
||||
return {"ok": True, "confirmed": True, "pending": False, "cancel_pending": False,
|
||||
"status": ins['status'],
|
||||
"message": f"指令 {instruction_id} 已结束"}
|
||||
elif ins['status'] not in LIVE:
|
||||
return {"ok": False, "error": f"指令处于 {ins['status']}, 不可撤销"}
|
||||
r = dispatcher.cancel(instruction_id=instruction_id,
|
||||
dispatch_ref=ins.get("dispatch_ref")) or {}
|
||||
# **下游没撤成就不能在本端标 CANCELLED。** 原来 r 拿到手却从不检查, 一律回「已撤销」
|
||||
# 并把父指令置终态 —— 而终态之后没有任何东西再跟踪它, 下游那张委托继续挂着、继续成交,
|
||||
# 成交回来还会因为找不到在途父指令而变成孤儿。撤不掉就保持在途, 让它继续被择时/收口/
|
||||
# 对账看见, 由人再处理。
|
||||
if not r.get("ok"):
|
||||
logger.error("[撤单] 下游未受理 %s: %s —— 指令保持在途, 下游委托可能仍挂着",
|
||||
instruction_id, r.get("error") or r)
|
||||
return {"ok": False, "downstream": r, "instruction_id": instruction_id,
|
||||
"message": f"指令 {instruction_id} **未能撤销**: "
|
||||
f"{r.get('error') or '下游未受理'} —— 指令仍在途, "
|
||||
f"请在 QMT 侧确认该委托是否还挂着"}
|
||||
# 进终态前把成交进度回写方案 (与 ledger._settle_instruction 同一条纪律, 2026-08-28)
|
||||
if ins.get("origin_type") == "plan" and ins.get("origin_id"):
|
||||
try:
|
||||
pms_repo.update_plan(ins["origin_id"], filled_qty=int(ins.get("exec_qty") or 0))
|
||||
except Exception as e:
|
||||
logger.warning("撤销指令进度回写失败 %s: %s", instruction_id, e)
|
||||
pms_repo.update_instruction(instruction_id, status=ST_CANCELLED)
|
||||
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} 已撤销"}
|
||||
progress = dict(ins.get('progress') or {})
|
||||
if not progress.get('cancel_requested'):
|
||||
progress['cancel_requested'] = {'reason': reason, 'arbiter': arbiter,
|
||||
'at': datetime.now().isoformat(),
|
||||
'final_status': ST_EXPIRED if ins['status'] == ST_EXPIRED else final_status}
|
||||
if not pms_repo.update_instruction(instruction_id, progress=progress):
|
||||
raise RuntimeError('父指令停止下发标记未写入')
|
||||
result = dispatcher.cancel(instruction_id=instruction_id,
|
||||
dispatch_ref=ins.get('dispatch_ref')) or {}
|
||||
if not result.get('ok'):
|
||||
return {'ok': False, 'downstream': result, 'instruction_id': instruction_id,
|
||||
'message': '撤单请求未成功,父指令停止新增下发并等待重试'}
|
||||
if dispatcher.mode() == dispatcher.MODE_WS:
|
||||
state = execution_orders.replacement_state(instruction_id)
|
||||
if not state['ready']:
|
||||
return {'ok': True, 'confirmed': False, 'pending': True, 'cancel_pending': True,
|
||||
'downstream': result, 'instruction_id': instruction_id,
|
||||
'message': f'指令 {instruction_id} 已请求撤单,等待委托终态与成交入账确认'}
|
||||
fresh = pms_repo.get_instruction(instruction_id) or ins
|
||||
done = int(fresh.get('exec_qty') or 0)
|
||||
if fresh.get('origin_type') == 'plan' and fresh.get('origin_id'):
|
||||
pms_repo.update_plan(fresh['origin_id'], filled_qty=done)
|
||||
requested_status = ((fresh.get('progress') or {}).get('cancel_requested') or {}).get('final_status', ST_CANCELLED)
|
||||
status = ST_CONFIRMED if done >= int(fresh['qty']) else requested_status
|
||||
if status not in (ST_CONFIRMED, ST_CANCELLED, ST_EXPIRED):
|
||||
raise ValueError('撤单确认的父指令终态无效')
|
||||
if not pms_repo.update_instruction(instruction_id, status=status):
|
||||
raise RuntimeError('父指令撤单确认未落表')
|
||||
pms_repo.insert_ledger(ts_code=fresh['ts_code'], action=fresh.get('action'),
|
||||
arbiter=arbiter, verdict='REJECT', price_at=0, ref_id=instruction_id,
|
||||
reason=reason, hard_numbers=(fresh.get('progress') or {}).get('plan') or {})
|
||||
return {'ok': True, 'confirmed': True, 'pending': False, 'cancel_pending': False, 'downstream': result,
|
||||
'status': status,
|
||||
'message': f'指令 {instruction_id} 已全额成交' if status == ST_CONFIRMED else f'指令 {instruction_id} 撤单已确认'}
|
||||
except Exception as exc:
|
||||
logger.exception('撤单确认失败 %s', instruction_id)
|
||||
return {'ok': False, 'pending': True, 'confirmed': False, 'instruction_id': instruction_id,
|
||||
'error': str(exc), 'message': '撤单状态待核实:'+str(exc)}
|
||||
|
||||
|
||||
# ================================================================ 内部
|
||||
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:
|
||||
|
|
@ -516,6 +613,9 @@ def _parent_available(ins: dict, children: list) -> int:
|
|||
在途子单再预留尚未成交的数量;终态只释放未成交部分。必须跨日查询,
|
||||
也必须包含已入出口但没写回 progress 的子单。查询失败由调用方报错,禁止下发。
|
||||
"""
|
||||
from app.services import execution_orders
|
||||
if execution_orders.correction_blocker(ins):
|
||||
return 0
|
||||
target = int(ins['qty'])
|
||||
booked = int(ins.get('exec_qty') or 0)
|
||||
if dispatcher.mode() != dispatcher.MODE_WS:
|
||||
|
|
@ -528,13 +628,8 @@ def _parent_available(ins: dict, children: list) -> int:
|
|||
raise ValueError('同一父指令的出口子单重复,暂停下发')
|
||||
seen.add(ref)
|
||||
qty = int(order['qty'])
|
||||
done = int(order.get('cum_qty') or 0)
|
||||
if qty <= 0 or done < 0 or done > qty:
|
||||
raise ValueError('出口委托数量异常,暂停下发')
|
||||
done = execution_orders.effective_filled(order)
|
||||
status = str(order.get('status') or '').upper()
|
||||
# FILLED 却缺累计成交数属于不完整回报,不能据此释放整笔额度。
|
||||
if status == qmt_repo.OS_FILLED:
|
||||
done = qty
|
||||
filled += done
|
||||
if status not in qmt_repo.FINAL:
|
||||
pending += qty - done
|
||||
|
|
|
|||
|
|
@ -257,6 +257,14 @@ def request(candidate: dict, context: dict = None, *, timeout: int = None,
|
|||
to = int(timeout or param_store.get_int("PMS_JUDGE_TIMEOUT", 90))
|
||||
url = base_url() + (param_store.get("PMS_JUDGE_PATH", "/api/intraday/pms_judge") or "")
|
||||
payload = jsonable(payload) # 数据库类型 (Decimal/日期) 换成 JSON 认得的, 见 jsonable
|
||||
if param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False):
|
||||
from app.services import judge_async
|
||||
from app.core import strategy_book
|
||||
from config.settings import settings
|
||||
book = candidate.get('book_id') or candidate.get('book') or strategy_book.CURRENT.get()
|
||||
payload['client_scope'] = ':'.join(('pms', settings.PMS_TABLE_PREFIX or 'simulation',
|
||||
book, str((candidate.get('hard_numbers') or {}).get('candidate_source') or 'default')))
|
||||
return judge_async.request(candidate, payload, base_url())
|
||||
try:
|
||||
import requests
|
||||
r = requests.post(url, json=payload, timeout=to)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,148 @@
|
|||
"""研判请求先持久化,短请求登记或查询;不在执行循环等待模型。"""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from app.core.execution_policy import local_now, timestamp
|
||||
from app.repo import rotation_repo as repo
|
||||
from app.services import param_store
|
||||
|
||||
logger = logging.getLogger('pms.judge_async')
|
||||
KIND = 'judge_request'
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':'), allow_nan=False).encode()).hexdigest()
|
||||
|
||||
|
||||
def identity(candidate, payload):
|
||||
"""研究内容和实际持仓变更才换请求;价格、资金、候选排名每跳重核。"""
|
||||
hard = candidate.get('hard_numbers') or {}
|
||||
research = hard.get('plan_basis')
|
||||
if research is None:
|
||||
research = {k: v for k, v in payload.get('hard_numbers', {}).items()
|
||||
if k in ('score', 'theme', 'tier', 'upside', 'heat', 'sector', 'verdict', 'reasons',
|
||||
'missing', 'risk', 'events_text', 'pricing_text', 'news_text',
|
||||
'company_review_text', 'intraday_buy_signal', 'intraday_buy_reason',
|
||||
'logic_state', 'support', 'pressure', 'ref_source')}
|
||||
position = (payload.get('context') or {}).get('position') or {}
|
||||
return digest({'research': research, 'position': {k:position.get(k) for k in
|
||||
('total_qty', 'base_qty', 'add_qty', 'dca_qty', 'avg_cost', 'support_ref', 'pressure_ref', 'stop_ref')},
|
||||
'book': candidate.get('book'), 'source': hard.get('candidate_source'),
|
||||
'stage': {k: hard.get(k) for k in ('dca_stage', 'stage', 'dca_count', 'trigger', 'logic_state')},
|
||||
# OPEN数量由PMS实时复核,持仓增持的模型证据还包含本次动作数量。
|
||||
'action_qty': candidate.get('qty') if payload.get('action') != 'OPEN' else None})
|
||||
|
||||
|
||||
def unavailable(reason, **extra):
|
||||
return {'verdict': 'UNAVAILABLE', 'reason': reason, 'degraded': True,
|
||||
'confidence': None, 'raw': extra or None}
|
||||
|
||||
|
||||
def pending(doc):
|
||||
return {'verdict': 'PENDING', 'reason': '研判已登记,等待结果,其他执行继续',
|
||||
'degraded': False, 'confidence': None,
|
||||
'raw': {'request_id': doc['request_id'], 'deadline_at': doc['deadline_at']}}
|
||||
|
||||
|
||||
def _result(doc, candidate):
|
||||
from app.services.judge import _map_verdict
|
||||
if doc.get('reask'):
|
||||
candidate['reask'] = copy.deepcopy(doc['reask'])
|
||||
return _map_verdict(doc['result'])
|
||||
|
||||
|
||||
def request(candidate, payload, base, now=None):
|
||||
"""同一逻辑请求重启后续查;网络故障重发原编号,过期不补发模型。"""
|
||||
current = local_now(now)
|
||||
code = str(payload.get('ts_code') or '').upper()
|
||||
if not re.fullmatch(r'(?:60[0-9]{4}\.SH|68[0-9]{4}\.SH|00[0-9]{4}\.SZ|30[0-9]{4}\.SZ)', code):
|
||||
return unavailable('研判证券不在沪深支持范围')
|
||||
scope = {'day': str(current.date()), 'code': code, 'action': payload.get('action'),
|
||||
'book': candidate.get('book_id') or candidate.get('book'), 'client_scope': payload.get('client_scope'),
|
||||
'source': (candidate.get('hard_numbers') or {}).get('candidate_source')}
|
||||
key = 'judge:' + digest(scope)
|
||||
material = identity(candidate, payload)
|
||||
saved = None
|
||||
try:
|
||||
with repo.locked(key, KIND, {}) as doc:
|
||||
stale = (doc.get('result', {}).get('verdict') in ('PASS', 'REJECT')
|
||||
and current >= timestamp(doc['cache_until']))
|
||||
force_new = payload.get('force_refresh') and not doc.get('forced')
|
||||
if not doc or doc.get('material') != material or stale or force_new:
|
||||
doc.clear()
|
||||
deadline = current + timedelta(seconds=param_store.get_int('PMS_JUDGE_ASYNC_DEADLINE_SEC', 120))
|
||||
doc.update(scope=scope, request_id='PMS_'+uuid.uuid4().hex, payload=copy.deepcopy(payload),
|
||||
material=material, fingerprint=digest(payload), deadline_at=deadline.isoformat(),
|
||||
cache_until=(deadline+timedelta(seconds=param_store.get_int('PMS_JUDGE_ASYNC_CACHE_SEC',120))).isoformat(),
|
||||
created_at=current.isoformat(), forced=bool(payload.get('force_refresh')),
|
||||
reask=copy.deepcopy(candidate.get('reask')), submitted=False)
|
||||
if doc.get('result'):
|
||||
doc['delivered'] = True
|
||||
return _result(doc, candidate)
|
||||
if current >= timestamp(doc['deadline_at']):
|
||||
doc['result'] = {'verdict':'UNAVAILABLE', 'reason':'研判总等待时间已到,转人工确认', 'error_code':'EXPIRED'}
|
||||
doc['delivered'] = True
|
||||
return _result(doc, candidate)
|
||||
# 短租约避免同一请求被两个扫描同时轮询。网络不在数据库事务内。
|
||||
lease = timestamp(doc.get('poll_until'))
|
||||
if lease and current < lease:
|
||||
return pending(doc)
|
||||
doc['poll_until'] = (current+timedelta(seconds=param_store.get_int('PMS_JUDGE_ASYNC_HTTP_TIMEOUT',3)+2)).isoformat()
|
||||
saved = copy.deepcopy(doc)
|
||||
import requests
|
||||
timeout = min(param_store.get_int('PMS_JUDGE_ASYNC_HTTP_TIMEOUT',3),
|
||||
max(.1,(timestamp(saved['deadline_at'])-current).total_seconds()))
|
||||
if saved['submitted']:
|
||||
response = requests.get(base+'/api/intraday/pms_judge_result/'+saved['request_id'], timeout=timeout)
|
||||
else:
|
||||
response = requests.post(base+'/api/intraday/pms_judge_submit', timeout=timeout,
|
||||
json=dict(saved['payload'], request_id=saved['request_id'], deadline_at=saved['deadline_at'],
|
||||
evidence_fingerprint=saved['fingerprint']))
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
finished = local_now() if now is None else current
|
||||
with repo.locked(key, KIND, {}) as doc:
|
||||
if doc.get('request_id') != saved['request_id']:
|
||||
return unavailable('研究依据已变化,本次旧结果已作废', error_code='SUPERSEDED')
|
||||
doc.pop('poll_until', None)
|
||||
if finished >= timestamp(doc['deadline_at']):
|
||||
data = {'verdict':'UNAVAILABLE', 'reason':'结果到达时已超过截止时间,转人工确认', 'error_code':'EXPIRED'}
|
||||
elif (not isinstance(data,dict) or data.get('request_id') != doc['request_id']
|
||||
or (data.get('verdict') in ('PASS','REJECT','PENDING') and
|
||||
data.get('evidence_fingerprint') != doc['fingerprint'])):
|
||||
data = {'verdict':'UNAVAILABLE', 'reason':'研判结果编号或证据不匹配,转人工确认', 'error_code':'INVALID_RESPONSE'}
|
||||
if data.get('error_code') == 'NOT_FOUND':
|
||||
doc['submitted'] = False # 同编号重试,不另造一个模型任务。
|
||||
return pending(doc)
|
||||
doc['submitted'] = True
|
||||
if data.get('verdict') == 'PENDING':
|
||||
return pending(doc)
|
||||
doc['result'] = data
|
||||
doc['completed_at'] = finished.isoformat()
|
||||
doc['cache_until'] = (finished+timedelta(seconds=param_store.get_int('PMS_JUDGE_ASYNC_CACHE_SEC',120))).isoformat()
|
||||
doc['delivered'] = True
|
||||
return _result(doc, candidate)
|
||||
except Exception as exc:
|
||||
logger.warning('研判登记或查询暂不可用 [%s]: %s', code, type(exc).__name__)
|
||||
# 已可靠登记且尚未过期,传输失败保留轮询;否则在途提议会挡住结果消费。
|
||||
if saved is not None and local_now(now) < timestamp(saved['deadline_at']):
|
||||
return pending(saved)
|
||||
return unavailable('研判登记或查询暂不可用,转人工确认', error_code=type(exc).__name__)
|
||||
|
||||
|
||||
def resumable_reasks(now=None):
|
||||
"""仅让已经登记的重问穿过旧模型驳回,不越过用户拒绝、在途或规则闸。"""
|
||||
today = str(local_now(now).date())
|
||||
values = {}
|
||||
for row in repo.recent(KIND,1000):
|
||||
doc = row['value']
|
||||
if doc.get('scope',{}).get('day') == today and doc.get('reask') and not doc.get('delivered'):
|
||||
scope = doc['scope']
|
||||
values[(scope['code'],scope['action'])] = copy.deepcopy(doc['reask'])
|
||||
return values
|
||||
|
|
@ -27,6 +27,7 @@ from app.core import tradedays as td
|
|||
from app.core import ws_codec as wsc
|
||||
from app.repo import downstream_repo, pms_repo, qmt_repo
|
||||
from app.services import market, param_store, portfolio
|
||||
from config.settings import settings
|
||||
|
||||
logger = logging.getLogger("pms.ledger")
|
||||
|
||||
|
|
@ -131,7 +132,7 @@ def consume_ws_trades(*, limit: int = 500) -> dict:
|
|||
"""
|
||||
out = {"ok": True, "trades": 0, "actions": 0, "fees": 0, "alerts": [], "errors": []}
|
||||
try:
|
||||
rows = qmt_repo.inbox_pending(limit=limit)
|
||||
rows = qmt_repo.inbox_pending(limit=limit, msg_type='trade')
|
||||
except Exception as e:
|
||||
# ws 三表没建 (影子期正常) 或库不可用 —— 不该让整个回放任务失败
|
||||
out["skipped"] = f"inbox 不可读: {type(e).__name__}"
|
||||
|
|
@ -214,6 +215,11 @@ def consume_ws_trades(*, limit: int = 500) -> dict:
|
|||
if not pid:
|
||||
continue
|
||||
try:
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.core.strategy_book import scope
|
||||
with scope('all'):
|
||||
ins = pms_repo.get_instruction(pid)
|
||||
else:
|
||||
ins = pms_repo.get_instruction(pid)
|
||||
if ins:
|
||||
parent_actions[pid] = ins.get("action")
|
||||
|
|
@ -237,6 +243,15 @@ def consume_ws_trades(*, limit: int = 500) -> dict:
|
|||
booked_codes, booked_seqs = set(), []
|
||||
for act in mapped["actions"]:
|
||||
seq = act.get("seq")
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
try:
|
||||
from app.services.rotation_execution import book_trade
|
||||
if book_trade(act, fees_by_no.get(act.get('order_id')) or [], seq):
|
||||
out['actions'] += 1
|
||||
booked_seqs.append(seq)
|
||||
except Exception as e:
|
||||
out['errors'].append(f"策略成交入账未完成,保留待重试: {type(e).__name__}: {e}")
|
||||
continue
|
||||
try:
|
||||
_apply_action(act)
|
||||
out["actions"] += 1
|
||||
|
|
@ -367,10 +382,19 @@ def replay_fills(*, limit: int = 500) -> dict:
|
|||
out["ws"] = consume_ws_trades(limit=limit)
|
||||
if out["ws"].get("errors"):
|
||||
out["errors"].extend(out["ws"]["errors"])
|
||||
# 原成交先入账,修正再核对双报文;修正不会走新成交的批次或费用入口。
|
||||
from app.services import trade_correction
|
||||
out['corrections'] = trade_correction.consume(limit=limit)
|
||||
out['errors'].extend(out['corrections'].get('errors') or [])
|
||||
correction_ok = out['corrections'].get('ok') is not False
|
||||
for alert in out['corrections'].get('alerts') or []:
|
||||
visible = dict(alert, message=alert.get('message') or alert.get('reason') or '成交更正待人工核实')
|
||||
out['alerts'].append(visible)
|
||||
logger.warning('[成交更正告警] %s', visible['message'])
|
||||
state, note = _cursor_load(pms_repo.get_param(CURSOR_KEY))
|
||||
if state is None: # 从未设过 / 旧格式 —— 冷启动, 只对齐游标不入账
|
||||
r = _seed_cursor(out, note_extra=note)
|
||||
r["ok"] = not r.get("errors")
|
||||
r["ok"] = not r.get("errors") and correction_ok
|
||||
return r
|
||||
|
||||
since = str(state["t"])
|
||||
|
|
@ -383,14 +407,15 @@ def replay_fills(*, limit: int = 500) -> dict:
|
|||
try:
|
||||
fills = downstream_repo.fetch_filled_orders(since_time=since, limit=limit)
|
||||
except Exception as e:
|
||||
out.update({"ok": False, "errors": [f"读 trading_order 失败: {type(e).__name__}: {e}"]})
|
||||
out["errors"].append(f"读 trading_order 失败: {type(e).__name__}: {e}")
|
||||
out["ok"] = False
|
||||
return out
|
||||
seen = state["seen"]
|
||||
fresh = [f for f in fills if _fill_key(f) not in seen]
|
||||
out["fills"] = len(fresh)
|
||||
if not fresh:
|
||||
out["cursor"] = state["t"]
|
||||
out["ok"] = not out["errors"] # 早退也要按 errors 定 ok (ws 那半的错不能吞)
|
||||
out["ok"] = not out["errors"] and correction_ok # 早退也要按 errors 定 ok (ws 那半的错不能吞)
|
||||
return out
|
||||
|
||||
# 2026-10-15:155 模拟仓三项差异均来自同一 ws 委托被汇总表再次回放。
|
||||
|
|
@ -417,6 +442,18 @@ def replay_fills(*, limit: int = 500) -> dict:
|
|||
if ws_owned:
|
||||
logger.info("[回放] %s 笔本实例 ws 委托的汇总镜像跳过,逐笔通道负责入账", len(ws_owned))
|
||||
fresh = external
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and fresh:
|
||||
from app.repo import rotation_repo
|
||||
import hashlib
|
||||
for fill in fresh:
|
||||
key = _fill_key(fill)
|
||||
rotation_repo.put_once('external:'+hashlib.sha256(key.encode()).hexdigest()[:40],
|
||||
'unattributed_fill', fill)
|
||||
ft = str(fill.get('done_time') or '')[:19] or t_max
|
||||
seen[key] = ft
|
||||
t_max = max(t_max, ft)
|
||||
out['unattributed'] = len(fresh)
|
||||
fresh = []
|
||||
|
||||
try:
|
||||
instrs = _open_instructions()
|
||||
|
|
@ -481,9 +518,10 @@ def replay_fills(*, limit: int = 500) -> dict:
|
|||
except Exception:
|
||||
state["seen"] = seen
|
||||
_cursor_save(state, out)
|
||||
out["ok"] = not out["errors"]
|
||||
out["ok"] = not out["errors"] and correction_ok
|
||||
for a in out["alerts"]:
|
||||
logger.warning("[回放告警] %s", a.get("message"))
|
||||
if a.get("type") != "TRADE_CORRECTION_HELD":
|
||||
logger.warning("[回放告警] %s", a.get("message") or a.get("reason"))
|
||||
return out
|
||||
|
||||
|
||||
|
|
@ -805,6 +843,9 @@ def reconcile(*, apply_fix: bool = True, force: bool = False) -> dict:
|
|||
force=True 绕过爆炸半径限制 (见 _recon_blast_guard) —— 只在人工确认下游读数确实
|
||||
正确之后使用。
|
||||
"""
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.services.rotation_service import reconcile_books
|
||||
return reconcile_books()
|
||||
out = {"ok": True, "diffs": [], "fixes": [], "errors": [], "columns": {}, "severity": rc.SEV_OK}
|
||||
src = positions_source()
|
||||
ds = {"rows": src["rows"], "columns": src["columns"], "raw_count": src["raw_count"]}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ from __future__ import annotations
|
|||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
|
@ -490,6 +491,25 @@ def gate_state() -> dict:
|
|||
|
||||
|
||||
# ================================================================ 页面
|
||||
def published_reading() -> dict:
|
||||
"""展示已发布值,读取失败不回填另一口径或把空值当零。"""
|
||||
out = {"source": "gp_stock_fx_hedge_index", "ready": False}
|
||||
try:
|
||||
row = macro_repo.latest_published_hedge()
|
||||
if not row or row.get("hedge_index") is None:
|
||||
return {**out, "error": "已发布指数暂无有效记录"}
|
||||
value = float(row["hedge_index"])
|
||||
day = mr.norm_ymd(row.get("trade_date"))
|
||||
if not day or day > td.ymd() or not math.isfinite(value):
|
||||
return {**out, "error": "已发布指数日期或数值无效"}
|
||||
return {**out, "ready": True, "value": value, "data_ymd": day,
|
||||
"row_id": row["id"], "zone": row.get("zone"),
|
||||
"recorded_at": str(row.get("create_time") or "")}
|
||||
except Exception:
|
||||
logger.exception("已发布股汇指数读取失败")
|
||||
return {**out, "error": "已发布指数暂时读取失败"}
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
"""面板快照: 各信号的当前值/区域/近 20 日序列/当日建议/最近命令/冷却, 加闸状态。"""
|
||||
p = _params()
|
||||
|
|
@ -502,6 +522,8 @@ def status() -> dict:
|
|||
"signals": []}
|
||||
for key in _enabled_signals(p):
|
||||
item = {"key": key, "label": SIGNALS[key].get("label") or key}
|
||||
if key == "hedge_fx":
|
||||
item["published"] = published_reading()
|
||||
try:
|
||||
rows = macro_repo.recent_signals(key, limit=22)
|
||||
except Exception as e: # noqa: BLE001
|
||||
|
|
@ -510,6 +532,7 @@ def status() -> dict:
|
|||
continue
|
||||
latest = rows[0] if rows else None
|
||||
item["history"] = [{"ymd": int(r["trade_date"]),
|
||||
"data_ymd": (r.get("detail") or {}).get("zs_last"),
|
||||
"value": (None if r.get("value") is None
|
||||
else float(r["value"])),
|
||||
"zone": r.get("zone")} for r in reversed(rows)]
|
||||
|
|
@ -517,6 +540,7 @@ def status() -> dict:
|
|||
det = latest.get("detail") or {}
|
||||
item.update({
|
||||
"ymd": int(latest["trade_date"]),
|
||||
"data_ymd": det.get("zs_last"),
|
||||
"value": None if latest.get("value") is None else float(latest["value"]),
|
||||
"zone": latest.get("zone"), "note": latest.get("note"),
|
||||
"action": latest.get("action"), "ref_id": latest.get("ref_id"),
|
||||
|
|
|
|||
|
|
@ -113,6 +113,46 @@ def day_snapshot(ts_code: str) -> dict:
|
|||
return {}
|
||||
|
||||
|
||||
|
||||
def execution_quote(code, now=None, limits=None):
|
||||
"""执行用分钟行情。没有盘口或停牌证据时保留未知,不把昨收冒充现价。"""
|
||||
import re
|
||||
from app.core.execution_policy import local_now
|
||||
code = str(code or '').strip().upper()
|
||||
if not re.fullmatch(r'(?:60[0-9]{4}\.SH|68[0-9]{4}\.SH|00[0-9]{4}\.SZ|30[0-9]{4}\.SZ)', code):
|
||||
return {}
|
||||
current = local_now(now)
|
||||
bars = _bars(code)
|
||||
if not bars:
|
||||
return {}
|
||||
last = bars[-1]
|
||||
try:
|
||||
at = datetime.fromisoformat(str(last.get('time') or '').replace('Z', '+00:00'))
|
||||
# 已核实源分钟线time为北京时间;必须带完整日期,不能用今天补造旧行情。
|
||||
at = local_now(at)
|
||||
price = float(last.get('close') or 0)
|
||||
if price <= 0:
|
||||
return {}
|
||||
except (ValueError, TypeError):
|
||||
return {}
|
||||
if limits is None:
|
||||
if param_store.get_bool('PMS_LIMIT_CACHE_ENABLED', False):
|
||||
from app.services import price_limits
|
||||
limits = price_limits.get_limits(current.date(), [code]).get(code, {})
|
||||
else:
|
||||
rows = fetch_all('SELECT up_limit,down_limit FROM gp_stk_limit '
|
||||
'WHERE trade_date=:day AND ts_code=:code',
|
||||
{'day': current.date().isoformat(), 'code': code})
|
||||
limits = rows[0] if rows else {}
|
||||
return {'kind': 'minute', 'source': 'tushare:rt_min:1MIN',
|
||||
'as_of': at.isoformat(), 'last': price, 'bid': None, 'ask': None,
|
||||
'limit_up': (limits or {}).get('up_limit'),
|
||||
'limit_down': (limits or {}).get('down_limit'), 'halted': None,
|
||||
'limit_source': (limits or {}).get('source') or ('gp_stk_limit' if
|
||||
(limits or {}).get('up_limit') and (limits or {}).get('down_limit') else None),
|
||||
'limit_version': (limits or {}).get('version'),
|
||||
'limit_fetched_at': (limits or {}).get('fetched_at')}
|
||||
|
||||
# ================================================================ 参考位
|
||||
def _shard_tables(months: int = 4) -> list:
|
||||
now = datetime.now()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,206 @@
|
|||
"""人工关注的独立研究覆盖。只发布观察名单和读取回执,不产生交易候选。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import date, datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.core.command_spec import is_stock_code, normalize_code
|
||||
from app.services import param_store, signal_service
|
||||
from config.settings import settings
|
||||
|
||||
logger = logging.getLogger("pms.monitor_watch")
|
||||
TZ = ZoneInfo("Asia/Shanghai")
|
||||
SOURCE_KEY = "pms:monitor_watch:v1:"
|
||||
STATUS_KEY = "bionic:monitor_watch:status:v1:"
|
||||
SCOPE = "pms-sim-155"
|
||||
|
||||
# 旧轮次晚返回时,不能把刚移除的关注重新写回。相同登记版本也只接受更新的快照。
|
||||
_REPLACE = """
|
||||
local old = redis.call('GET', KEYS[1])
|
||||
local new = cjson.decode(ARGV[1])
|
||||
if old then
|
||||
local ok, prior = pcall(cjson.decode, old)
|
||||
if ok and prior.source_revision then
|
||||
if tonumber(prior.source_revision) > tonumber(new.source_revision) then return 0 end
|
||||
if tonumber(prior.source_revision) == tonumber(new.source_revision)
|
||||
and tostring(prior.generated_at) > tostring(new.generated_at) then return 0 end
|
||||
end
|
||||
end
|
||||
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
|
||||
return 1
|
||||
"""
|
||||
|
||||
|
||||
def _now(now=None):
|
||||
return (now or datetime.now(TZ)).astimezone(TZ)
|
||||
|
||||
|
||||
def _time(value):
|
||||
try:
|
||||
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
||||
return dt if dt.tzinfo is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def code_of(row):
|
||||
code = normalize_code(str(row.get("ts_code") or row.get("code") or ""))
|
||||
return code if code.endswith((".SH", ".SZ")) and is_stock_code(code) else ""
|
||||
|
||||
|
||||
def active(row, now=None):
|
||||
if not code_of(row) or row.get("removed_at") or row.get("status") in ("removed", "expired"):
|
||||
return False
|
||||
try:
|
||||
return date.fromisoformat(str(row.get("expires_on"))) >= _now(now).date()
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def scope():
|
||||
value = str(param_store.get("PMS_MONITOR_WATCH_SCOPE", "") or "").strip()
|
||||
if value not in ("", SCOPE):
|
||||
raise ValueError("人工关注观察来源配置无效")
|
||||
return value
|
||||
|
||||
|
||||
def build_snapshot(registry, *, now=None, ttl=600):
|
||||
now = _now(now)
|
||||
revision = registry.get("revision")
|
||||
if registry.get("ok") is not True or not isinstance(registry.get("rows"), list):
|
||||
raise ValueError("人工关注登记读取不完整")
|
||||
if type(revision) is not int or revision < 0:
|
||||
raise ValueError("人工关注登记版本缺失")
|
||||
items = []
|
||||
for row in registry["rows"]:
|
||||
if not isinstance(row, dict) or not active(row, now) or row.get("review_status") != "completed":
|
||||
continue
|
||||
ref = str(row.get("review_ref") or "")
|
||||
review = row.get("company_review")
|
||||
# 最近核对时间可能晚于报告生成;监控依据必须保留报告自身的真实日期。
|
||||
completed = _time((review or {}).get("report_ran_at")) if isinstance(review, dict) else None
|
||||
data_date = str(row.get("review_data_date") or "")
|
||||
try:
|
||||
day = date.fromisoformat(data_date)
|
||||
except ValueError:
|
||||
day = None
|
||||
if (not completed or completed > now + timedelta(seconds=30) or not day or day > now.date()
|
||||
or day != completed.astimezone(TZ).date()
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", ref) or not isinstance(review, dict) or not review
|
||||
or not re.fullmatch(r"[0-9a-f]{32}", str(row.get("id") or ""))):
|
||||
raise ValueError("已完成的买方评析缺少有效来源或日期")
|
||||
items.append({"ts_code": code_of(row), "watch_id": row["id"], "watch_revision": revision,
|
||||
"active": True, "expires_on": row["expires_on"], "review_status": "ready",
|
||||
"review_ref": ref, "review_completed_at": completed.isoformat(),
|
||||
"review_data_date": data_date,
|
||||
"review_summary": str(row.get("company_review_text") or review.get("overall") or "")[:2000]})
|
||||
return {"schema_version": 1, "source_scope": SCOPE, "source_revision": revision,
|
||||
"generated_at": now.isoformat(), "expires_at": (now + timedelta(seconds=ttl)).isoformat(),
|
||||
"items": items}
|
||||
|
||||
|
||||
def sync():
|
||||
"""每分钟全量发布;读取失败保留旧快照,短期过期后由消费者停止覆盖。"""
|
||||
try:
|
||||
source = scope()
|
||||
if not source:
|
||||
return {"ok": True, "skipped": "disabled"}
|
||||
from app.services import plan_candidates
|
||||
started = _now()
|
||||
registry = plan_candidates.request()
|
||||
ttl = param_store.get_int("PMS_MONITOR_WATCH_TTL_SEC", 600)
|
||||
if not 120 <= ttl <= 600:
|
||||
raise ValueError("人工关注观察快照有效期无效")
|
||||
payload = build_snapshot(registry, now=started, ttl=ttl)
|
||||
client = signal_service._client(settings.SIGNAL_REDIS_DB_INTRADAY)
|
||||
result = client.eval(_REPLACE, 1, SOURCE_KEY + source,
|
||||
json.dumps(payload, ensure_ascii=False), ttl)
|
||||
if result != 1:
|
||||
return {"ok": False, "error": "较新的人工关注版本已发布,本轮旧版本未写入"}
|
||||
return {"ok": True, "returned": len(payload["items"]), "source_revision": payload["source_revision"]}
|
||||
except Exception as exc:
|
||||
logger.warning("人工关注观察名单未更新:%s", type(exc).__name__)
|
||||
return {"ok": False, "error": "观察名单同步失败,等待下次重试;旧名单将按有效期失效"}
|
||||
|
||||
|
||||
def coverage(registry, *, now=None):
|
||||
"""只读回执;来源过期、登记版本或评析版本不匹配时,不冒充仍被覆盖。"""
|
||||
now = _now(now)
|
||||
try:
|
||||
source = scope()
|
||||
if not source:
|
||||
return {}, "观察名单同步尚未启用"
|
||||
client = signal_service._client(settings.SIGNAL_REDIS_DB_INTRADAY)
|
||||
published = json.loads(client.get(SOURCE_KEY + source) or "null")
|
||||
report = json.loads(client.get(STATUS_KEY + source) or "null")
|
||||
if not isinstance(published, dict) or published.get("source_scope") != source:
|
||||
return {}, "等待观察名单同步"
|
||||
expiry = _time(published.get("expires_at"))
|
||||
generated = _time(published.get("generated_at"))
|
||||
if (not generated or generated > now + timedelta(seconds=30) or not expiry or expiry <= now
|
||||
or expiry <= generated or (expiry - generated).total_seconds() > 600):
|
||||
return {}, "观察名单已过期,等待重新同步"
|
||||
if (published.get("schema_version") != 1 or published.get("source_revision") != registry.get("revision")
|
||||
or not isinstance(report, dict) or report.get("schema_version") != 1
|
||||
or report.get("source_scope") != source):
|
||||
return {}, "等待新的分析回执"
|
||||
published_rows = {r.get("ts_code"): r for r in published.get("items", []) if isinstance(r, dict)}
|
||||
reports = report.get("items") or {}
|
||||
result = {}
|
||||
for row in registry.get("rows", []):
|
||||
code = code_of(row)
|
||||
receipt, sent = reports.get(code) or {}, published_rows.get(code) or {}
|
||||
if (not active(row, now) or row.get("review_status") != "completed"
|
||||
or sent.get("watch_id") != row.get("id") or not sent.get("active")
|
||||
or sent.get("review_ref") != row.get("review_ref")
|
||||
or receipt.get("watch_id") != row.get("id")
|
||||
or receipt.get("watch_revision") != registry.get("revision")
|
||||
or receipt.get("review_ref") != row.get("review_ref")):
|
||||
continue
|
||||
stages = {}
|
||||
for key in ("daily", "intraday"):
|
||||
stage = dict(receipt.get(key) or {})
|
||||
if stage.get("state") in ("QUEUED", "RUNNING"):
|
||||
deadline = _time(stage.get("deadline_at"))
|
||||
if not deadline:
|
||||
stage.update(state="UNAVAILABLE", reason="分析回执缺少有效截止时间")
|
||||
elif deadline <= now:
|
||||
stage.update(state="EXPIRED", reason="分析等待已超时,等待新的回执")
|
||||
stages[key] = stage
|
||||
result[code] = stages
|
||||
return result, ""
|
||||
except Exception:
|
||||
return {}, "分析覆盖回执暂不可用"
|
||||
|
||||
|
||||
def listing():
|
||||
from app.services import plan_candidates
|
||||
from app.repo import downstream_repo
|
||||
registry = plan_candidates.request()
|
||||
rows = [dict(r, ts_code=code_of(r), active=active(r)) for r in registry.get("rows", [])
|
||||
if isinstance(r, dict) and code_of(r)]
|
||||
receipts, note = coverage(registry)
|
||||
try:
|
||||
latest = downstream_repo.fetch_nightly_verdicts([r["ts_code"] for r in rows])
|
||||
nightly_error = ""
|
||||
except Exception:
|
||||
latest, nightly_error = {}, "最近研判暂不可用"
|
||||
for row in rows:
|
||||
read = latest.get(row["ts_code"]) or {}
|
||||
row.update(last_analysis_date=read.get("trade_date"), last_analysis_signal=read.get("verdict"),
|
||||
analysis_coverage=receipts.get(row["ts_code"], {}), coverage_note=note,
|
||||
last_analysis_error=nightly_error)
|
||||
return dict(registry, rows=rows)
|
||||
|
||||
|
||||
def research_row(code):
|
||||
if not code_of({'code': code}):
|
||||
return None
|
||||
from app.services import plan_candidates
|
||||
for row in plan_candidates.request().get("rows", []):
|
||||
if active(row) and code_of(row) == code and row.get("review_status") == "completed":
|
||||
return row
|
||||
return None
|
||||
|
|
@ -36,10 +36,63 @@ INFRA_PREFIX = ("PROXY_DB", "SOURCE_DB", "DB_MYSQL", "SIGNAL_REDIS", "PMS_REDIS"
|
|||
# 2026-09-03 补进会话票签名密钥 PMS_SESSION_SECRET: 它 2026-08 随登录一起加进 settings,
|
||||
# 当时漏了这份名单, 于是参数设置页把它当普通业务参数原文显示出来 (登录中间件读的是
|
||||
# settings, 功能没受影响, 但密钥不该出现在页面上)。
|
||||
SECRET_KEYS = ("PMS_QMT_SIGN_SEED_HEX", "PMS_QMT_PEER_PUBKEY_B64", "PMS_SESSION_SECRET")
|
||||
SECRET_KEYS = ("PMS_QMT_SIGN_SEED_HEX", "PMS_QMT_PEER_PUBKEY_B64", "PMS_SESSION_SECRET", "PMS_PLAN_WRITE_KEY", "PMS_TUSHARE_TOKEN")
|
||||
LIMIT_FLAGS = ('PMS_LIMIT_CACHE_ENABLED', 'PMS_LIMIT_COLLECT_ENABLED')
|
||||
|
||||
|
||||
def _valid_limit_flag(value):
|
||||
return isinstance(value, bool) or (type(value) in (str, int) and
|
||||
str(value).strip().lower() in ('1', 'true', 'yes', 'on', 'y', '0', 'false', 'no', 'off', 'n'))
|
||||
|
||||
# 运行态开关: key -> (默认值, 类型, 说明)
|
||||
RUNTIME_EXTRA = {
|
||||
'PMS_MONITOR_WATCH_SCOPE': ('', str, '人工关注研究覆盖来源;仅155模拟实例设置pms-sim-155,留空停用'),
|
||||
'PMS_MONITOR_WATCH_TTL_SEC': (600, int, '人工关注研究名单有效期,秒;与交易候选和交易开关分离'),
|
||||
'PMS_LIMIT_CACHE_ENABLED': (False, bool, '执行报价读取已核实的当日限制价缓存;缺失时逐票等待'),
|
||||
'PMS_LIMIT_COLLECT_ENABLED': (False, bool, '独立采集进程补齐目标证券的当日限制价,不生成交易指令'),
|
||||
'PMS_LIMIT_FETCH_TIMEOUT_SEC': (5, int, '限制价来源单次请求超时,秒'),
|
||||
'PMS_LIMIT_ROUND_BUDGET_SEC': (30, int, '每轮限制价HTTP采集阶段预算,秒'),
|
||||
'PMS_LIMIT_ROUND_MAX_CODES': (25, int, '每轮最多请求的目标证券数'),
|
||||
'PMS_LIMIT_MIN_REQUEST_INTERVAL_SEC': (1.2, float, '独立采集进程全部请求之间的最小间隔,秒'),
|
||||
'PMS_LIMIT_RETRY_BASE_SEC': (60, int, '限制价采集失败后的首次退避秒数'),
|
||||
'PMS_LIMIT_RETRY_MAX_SEC': (900, int, '限制价连续失败的最大退避秒数'),
|
||||
'PMS_LIMIT_MAX_FAILURES_PER_DAY': (32, int, '每只证券每日最多连续失败次数,成功清零;达到后停止当天重试'),
|
||||
'PMS_LIMIT_REFRESH_SEC': (900, int, '已有效限制价的再次核验间隔,秒'),
|
||||
'PMS_LIMIT_COLLECT_START': ('08:55', str, '限制价采集开始时间,北京时间HH:MM;无效时不采集'),
|
||||
'PMS_LIMIT_COLLECT_END': ('18:00', str, '限制价采集结束时间,北京时间HH:MM;仅交易日且日历可用时采集'),
|
||||
'PMS_EXEC_REJECT_COOLDOWN_SEC': (60, int, '拒单后的首次退避秒数,不限制正常改价'),
|
||||
'PMS_EXEC_REJECT_MAX_COOLDOWN_SEC': (900, int, '重复拒单退避最大秒数'),
|
||||
'PMS_EXEC_REPRICE_ENABLED': (False, bool, '已授权委托按新鲜行情撤单确认后重挂;先发布上游执行依据接口'),
|
||||
'PMS_EXEC_BASIS_REFRESH_SEC': (60, int, '执行依据刷新间隔,秒'),
|
||||
'PMS_EXEC_BASIS_REFRESH_BUDGET_SEC': (20, int, '每轮依据刷新时间预算,秒'),
|
||||
'PMS_EXEC_BASIS_SOURCE_MAX_DAYS': (7, int, '执行依据原始数据最大自然日龄'),
|
||||
'PMS_EXEC_QUOTE_MAX_AGE_SEC': (15, int, '实时盘口最大允许时龄,秒'),
|
||||
'PMS_EXEC_ALLOW_MINUTE_QUOTE': (True, bool, '允许明确留痕的分钟行情降级报价;不冒充盘口'),
|
||||
'PMS_EXEC_MINUTE_MAX_AGE_SEC': (90, int, '分钟行情最大允许时龄,秒'),
|
||||
'PMS_EXEC_PRICE_OFFSET_TICKS': (1, int, '相对对手盘增加的最小价格单位数'),
|
||||
'PMS_EXEC_REPRICE_MIN_SEC': (60, int, '两次撤换委托的最小间隔,秒'),
|
||||
'PMS_EXEC_REPRICE_TICKS': (2, int, '触发撤换的最小价差单位数'),
|
||||
'PMS_EXEC_REPRICE_MAX_ATTEMPTS': (0, int, '窗口内撤换次数上限,0表示不限;始终受命令和时段约束'),
|
||||
'PMS_EXEC_MAX_SLIPPAGE_PCT': (0.01, float, '相对本次新鲜行情的最大报价偏移,不锁定首笔价格'),
|
||||
'PMS_EXEC_MINUTE_SLIPPAGE_PCT': (0.002, float, '分钟行情降级限价偏移比例'),
|
||||
'PMS_ROTATION_CANDIDATE_POOL_SIZE': (100, int, '微盘v3冻结候选总数,包含首选和有序备选'),
|
||||
'PMS_JUDGE_ASYNC_ENABLED': (False, bool, '异步登记研判并轮询结果,超时转人工;须先发布上游'),
|
||||
'PMS_JUDGE_ASYNC_HTTP_TIMEOUT': (3, int, '异步提交或查询单次网络超时,秒'),
|
||||
'PMS_JUDGE_ASYNC_DEADLINE_SEC': (120, int, '含排队时间的研判总截止秒数'),
|
||||
'PMS_JUDGE_ASYNC_CACHE_SEC': (120, int, '相同研究依据结果可复用时间,秒'),
|
||||
'PMS_JUDGE_ASYNC_SCAN_BUDGET_SEC': (20, int, '每轮异步研判登记与查询总预算,秒'),
|
||||
|
||||
"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, '微盘监控只读接口根地址,留空停用拉取'),
|
||||
'PMS_ROTATION_CONTROL': ('run', str, '轮换控制:run运行、pause_new暂停新增、pause_all暂停全部、exit_disable退出并停用'),
|
||||
'PMS_ROTATION_RULE_VERSION': ('micro50-v2-20261028', str, '微盘完整规则版本,8%入场、85%退出、50只绑定发布;不支持持仓期间隐式换版'),
|
||||
'PMS_MICRO30_ALLOWED_BOARDS': ('', str, '实际已核实板块权限,MAIN、CHINEXT、STAR逗号分隔;留空不得自动买入'),
|
||||
'PMS_MICRO30_COMMISSION_RATE': (0.0002, float, '微盘佣金估算率;自动执行前核实实际费率'),
|
||||
'PMS_MICRO30_MIN_COMMISSION': (5.0, float, '微盘每笔最低佣金估算,元;自动执行前核实'),
|
||||
'PMS_MICRO30_SELL_TAX': (0.0005, float, '微盘卖出印花税估算率;自动执行前核实'),
|
||||
'PMS_MICRO30_TRANSFER_RATE': (0.00001, float, '微盘过户费用估算率;自动执行前核实'),
|
||||
'PMS_PLAN_VERSION_RECHECK': (False, bool, '自主建仓采纳前核验计划版本;新版发布与留痕验收后开启,当前不可核验时暂停采纳'),
|
||||
"PMS_GLOBAL_BUY_HALT": (False, bool, "全局暂停买入 (HALT_BUY 命令置位)"),
|
||||
"PMS_GLOBAL_EXEC_HALT": (False, bool, "全局暂停执行"),
|
||||
|
|
@ -153,6 +206,9 @@ RUNTIME_EXTRA = {
|
|||
# 冷启、连库超时), 全局暂停买入、休假模式、组合刹车就一起静默解除, 且没有任何调用方
|
||||
# 看得出这是降级。安全开关的默认方向必须是"拦", 不是"放"。
|
||||
FAIL_CLOSED = {
|
||||
'PMS_MONITOR_WATCH_SCOPE': '',
|
||||
"PMS_LIMIT_CACHE_ENABLED": True, # 无法确认开关时仍走严格本地缓存,不退到旧读取。
|
||||
"PMS_LIMIT_COLLECT_ENABLED": False,
|
||||
"PMS_GLOBAL_BUY_HALT": True, # 读不到 → 当作已暂停买入
|
||||
"PMS_GLOBAL_EXEC_HALT": True, # 读不到 → 当作已暂停执行
|
||||
# 自主新建仓的默认值是 full (无人值守地开新仓), 所以它读不到时的安全方向格外要紧:
|
||||
|
|
@ -237,7 +293,7 @@ DESC = {
|
|||
"PMS_PLAN_CACHE_SEC": "计划缓存秒数 (上游日频产出)",
|
||||
"PMS_PLAN_TOP": "发给上游的 top: 主榜要多少条 (上游默认 20; 0=不传)",
|
||||
"PMS_PLAN_OBS_TOP": "发给上游的 obs_top: 观察档要多少条 (上游默认 10; 0=不传)",
|
||||
"PMS_PLAN_THEME_CAP": "发给上游的 theme_cap: 上游侧同主题限额 (上游默认 5; 设大值=让上游别裁, 由 PMS 自己裁; 0=不传)",
|
||||
"PMS_PLAN_THEME_CAP": "上游同主题候选数量上限,0=不限;明确传给上游,不使用上游默认限额",
|
||||
"PMS_PLAN_THEME_CAP_LOCAL": "PMS 侧同主题限额, 在 TOP_N 截断之前按 score 序生效, 0=不限。防止宽池子里前 N 名被单一主题垄断、切完再被规则闸拦掉",
|
||||
"PMS_PLAN_TOP_N": "主榜按 score 降序取前 N 只进候选池",
|
||||
"PMS_PLAN_TIERS": "传导档白名单 (如 强传导), 留空=不按档过滤",
|
||||
|
|
@ -255,6 +311,7 @@ DESC = {
|
|||
"PMS_SECTOR_MAX_RATIO": "同行业最大占总仓比例 (硬拦截)",
|
||||
"PMS_EXEC_WINDOW_TDAYS": "任务命令默认执行窗口 (交易日)",
|
||||
"PMS_EXEC_IMPL": "择时实现: B=内置保守择时 / A=委托决策系统按凌晨结论给执行区间 (不可用自动退B)",
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": "限价直接提交QMT等待成交,PMS保留数量、资金及用户命令检查",
|
||||
"PMS_EXEC_API_BASE": "择时实现A接口根地址; 留空=沿用 PMS_JUDGE_API_BASE",
|
||||
"PMS_EXEC_PATH": "择时接口路径 (bionic 侧 /api/intraday/pms_exec)",
|
||||
"PMS_EXEC_TIMEOUT_SEC": "择时咨询超时 (秒), 超时本轮退实现B",
|
||||
|
|
@ -269,6 +326,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": "组合敞口告警线",
|
||||
|
|
@ -427,6 +485,8 @@ def get(key: str, default=None):
|
|||
"宁可多拦一轮也不放行", key, _cache["error"], FAIL_CLOSED[key])
|
||||
return FAIL_CLOSED[key]
|
||||
if key in rows:
|
||||
if key in LIMIT_FLAGS and not _valid_limit_flag(rows[key].get('param_value')):
|
||||
return FAIL_CLOSED[key]
|
||||
try:
|
||||
return _coerce(rows[key]["param_value"], t)
|
||||
except (TypeError, ValueError):
|
||||
|
|
@ -475,6 +535,8 @@ def get_tuple_floats(key, default=(0.5, 0.25, 0.25)):
|
|||
def set_param(key: str, value, updated_by: str = "user") -> dict:
|
||||
"""页面改参入口。校验键名与类型后落表, 并立即失效缓存。"""
|
||||
editable = _editable_keys()
|
||||
if key in LIMIT_FLAGS and not _valid_limit_flag(value):
|
||||
return {'ok': False, 'error': '限制价开关必须为明确的布尔值'}
|
||||
if key not in editable and key not in RUNTIME_EXTRA and not key.startswith("PMS_SECTOR_CAP_"):
|
||||
return {"ok": False, "error": f"参数 {key} 不可修改 (基础设施参数只在 .env 维护)"}
|
||||
t = _type_of(key)
|
||||
|
|
@ -496,6 +558,34 @@ def set_param(key: str, value, updated_by: str = "user") -> dict:
|
|||
|
||||
|
||||
_RANGES = {
|
||||
'PMS_MONITOR_WATCH_TTL_SEC': (120, 600),
|
||||
'PMS_LIMIT_FETCH_TIMEOUT_SEC': (1, 10),
|
||||
'PMS_LIMIT_ROUND_BUDGET_SEC': (5, 60),
|
||||
'PMS_LIMIT_ROUND_MAX_CODES': (1, 60),
|
||||
'PMS_LIMIT_MIN_REQUEST_INTERVAL_SEC': (1, 10),
|
||||
'PMS_LIMIT_RETRY_BASE_SEC': (30, 600),
|
||||
'PMS_LIMIT_RETRY_MAX_SEC': (60, 3600),
|
||||
'PMS_LIMIT_MAX_FAILURES_PER_DAY': (1, 100),
|
||||
'PMS_LIMIT_REFRESH_SEC': (300, 7200),
|
||||
'PMS_EXEC_REJECT_COOLDOWN_SEC': (1, 3600),
|
||||
'PMS_EXEC_REJECT_MAX_COOLDOWN_SEC': (1, 86400),
|
||||
'PMS_EXEC_BASIS_REFRESH_SEC': (0, 3600),
|
||||
'PMS_EXEC_BASIS_REFRESH_BUDGET_SEC': (0, 3600),
|
||||
'PMS_EXEC_BASIS_SOURCE_MAX_DAYS': (0, 30),
|
||||
'PMS_EXEC_QUOTE_MAX_AGE_SEC': (0, 3600),
|
||||
'PMS_EXEC_MINUTE_MAX_AGE_SEC': (0, 3600),
|
||||
'PMS_EXEC_PRICE_OFFSET_TICKS': (0, 3600),
|
||||
'PMS_EXEC_REPRICE_MIN_SEC': (0, 3600),
|
||||
'PMS_EXEC_REPRICE_TICKS': (0, 3600),
|
||||
'PMS_EXEC_REPRICE_MAX_ATTEMPTS': (0, 3600),
|
||||
'PMS_ROTATION_CANDIDATE_POOL_SIZE': (50, 500),
|
||||
'PMS_JUDGE_ASYNC_HTTP_TIMEOUT': (1, 10),
|
||||
'PMS_JUDGE_ASYNC_DEADLINE_SEC': (10, 180),
|
||||
'PMS_JUDGE_ASYNC_CACHE_SEC': (0, 3600),
|
||||
'PMS_JUDGE_ASYNC_SCAN_BUDGET_SEC': (0, 3600),
|
||||
'PMS_EXEC_MAX_SLIPPAGE_PCT': (0, 0.1),
|
||||
'PMS_EXEC_MINUTE_SLIPPAGE_PCT': (0, 0.05),
|
||||
|
||||
"PMS_PORTFOLIO_CAP": (0, 1), "PMS_STOCK_CAP": (0, 1), "PMS_STOCK_TARGET_DEFAULT": (0, 1),
|
||||
"PMS_CASH_RESERVE": (0, 1), "PMS_CUSHION_SOLID": (0, 1), "PMS_TRIM_GIVEBACK": (0, 1),
|
||||
"PMS_DCA_MAX_RATIO": (0, 1), "PMS_SECTOR_MAX_RATIO": (0, 1), "PMS_T0_RATIO_MAX": (0, 0.3334),
|
||||
|
|
@ -550,6 +640,8 @@ _RANGES = {
|
|||
|
||||
|
||||
def _range_check(key, v):
|
||||
if key == 'PMS_MONITOR_WATCH_SCOPE' and v not in ('', 'pms-sim-155'):
|
||||
return '人工关注研究覆盖仅支持155模拟实例,其他实例请留空'
|
||||
if key == "PMS_AUTONOMY" and v not in ("full", "propose_only", "off"):
|
||||
return "PMS_AUTONOMY 只能是 full / propose_only / off"
|
||||
if key == "PMS_MACRO_AUTONOMY" and v not in ("full", "propose_only", "off"):
|
||||
|
|
|
|||
|
|
@ -0,0 +1,53 @@
|
|||
"""选股计划的用户候选入口;只登记来源,不创建交易命令。"""
|
||||
import re
|
||||
|
||||
from app.services import param_store, plan_feed
|
||||
from config.settings import settings
|
||||
|
||||
|
||||
def request(method='GET', *, payload=None, identity=None, actor='user', query=None):
|
||||
import requests
|
||||
base = str(param_store.get('PMS_PLAN_API_BASE', '') or '').rstrip('/')
|
||||
if not base:
|
||||
raise ValueError('选股计划暂不可用,请稍后重试')
|
||||
secret = settings.PMS_PLAN_WRITE_KEY
|
||||
if method != 'GET' and not secret:
|
||||
raise ValueError('添加功能尚未启用,请联系管理员')
|
||||
path = '/plan/user-candidates'
|
||||
if query is not None:
|
||||
path += '/search'
|
||||
if identity is not None:
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', str(identity)):
|
||||
raise ValueError('添加记录无效,请刷新后重试')
|
||||
path += '/' + identity + '/remove'
|
||||
body = {k: (payload or {}).get(k) for k in ('codes', 'reason', 'expires_on')}
|
||||
body['actor'] = actor
|
||||
try:
|
||||
response = requests.request(method, base + path,
|
||||
json=body if method != 'GET' else None,
|
||||
headers={'X-Job-Key': secret} if method != 'GET' else {},
|
||||
params={'q': str(query)[:40]} if query is not None else None,
|
||||
timeout=15, allow_redirects=False)
|
||||
except requests.RequestException as exc:
|
||||
raise ValueError('选股系统暂未回应,请刷新列表核对后再试') from None
|
||||
if response.status_code in (404, 405):
|
||||
raise ValueError('选股系统暂不支持添加,请联系管理员完成更新')
|
||||
if response.status_code in (401, 403, 503):
|
||||
raise ValueError('选股系统暂不能处理添加,请联系管理员检查连接')
|
||||
if response.status_code != 200:
|
||||
if response.status_code == 400:
|
||||
detail = response.json().get('detail')
|
||||
if isinstance(detail, str):
|
||||
raise ValueError(detail[:300])
|
||||
raise ValueError('操作未完成,请刷新列表核对后再试')
|
||||
try:
|
||||
result = response.json()
|
||||
except ValueError:
|
||||
raise ValueError('选股系统返回异常,请稍后重试') from None
|
||||
if not isinstance(result, dict) or result.get('ok') is not True:
|
||||
raise ValueError('操作未完成,请刷新列表核对后再试')
|
||||
if method != 'GET':
|
||||
plan_feed.invalidate()
|
||||
from app.services import monitor_watch
|
||||
result['monitor_sync'] = monitor_watch.sync()
|
||||
return dict(result, writable=bool(secret))
|
||||
|
|
@ -343,6 +343,8 @@ def _rows(raw, bucket: str) -> list:
|
|||
"research_rank": _int_or_none(it.get('research_rank')),
|
||||
"research": it.get('research') if isinstance(it.get('research'), dict) else None,
|
||||
"review_ref": _text_or_none(it.get('review_ref')),
|
||||
'user_candidate': it.get('user_candidate') if isinstance(it.get('user_candidate'), dict) else None,
|
||||
'user_required': bool(it.get('user_required')),
|
||||
})
|
||||
return out
|
||||
|
||||
|
|
@ -496,6 +498,9 @@ def select_candidates(plan: dict, *, held=(), black=(), top_n: int = 30, tiers=N
|
|||
规则闸按 PMS_SECTOR_MAX_NAMES 一拦就剩 4 只, 白瞎 26 个名额且**日志上看不出来**。
|
||||
在候选阶段先按主题摊开, top_n 切出来的才是能用的票。
|
||||
"""
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
today = datetime.now(ZoneInfo('Asia/Shanghai')).date().isoformat()
|
||||
held = {normalize_code(c) for c in (held or []) if c}
|
||||
black = {normalize_code(c) for c in (black or []) if c}
|
||||
tiers = {str(t).strip() for t in (tiers or []) if str(t).strip()}
|
||||
|
|
@ -541,6 +546,10 @@ def select_candidates(plan: dict, *, held=(), black=(), top_n: int = 30, tiers=N
|
|||
drop('dup', c)
|
||||
continue
|
||||
seen.add(c)
|
||||
if r.get('user_required') and str((r.get('user_candidate') or {}).get('expires_on') or '') < today:
|
||||
drop('display', c)
|
||||
display_only.append({'ts_code': c, 'basis': '用户关注已到期'})
|
||||
continue
|
||||
if c in held:
|
||||
drop('held', c)
|
||||
continue
|
||||
|
|
@ -609,7 +618,7 @@ def select_candidates(plan: dict, *, held=(), black=(), top_n: int = 30, tiers=N
|
|||
# 排序轴四键 (2026-09-17 工作包乙): 原样透传给动作引擎与提议卡, 缺就是 None。
|
||||
"quality_band": r.get("quality_band"), "pointed": r.get("pointed"),
|
||||
"rank_axis": r.get("rank_axis"), "rank_old": r.get("rank_old"),
|
||||
**{k: r.get(k) for k in ('research_rank', 'research', 'review_ref')}}
|
||||
**{k: r.get(k) for k in ('research_rank', 'research', 'review_ref', 'user_candidate', 'user_required')}}
|
||||
for r in passed[:n]]
|
||||
for i, item in enumerate(items, 1):
|
||||
item.update(selection_rank=i, decision=plan.get('decision'),
|
||||
|
|
@ -696,10 +705,12 @@ def build_query(p: dict) -> dict:
|
|||
已经知道签名了, 走各自的显式参数 —— 同一件事有两个入口的时候, 得有个明确的赢家。
|
||||
"""
|
||||
q = dict(p.get("query_extra") or {})
|
||||
for key, name in (("top", "top"), ("obs_top", "obs_top"), ("theme_cap", "theme_cap")):
|
||||
for key, name in (("top", "top"), ("obs_top", "obs_top")):
|
||||
v = int(p.get(key) or 0)
|
||||
if v > 0:
|
||||
q[name] = str(v) # 0 = 不传该参数, 用上游默认
|
||||
# 上游明确以 0 表示不设主题限额;省略会重新启用默认的每主题 5 只。
|
||||
q["theme_cap"] = str(int(p.get("theme_cap") or 0))
|
||||
return q
|
||||
|
||||
|
||||
|
|
@ -777,6 +788,7 @@ def fetch(*, date=None, base=None, path=None, timeout=None, extra_params=None) -
|
|||
url = base + path
|
||||
to = int(timeout or 10)
|
||||
q = dict(extra_params or {})
|
||||
q['include_user_candidates'] = 1 # 新版 PMS 明确支持人工来源及其失效核验。
|
||||
if date:
|
||||
q["date"] = date # date 是我们自己的语义, 不许被 extra 覆盖
|
||||
try:
|
||||
|
|
@ -912,7 +924,7 @@ def read_current_plan(*, code=None):
|
|||
import requests
|
||||
try:
|
||||
r = requests.get(p['base'].rstrip('/') + '/' + p['path'].strip('/') + '/check',
|
||||
params={'code': code}, timeout=(1, min(3, max(1, p['timeout']))))
|
||||
params={'code': code, 'include_user_candidates': 1}, timeout=(1, min(3, max(1, p['timeout']))))
|
||||
r.raise_for_status()
|
||||
payload = r.json()
|
||||
if (not isinstance(payload, dict) or normalize_code(payload.get('check_code')) != code
|
||||
|
|
@ -1177,7 +1189,7 @@ def snapshot_log(*, plan_date=None, limit: int = 50) -> dict:
|
|||
|
||||
# ================================================================ 对外: 候选与状态
|
||||
def candidates(*, held=(), black=(), route_by_verdict: bool = False, force=False,
|
||||
record=True, recheck_code=None, plan_override=None) -> dict:
|
||||
record=True, recheck_code=None, plan_override=None, allow_user=True) -> dict:
|
||||
"""参数驱动的候选清单 (不含价格 —— 价格由调用方用 market.get_price 现取)。
|
||||
|
||||
route_by_verdict 默认 False: 命令驱动建仓 (command_service._candidates) 不传, 于是用户
|
||||
|
|
@ -1189,6 +1201,8 @@ def candidates(*, held=(), black=(), route_by_verdict: bool = False, force=False
|
|||
p = _params()
|
||||
plan = plan_override if plan_override is not None else (get_plan(force=force) if force else get_plan())
|
||||
route = bool(route_by_verdict)
|
||||
if not allow_user:
|
||||
plan = dict(plan, **{b: [r for r in plan.get(b, []) if not r.get('user_required')] for b in ('main', 'observe')})
|
||||
out = select_candidates(plan, held=held, black=black, top_n=0 if recheck_code else p["top_n"], tiers=p["tiers"],
|
||||
include_observe=p["include_observe"],
|
||||
min_score=(p["min_score"] or None),
|
||||
|
|
|
|||
|
|
@ -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):
|
||||
|
|
@ -269,6 +271,8 @@ def refresh_one(p, *, now=None, deadline=None):
|
|||
td.ymd() < param_store.get_int('PMS_BRAKE_UNTIL', 0), now, True, out,
|
||||
review_only=True, deadline=deadline, prepared_verdict=verdict)
|
||||
if not result:
|
||||
if any(r.get('by') == 'judge_pending' for r in out.get('skipped', [])):
|
||||
return _pending_response(p, '研究更新已登记,等待研判结果', 'judge_pending')
|
||||
return _failed_recheck(p, out)
|
||||
hn = c['hard_numbers']
|
||||
hn.update({k:hard[k] for k in ('requested_by','requested_at') if k in hard})
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import json
|
|||
import logging
|
||||
|
||||
from app.core import cushion as cu
|
||||
from app.core import strategy_book as books
|
||||
from app.core import ws_codec as wsc
|
||||
from app.repo import pms_repo, qmt_repo
|
||||
from app.services import industry, market, param_store
|
||||
|
|
@ -24,6 +25,46 @@ NEG_STREAK_KEY = "PMS_CUSHION_NEG_STREAK"
|
|||
CASH_WS, CASH_EST = "ws", "estimate"
|
||||
|
||||
|
||||
def position_groups(original_view: dict) -> list:
|
||||
"""页面按策略展示;保留主观量化快照和交易计算的默认范围。"""
|
||||
from config.settings import settings
|
||||
|
||||
def group(book, name, view, *, ready=True):
|
||||
rows = [{**r, "book_id": book} for r in view.get("positions", [])]
|
||||
held = [r for r in rows if r["total_qty"] > 0]
|
||||
totals = view.get("totals", {})
|
||||
missing = view.get("price_missing", [])
|
||||
return {"book_id": book, "name": name, "positions": rows, "held": held,
|
||||
"ready": ready, "price_missing": missing,
|
||||
"totals": {"names_count": len(held),
|
||||
"market_value": totals.get("portfolio_mv", 0) if ready else None,
|
||||
"pnl": totals.get("float_pnl", 0) if ready and not missing else None}}
|
||||
|
||||
result = [group(books.ORIGINAL, "主观量化", original_view)]
|
||||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
result.append(group(books.MICRO, "微盘轮动", {}))
|
||||
return result
|
||||
try:
|
||||
with books.scope(books.MICRO):
|
||||
micro = positions_view()
|
||||
result.append(group(books.MICRO, "微盘轮动", micro))
|
||||
except Exception:
|
||||
logger.exception("微盘持仓读取失败")
|
||||
result.append(group(books.MICRO, "微盘轮动", {}, ready=False))
|
||||
return result
|
||||
|
||||
|
||||
def position_lots(ts_code: str, book_id: str, status: str | None) -> list:
|
||||
"""同名股票按策略查看批次;旧表未迁移时微盘必须为空。"""
|
||||
from config.settings import settings
|
||||
if book_id not in (books.ORIGINAL, books.MICRO):
|
||||
raise ValueError("未知策略")
|
||||
if book_id == books.MICRO and not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
return []
|
||||
with books.scope(book_id):
|
||||
return pms_repo.list_lots(ts_code, status=status)
|
||||
|
||||
|
||||
def cash_view() -> dict:
|
||||
"""真实可用资金 (ws 资金快照 §5.7 kind=funds)。取不到则回落估算并**标明是估的**。
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,250 @@
|
|||
"""155模拟实例的独立限制价采集;不调用交易、研判或QMT动作。"""
|
||||
import copy
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from config.settings import settings
|
||||
from app.core import price_limits as core, tradedays
|
||||
from app.core.execution_policy import local_now, timestamp
|
||||
from app.db import session as db
|
||||
from app.repo import rotation_repo as store
|
||||
from app.services import param_store, price_limit_targets, price_limit_provider
|
||||
from app.services.price_limits import day_key
|
||||
|
||||
LEASE_KEY = 'price-limits:collector'
|
||||
LEASE_SECONDS = 300
|
||||
TARGET_CAP = 1200
|
||||
|
||||
|
||||
def _summary(status, day, targets=(), entries=None, errors=(), requests=0):
|
||||
entries = entries or {}
|
||||
errors = list(errors) + [c+': '+entries[c]['last_error'] for c in targets
|
||||
if entries.get(c, {}).get('last_error')]
|
||||
valid = sum(entries.get(c, {}).get('status') == 'VALID' for c in targets)
|
||||
return {'status': status, 'day': day, 'target_count': len(targets),
|
||||
'valid_count': valid, 'missing_count': len(targets)-valid,
|
||||
'error_count': len(errors), 'errors': list(errors), 'requests': requests}
|
||||
|
||||
|
||||
def _acquire(owner, now):
|
||||
with store.locked(LEASE_KEY, 'price_limit_lease', {}) as lease:
|
||||
until = timestamp(lease.get('until'))
|
||||
if until and until > now:
|
||||
return False
|
||||
lease.update(owner=owner, until=(now+timedelta(seconds=LEASE_SECONDS)).isoformat())
|
||||
return True
|
||||
|
||||
|
||||
def _release(owner):
|
||||
with store.locked(LEASE_KEY, 'price_limit_lease', {}) as lease:
|
||||
if lease.get('owner') == owner:
|
||||
lease.pop('owner', None)
|
||||
lease.pop('until', None)
|
||||
|
||||
|
||||
def _save(owner, document, now):
|
||||
# 租约锁与缓存锁同一事务;不把HTTP或目标读取放进事务。
|
||||
with store.locked(LEASE_KEY, 'price_limit_lease', {}) as lease:
|
||||
until = timestamp(lease.get('until'))
|
||||
if lease.get('owner') != owner or not until or now >= until:
|
||||
return False
|
||||
with store.locked(day_key(document['trade_date']), 'price_limits', {}) as value:
|
||||
value.clear()
|
||||
value.update(document)
|
||||
return True
|
||||
|
||||
|
||||
def _config():
|
||||
p = param_store
|
||||
return {'timeout': p.get_int('PMS_LIMIT_FETCH_TIMEOUT_SEC', 5),
|
||||
'budget': p.get_int('PMS_LIMIT_ROUND_BUDGET_SEC', 30),
|
||||
'max_codes': p.get_int('PMS_LIMIT_ROUND_MAX_CODES', 25),
|
||||
'interval': p.get_float('PMS_LIMIT_MIN_REQUEST_INTERVAL_SEC', 1.2),
|
||||
'retry_base': p.get_int('PMS_LIMIT_RETRY_BASE_SEC', 60),
|
||||
'retry_max': p.get_int('PMS_LIMIT_RETRY_MAX_SEC', 900),
|
||||
'max_failures': p.get_int('PMS_LIMIT_MAX_FAILURES_PER_DAY', 32),
|
||||
'refresh': p.get_int('PMS_LIMIT_REFRESH_SEC', 900)}
|
||||
|
||||
|
||||
def _failure(entry, reason, now, cfg, quarantine=False):
|
||||
# 连接故障保留此前有效内容与原获取时间;确切坏值才撤销可执行资格。
|
||||
entry['failures'] = min(100, int(entry.get('failures') or 0)+1)
|
||||
entry['last_attempt'] = now.isoformat()
|
||||
entry['last_error'] = reason
|
||||
wait = min(cfg['retry_max'], cfg['retry_base'] * (2 ** min(entry['failures']-1, 10)))
|
||||
entry['next_try'] = (now+timedelta(seconds=wait)).isoformat()
|
||||
if quarantine or entry.get('status') != 'VALID':
|
||||
entry['status'] = 'INVALID' if quarantine else 'MISSING'
|
||||
|
||||
|
||||
def _accept(entry, record, source, now, cfg):
|
||||
old = entry.get('record') or {}
|
||||
if old and old.get('version') != record['version']:
|
||||
history = entry.setdefault('revisions', [])
|
||||
history.append({'record': old, 'source': entry.get('source'),
|
||||
'fetched_at': entry.get('fetched_at'), 'superseded_at': now.isoformat()})
|
||||
entry['revisions'] = history[-5:]
|
||||
entry.update(status='VALID', record=record, source=source, fetched_at=now.isoformat(),
|
||||
last_attempt=now.isoformat(), last_error='', failures=0,
|
||||
next_try=(now+timedelta(seconds=cfg['refresh'])).isoformat())
|
||||
|
||||
|
||||
def _shared_rows(day, codes):
|
||||
if not codes:
|
||||
return []
|
||||
params = {'day': day}
|
||||
params.update({f'c{i}': c for i, c in enumerate(codes)})
|
||||
names = ','.join(':'+k for k in params if k != 'day')
|
||||
return db.fetch_all('SELECT ts_code,trade_date,pre_close,up_limit,down_limit FROM gp_stk_limit '
|
||||
'WHERE trade_date=:day AND ts_code IN ('+names+')', params)
|
||||
|
||||
|
||||
def _reserve_request(owner, now, interval):
|
||||
"""持久化限速水位;重建进程也不会立刻重复请求。"""
|
||||
with store.locked(LEASE_KEY, 'price_limit_lease', {}) as lease:
|
||||
until = timestamp(lease.get('until'))
|
||||
if lease.get('owner') != owner or not until or now >= until:
|
||||
return None
|
||||
last = timestamp(lease.get('next_request_at'))
|
||||
if last and last > now:
|
||||
return (last-now).total_seconds()
|
||||
lease['next_request_at'] = (now+timedelta(seconds=interval)).isoformat()
|
||||
return 0.0
|
||||
|
||||
|
||||
def run_once(now=None):
|
||||
"""只采集实际北京日;now仅供隔离测试注入时钟,无历史补数入口。"""
|
||||
current = local_now(now)
|
||||
day = current.date().isoformat()
|
||||
if settings.PMS_TABLE_PREFIX:
|
||||
return _summary('UNAUTHORIZED_INSTANCE', day)
|
||||
if not param_store.get_bool('PMS_LIMIT_COLLECT_ENABLED', False):
|
||||
return _summary('DISABLED', day)
|
||||
if tradedays.calendar_degraded(current.date()) or not tradedays.is_trade_day(current.date()):
|
||||
return _summary('CALENDAR_WAIT', day)
|
||||
try:
|
||||
start = datetime.strptime(param_store.get('PMS_LIMIT_COLLECT_START', '08:55'), '%H:%M').time()
|
||||
end = datetime.strptime(param_store.get('PMS_LIMIT_COLLECT_END', '18:00'), '%H:%M').time()
|
||||
except (TypeError, ValueError):
|
||||
return _summary('INVALID_WINDOW', day)
|
||||
if not start <= current.time().replace(tzinfo=None) <= end:
|
||||
return _summary('OUTSIDE_WINDOW', day)
|
||||
owner = uuid.uuid4().hex
|
||||
if not _acquire(owner, current):
|
||||
return _summary('BUSY', day)
|
||||
started = time.monotonic()
|
||||
# 实际墙钟由单调时钟增量推进,测试也能准确覆盖跨日、租约和超时。
|
||||
clock = lambda: current+timedelta(seconds=time.monotonic()-started)
|
||||
try:
|
||||
cfg = _config()
|
||||
if not (1 <= cfg['timeout'] <= 10 and 5 <= cfg['budget'] <= 60 and
|
||||
1 <= cfg['max_codes'] <= 60 and 1 <= cfg['interval'] <= 10 and
|
||||
30 <= cfg['retry_base'] <= 600 and cfg['retry_base'] <= cfg['retry_max'] <= 3600 and
|
||||
1 <= cfg['max_failures'] <= 100 and 300 <= cfg['refresh'] <= 7200):
|
||||
return _summary('INVALID_CONFIG', day)
|
||||
target_info = price_limit_targets.collect_targets(day)
|
||||
all_codes = sorted({c for c in target_info['codes'] if core.supported(c)})
|
||||
codes, errors = all_codes[:TARGET_CAP], list(target_info['errors'])
|
||||
if len(all_codes) > TARGET_CAP:
|
||||
errors.append('采集目标超过1200只,未覆盖部分保持等待')
|
||||
previous, _ = store.get(day_key(day))
|
||||
document = copy.deepcopy(previous) if isinstance(previous, dict) and previous.get('trade_date') == day else {}
|
||||
document.update(trade_date=day, schema_version=1, targets=codes,
|
||||
target_sources={c: target_info['sources'].get(c, []) for c in codes})
|
||||
entries = document.get('entries')
|
||||
if not isinstance(entries, dict):
|
||||
entries = document['entries'] = {}
|
||||
# 再校验已存值,损坏或异日内容不能靠VALID标记继续使用。
|
||||
for code, entry in list(entries.items()):
|
||||
if not core.supported(code) or not isinstance(entry, dict):
|
||||
entries.pop(code, None)
|
||||
continue
|
||||
if type(entry.get('failures')) is not int or not 0 <= entry['failures'] <= 100:
|
||||
entry['failures'] = 0
|
||||
for field in ('next_try', 'last_attempt'):
|
||||
stamp = timestamp(entry.get(field))
|
||||
if not stamp or stamp.date().isoformat() != day:
|
||||
entry.pop(field, None)
|
||||
else:
|
||||
entry[field] = stamp.isoformat()
|
||||
if not isinstance(entry.get('revisions'), list):
|
||||
entry['revisions'] = []
|
||||
for field in ('last_error', 'shared_invalid_reason'):
|
||||
reason = entry.get(field)
|
||||
if reason and (not isinstance(reason, str) or not re.fullmatch('[A-Z_]{1,64}', reason)):
|
||||
entry[field] = 'CACHE_META_INVALID'
|
||||
if entry.get('status') == 'VALID':
|
||||
checked = core.normalize_rows([entry.get('record')], day, [code])['records'].get(code)
|
||||
if (not checked or checked['version'] != (entry.get('record') or {}).get('version')
|
||||
or entry.get('source') not in ('gp_stk_limit', 'tushare.stk_limit')):
|
||||
entry.update(status='INVALID', last_error='CACHE_INVALID', next_try=current.isoformat())
|
||||
for code in codes:
|
||||
entries.setdefault(code, {'status': 'MISSING', 'failures': 0})
|
||||
try:
|
||||
shared = core.normalize_rows(_shared_rows(day, codes), day, codes) if codes else {'records': {}, 'invalid': {}, 'errors': []}
|
||||
errors.extend(shared['errors'])
|
||||
for code, record in shared['records'].items():
|
||||
entry = entries[code]
|
||||
if entry.get('source') == 'tushare.stk_limit':
|
||||
continue
|
||||
if entry.get('status') != 'VALID' or (entry.get('record') or {}).get('version') != record['version']:
|
||||
_accept(entry, record, 'gp_stk_limit', clock(), cfg)
|
||||
entry.pop('shared_invalid_reason', None)
|
||||
for code, reason in shared['invalid'].items():
|
||||
if code in entries and entries[code].get('source') != 'tushare.stk_limit':
|
||||
entry = entries[code]
|
||||
# 相同坏值不在每轮重置退避;第一次仍允许直接向Tushare补齐。
|
||||
if entry.get('shared_invalid_reason') != reason:
|
||||
entry.update(status='INVALID', last_error=reason, next_try=current.isoformat())
|
||||
entry['shared_invalid_reason'] = reason
|
||||
except Exception:
|
||||
errors.append('共享限制价读取失败')
|
||||
# 没有采到过的票先查,避免前排失败长时间挤占后排。每票退避独立。
|
||||
due = [c for c in codes if int(entries[c].get('failures') or 0) < cfg['max_failures']
|
||||
and (timestamp(entries[c].get('next_try')) or current) <= clock()]
|
||||
due.sort(key=lambda c: (entries[c].get('status') == 'VALID', entries[c].get('last_attempt') or '', c))
|
||||
deadline = time.monotonic()+cfg['budget']
|
||||
count = 0
|
||||
if not settings.PMS_TUSHARE_TOKEN and due:
|
||||
errors.append('采集密钥未配置')
|
||||
else:
|
||||
for code in due:
|
||||
left = deadline-time.monotonic()
|
||||
if count >= cfg['max_codes'] or left < 1 or clock().date().isoformat() != day:
|
||||
break
|
||||
delay = _reserve_request(owner, clock(), cfg['interval'])
|
||||
if delay is None:
|
||||
return _summary('LEASE_LOST', day, codes, entries, errors, count)
|
||||
if delay:
|
||||
if delay+1 > left:
|
||||
break
|
||||
time.sleep(delay)
|
||||
delay = _reserve_request(owner, clock(), cfg['interval'])
|
||||
if delay is None or delay > 0:
|
||||
break
|
||||
result = price_limit_provider.fetch_limit(code, day, settings.PMS_TUSHARE_TOKEN,
|
||||
timeout_sec=min(cfg['timeout'], max(1, deadline-time.monotonic())))
|
||||
count += 1
|
||||
at = clock()
|
||||
if at.date().isoformat() != day or time.monotonic() > deadline:
|
||||
_failure(entries[code], 'ROUND_TIMEOUT', at, cfg)
|
||||
errors.append('本轮采集超时,迟到响应未采纳')
|
||||
break
|
||||
entry = entries[code]
|
||||
if code in result['records']:
|
||||
_accept(entry, result['records'][code], 'tushare.stk_limit', at, cfg)
|
||||
else:
|
||||
invalid = result.get('invalid') or {}
|
||||
reason = invalid.get(code) or (result['errors'][0] if result['errors'] else ('UNEXPECTED_SECURITY' if invalid else 'NOT_PUBLISHED'))
|
||||
_failure(entry, reason, at, cfg, quarantine=bool(invalid))
|
||||
end_at = clock()
|
||||
summary = _summary('COMPLETE' if not errors and all(entries[c].get('status') == 'VALID' and not entries[c].get('last_error') for c in codes) else 'PARTIAL',
|
||||
day, codes, entries, errors, count)
|
||||
document.update(last_round_at=end_at.isoformat(), last_summary=summary)
|
||||
if end_at.date().isoformat() != day or not _save(owner, document, end_at):
|
||||
return _summary('LEASE_LOST', day, codes, entries, errors, count)
|
||||
return summary
|
||||
finally:
|
||||
_release(owner)
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
"""单证券限制价主源。只访问固定地址,不重试、不输出凭据或响应正文。
|
||||
|
||||
Timeout.total 限定一次 HTTP 连接/读取的超时预算;流式读取还会检查单调时钟。
|
||||
DNS 解析及两次流块之间的阻塞不保证被总预算中断,因此这不是绝对墙钟期限。
|
||||
整轮预算、重试和退避由采集任务负责,执行报价路径只读本地缓存。
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
|
||||
import requests
|
||||
from urllib3.exceptions import TimeoutError as TransportTimeout
|
||||
from urllib3.util import Timeout
|
||||
|
||||
from app.core import price_limits
|
||||
|
||||
ENDPOINT = 'https://api.tushare.pro'
|
||||
FIELDS = 'ts_code,trade_date,pre_close,up_limit,down_limit'
|
||||
MAX_BODY_BYTES = 64 * 1024
|
||||
|
||||
|
||||
def _error(reason):
|
||||
return {'records': {}, 'invalid': {}, 'errors': [reason]}
|
||||
|
||||
|
||||
def fetch_limit(code, day, token, timeout_sec=5):
|
||||
"""查询指定交易日的一只沪深证券;所有失败仅返回固定原因码。"""
|
||||
if not price_limits.supported(code):
|
||||
return _error('INVALID_REQUEST_CODE')
|
||||
code = code.strip().upper()
|
||||
try:
|
||||
target = price_limits._day(day)
|
||||
except (TypeError, ValueError):
|
||||
return _error('INVALID_TARGET_DATE')
|
||||
if not isinstance(token, str) or not token.strip():
|
||||
return _error('MISSING_PROVIDER_TOKEN')
|
||||
if isinstance(timeout_sec, bool):
|
||||
return _error('INVALID_HTTP_TIMEOUT')
|
||||
try:
|
||||
budget = float(timeout_sec)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return _error('INVALID_HTTP_TIMEOUT')
|
||||
if not math.isfinite(budget) or budget <= 0:
|
||||
return _error('INVALID_HTTP_TIMEOUT')
|
||||
|
||||
session = response = None
|
||||
deadline = time.monotonic() + budget
|
||||
try:
|
||||
session = requests.Session()
|
||||
# 不读取环境代理、.netrc 或环境 CA 设置,凭据只发往固定 HTTPS 地址。
|
||||
session.trust_env = False
|
||||
response = session.post(ENDPOINT, json={
|
||||
'api_name': 'stk_limit', 'token': token.strip(),
|
||||
'params': {'ts_code': code, 'trade_date': target.replace('-', '')},
|
||||
'fields': FIELDS,
|
||||
}, headers={'Accept': 'application/json', 'Accept-Encoding': 'identity'},
|
||||
allow_redirects=False, stream=True,
|
||||
timeout=Timeout(total=budget, connect=min(2., budget), read=budget))
|
||||
if time.monotonic() >= deadline:
|
||||
return _error('HTTP_TIMEOUT')
|
||||
if response.status_code != 200:
|
||||
return _error('HTTP_ERROR')
|
||||
declared = response.headers.get('Content-Length')
|
||||
if declared is not None:
|
||||
try:
|
||||
length = int(declared)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return _error('INVALID_PROVIDER_RESPONSE')
|
||||
if length < 0:
|
||||
return _error('INVALID_PROVIDER_RESPONSE')
|
||||
if length > MAX_BODY_BYTES:
|
||||
return _error('RESPONSE_TOO_LARGE')
|
||||
body = bytearray()
|
||||
for chunk in response.iter_content(chunk_size=4096):
|
||||
if time.monotonic() >= deadline:
|
||||
return _error('HTTP_TIMEOUT')
|
||||
if not isinstance(chunk, bytes):
|
||||
return _error('INVALID_PROVIDER_RESPONSE')
|
||||
if len(body) + len(chunk) > MAX_BODY_BYTES:
|
||||
return _error('RESPONSE_TOO_LARGE')
|
||||
body.extend(chunk)
|
||||
if time.monotonic() >= deadline:
|
||||
return _error('HTTP_TIMEOUT')
|
||||
try:
|
||||
decoded = json.loads(body)
|
||||
# 永远传非空单代码白名单,不能借空集合放开到全市场。
|
||||
result = price_limits.provider_decode(decoded, target, requested_codes=[code])
|
||||
except Exception:
|
||||
return _error('INVALID_PROVIDER_RESPONSE')
|
||||
if time.monotonic() >= deadline:
|
||||
return _error('HTTP_TIMEOUT')
|
||||
return result
|
||||
except (requests.exceptions.Timeout, TransportTimeout):
|
||||
return _error('HTTP_TIMEOUT')
|
||||
except requests.exceptions.ConnectionError as exc:
|
||||
# requests 的流式读取会把 urllib3 读超时包装成 ConnectionError。
|
||||
if any(isinstance(cause, TransportTimeout) for cause in exc.args):
|
||||
return _error('HTTP_TIMEOUT')
|
||||
return _error('HTTP_ERROR')
|
||||
except Exception:
|
||||
# Requests 异常可包含URL、请求信息或上游正文,禁止回显和记完整日志。
|
||||
return _error('HTTP_ERROR')
|
||||
finally:
|
||||
for resource in (response, session):
|
||||
if resource is not None:
|
||||
try:
|
||||
resource.close()
|
||||
except Exception:
|
||||
pass # 清理异常不覆盖固定错误结果,也不输出潜在凭据。
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
"""独立采集进程的限制价目标清单。只读资料,不授权交易或写入业务状态。
|
||||
|
||||
监控读取复用 rotation_service.pull,HTTP 连接和读取超时分别为 3、15 秒。
|
||||
本函数不得在下单事务或账户锁内调用。未冻结快照只用于预取限制价,
|
||||
实际轮换仍须执行原有的冻结、信号、资金和权限校验。
|
||||
"""
|
||||
import datetime as dt
|
||||
import re
|
||||
|
||||
from app.core import micro_rotation, strategy_book as books
|
||||
from app.repo import pms_repo, qmt_repo, rotation_repo
|
||||
from app.services import rotation_service
|
||||
|
||||
|
||||
SOURCE_CAP = 5000
|
||||
# 仓储 recent 自身最多返回 1000 行,不能按 5000 行误判为读取完整。
|
||||
SNAPSHOT_CAP = 1000
|
||||
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
||||
|
||||
|
||||
def collect_targets(day):
|
||||
"""返回证券、逐来源错误和来源名;一个来源失败不丢弃其他已知证券。"""
|
||||
day = day.isoformat() if isinstance(day, dt.date) and not isinstance(day, dt.datetime) else day
|
||||
try:
|
||||
if not isinstance(day, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
|
||||
raise ValueError('date')
|
||||
dt.date.fromisoformat(day)
|
||||
except (TypeError, ValueError):
|
||||
return {'codes': [], 'errors': ['目标交易日格式无效'], 'sources': {}}
|
||||
|
||||
sources, errors = {}, []
|
||||
|
||||
def error(reason):
|
||||
if reason not in errors:
|
||||
errors.append(reason)
|
||||
|
||||
def add(code, name):
|
||||
code = code.strip().upper() if isinstance(code, str) else ''
|
||||
if micro_rotation.mainland_code(code):
|
||||
sources.setdefault(code, set()).add(name)
|
||||
|
||||
def read(name, loader, cap=SOURCE_CAP):
|
||||
try:
|
||||
rows = loader()
|
||||
except Exception:
|
||||
error(name+'读取失败')
|
||||
return []
|
||||
if not isinstance(rows, list):
|
||||
error(name+'记录格式异常')
|
||||
return []
|
||||
if len(rows) >= cap:
|
||||
error(name+'达到读取上限,结果可能不完整')
|
||||
return rows[:cap]
|
||||
|
||||
with books.scope('all'):
|
||||
loaders = (
|
||||
('策略持仓', lambda: pms_repo.list_positions(only_open=True)),
|
||||
('待执行指令', lambda: pms_repo.list_instructions(statuses=LIVE, limit=SOURCE_CAP)),
|
||||
('QMT在途委托', lambda: qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=SOURCE_CAP)),
|
||||
('执行计划', lambda: pms_repo.list_plans(statuses=('PENDING', 'GATED', 'EXECUTING'), limit=SOURCE_CAP)),
|
||||
('交易建议', lambda: pms_repo.list_proposals(statuses=('WAIT_USER', 'ACCEPTED'), limit=SOURCE_CAP)),
|
||||
)
|
||||
for name, loader in loaders:
|
||||
for row in read(name, loader):
|
||||
if not isinstance(row, dict) or 'ts_code' not in row:
|
||||
error(name+'记录格式异常')
|
||||
continue
|
||||
add(row['ts_code'], name)
|
||||
|
||||
try:
|
||||
state, _ = rotation_repo.get('state:live')
|
||||
rotation = (state or {}).get('rotation') or {}
|
||||
targets = rotation.get('target') or []
|
||||
if not isinstance(targets, list):
|
||||
raise ValueError('target')
|
||||
if len(targets) >= SOURCE_CAP:
|
||||
error('微盘执行目标达到读取上限,结果可能不完整')
|
||||
for code in targets[:SOURCE_CAP]:
|
||||
add(code, '微盘执行目标')
|
||||
except Exception:
|
||||
error('微盘执行目标读取失败')
|
||||
|
||||
try:
|
||||
config = rotation_service.configuration()
|
||||
rule = config['rule_version']
|
||||
pool_size = config.get('candidate_pool_size', 100)
|
||||
micro_rotation.rule_parameters(rule, pool_size)
|
||||
except Exception:
|
||||
error('微盘运行规则读取失败')
|
||||
config = None
|
||||
|
||||
def snapshot_codes(value, name):
|
||||
if not isinstance(value, dict):
|
||||
error(name+'记录格式异常')
|
||||
return
|
||||
# effective_date 是既有快照的执行日字段;历史日期和历史规则不参与本次采集。
|
||||
if value.get('effective_date') != day or value.get('rule_version') != rule:
|
||||
return
|
||||
try:
|
||||
issues = micro_rotation.snapshot_check(value, day, require_frozen=False,
|
||||
expected_rule=rule, candidate_pool_size=pool_size)
|
||||
except Exception:
|
||||
issues = ['invalid']
|
||||
if issues:
|
||||
error(name+'校验未通过')
|
||||
return
|
||||
if not value.get('basket_ready'):
|
||||
error(name+'名单尚未就绪')
|
||||
return
|
||||
members = value['candidates'] if rule == micro_rotation.EXECUTION_RULE else value['members']
|
||||
for member in members:
|
||||
add(member['code'], name)
|
||||
|
||||
if config is not None:
|
||||
for row in read('近期微盘快照', lambda: rotation_repo.recent('snapshot', limit=SNAPSHOT_CAP), SNAPSHOT_CAP):
|
||||
snapshot_codes(row.get('value') if isinstance(row, dict) else None, '微盘保存快照')
|
||||
if not config.get('url'):
|
||||
error('微盘监控地址未配置')
|
||||
else:
|
||||
try:
|
||||
value = rotation_service.pull(day)
|
||||
except Exception:
|
||||
error('微盘监控快照读取失败')
|
||||
else:
|
||||
if not isinstance(value, dict) or value.get('effective_date') != day or value.get('rule_version') != rule:
|
||||
error('微盘监控快照日期或规则不符')
|
||||
else:
|
||||
snapshot_codes(value, '微盘监控快照')
|
||||
|
||||
codes = sorted(sources)
|
||||
return {'codes': codes, 'errors': errors,
|
||||
'sources': {code: sorted(sources[code]) for code in codes}}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
"""执行限制价的本地只读入口,不调用外部行情接口。"""
|
||||
from app.core import price_limits as core
|
||||
from app.core.execution_policy import timestamp, local_now
|
||||
from app.db import session as db
|
||||
from app.repo import rotation_repo as store
|
||||
from app.services import param_store
|
||||
|
||||
SOURCES = ('gp_stk_limit', 'tushare.stk_limit')
|
||||
|
||||
|
||||
def day_key(day):
|
||||
return 'price-limits:' + core._day(day)
|
||||
|
||||
|
||||
def read_cache(day):
|
||||
"""坏缓存按无值处理;执行读取不更新缓存、不延长有效日期。"""
|
||||
target = core._day(day)
|
||||
value, _ = store.get(day_key(target))
|
||||
if not isinstance(value, dict) or value.get('trade_date') != target:
|
||||
return {}
|
||||
entries = value.get('entries')
|
||||
if not isinstance(entries, dict):
|
||||
return {}
|
||||
valid = {}
|
||||
for code, entry in entries.items():
|
||||
if not core.supported(code) or not isinstance(entry, dict):
|
||||
continue
|
||||
record = entry.get('record')
|
||||
if entry.get('status') != 'VALID' or entry.get('source') not in SOURCES or not entry.get('fetched_at'):
|
||||
continue
|
||||
fetched = timestamp(entry['fetched_at'])
|
||||
if not fetched or fetched.date().isoformat() != target or fetched > local_now():
|
||||
continue
|
||||
result = core.normalize_rows([record], target, [code])
|
||||
normalized = result['records'].get(code)
|
||||
if normalized and normalized['version'] == (record or {}).get('version'):
|
||||
valid[code] = dict(normalized, source=entry['source'], fetched_at=entry['fetched_at'])
|
||||
return valid
|
||||
|
||||
|
||||
def get_limits(day, codes=None):
|
||||
"""开关开启后只读本实例当日缓存;失败不混用其他日期或推算来源。"""
|
||||
day = core._day(day)
|
||||
wanted = None if codes is None else {str(c).strip().upper() for c in codes if core.supported(c)}
|
||||
if wanted == set():
|
||||
return {}
|
||||
if param_store.get_bool('PMS_LIMIT_CACHE_ENABLED', False):
|
||||
try:
|
||||
result = read_cache(day)
|
||||
except Exception:
|
||||
return {}
|
||||
return {c: r for c, r in result.items() if wanted is None or c in wanted}
|
||||
# 关闭新功能时保留原有数据路径,但在读取入口限定沪深证券。
|
||||
params = {'day': day}
|
||||
where = ''
|
||||
if wanted is not None:
|
||||
params.update({f'c{i}': c for i, c in enumerate(sorted(wanted))})
|
||||
where = ' AND ts_code IN (' + ','.join(':'+k for k in params if k != 'day') + ')'
|
||||
else:
|
||||
where = " AND (ts_code LIKE '60____.SH' OR ts_code LIKE '68____.SH' OR ts_code LIKE '00____.SZ' OR ts_code LIKE '30____.SZ')"
|
||||
rows = db.fetch_all('SELECT ts_code,up_limit,down_limit FROM gp_stk_limit WHERE trade_date=:day'+where, params)
|
||||
return {r['ts_code']: r for r in rows if core.supported(r.get('ts_code'))}
|
||||
|
|
@ -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,
|
||||
|
|
@ -129,6 +131,9 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict:
|
|||
_unlocked = reask_service.evaluate_all(_jk, now)
|
||||
except Exception as e:
|
||||
logger.warning("[新建仓] 解锁判定出错 (本轮当日闸照旧全挡): %s", e)
|
||||
if param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False):
|
||||
from app.services import judge_async
|
||||
_unlocked.update(judge_async.resumable_reasks(now))
|
||||
for _k in _unlocked:
|
||||
_jk.pop(_k, None)
|
||||
out["reask_unlocked"] = [{"ts_code": c, "action": a, "why": v.get("why"),
|
||||
|
|
@ -137,7 +142,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 +216,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}")
|
||||
|
|
@ -223,16 +232,42 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict:
|
|||
# 候选池发布给择时决策系统 (2026-09-09, 台账 004): 它的盘中强势扫描拿这份当覆盖面,
|
||||
# 读不到就本轮不扫、绝不回退全市场。这里只写代码不写别的; 写失败只记日志, 不影响本轮。
|
||||
# 落点选在候选产出之后、分流之前: 发布的是"今天该盯哪几只", 与它们最后买没买无关。
|
||||
if not dry_run and open_cands:
|
||||
monitor_codes = {x.get('ts_code') for x in open_cands}
|
||||
if not dry_run and monitor_codes:
|
||||
try:
|
||||
candidate_pub.publish([x.get("ts_code") for x in open_cands])
|
||||
candidate_pub.publish(monitor_codes)
|
||||
except Exception as e:
|
||||
logger.warning("[新建仓] 候选池发布失败 (不影响本轮): %s", e)
|
||||
|
||||
# 研判的时间预算从这一刻起算。**先跑已有持仓的四类, 再跑新建仓** —— 预算真用尽时,
|
||||
# 被推到下一跳的一定是新建仓, 已有持仓的动作行为与 2026-08-06 之前一致。
|
||||
deadline = time.monotonic() + max(
|
||||
0, param_store.get_int("PMS_JUDGE_TICK_BUDGET_SEC", 150))
|
||||
budget = (param_store.get_int('PMS_JUDGE_ASYNC_SCAN_BUDGET_SEC', 20)
|
||||
if param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False)
|
||||
else param_store.get_int('PMS_JUDGE_TICK_BUDGET_SEC', 150))
|
||||
deadline = time.monotonic() + max(0, budget)
|
||||
|
||||
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:
|
||||
|
|
@ -315,7 +350,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) 有意不同的两点:
|
||||
|
|
@ -358,6 +394,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 复用本函数, 页面「系统在盯的候选」
|
||||
# 由此显示「选股系统判为仅展示」而不是一个说不清的空白。
|
||||
|
|
@ -367,6 +405,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:
|
||||
|
|
@ -375,6 +419,9 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None,
|
|||
|
||||
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 为空会整段跳过, 行业集中度那道硬拦截就静默失效了。
|
||||
|
|
@ -397,12 +444,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"]
|
||||
|
|
@ -418,6 +467,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"已持有的票照常处理。"
|
||||
|
|
@ -541,6 +592,10 @@ def _attach_consensus(cands, out=None, now=None) -> None:
|
|||
codes = [c.get("ts_code") for c in cands if c.get("ts_code")]
|
||||
nightly = consensus_service.nightly_map(codes)
|
||||
tech_states = consensus_service.state_map()
|
||||
missing_user = [r['ts_code'] for r in cands if r.get('user_candidate') and r['ts_code'] not in tech_states]
|
||||
if missing_user:
|
||||
from app.services import tech_service
|
||||
tech_states = dict(tech_states, **tech_service.read_states_for(missing_user))
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("[合议] 批量取数失败, 本轮候选不装配合议: %s", e)
|
||||
return
|
||||
|
|
@ -610,7 +665,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 提议, 只算**尚未持有**
|
||||
|
|
@ -623,6 +678,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 ''),
|
||||
|
|
@ -635,6 +692,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),
|
||||
|
|
@ -889,9 +948,17 @@ def _route_one(c, view, params, stock_params, brake_active, now, dry_run, out,
|
|||
previous = None
|
||||
# 即使上一跳因版本变化放弃自动采纳,下一跳也不能复用该票旧批准的缓存。
|
||||
_force = _force or needs_new_judgement(c.get('hard_numbers') or {}, previous)
|
||||
if dry_run and not review_only and param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False):
|
||||
verdict = {'verdict': judge.UNAVAILABLE, 'degraded': True, 'confidence': None,
|
||||
'reason': '试算不登记异步研判,实际处理时再请求'}
|
||||
else:
|
||||
verdict = judge.request(c, context={"position": _judge_ctx(pos),
|
||||
"recent_ledger": _recent_ledger(code)},
|
||||
force=_force or bool(c.get('_plan_recheck')), reask_text=_rtext)
|
||||
if verdict.get('verdict') == 'PENDING':
|
||||
out['skipped'].append({'ts_code': code, 'action': action, 'by': 'judge_pending',
|
||||
'why': verdict['reason'], 'request': verdict.get('raw')})
|
||||
return
|
||||
# 新建仓的低把握驳回改交人 (2026-09-07, 第二道保险)。择时决策系统的提示词已改成
|
||||
# 「证据不足以判断 → 不可用」, 但模型未必每次守得住; 它给的把握度是现成的读数,
|
||||
# 低于阈值的驳回按「不可用」处理 —— 进人的待确认队列, 不记驳回、不杀提议。
|
||||
|
|
@ -1040,7 +1107,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(
|
||||
|
|
@ -1166,7 +1234,9 @@ def _judge_budget_left(deadline) -> bool:
|
|||
"""
|
||||
if deadline is None:
|
||||
return True
|
||||
need = max(1, param_store.get_int("PMS_JUDGE_TIMEOUT", 90))
|
||||
need = max(1, param_store.get_int('PMS_JUDGE_ASYNC_HTTP_TIMEOUT', 3)
|
||||
if param_store.get_bool('PMS_JUDGE_ASYNC_ENABLED', False)
|
||||
else param_store.get_int("PMS_JUDGE_TIMEOUT", 90))
|
||||
return (time.monotonic() + need) <= deadline
|
||||
|
||||
|
||||
|
|
@ -1659,7 +1729,7 @@ def _declined_today_keys() -> dict:
|
|||
return keys
|
||||
|
||||
|
||||
def _inflight_keys() -> dict:
|
||||
def _inflight_keys(exclude_instruction=None) -> dict:
|
||||
"""已有在途提议或在途指令的 {(代码, 动作): 原因} —— 同一件事不重复提。
|
||||
|
||||
提议与指令分开写原因, 并且**指令写在后面覆盖提议**: 一条提议被采纳之后会变成指令,
|
||||
|
|
@ -1679,14 +1749,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
|
||||
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@
|
|||
* 自然天数 = 起始日到截止日**含头含尾** (模板实测口径: 7-03 到 8-03 记 32 天)。
|
||||
|
||||
金额口径 (逐项对模板核过数):
|
||||
* 持仓行: 浮动盈亏 = (现价 − 成本) × 数量, **不含费** (模板 S 列与 Q×L 逐分一致)。
|
||||
* 持仓行: 浮动盈亏 = 市值 − 成本金额, **不含费**。均价保留计算精度、显示三位,
|
||||
金额按分舍入;不能先把均价舍入到三位再乘数量。
|
||||
* 平仓行: 盈亏 = 批次已实现盈亏 − **平仓当日该票的费用** (模板卖出行含费:
|
||||
Q×L 与 S 的差恰为双边费用)。费用取 pms_cash_flow 的 FEE 行按 (日期, 代码) 聚合;
|
||||
买入侧费用与无代码归属的校准费摊不进任何一行, 有此残差时在表尾如实标注金额 ——
|
||||
|
|
@ -44,6 +45,7 @@ import logging
|
|||
import os
|
||||
from copy import copy
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
|
||||
from app.repo import downstream_repo, pms_repo
|
||||
from app.services import market, param_store
|
||||
|
|
@ -58,6 +60,16 @@ TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__f
|
|||
# 1 标题 · 2 起始时间 · 3 更新时间 · 4 持仓表头 · 5 持仓样式行 · 6 持仓小计
|
||||
# 7 卖出表头 · 8 卖出样式行 · 9 卖出小计 · 10 存量合计行 · 11 底部指标行
|
||||
_R_HPROTO, _R_HSUB, _R_CHEAD, _R_CPROTO, _R_CSUB, _R_SUM1, _R_SUM2 = 5, 6, 7, 8, 9, 10, 11
|
||||
_ZERO = Decimal('0')
|
||||
|
||||
|
||||
def _decimal(value):
|
||||
return value if isinstance(value, Decimal) else Decimal(str(value or 0))
|
||||
|
||||
|
||||
def _money(value):
|
||||
"""与表格 ROUND(..., 2) 一致,半分远离零舍入;不用于原始均价。"""
|
||||
return _decimal(value).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 取数与口径
|
||||
|
|
@ -100,10 +112,11 @@ def _display_name(v, code: str) -> str:
|
|||
|
||||
|
||||
def _fee_map() -> dict:
|
||||
"""{(ymd, ts_code): 费用合计}。读不到按空 —— 费用缺席只影响平仓行含费口径,
|
||||
"""{(ymd, ts_code): 费用成本}:流出负现金流转为正费用,退款为负费用。
|
||||
读不到按空 —— 费用缺席只影响平仓行含费口径,
|
||||
表尾会把未摊费用标出来, 不拦导出。"""
|
||||
try:
|
||||
return {(int(r["ymd"]), r["ts_code"]): float(r["fee"] or 0)
|
||||
return {(int(r["ymd"]), r["ts_code"]): -_decimal(r["fee"])
|
||||
for r in pms_repo.fee_sum_by_code()}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("公示导出读费用失败 (平仓行按不含费出): %s", e)
|
||||
|
|
@ -111,6 +124,16 @@ def _fee_map() -> dict:
|
|||
|
||||
|
||||
def compute_snapshot() -> dict:
|
||||
# 公示净值属于全账户;策略归属启用后,不能只计默认的原策略。
|
||||
from config.settings import settings
|
||||
from app.core import strategy_book as books
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
with books.scope('all'):
|
||||
return _compute_snapshot()
|
||||
return _compute_snapshot()
|
||||
|
||||
|
||||
def _compute_snapshot() -> dict:
|
||||
"""组装公示快照: 持仓明细 / 平仓明细 / 汇总 / 当日净值。全部只读。"""
|
||||
today = date.today()
|
||||
scale = _nav_scale()
|
||||
|
|
@ -136,9 +159,9 @@ def compute_snapshot() -> dict:
|
|||
for r in open_lots:
|
||||
code = r["ts_code"]
|
||||
qty = int(r.get("qty") or 0)
|
||||
cost = float(r.get("open_price") or 0)
|
||||
cost = _decimal(r.get("open_price"))
|
||||
od = _as_date(r.get("open_date")) or today
|
||||
g = grp.setdefault(code, {"qty": 0, "amount": 0.0, "open_date": od})
|
||||
g = grp.setdefault(code, {"qty": 0, "amount": _ZERO, "open_date": od})
|
||||
g["qty"] += qty
|
||||
g["amount"] += cost * qty
|
||||
g["open_date"] = min(g["open_date"], od)
|
||||
|
|
@ -156,9 +179,9 @@ def compute_snapshot() -> dict:
|
|||
holdings.append({
|
||||
"account": account, "code": code.split(".")[0],
|
||||
"name": _display_name(names.get(code), code),
|
||||
"amount": round(g["amount"], 2), "open_date": g["open_date"],
|
||||
"upd_date": today, "structure": structure, "cost": round(cost, 3),
|
||||
"qty": g["qty"], "price": round(float(px), 3),
|
||||
"amount": float(_money(g["amount"])), "open_date": g["open_date"],
|
||||
"upd_date": today, "structure": structure, "cost": float(cost),
|
||||
"qty": g["qty"], "price": float(px),
|
||||
"days": _days(g["open_date"], today),
|
||||
})
|
||||
|
||||
|
|
@ -169,55 +192,58 @@ def compute_snapshot() -> dict:
|
|||
cq = int(r.get("closed_qty") or 0)
|
||||
if cq <= 0:
|
||||
continue
|
||||
cost = float(r.get("open_price") or 0)
|
||||
settle = float(r.get("close_avg_price") or 0)
|
||||
cost = _decimal(r.get("open_price"))
|
||||
settle = _decimal(r.get("close_avg_price"))
|
||||
od = _as_date(r.get("open_date")) or today
|
||||
cd = _as_date(r.get("updated_at")) or today
|
||||
g = cgrp.setdefault((code, cd), {"qty": 0, "amount": 0.0, "settle_amt": 0.0,
|
||||
"pnl": 0.0, "open_date": od})
|
||||
g = cgrp.setdefault((code, cd), {"qty": 0, "amount": _ZERO, "settle_amt": _ZERO,
|
||||
"pnl": _ZERO, "open_date": od})
|
||||
g["qty"] += cq
|
||||
g["amount"] += cost * cq
|
||||
g["settle_amt"] += settle * cq
|
||||
g["pnl"] += float(r.get("realized_pnl") or 0)
|
||||
g["pnl"] += _decimal(r.get("realized_pnl"))
|
||||
g["open_date"] = min(g["open_date"], od)
|
||||
|
||||
closed, fee_alloc = [], 0.0
|
||||
closed, fee_alloc = [], _ZERO
|
||||
for (code, cd) in sorted(cgrp, key=lambda k: (k[1], k[0])):
|
||||
g = cgrp[(code, cd)]
|
||||
fee = fees.get((int(cd.strftime("%Y%m%d")), code), 0.0)
|
||||
fee = fees.get((int(cd.strftime("%Y%m%d")), code), _ZERO)
|
||||
fee_alloc += fee
|
||||
closed.append({
|
||||
"account": account, "code": code.split(".")[0],
|
||||
"name": _display_name(names.get(code), code),
|
||||
"amount": round(g["amount"], 2), "open_date": g["open_date"],
|
||||
"amount": float(_money(g["amount"])), "open_date": g["open_date"],
|
||||
"close_date": cd, "structure": structure,
|
||||
"cost": round(g["amount"] / g["qty"], 3), "qty": g["qty"],
|
||||
"settle": round(g["settle_amt"] / g["qty"], 3),
|
||||
"cost": float(g["amount"] / g["qty"]), "qty": g["qty"],
|
||||
"settle": float(g["settle_amt"] / g["qty"]),
|
||||
"days": _days(g["open_date"], cd),
|
||||
"pnl": round(g["pnl"] - fee, 2),
|
||||
"pnl": float(_money(g["pnl"] - fee)),
|
||||
})
|
||||
|
||||
# 未摊入明细的费用 (买入侧 + 无代码归属的校准行): 表尾如实标注, 不悄悄吞掉
|
||||
try:
|
||||
fee_total = float(pms_repo.sum_fee_all())
|
||||
# 仓储返回有符号现金流,导出费用按成本口径反号;退款不可取绝对值。
|
||||
fee_total = -_decimal(pms_repo.sum_fee_all())
|
||||
except Exception: # noqa: BLE001
|
||||
fee_total = fee_alloc
|
||||
fee_resid = round(fee_total - fee_alloc, 2)
|
||||
fee_resid = float(_money(fee_total - fee_alloc))
|
||||
|
||||
hold_cost = sum(h["amount"] for h in holdings)
|
||||
hold_pnl = sum(round((h["price"] - h["cost"]) * h["qty"], 2) for h in holdings)
|
||||
realized = sum(c["pnl"] for c in closed)
|
||||
hold_cost = sum((_decimal(h["amount"]) for h in holdings), _ZERO)
|
||||
# 金额先核算到分,均价只在页面/单元格格式上显示三位;不能先截均价再乘股数。
|
||||
hold_pnl = sum((_money(_decimal(h["price"]) * h["qty"]) - _decimal(h["amount"])
|
||||
for h in holdings), _ZERO)
|
||||
realized = sum((_decimal(c["pnl"]) for c in closed), _ZERO)
|
||||
total_pnl = hold_pnl + realized
|
||||
nav = 1.0 + total_pnl / scale
|
||||
openable = scale + realized # 可开仓总金额 = 净值规模 + 已实现盈亏 (模板口径)
|
||||
nav = 1.0 + float(total_pnl) / scale
|
||||
openable = _decimal(scale) + realized # 可开仓总金额 = 净值规模 + 已实现盈亏 (模板口径)
|
||||
return {
|
||||
"today": today, "scale": scale, "holdings": holdings, "closed": closed,
|
||||
"hold_cost": round(hold_cost, 2), "hold_pnl": round(hold_pnl, 2),
|
||||
"closed_cost": round(sum(c["amount"] for c in closed), 2),
|
||||
"realized": round(realized, 2), "total_pnl": round(total_pnl, 2),
|
||||
"nav": round(nav, 4), "openable": round(openable, 2),
|
||||
"open_room": round(openable - hold_cost, 2),
|
||||
"pos_ratio": round(hold_cost / openable, 4) if openable > 0 else None,
|
||||
"hold_cost": float(_money(hold_cost)), "hold_pnl": float(_money(hold_pnl)),
|
||||
"closed_cost": float(_money(sum((_decimal(c["amount"]) for c in closed), _ZERO))),
|
||||
"realized": float(_money(realized)), "total_pnl": float(_money(total_pnl)),
|
||||
"nav": round(nav, 4), "openable": float(_money(openable)),
|
||||
"open_room": float(_money(openable - hold_cost)),
|
||||
"pos_ratio": round(float(hold_cost / openable), 4) if openable > 0 else None,
|
||||
"price_missing": sorted(price_missing), "fee_resid": fee_resid,
|
||||
"title": str(param_store.get("PMS_PUBLISH_TITLE") or "量化产品基本信息"),
|
||||
}
|
||||
|
|
@ -273,9 +299,16 @@ def _entry_row(ws, row, seq, e, *, date2, px):
|
|||
f"=IF(K{row}=0,0,Q{row}/K{row})"] # R 较期初价涨跌幅
|
||||
for i, v in enumerate(vals):
|
||||
_put(ws, row, 3 + i, v)
|
||||
# S 总持股浮动盈亏: 持仓 = Q×L (不含费, 模板同); 平仓 = 含费实得, 写值
|
||||
# 均价统一显示三位、金额两位;格式不能反过来截断原始数值。
|
||||
for col in (11, 13, 17):
|
||||
ws.cell(row=row, column=col).number_format = "0.000"
|
||||
for col in (7, 19):
|
||||
ws.cell(row=row, column=col).number_format = "#,##0.00"
|
||||
# 表格里手动修订成本或股数后,成本金额和持仓盈亏必须一起重算。
|
||||
_put(ws, row, 7, f"=ROUND(K{row}*L{row},2)")
|
||||
# S 总持股浮动盈亏: 持仓 = 市值减成本金额;平仓 = 含费实得,沿用账本数值
|
||||
if e.get("pnl") is None:
|
||||
_put(ws, row, 19, f"=Q{row}*L{row}")
|
||||
_put(ws, row, 19, f"=ROUND(ROUND(M{row}*L{row},2)-G{row},2)")
|
||||
else:
|
||||
_put(ws, row, 19, e["pnl"])
|
||||
_put(ws, row, 20, f"=IF(G{row}=0,0,S{row}/G{row})") # T 持有收益率
|
||||
|
|
@ -402,13 +435,14 @@ def build_workbook(s: dict, nav_rows: list) -> bytes:
|
|||
|
||||
# ---- 表尾注 (模板之外的诚实行: 缺价与未摊费用不许静默) ----
|
||||
note_row = sum2 + 1
|
||||
notes = []
|
||||
notes = ["持仓成本和成交均价不含手续费,费用单独列示;未回报费用不视为零"]
|
||||
if s["price_missing"]:
|
||||
notes.append(f"{len(s['price_missing'])} 只标的当日无行情,按成本价计入市值"
|
||||
f"({'、'.join(s['price_missing'][:5])}"
|
||||
f"{' 等' if len(s['price_missing']) > 5 else ''})")
|
||||
if s.get("fee_resid"):
|
||||
notes.append(f"另有 {s['fee_resid']:.2f} 元费用(买入侧/校准)未摊入明细行")
|
||||
label = "费用" if s["fee_resid"] > 0 else "费用返还"
|
||||
notes.append(f"另有 {abs(s['fee_resid']):.2f} 元{label}(买入侧/校准)未摊入明细行")
|
||||
if notes:
|
||||
c = _put(ws, note_row, 2, "注:" + ";".join(notes) + "。")
|
||||
c.font = Font(name="宋体", size=10)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,121 @@
|
|||
"""实有策略现金与净值。账本迁移演练后,在无在途委托的维护窗口初始化。"""
|
||||
import datetime as dt
|
||||
import math
|
||||
from app.core import rotation_account as core, strategy_book as books
|
||||
from app.repo import rotation_repo as store, pms_repo, qmt_repo
|
||||
from app.services import market
|
||||
from app.core import ws_codec
|
||||
|
||||
|
||||
def marked_values(*, strict=True):
|
||||
"""默认给资金动作严格估值;展示允许缺行情,但未知值必须保留为空。"""
|
||||
values = {b: 0. for b in core.BOOKS}
|
||||
missing = []
|
||||
positions = []
|
||||
with books.scope('all'):
|
||||
rows = pms_repo.list_positions(only_open=True)
|
||||
for r in rows:
|
||||
quote = market.day_snapshot(r['ts_code'])
|
||||
raw_price = quote.get('price')
|
||||
try:
|
||||
price = float(raw_price) if raw_price is not None and not isinstance(raw_price, bool) else None
|
||||
except (TypeError, ValueError):
|
||||
price = None
|
||||
if price is None or not math.isfinite(price) or price <= 0:
|
||||
missing.append(r['ts_code'])
|
||||
price, value = None, None
|
||||
values[r['book_id']] = None
|
||||
else:
|
||||
value = int(r['total_qty'])*price
|
||||
if values[r['book_id']] is not None:
|
||||
values[r['book_id']] += value
|
||||
positions.append({'book_id': r['book_id'], 'code': r['ts_code'], 'qty': r['total_qty'],
|
||||
'market_value': value, 'price': price, 'cost': float(r.get('avg_cost') or 0)*int(r['total_qty'])})
|
||||
if missing and strict:
|
||||
raise ValueError('策略估值行情缺失:'+','.join(missing))
|
||||
return values, positions
|
||||
|
||||
|
||||
def initialize():
|
||||
"""只在显式迁移操作中调用;不可在交易路径猜测重建现金归属。"""
|
||||
from app.db import session as db
|
||||
from app.services.rotation_service import reconcile_books
|
||||
with store.account_guard():
|
||||
if store.get('capital:live')[0]:
|
||||
return {'exists': True}
|
||||
pending = db.fetch_all("SELECT instruction_id FROM pms_qmt_order WHERE status IN ('QUEUED','SENDING','SENT','ACCEPTED','SUBMITTED','PARTIAL') LIMIT 1")
|
||||
if pending or not reconcile_books()['ok']:
|
||||
raise ValueError('现金初始化需要无在途委托且数量对账一致')
|
||||
snap = qmt_repo.latest_snapshot('funds')
|
||||
if not snap or snap.get('age_sec', 999) > 60:
|
||||
raise ValueError('现金初始化需要一分钟内资金快照')
|
||||
funds = ws_codec.parse_funds_snapshot(snap['payload'])
|
||||
if funds.get('available_cash') is None or funds.get('frozen_cash', 0):
|
||||
raise ValueError('资金冻结未解除或现金未知')
|
||||
values, _ = marked_values()
|
||||
if values['micro30']:
|
||||
raise ValueError('迁移初始微盘账本必须为空')
|
||||
value = core.seed(float(funds['available_cash']), values)
|
||||
value.update(started_at=dt.datetime.now().isoformat(), source_funds_seq=snap['seq'])
|
||||
store.put_once('capital:live', 'capital', value)
|
||||
return {'initialized': True, 'source_funds_seq': snap['seq']}
|
||||
|
||||
|
||||
def reserve_book(book, demand, pending, phase):
|
||||
"""账户锁内调用。只划拨已存在现金,跨策略在途保留不可再次使用。"""
|
||||
reserved = {b: 0. for b in core.BOOKS}
|
||||
with books.scope('all'):
|
||||
for o in pending:
|
||||
if o['side'] != 'buy':
|
||||
continue
|
||||
parent = pms_repo.get_instruction(o['parent_id'])
|
||||
if not parent or parent.get('book_id') not in core.BOOKS:
|
||||
raise ValueError('在途委托策略归属未知')
|
||||
remaining = max(0, int(o['qty'])-int(o.get('cum_qty') or 0))
|
||||
if remaining:
|
||||
from app.services.rotation_service import configuration
|
||||
from app.core.micro_rotation import fee
|
||||
amount = remaining*float(o['limit_price'])
|
||||
reserved[parent['book_id']] += amount+fee(amount,'buy',**configuration()['costs'])
|
||||
with store.locked('capital:live', 'capital', {}) as value:
|
||||
if not value.get('cash'):
|
||||
raise ValueError('分策略现金尚未初始化')
|
||||
need = max(0., demand-(value['cash'][book]-reserved[book]))
|
||||
if not need:
|
||||
return
|
||||
source = 'original' if book == 'micro30' else 'micro30'
|
||||
if (book == 'micro30' and phase not in ('entering_micro','micro')) or (book == 'original' and phase not in ('returning_original','original')):
|
||||
raise ValueError('当前阶段不允许现金划拨')
|
||||
if value['cash'][source]-reserved[source] < need-1e-6:
|
||||
raise ValueError('源策略现金不足或仍被在途委托占用')
|
||||
values, _ = marked_values()
|
||||
key = 'allocation:'+str(len(value['transfers'])+1)
|
||||
core.transfer(value, source, book, need, values, key)
|
||||
store.put_once('transfer:'+key, 'cash_transfer', {'key': key, **value['transfers'][key]})
|
||||
|
||||
|
||||
def record_fill(book, side, amount, fees, key):
|
||||
with store.locked('capital:live', 'capital', {}) as value:
|
||||
if not value.get('cash'):
|
||||
raise ValueError('分策略现金尚未初始化')
|
||||
core.fill(value, book, side, amount, fees, key)
|
||||
|
||||
|
||||
def view():
|
||||
value, _ = store.get('capital:live')
|
||||
if not value:
|
||||
return {'ready': False, 'reason': '分策略现金尚未初始化'}
|
||||
values, positions = marked_values(strict=False)
|
||||
missing = sorted({p['code'] for p in positions if p['market_value'] is None})
|
||||
result = core.metrics(value, values)
|
||||
snap = qmt_repo.latest_snapshot('funds')
|
||||
cash_difference = None
|
||||
if snap and snap.get('age_sec', 999) <= 60:
|
||||
funds = ws_codec.parse_funds_snapshot(snap['payload'])
|
||||
if funds.get('available_cash') is not None and funds.get('frozen_cash') is not None:
|
||||
cash_difference = result['account']['cash']-funds['available_cash']-funds['frozen_cash']
|
||||
return {'ready': not missing, 'cash_ready': True, 'valuation_ready': not missing,
|
||||
'valuation_missing': missing,
|
||||
'reason': '持仓估值等待行情:'+','.join(missing)+';现金和持仓数量仍单独核对。' if missing else None,
|
||||
'metrics': result, 'positions': positions, 'cash_difference': cash_difference,
|
||||
'started_at': value.get('started_at'), 'transfer_count': len(value['transfers'])}
|
||||
|
|
@ -0,0 +1,380 @@
|
|||
"""策略轮换执行适配,共用PMS出口和账户资金串行保护。"""
|
||||
import datetime as dt
|
||||
from app.core import strategy_book as books, micro_rotation as core, ws_codec
|
||||
from app.db import session as db
|
||||
from app.repo import pms_repo, qmt_repo, rotation_repo as store
|
||||
from app.services import param_store
|
||||
from config.settings import settings
|
||||
|
||||
TERMINAL = qmt_repo.FINAL
|
||||
|
||||
|
||||
def _later_snapshot(received_at, final_at):
|
||||
from app.core.execution_policy import local_now
|
||||
try:
|
||||
received = received_at if isinstance(received_at, dt.datetime) else dt.datetime.fromisoformat(str(received_at))
|
||||
final = final_at if isinstance(final_at, dt.datetime) else dt.datetime.fromisoformat(str(final_at))
|
||||
return local_now(received) > local_now(final)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def release_settled_reservations(account, funds):
|
||||
"""逐单释放已确认撤回的未成交金额,不重复扣QMT冻结、不预支卖出收入。"""
|
||||
from app.services import execution_orders
|
||||
from app.repo import execution_repo
|
||||
if execution_repo.pending_corrections():
|
||||
return
|
||||
initial = account.setdefault('original_reservations', {})
|
||||
for iid, held in list(account['orders'].items()):
|
||||
initial.setdefault(iid, float(held))
|
||||
order = qmt_repo.get_order(iid)
|
||||
if not order or order['status'] not in TERMINAL or not _later_snapshot(funds.get('received_at'), execution_orders.settlement_cutoff(order)):
|
||||
continue
|
||||
settled = execution_orders.replacement_state(order['parent_id'])
|
||||
if settled['pending_trades'] or settled['booked'] < settled['confirmed_filled'] or settled['missing_orders']:
|
||||
continue
|
||||
qty, done, price = int(order['qty']), execution_orders.effective_filled(order), float(order['limit_price'])
|
||||
original = initial[iid]
|
||||
if qty <= 0 or not 0 <= done <= qty or price <= 0 or original+1e-6 < qty*price:
|
||||
raise ValueError('委托原始资金保留不可核实')
|
||||
# 成交价不会高于买入限价。已成部分保留原限价本金和整笔原费用,避免低估占用。
|
||||
retained = min(original, done*price+max(0., original-qty*price)) if done else 0.
|
||||
account['orders'][iid] = retained
|
||||
|
||||
|
||||
def _reservation_fills_booked(orders):
|
||||
from app.services import execution_orders
|
||||
from app.repo import execution_repo
|
||||
if execution_repo.pending_corrections():
|
||||
return False
|
||||
for order in orders:
|
||||
state = execution_orders.replacement_state(order['parent_id'])
|
||||
if state['pending_trades'] or state['booked'] < state['confirmed_filled'] or state['missing_orders']:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def enqueue_with_reservation(payload, parent_id):
|
||||
"""所有策略共用一个账户锁;出口行与预算保留同一事务提交。"""
|
||||
from app.services import rotation_service as service, execution_orders
|
||||
with store.locked('account-execution', 'funds_reservation', {'epoch_seq': 0, 'available': 0., 'orders': {}}) as account:
|
||||
code, side, qty, price = payload['ts_code'], payload['side'], int(payload['qty']), float(payload['limit_price'])
|
||||
old = qmt_repo.get_order(payload['instruction_id'])
|
||||
if old:
|
||||
if any(old[k] != v for k, v in [('parent_id', parent_id), ('ts_code', code), ('side', side), ('qty', qty)]) or abs(float(old['limit_price'])-price) > 1e-8:
|
||||
raise ValueError('委托幂等键与内容冲突')
|
||||
return
|
||||
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
||||
raise ValueError('用户暂停全部执行')
|
||||
with books.scope('all'):
|
||||
parent = pms_repo.get_instruction(parent_id)
|
||||
if not parent:
|
||||
raise ValueError('委托没有可核实的策略父指令')
|
||||
blocked = execution_orders.correction_blocker(parent, ts_code=code, side=side)
|
||||
if blocked:
|
||||
raise ValueError(blocked)
|
||||
book = parent['book_id']
|
||||
if side == 'buy':
|
||||
if param_store.get_bool('PMS_GLOBAL_BUY_HALT', False):
|
||||
raise ValueError('用户暂停买入')
|
||||
reason = service.strategy_buy_blocker(book, parent)
|
||||
if reason:
|
||||
raise ValueError(reason)
|
||||
# 同名股票全账户互斥。最多读取10001行,达到上限拒绝继续,避免截断漏检查。
|
||||
active = db.fetch_all("SELECT * FROM pms_qmt_order WHERE status NOT IN ('FILLED','CANCELLED','REJECTED','EXPIRED','SEND_FAILED','ABORTED') ORDER BY id LIMIT 10001")
|
||||
if len(active) > 10000:
|
||||
raise ValueError('在途委托超出核验上限')
|
||||
if any(o['ts_code'] == code for o in active):
|
||||
raise ValueError('同名股票仍有在途委托,等待终态及成交入账')
|
||||
if side == 'sell':
|
||||
with books.scope(book):
|
||||
position = pms_repo.get_position(code) or {}
|
||||
booked = sum(int(o['qty'])-int(o.get('cum_qty') or 0) for o in active if o['ts_code'] == code and o['side'] == 'sell')
|
||||
from app.services.ledger_service import positions_source
|
||||
source = positions_source()
|
||||
physical = next((r for r in source['rows'] if r['ts_code'] == code), {})
|
||||
if source['source'] != 'ws':
|
||||
raise ValueError('实际可卖量需要新鲜QMT快照')
|
||||
physical_available = int(physical.get('available_qty', physical.get('avail_qty', 0)) or 0)
|
||||
# 已受理卖单通常已从QMT可卖量扣除。只额外预留尚未发出的数量。
|
||||
unsent = sum(int(o['qty'])-int(o.get('cum_qty') or 0) for o in active if o['ts_code'] == code and o['side'] == 'sell' and o['status'] in ('QUEUED','SENDING','SENT'))
|
||||
available = min(int(position.get('avail_qty') or 0)-booked, physical_available-unsent)
|
||||
if qty > max(0, available):
|
||||
raise ValueError('账户或策略实际可卖数量不足')
|
||||
if qty != int(position.get('total_qty') or 0) and (qty < core.min_qty(code) or qty % 100):
|
||||
raise ValueError('部分卖出数量不符合交易单位')
|
||||
else:
|
||||
with books.scope(books.MICRO if book == books.ORIGINAL else books.ORIGINAL):
|
||||
other = pms_repo.get_position(code) or {}
|
||||
if int(other.get('total_qty') or 0) > 0:
|
||||
raise ValueError('同名股票旧策略持仓尚未卖清')
|
||||
if qty < core.min_qty(code) or qty % 100:
|
||||
raise ValueError('买入数量不符合交易单位')
|
||||
funds = qmt_repo.latest_snapshot('funds')
|
||||
if not funds or funds.get('age_sec') is None or not 0 <= funds['age_sec'] <= 60:
|
||||
raise ValueError('账户资金快照超过一分钟或不可用')
|
||||
parsed = ws_codec.parse_funds_snapshot(funds['payload'])
|
||||
available = parsed.get('available_cash')
|
||||
if available is None:
|
||||
raise ValueError('账户可用现金不可核实')
|
||||
reserved = account['orders']
|
||||
terminal = []
|
||||
for iid in reserved:
|
||||
order = qmt_repo.get_order(iid)
|
||||
if order and order['status'] in TERMINAL and order.get('final_at'):
|
||||
terminal.append(order)
|
||||
# 全部委托终态,且新的资金快照晚于全部终态,才开启新预算周期。
|
||||
settled = not reserved or (len(terminal) == len(reserved)
|
||||
and all(_later_snapshot(funds['received_at'], execution_orders.settlement_cutoff(o)) for o in terminal)
|
||||
and _reservation_fills_booked(terminal))
|
||||
if settled and funds['seq'] > account['epoch_seq']:
|
||||
account.update(epoch_seq=funds['seq'], available=float(available), orders={}, original_reservations={}, market_value=float(parsed.get('market_value') or 0))
|
||||
else:
|
||||
release_settled_reservations(account, funds)
|
||||
costs = service.configuration()['costs']
|
||||
demand = qty*price+core.fee(qty*price, 'buy', **costs)
|
||||
remaining = account['available']-sum(account['orders'].values())
|
||||
reserve_cash = param_store.get_float('PMS_TOTAL_SCALE', 0)*param_store.get_float('PMS_CASH_RESERVE', 0)
|
||||
cash_limit = min(float(available), remaining)-reserve_cash
|
||||
# 不另扣QMT冻结现金,不额外增加卖出回笼。
|
||||
scale = param_store.get_float('PMS_TOTAL_SCALE', 0)
|
||||
cap = scale*param_store.get_float('PMS_PORTFOLIO_CAP', 0)
|
||||
mv = parsed.get('market_value')
|
||||
if mv is None:
|
||||
mv = parsed.get('total_market_value')
|
||||
if mv is None:
|
||||
raise ValueError('账户总市值不可核实')
|
||||
# 委托未终态前保守保留本预算周期新增市值;不借旧行情绕过全账户上限。
|
||||
cap_remaining = min(cap-float(mv), cap-float(account.get('market_value', mv))-sum(account['orders'].values()))
|
||||
if demand > cash_limit+1e-8 or qty*price > cap_remaining+1e-8:
|
||||
raise ValueError('账户可用现金或全账户仓位预算不足')
|
||||
from app.services import rotation_accounting
|
||||
live, _ = store.get('state:live')
|
||||
phase = (live or {}).get('rotation', {}).get('phase', 'original')
|
||||
rotation_accounting.reserve_book(book, demand, active, phase)
|
||||
account['orders'][payload['instruction_id']] = demand
|
||||
account.setdefault('original_reservations', {})[payload['instruction_id']] = demand
|
||||
qmt_repo.enqueue_order(instruction_id=payload['instruction_id'], parent_id=parent_id,
|
||||
ts_code=code, side=side, qty=qty, limit_price=price, valid_until=payload['valid_until'],
|
||||
intent=payload['intent'], note=payload.get('note'))
|
||||
|
||||
|
||||
def send_intent(intent, price, now, snapshot_version):
|
||||
from app.services import dispatcher, execution_orders
|
||||
if dispatcher.mode() != 'ws':
|
||||
raise ValueError('轮换自动执行只支持唯一WS通道,不使用shadow成交认领')
|
||||
parent = intent['id']
|
||||
book = intent['book_id']
|
||||
with books.scope(book), db.transaction():
|
||||
blocker = execution_orders.code_settlement_blocker(intent['ts_code'])
|
||||
if blocker:
|
||||
raise ValueError(blocker)
|
||||
existing = pms_repo.get_instruction(parent)
|
||||
if not existing:
|
||||
command = 'ROT_CMD_'+book+'_'+now.strftime('%Y%m%d')
|
||||
if not pms_repo.get_command(command):
|
||||
pms_repo.insert_command(command_id=command, cmd_class='task', cmd_type='ROTATE_MICRO',
|
||||
ts_code=None, params={'rule_version': intent.get('rule_version', core.RULE), 'snapshot_version': snapshot_version},
|
||||
status='EXECUTING', issued_by='rotation', note='微盘与原策略账户轮换')
|
||||
plan = 'P_'+parent
|
||||
action = 'OPEN' if intent['side'] == 'buy' else 'EXIT'
|
||||
pms_repo.insert_plans([{'plan_id': plan, 'command_id': command, 'ts_code': intent['ts_code'],
|
||||
'action': action, 'qty': intent['qty'], 'amount': intent['qty']*price,
|
||||
'deadline': now.date(), 'status': 'EXECUTING', 'reason': intent['reason']}])
|
||||
pms_repo.insert_instruction(instruction_id=parent, origin_type='plan', origin_id=plan,
|
||||
ts_code=intent['ts_code'], action=action, side=intent['side'], qty=intent['qty'],
|
||||
window_tdays=1, progress={'execution_profile': 'rotation', 'snapshot_version': snapshot_version,
|
||||
'rule_version': intent.get('rule_version', core.RULE),
|
||||
'deadline': now.date().isoformat(), 'is_command': True, 'children': []})
|
||||
elif existing['status'] not in ('PROPOSED', 'DISPATCHED'):
|
||||
return {'instruction_id': parent, 'state': '已有终态记录,次日重新规划'}
|
||||
elif (existing.get('progress') or {}).get('cancel_requested'):
|
||||
return {'instruction_id': parent, 'state': '父指令正在撤销,停止重挂', 'pending': True}
|
||||
settled = execution_orders.replacement_state(parent)
|
||||
if not settled.get('ready'):
|
||||
return {'instruction_id': parent, 'state': '旧委托或成交尚未结清', 'pending': True}
|
||||
quantity = min(int(intent['qty']), int(settled.get('remaining', intent['qty'])))
|
||||
if quantity <= 0:
|
||||
return {'instruction_id': parent, 'state': '目标数量已完成'}
|
||||
retry_reason = execution_orders.retry_reason(parent, now=now)
|
||||
if retry_reason:
|
||||
return {'instruction_id': parent, 'state': retry_reason, 'pending': True}
|
||||
child = execution_orders.next_child_id(parent)
|
||||
result = dispatcher.dispatch(instruction_id=child, parent_id=parent, intent='OPEN' if intent['side'] == 'buy' else 'EXIT',
|
||||
ts_code=intent['ts_code'], side=intent['side'], qty=quantity, limit_price=price,
|
||||
valid_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))), note=intent['reason'])
|
||||
if not result.get('ok'):
|
||||
raise ValueError('轮换委托未下发:'+str(result.get('error')))
|
||||
progress = (pms_repo.get_instruction(parent) or {}).get('progress', {})
|
||||
progress.setdefault('children', []).append({'ref': child, 'qty': quantity, 'limit': price,
|
||||
'mode': 'ws', 'ymd': int(now.strftime('%Y%m%d')), 'at': now.strftime('%H:%M:%S'), 'valid_until': '10:00'})
|
||||
progress['quote'] = intent.get('quote_basis')
|
||||
pms_repo.update_instruction(parent, status='DISPATCHED', dispatch_ref=child, progress=progress)
|
||||
return {'instruction_id': parent, 'book_id': book, 'result': result}
|
||||
|
||||
|
||||
def pending_instructions():
|
||||
"""父记录与真实出口合并,父单本地结束不能隐去仍活动的子委托。"""
|
||||
with books.scope('all'):
|
||||
parents = pms_repo.list_instructions(statuses=('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW'), limit=10000)
|
||||
by_id = {p['instruction_id']: p for p in parents}
|
||||
children = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
|
||||
if len(children) > 10000:
|
||||
raise ValueError('在途委托超出核验上限')
|
||||
for child in children:
|
||||
pid = child['parent_id']
|
||||
if pid not in by_id:
|
||||
parent = pms_repo.get_instruction(pid)
|
||||
if not parent:
|
||||
raise ValueError('活动子委托的策略归属无法核实')
|
||||
by_id[pid] = parent
|
||||
return list(by_id.values())
|
||||
|
||||
|
||||
def suspended_rejections(now):
|
||||
"""只消费当日已落库的精确停牌拒绝码,不凭行情缺失或柜台错误文字递补。"""
|
||||
from app.services import execution_orders
|
||||
day = now.date()
|
||||
rows = db.fetch_all("SELECT * FROM pms_qmt_order WHERE status='REJECTED' "
|
||||
"AND reject_code='SUSPENDED' AND side='buy' AND final_at>=:start AND final_at<:end "
|
||||
"ORDER BY id DESC LIMIT 10001", {'start': day, 'end': day+dt.timedelta(days=1)})
|
||||
if len(rows) > 10000:
|
||||
raise ValueError('当日停牌拒单超过核验上限')
|
||||
result = {}
|
||||
with books.scope('all'):
|
||||
for order in rows:
|
||||
if order.get('reject_code') != 'SUSPENDED' or order.get('status') != 'REJECTED' or int(order.get('cum_qty') or 0):
|
||||
continue
|
||||
parent = pms_repo.get_instruction(order['parent_id'])
|
||||
progress = (parent or {}).get('progress') or {}
|
||||
if not parent or parent.get('book_id') != books.MICRO or int(parent.get('exec_qty') or 0) or progress.get('execution_profile') != 'rotation' or progress.get('rule_version') != core.EXECUTION_RULE or str(progress.get('deadline')) != day.isoformat():
|
||||
continue
|
||||
settled = execution_orders.replacement_state(parent['instruction_id'])
|
||||
if settled['ready'] and settled['confirmed_filled'] == 0:
|
||||
result[order['ts_code']] = 'QMT已确认停牌拒单SUSPENDED,委托'+order['instruction_id']
|
||||
return result
|
||||
|
||||
|
||||
def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable):
|
||||
"""v3只调整已授权剩余量。撤改先等旧子单终态,个股等待不阻塞整篮。"""
|
||||
from app.services import execution_orders, executor
|
||||
results, waits = [], []
|
||||
for parent in parents:
|
||||
progress = parent.get('progress') or {}
|
||||
if progress.get('execution_profile') != 'rotation' or progress.get('rule_version') != core.EXECUTION_RULE:
|
||||
continue
|
||||
code, side = parent['ts_code'], parent['side']
|
||||
if str(progress.get('deadline')) != now.date().isoformat():
|
||||
continue
|
||||
with books.scope(parent['book_id']):
|
||||
if side == 'buy' and (code in unavailable or code not in target):
|
||||
result = executor.cancel_instruction(parent['instruction_id'], reason='微盘成员不可交易或已调出', arbiter='system')
|
||||
waits.append(code+'撤单确认后处理剩余席位')
|
||||
if not result.get('ok'):
|
||||
waits.append(code+'撤单请求待重试')
|
||||
continue
|
||||
if progress.get('cancel_requested'):
|
||||
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, {})
|
||||
priced = execution_orders.quote_order(side, quote, now)
|
||||
if priced.get('action') != 'FIRE':
|
||||
waits.append(code+str(priced.get('reason') or '执行报价不可用'))
|
||||
if live:
|
||||
try:
|
||||
with db.savepoint():
|
||||
execution_orders.request_replace(parent['instruction_id'], '行情不可核实,撤清后等待恢复', now=now)
|
||||
except Exception as exc:
|
||||
waits.append(code+'缺行情撤单待重试:'+type(exc).__name__)
|
||||
continue
|
||||
if live:
|
||||
# 仍可按现价成交的限价不反复撤掉,保留原排队位置。
|
||||
changed = any((side == 'buy' and float(c['limit_price']) < priced['limit_price']) or
|
||||
(side == 'sell' and float(c['limit_price']) > priced['limit_price']) for c in live)
|
||||
if not changed or not execution_orders.should_replace(parent, priced, now=now):
|
||||
continue
|
||||
try:
|
||||
with db.savepoint():
|
||||
execution_orders.request_replace(parent['instruction_id'], '微盘限价随有效行情更新', now=now)
|
||||
except Exception as exc:
|
||||
waits.append(code+'改价撤单待重试:'+type(exc).__name__)
|
||||
continue
|
||||
waits.append(code+'改价撤单待终态')
|
||||
continue
|
||||
status = execution_orders.replacement_state(parent['instruction_id'])
|
||||
if not status.get('ready') or int(status.get('remaining') or 0) <= 0:
|
||||
continue
|
||||
intent = {'id': parent['instruction_id'], 'book_id': parent['book_id'], 'ts_code': code,
|
||||
'side': side, 'qty': int(parent['qty']), 'reason': '微盘剩余数量继续执行',
|
||||
'rule_version': core.EXECUTION_RULE, 'quote_basis': {**quote, **priced}}
|
||||
try:
|
||||
with db.savepoint():
|
||||
results.append(send_intent(intent, priced['limit_price'], now, snapshot_version))
|
||||
except Exception as exc:
|
||||
waits.append(code+'重挂待重试:'+type(exc).__name__)
|
||||
return results, waits
|
||||
|
||||
|
||||
def cancel_expired(now):
|
||||
from app.services import executor
|
||||
with books.scope('all'):
|
||||
rows = pms_repo.list_instructions(statuses=('PROPOSED', 'DISPATCHED'), limit=10000)
|
||||
for row in rows:
|
||||
p = row.get('progress') or {}
|
||||
if p.get('execution_profile') != 'rotation':
|
||||
continue
|
||||
deadline = str(p.get('deadline') or '')
|
||||
if deadline < now.date().isoformat() or (deadline == now.date().isoformat() and now.hour >= 10):
|
||||
with books.scope(row['book_id']):
|
||||
result = executor.cancel_instruction(row['instruction_id'], reason='轮换当日执行窗口结束', arbiter='system')
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('轮换委托撤销未确认')
|
||||
|
||||
|
||||
def book_trade(act, fees, seq):
|
||||
"""策略归属、批次、费用、指令进度和inbox标记同成同败。"""
|
||||
from app.services import ledger_service as ledger
|
||||
from app.services import trade_lineage
|
||||
parent = act.get('instruction_id')
|
||||
if not parent:
|
||||
raise ValueError('逐笔成交缺少父指令归属')
|
||||
with store.account_guard(), db.transaction():
|
||||
inbox = db.fetch_one('SELECT processed FROM pms_qmt_inbox WHERE seq=:seq FOR UPDATE', {'seq': seq})
|
||||
if not inbox or inbox['processed'] != 0:
|
||||
return False
|
||||
with books.scope('all'):
|
||||
instruction = pms_repo.get_instruction(parent)
|
||||
if not instruction or instruction.get('book_id') not in (books.ORIGINAL, books.MICRO):
|
||||
raise ValueError('父指令策略归属不可核实')
|
||||
if instruction['ts_code'] != act['ts_code'] or instruction['side'] != ('buy' if act['kind'] == 'BUY' else 'sell'):
|
||||
raise ValueError('成交证券或方向与父指令冲突')
|
||||
if int(instruction['exec_qty'])+int(act['qty']) > int(instruction['qty']):
|
||||
raise ValueError('成交超过父指令剩余数量,等待核对')
|
||||
with books.scope(instruction['book_id']):
|
||||
before = pms_repo.get_position(act['ts_code']) or {}
|
||||
lots_before = trade_lineage.lots(act['ts_code'])
|
||||
qty = int(act['qty'])
|
||||
if act['kind'] != 'BUY' and qty > int(before.get('total_qty') or 0):
|
||||
raise ValueError('卖出成交超出所属策略持仓,等待核对')
|
||||
ledger._apply_action(act)
|
||||
after = pms_repo.get_position(act['ts_code']) or {}
|
||||
delta = qty if act['kind'] == 'BUY' else -qty
|
||||
if int(after.get('total_qty') or 0) != int(before.get('total_qty') or 0)+delta:
|
||||
raise ValueError('成交数量未完整入账')
|
||||
fresh = pms_repo.get_instruction(parent)
|
||||
if int(fresh['exec_qty']) != int(instruction['exec_qty'])+qty:
|
||||
raise ValueError('指令成交进度未原子更新')
|
||||
for f in fees:
|
||||
pms_repo.insert_cash_flow(ymd=int(dt.datetime.now().strftime('%Y%m%d')), kind='FEE',
|
||||
amount=f['amount'], ts_code=f['ts_code'], estimated=f['estimated'],
|
||||
trade_no=f['trade_no'], instruction_id=f['instruction_id'], note=f['note'])
|
||||
from app.services.rotation_accounting import record_fill
|
||||
record_fill(instruction['book_id'], 'buy' if act['kind'] == 'BUY' else 'sell',
|
||||
qty*float(act['price']), -sum(float(f['amount']) for f in fees), str(seq))
|
||||
ledger.recompute_position(act['ts_code'])
|
||||
trade_lineage.record(act, instruction, seq, lots_before, trade_lineage.lots(act['ts_code']))
|
||||
if not qmt_repo.inbox_mark([seq], processed=qmt_repo.PROC_BOOKED, note='按策略归属原子入账'):
|
||||
raise RuntimeError('逐笔成交入账标记未写入')
|
||||
return True
|
||||
|
|
@ -0,0 +1,692 @@
|
|||
"""宏观微盘策略编排。观察与纸面状态独立;只有验收完成才能接现有委托通道。"""
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
from zoneinfo import ZoneInfo
|
||||
import requests
|
||||
from config.settings import settings
|
||||
from app.core import micro_rotation as core, strategy_book as books, tradedays as td
|
||||
from app.repo import pms_repo, qmt_repo, rotation_repo as store
|
||||
from app.services import param_store, portfolio, market
|
||||
|
||||
TZ = ZoneInfo('Asia/Shanghai')
|
||||
logger = logging.getLogger('pms.rotation')
|
||||
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
||||
TERMINAL = qmt_repo.FINAL
|
||||
|
||||
|
||||
def documents_ready():
|
||||
return settings.INFRA_ROTATION_DOCUMENT_SCHEMA or settings.INFRA_STRATEGY_BOOK_SCHEMA
|
||||
|
||||
|
||||
def configuration():
|
||||
return {'mode': str(param_store.get('PMS_ROTATION_MODE', 'observe')),
|
||||
'rule_version': str(param_store.get('PMS_ROTATION_RULE_VERSION', core.RULE)),
|
||||
'candidate_pool_size': param_store.get_int('PMS_ROTATION_CANDIDATE_POOL_SIZE', 100),
|
||||
'control': str(param_store.get('PMS_ROTATION_CONTROL', 'run')),
|
||||
'url': str(param_store.get('PMS_ROTATION_MONITOR_URL', '')).rstrip('/'),
|
||||
'boards': set(str(param_store.get('PMS_MICRO30_ALLOWED_BOARDS', '')).split(','))-{''},
|
||||
'costs': {'rate': param_store.get_float('PMS_MICRO30_COMMISSION_RATE', .0002),
|
||||
'minimum': param_store.get_float('PMS_MICRO30_MIN_COMMISSION', 5.),
|
||||
'sell_tax': param_store.get_float('PMS_MICRO30_SELL_TAX', .0005),
|
||||
'transfer_rate': param_store.get_float('PMS_MICRO30_TRANSFER_RATE', .00001)}}
|
||||
|
||||
|
||||
def pull(execution_date=None):
|
||||
config = configuration()
|
||||
if config['rule_version'] not in core.SUPPORTED_RULES:
|
||||
raise ValueError('运行规则与已部署代码不一致')
|
||||
day = execution_date or dt.datetime.now(TZ).date().isoformat()
|
||||
if not config['url']:
|
||||
return None
|
||||
response = requests.get(config['url']+'/v1/snapshot', params={'effective_date': day}, timeout=(3, 15))
|
||||
response.raise_for_status()
|
||||
if len(response.content) > 1024*1024:
|
||||
raise ValueError('监控快照超过大小限制')
|
||||
value = response.json()
|
||||
errors = core.snapshot_check(value, day, require_frozen=False, expected_rule=config['rule_version'], candidate_pool_size=config.get('candidate_pool_size', 100))
|
||||
if errors:
|
||||
raise ValueError(';'.join(errors))
|
||||
return value
|
||||
|
||||
|
||||
def activation_errors():
|
||||
if settings.PMS_TABLE_PREFIX:
|
||||
return ['本次策略只开放155模拟实例']
|
||||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
return ['策略账本迁移尚未启用']
|
||||
if configuration()['rule_version'] not in core.SUPPORTED_RULES:
|
||||
return ['运行规则与已部署版本不一致']
|
||||
if param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False):
|
||||
# 用户授权155模拟仓直接运行。该授权不伪造历史验收或交易日记录。
|
||||
errors = []
|
||||
capital, _ = store.get('capital:live')
|
||||
if not capital or not capital.get('cash') or not capital.get('source_funds_seq'):
|
||||
errors.append('分策略现金尚未按实际账户初始化')
|
||||
if param_store.get('PMS_DISPATCH_MODE', 'shadow') != 'ws' or not param_store.get_bool('PMS_QMT_WS_ENABLED', False):
|
||||
errors.append('自动执行需要启用唯一QMT直连通道')
|
||||
config = configuration()
|
||||
if not {'MAIN', 'STAR', 'CHINEXT'} <= config['boards']:
|
||||
errors.append('沪深及创业板、科创板权限尚未确认')
|
||||
if any(not math.isfinite(v) or v < 0 for v in config['costs'].values()):
|
||||
errors.append('交易费用参数无效')
|
||||
return errors
|
||||
evidence, _ = store.get('validation:'+configuration()['rule_version'])
|
||||
evidence = evidence or {}
|
||||
required = ('backtest', 'capacity', 'fees', 'board_permissions', 'migration', 'regression', 'browser', 'fill_attribution', 'fund_reservation')
|
||||
labels = dict(backtest='回测', capacity='成交容量', fees='交易费用', board_permissions='板块权限',
|
||||
migration='策略账本迁移', regression='回归测试', browser='页面检查', fill_attribution='成交归属', fund_reservation='资金占用')
|
||||
errors = [labels[k]+'尚未验收' for k in required if not evidence.get(k)]
|
||||
observed = store.recent('observed_day', 1000)
|
||||
paper = store.recent('paper_day', 1000)
|
||||
dates = sorted({r['value']['date'] for r in observed if r['value'].get('rule_version') == configuration()['rule_version']})
|
||||
paper_dates = sorted({r['value']['date'] for r in paper if r['value'].get('rule_version') == configuration()['rule_version'] and r['value'].get('healthy')})
|
||||
if len(dates) < 3:
|
||||
errors.append('有效观察不足3个交易日')
|
||||
if len(paper_dates) < 10 or (len(dates) >= 3 and any(d <= dates[2] for d in paper_dates[:10])):
|
||||
errors.append('观察完成后的健康纸面运行不足10个交易日')
|
||||
return errors
|
||||
|
||||
|
||||
def signal_history(end, limit=60):
|
||||
"""只读展示历史,来自监控同一公式;不参与轮换决策。"""
|
||||
day = dt.date.fromisoformat(end)
|
||||
if day > dt.datetime.now(TZ).date():
|
||||
raise ValueError('趋势日期不能晚于今天')
|
||||
config = configuration()
|
||||
if config['rule_version'] not in core.SUPPORTED_RULES:
|
||||
raise ValueError('运行规则与趋势代码不一致')
|
||||
url = config['url']
|
||||
if not url:
|
||||
raise ValueError('监控地址未配置')
|
||||
n = max(1, min(120, int(limit)))
|
||||
response = requests.get(url+'/v1/history', params={'end': end, 'limit': n}, timeout=(3, 8))
|
||||
response.raise_for_status()
|
||||
if len(response.content) > 512*1024:
|
||||
raise ValueError('趋势数据超过大小限制')
|
||||
value = response.json()
|
||||
rows = value.get('records')
|
||||
if value.get('rule_version') != config['rule_version'] or value.get('rule_parameters') != core.rule_parameters(config['rule_version'], config.get('candidate_pool_size', 100)) or not isinstance(rows, list) or len(rows) > n:
|
||||
raise ValueError('趋势规则或格式不符')
|
||||
previous = ''
|
||||
for row in rows:
|
||||
date = row.get('date', '')
|
||||
dt.date.fromisoformat(date)
|
||||
if date <= previous or date > end:
|
||||
raise ValueError('趋势日期重复、乱序或超出范围')
|
||||
previous = date
|
||||
values = [row.get(k) for k in ('activity', 'activity_percentile', 'low_threshold', 'high_threshold')]
|
||||
values += list((row.get('group_percentiles') or {}).values())
|
||||
if any(v is not None and (isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v)) for v in values):
|
||||
raise ValueError('趋势数值无效')
|
||||
return value
|
||||
|
||||
|
||||
def status():
|
||||
config = configuration()
|
||||
out = {'mode': config['mode'], 'control': config['control'], 'rule_version': config['rule_version'],
|
||||
'rule_parameters': core.rule_parameters(config['rule_version'], config.get('candidate_pool_size', 100)) if config['rule_version'] in core.SUPPORTED_RULES else {},
|
||||
'simulation_direct': not settings.PMS_TABLE_PREFIX and param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False),
|
||||
'basket_size': core.SIZE, 'schema_ready': settings.INFRA_STRATEGY_BOOK_SCHEMA, 'documents_ready': documents_ready(),
|
||||
'phase': 'original', 'snapshot': None, 'errors': [], 'activation_errors': []}
|
||||
try:
|
||||
out['snapshot'] = pull()
|
||||
except Exception as exc:
|
||||
out['errors'].append('监控暂不可用:'+type(exc).__name__)
|
||||
if documents_ready():
|
||||
value, _ = store.get('state:'+('paper' if config['mode'] == 'paper' else 'live'))
|
||||
if value:
|
||||
out.update(state=value, phase=value.get('rotation', {}).get('phase', 'original'))
|
||||
out['activation_errors'] = activation_errors()
|
||||
out['recent'] = store.recent('execution', 30)
|
||||
out['observed_days'] = len({r['value']['date'] for r in store.recent('observed_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version']})
|
||||
out['paper_days'] = len({r['value']['date'] for r in store.recent('paper_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version'] and r['value'].get('healthy')})
|
||||
out['daily'] = store.recent('paper_day' if config['mode'] == 'paper' else 'live_day', 500)
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] != 'paper':
|
||||
try:
|
||||
from app.services.rotation_accounting import view
|
||||
out['accounting'] = view()
|
||||
if out['accounting'].get('reason'):
|
||||
out['errors'].append(out['accounting']['reason'])
|
||||
except Exception as exc:
|
||||
logger.warning('策略资金读取失败:%s', type(exc).__name__)
|
||||
out['errors'].append('策略资金暂不可用,请稍后刷新;持仓数量仍单独核对。')
|
||||
# 数量对账不依赖估值,单只股票没有分钟行情不能遮蔽账户持仓核验。
|
||||
try:
|
||||
out['reconciliation'] = reconcile_books()
|
||||
except Exception as exc:
|
||||
out['reconciliation'] = {'ok': False, 'diffs': [], 'fixes': [],
|
||||
'errors': ['持仓数量对账暂不可用'], 'severity': 'ERROR'}
|
||||
logger.warning('策略持仓数量对账失败:%s', type(exc).__name__)
|
||||
out['errors'].append('持仓数量暂未核实,请稍后刷新。')
|
||||
else:
|
||||
out['activation_errors'] = ['策略账本迁移尚未启用']
|
||||
out['stock_budget'] = param_store.get_float('PMS_TOTAL_SCALE', 0)*param_store.get_float('PMS_PORTFOLIO_CAP', 0)
|
||||
out['costs'] = config['costs']
|
||||
out['boards'] = sorted(config['boards'])
|
||||
return out
|
||||
|
||||
|
||||
def control(*, mode=None, action=None, actor='user'):
|
||||
if mode not in (None, 'observe', 'paper', 'auto') or action not in (None, 'run', 'pause_new', 'pause_all', 'exit_disable'):
|
||||
raise ValueError('轮换档位或控制动作非法')
|
||||
if mode in ('paper', 'auto') and not documents_ready():
|
||||
raise ValueError('观察与纸面记录表尚未建立')
|
||||
if mode == 'paper' and not (not settings.PMS_TABLE_PREFIX and param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False)):
|
||||
days = {r['value']['date'] for r in store.recent('observed_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version']}
|
||||
if len(days) < 3:
|
||||
raise ValueError('有效观察不足3个交易日,暂不进入纸面运行')
|
||||
if mode == 'auto':
|
||||
errors = activation_errors()
|
||||
if errors:
|
||||
raise ValueError(';'.join(errors))
|
||||
if mode:
|
||||
current, _ = store.get('state:live') if settings.INFRA_STRATEGY_BOOK_SCHEMA else (None, 0)
|
||||
if current and current.get('rotation', {}).get('phase') != 'original' and mode != 'auto':
|
||||
raise ValueError('实有微盘持仓或轮换在途,请先使用暂停或退出操作,不直接切换账本模式')
|
||||
result = param_store.set_param('PMS_ROTATION_MODE', mode, actor)
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('档位保存失败')
|
||||
if action:
|
||||
result = param_store.set_param('PMS_ROTATION_CONTROL', action, actor)
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('控制保存失败')
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and configuration()['mode'] == 'auto':
|
||||
cancel_control_orders(action)
|
||||
return status()
|
||||
|
||||
|
||||
def cancel_control_orders(action):
|
||||
"""先保存暂停,再撤已发出的轮换委托;失败保留暂停并由调度重试。"""
|
||||
if action not in ('pause_all', 'pause_new', 'exit_disable'):
|
||||
return
|
||||
from app.services import executor
|
||||
with books.scope('all'):
|
||||
rows = pms_repo.list_instructions(statuses=LIVE, limit=10000)
|
||||
failed = []
|
||||
for row in rows:
|
||||
if (row.get('progress') or {}).get('execution_profile') != 'rotation':
|
||||
continue
|
||||
if action != 'pause_all' and row['side'] != 'buy':
|
||||
continue
|
||||
with books.scope(row['book_id']):
|
||||
result = executor.cancel_instruction(row['instruction_id'], reason='用户轮换控制:'+action, arbiter='user')
|
||||
if not result.get('ok'):
|
||||
failed.append(row['instruction_id'])
|
||||
if failed:
|
||||
raise RuntimeError('已停止新增指令,部分既有委托尚未完成撤销')
|
||||
|
||||
|
||||
def positions(book):
|
||||
with books.scope(book):
|
||||
return pms_repo.list_positions(only_open=True)
|
||||
|
||||
|
||||
def _paper_seed():
|
||||
funds = portfolio.cash_view()
|
||||
if funds['source'] != 'ws' or funds.get('cash_avail') is None:
|
||||
raise ValueError('纸面账户初始化需要有效QMT资金快照')
|
||||
account = {'cash': funds['cash_avail'], 'books': {'original': {}, 'micro30': {}},
|
||||
'realized': {'original': 0., 'micro30': 0.}, 'fees': {'original': 0., 'micro30': 0.},
|
||||
'fills': {}, 'seeded_at': dt.datetime.now(TZ).isoformat(), 'seed_asset': funds.get('total_asset')}
|
||||
with books.scope('original'):
|
||||
for p in pms_repo.list_positions(only_open=True):
|
||||
lots = [{'date': str(r['open_date'])[:10], 'qty': int(r['qty'])} for r in pms_repo.list_lots(p['ts_code'])]
|
||||
if sum(r['qty'] for r in lots) != p['total_qty']:
|
||||
raise ValueError('原策略批次数量与主档不一致')
|
||||
account['books']['original'][p['ts_code']] = {'qty': p['total_qty'],
|
||||
'cost': float(p.get('avg_cost') or 0)*p['total_qty'], 'lots': lots,
|
||||
'base_qty': p['base_qty'], 'cushion_pct': float(p.get('cushion_pct') or 0)}
|
||||
return account
|
||||
|
||||
|
||||
def _paper_positions(account, book, day):
|
||||
return [{'ts_code': code, 'total_qty': p['qty'], 'avail_qty': sum(r['qty'] for r in p['lots'] if r['date'] < day),
|
||||
'base_qty': p.get('base_qty', p['qty']), 'cushion_pct': p.get('cushion_pct'), 'neg_cushion_days': p.get('neg_cushion_days', 0)}
|
||||
for code, p in account['books'][book].items() if p['qty']]
|
||||
|
||||
|
||||
def _quote(code, now):
|
||||
quote = market.day_snapshot(code)
|
||||
raw = quote.get('bar_time')
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
stamp = dt.datetime.fromisoformat(str(raw).replace('Z', '+00:00'))
|
||||
if stamp.tzinfo is None:
|
||||
stamp = stamp.replace(tzinfo=TZ)
|
||||
if not 0 <= (now-stamp).total_seconds() <= 180:
|
||||
return {}
|
||||
except ValueError:
|
||||
return {}
|
||||
return quote
|
||||
|
||||
|
||||
def _limits(day):
|
||||
if param_store.get_bool('PMS_LIMIT_CACHE_ENABLED', False):
|
||||
from app.services import price_limits
|
||||
return price_limits.get_limits(day)
|
||||
from app.db import session as db
|
||||
rows = db.fetch_all('SELECT ts_code,up_limit,down_limit FROM gp_stk_limit WHERE trade_date=:day '
|
||||
"AND (ts_code LIKE '60____.SH' OR ts_code LIKE '68____.SH' OR ts_code LIKE '00____.SZ' OR ts_code LIKE '30____.SZ')", {'day': day})
|
||||
return {r['ts_code']: r for r in rows}
|
||||
|
||||
|
||||
def _unavailable_candidates(snapshot, quotes, budget, boards, costs):
|
||||
"""仅明确停牌或静态交易资格问题递补;行情缺失和价格落后都不是停牌。"""
|
||||
unavailable = {}
|
||||
for member in snapshot.get('candidates', snapshot.get('members', [])):
|
||||
code = member['code']
|
||||
quote = quotes.get(code, {})
|
||||
if quote.get('halted') is True:
|
||||
unavailable[code] = '行情来源明确标记停牌'
|
||||
elif core.board(code) not in boards:
|
||||
unavailable[code] = '账户没有该板块权限'
|
||||
elif budget > 0 and not core.buy_qty(code, float(member.get('close') or 0), budget/core.SIZE, costs):
|
||||
unavailable[code] = '单股预算不足最低交易单位及费用'
|
||||
return unavailable
|
||||
|
||||
|
||||
def _micro_unsettled(pending):
|
||||
"""本地撤销不等于下游终态;未入账成交也不能视为退出已完成。"""
|
||||
if any(r['book_id'] == books.MICRO for r in pending) or qmt_repo.inbox_pending_count():
|
||||
return True
|
||||
rows = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
|
||||
if len(rows) > 10000:
|
||||
raise ValueError('在途委托超出轮换核验上限')
|
||||
with books.scope('all'):
|
||||
for row in rows:
|
||||
parent = pms_repo.get_instruction(row['parent_id'])
|
||||
if not parent:
|
||||
raise ValueError('在途委托策略归属尚未核实')
|
||||
if parent['book_id'] == books.MICRO:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def tick(now=None):
|
||||
"""先独立提交轮换决定,再执行;两段均先锁账户,再锁轮换状态。"""
|
||||
config = configuration()
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
||||
# 撤单、限制价查询或下发失败不能回滚已经确认的入场/退出任务。
|
||||
# 两段之间释放账户锁;执行段重新读取用户控制、资金和实际持仓。
|
||||
with store.account_guard():
|
||||
prepared = _tick(now, prepare_only=True)
|
||||
if not prepared.get('prepared'):
|
||||
return prepared
|
||||
with store.account_guard():
|
||||
return _tick(now)
|
||||
return _tick(now)
|
||||
|
||||
|
||||
def _tick(now=None, *, prepare_only=False):
|
||||
now = now or dt.datetime.now(TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=TZ)
|
||||
config = configuration()
|
||||
day = now.date().isoformat()
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
||||
cancel_control_orders(config['control'])
|
||||
if config['mode'] == 'auto' and settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
from app.services.rotation_execution import cancel_expired
|
||||
cancel_expired(now)
|
||||
if td.calendar_degraded(day) or not td.is_trade_day(day):
|
||||
return {'skipped': '交易日历不可用或非交易日'}
|
||||
key = 'state:'+('paper' if config['mode'] == 'paper' else 'live')
|
||||
saved, _ = store.get(key) if documents_ready() else (None, 0)
|
||||
saved = saved or {}
|
||||
exit_pending = saved.get('rotation', {}).get('phase') == 'returning_original' or config['control'] == 'exit_disable'
|
||||
value, errors = None, []
|
||||
try:
|
||||
value = pull(day)
|
||||
errors = core.snapshot_check(value, day, expected_rule=config['rule_version'], candidate_pool_size=config.get('candidate_pool_size', 100))
|
||||
except Exception as exc:
|
||||
errors = ['监控暂不可用:'+type(exc).__name__]
|
||||
if errors:
|
||||
value = None
|
||||
if not documents_ready():
|
||||
return {'snapshot': value, 'mode': 'observe', 'blocked': errors+['观察记录表尚未启用']}
|
||||
if value:
|
||||
store.put_once('snapshot:'+day+':'+value['snapshot_version'], 'snapshot', value)
|
||||
if value['signal_ready'] and value['basket_ready']:
|
||||
store.put_once('observed:'+day, 'observed_day', {'date': day, 'rule_version': config['rule_version'], 'snapshot_version': value['snapshot_version']})
|
||||
if config['mode'] == 'observe':
|
||||
return {'mode': 'observe', 'snapshot': value, 'blocked': errors}
|
||||
exit_pending = exit_pending or bool(value and value.get('signal_ready') and value.get('signal', {}).get('high') and saved.get('rotation', {}).get('phase') in ('entering_micro', 'micro'))
|
||||
if config['mode'] == 'auto':
|
||||
blocked = activation_errors()
|
||||
# 初次启用必须完成全部验收;已确认的退出不因监控/观察证据故障卡住。
|
||||
if blocked and not (exit_pending and settings.INFRA_STRATEGY_BOOK_SCHEMA):
|
||||
return {'blocked': blocked}
|
||||
if not value and not exit_pending:
|
||||
return {'blocked': errors}
|
||||
if value is None:
|
||||
# 仅作为已确认退出的执行上下文,不写成新快照、不生成任何入场。
|
||||
value = {'members': [], 'signal_ready': False, 'basket_ready': False,
|
||||
'effective_date': day, 'snapshot_version': saved.get('rotation', {}).get('last_snapshot'), 'signal': {}}
|
||||
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
||||
config['control'] = 'pause_all'
|
||||
elif param_store.get_bool('PMS_GLOBAL_BUY_HALT', False) and config['control'] == 'run':
|
||||
config['control'] = 'pause_new'
|
||||
manual_exit = config['control'] == 'exit_disable' and (570 <= now.hour*60+now.minute < 690 or 780 <= now.hour*60+now.minute < 895)
|
||||
if not 570 <= now.hour*60+now.minute < 600 and not manual_exit:
|
||||
if config['mode'] == 'auto':
|
||||
from app.services.rotation_execution import cancel_expired
|
||||
cancel_expired(now)
|
||||
return {'skipped': '执行窗口之外'}
|
||||
key = 'state:'+('paper' if config['mode'] == 'paper' else 'live')
|
||||
with store.locked(key, 'state', {'rotation': core.initial_state()}) as state:
|
||||
if config['mode'] == 'paper':
|
||||
if 'account' not in state:
|
||||
state['account'] = _paper_seed()
|
||||
account = state['account']
|
||||
original = _paper_positions(account, 'original', day)
|
||||
micro = _paper_positions(account, 'micro30', day)
|
||||
cash = account['cash']
|
||||
pending = []
|
||||
else:
|
||||
recon = reconcile_books()
|
||||
if recon['diffs'] or not recon['ok']:
|
||||
return {'blocked': ['策略账本与QMT尚未对齐']}
|
||||
original, micro = positions('original'), positions('micro30')
|
||||
funds = portfolio.cash_view()
|
||||
if funds['source'] != 'ws':
|
||||
raise ValueError('真实资金快照不可用')
|
||||
cash = funds['cash_avail']
|
||||
from app.services.rotation_execution import pending_instructions
|
||||
pending = pending_instructions()
|
||||
codes = {r['ts_code'] for r in original+micro}|{r['code'] for r in value.get('candidates', value['members'])}
|
||||
quotes = {c: _quote(c, now) for c in codes}
|
||||
missing = [r['ts_code'] for r in original+micro if not quotes.get(r['ts_code'])]
|
||||
if missing and not exit_pending:
|
||||
if config['mode'] == 'auto' and config['rule_version'] == core.EXECUTION_RULE:
|
||||
from app.services.rotation_execution import refresh_orders
|
||||
# 估值不完整时不增加风险,已发v3单先撤清,未知行情不触发递补。
|
||||
refresh_orders(pending, {}, now, value['snapshot_version'],
|
||||
set(state.get('rotation', {}).get('target') or []), {})
|
||||
state['blocked'] = ['持仓行情不完整,无法核算全账户仓位']+missing
|
||||
return {'blocked': state['blocked']}
|
||||
account_mv = sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in original+micro)
|
||||
if config['mode'] == 'paper' and 'capital' not in account and not missing:
|
||||
from app.core import rotation_account as capital
|
||||
account['capital'] = capital.seed(cash, {'original': account_mv, 'micro30': 0.})
|
||||
scale = param_store.get_float('PMS_TOTAL_SCALE', 0.)
|
||||
cap = scale*param_store.get_float('PMS_PORTFOLIO_CAP', 0.)
|
||||
reserve = scale*param_store.get_float('PMS_CASH_RESERVE', 0.)
|
||||
budget = max(0., min(cap, cash+account_mv-reserve))
|
||||
boards = config['boards'] if config['mode'] == 'auto' else {'MAIN', 'STAR', 'CHINEXT'}
|
||||
execution_quotes = {}
|
||||
buy_prices = {}
|
||||
quote_errors = []
|
||||
limits = None
|
||||
if config['rule_version'] == core.EXECUTION_RULE and not prepare_only:
|
||||
from app.services import execution_orders
|
||||
try:
|
||||
limits = _limits(day)
|
||||
except Exception as exc:
|
||||
limits = {}
|
||||
quote_errors.append('当日限制价查询失败:'+type(exc).__name__)
|
||||
for c in codes:
|
||||
try:
|
||||
execution_quotes[c] = market.execution_quote(c, now=now, limits=limits.get(c, {}))
|
||||
except Exception as exc:
|
||||
# 查询失败是未知,不能把故障改写成该股不可交易的资格结论。
|
||||
execution_quotes[c] = {}
|
||||
quote_errors.append(c+'执行行情查询失败:'+type(exc).__name__)
|
||||
for c, execution_quote in execution_quotes.items():
|
||||
priced = execution_orders.quote_order('buy', execution_quote, now)
|
||||
if priced.get('action') == 'FIRE':
|
||||
buy_prices[c] = {**quotes.get(c, {}), 'price': priced['limit_price']}
|
||||
unavailable = _unavailable_candidates(value, execution_quotes, budget, boards, config['costs'])
|
||||
if config['mode'] == 'auto' and config['rule_version'] == core.EXECUTION_RULE and not prepare_only:
|
||||
from app.services.rotation_execution import suspended_rejections
|
||||
unavailable.update(suspended_rejections(now))
|
||||
fresh_entry = state['rotation']['phase'] == 'original' and config['control'] == 'run' and value.get('signal_ready') and value.get('basket_ready') and not value['signal'].get('high') and (value['signal'].get('low') or value['signal'].get('growth_break'))
|
||||
if fresh_entry:
|
||||
# 先排除确定性整体不可执行,不能先清旧仓再发现根本没有建仓预算。
|
||||
static_issues = core.preflight(value['members'], budget, boards, config['costs'])
|
||||
if config['rule_version'] == core.EXECUTION_RULE:
|
||||
static_issues = ['没有可执行的初始建仓候选或预算'] if budget <= 0 or not any(m['code'] not in unavailable for m in value['candidates']) else []
|
||||
if static_issues:
|
||||
state['blocked'] = static_issues
|
||||
return {'blocked': static_issues}
|
||||
s = core.transition(state['rotation'], value, micro_qty=sum(r['total_qty'] for r in micro),
|
||||
original_qty=sum(r['total_qty'] for r in original), budget=budget, control=config['control'],
|
||||
micro_pending=config['mode'] == 'auto' and exit_pending and _micro_unsettled(pending))
|
||||
state['rotation'] = s
|
||||
target_waits = core.resolve_targets(s, value, micro=micro, pending=pending, unavailable=unavailable)
|
||||
if s['phase'] == 'returning_original' and not s.get('exit_date'):
|
||||
s['exit_date'] = day
|
||||
store.stage_locked(key, state)
|
||||
if prepare_only:
|
||||
return {'prepared': True, 'mode': config['mode'], 'phase': s['phase']}
|
||||
if config['mode'] == 'auto' and s['phase'] in ('entering_micro', 'returning_original'):
|
||||
from app.services import executor
|
||||
for old in pending:
|
||||
if old['side'] == 'buy' and not (old['book_id'] == 'original' and closing_t0(old)) and (s['phase'] == 'returning_original' or old['book_id'] == 'original'):
|
||||
with books.scope(old['book_id']):
|
||||
result = executor.cancel_instruction(old['instruction_id'], reason='策略轮换停止新增投入', arbiter='system')
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('原买入撤单尚未确认,暂停轮换')
|
||||
with books.scope('original'):
|
||||
t0_open = any((r.get('state') or {}).get('open_leg') for r in pms_repo.active_strategies() if r.get('type') == 'T0')
|
||||
if t0_open or any(p.get('t0_qty', 0) for p in original):
|
||||
state['blocked'] = ['原策略尚有做T批次,等待完成后继续轮换']
|
||||
return {'blocked': state['blocked']}
|
||||
from app.services import command_service
|
||||
black = command_service.blacklist()
|
||||
refreshed, refresh_waits = [], []
|
||||
if config['mode'] == 'auto' and s.get('rule_version') == core.EXECUTION_RULE and config['control'] == 'run':
|
||||
from app.services.rotation_execution import refresh_orders
|
||||
refreshed, refresh_waits = refresh_orders(pending, 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']):
|
||||
# 先完成已有单的撤销确认,避免全部停牌时卡住递补;不新卖原仓筹资。
|
||||
state['blocked'] = quote_errors+target_waits+refresh_waits+['目标成员当前没有可核实执行报价,暂不卖出原策略筹资']
|
||||
return {'blocked': state['blocked'], 'phase': s['phase'], 'results': refreshed}
|
||||
planning_quotes = {**quotes, **buy_prices}
|
||||
intents, waits = core.orders(s, value, original=original, micro=micro, quotes=planning_quotes,
|
||||
cash=cash, account_mv=account_mv, cap_amount=cap, reserve_cash=reserve,
|
||||
pending=pending, control=config['control'], blacklisted=black, costs=config['costs'])
|
||||
# 纸面档明确采用全沪深权限假设,不把它当实际账户权限判收。
|
||||
issues = core.preflight(value['members'], budget, boards, config['costs']) if value['basket_ready'] else ['名单未就绪']
|
||||
if issues and s.get('rule_version') != core.EXECUTION_RULE:
|
||||
intents = [r for r in intents if r['side'] == 'sell']
|
||||
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]
|
||||
waits.extend(quote_errors+target_waits+refresh_waits)
|
||||
if limits is None:
|
||||
limits = _limits(day)
|
||||
done = list(refreshed)
|
||||
for i, intent in enumerate(intents):
|
||||
c, side = intent['ts_code'], intent['side']
|
||||
quote = quotes.get(c, {})
|
||||
price = quote.get('price')
|
||||
lim = limits.get(c)
|
||||
if s.get('rule_version') == core.EXECUTION_RULE:
|
||||
from app.services import execution_orders
|
||||
priced = execution_orders.quote_order(side, execution_quotes.get(c, {}), now)
|
||||
if priced.get('action') != 'FIRE':
|
||||
waits.append(c+str(priced.get('reason') or '执行报价不可用'))
|
||||
continue
|
||||
price = priced['limit_price']
|
||||
intent['quote_basis'] = {**execution_quotes.get(c, {}), **priced}
|
||||
intent['rule_version'] = core.EXECUTION_RULE
|
||||
if not price or not lim or not lim.get('up_limit') or not lim.get('down_limit'):
|
||||
waits.append(c+'行情或限制价不完整')
|
||||
continue
|
||||
if s.get('rule_version') != core.EXECUTION_RULE and ((side == 'buy' and price >= float(lim['up_limit'])) or (side == 'sell' and price <= float(lim['down_limit']))):
|
||||
waits.append(c+'涨跌停阻止成交')
|
||||
continue
|
||||
rows = original if intent['book_id'] == 'original' else micro
|
||||
pos = next((r for r in rows if r['ts_code'] == c), {})
|
||||
if side == 'sell':
|
||||
intent['qty'] = min(intent['qty'], int(pos.get('avail_qty') or 0))
|
||||
if not intent['qty']:
|
||||
continue
|
||||
# 报价是可变执行信息,不进入父任务幂等键。
|
||||
identity = {k: v for k, v in intent.items() if k != 'quote_basis'}
|
||||
token = hashlib.sha256(json.dumps([day, s['cycle'], identity, len(state.get('account', {}).get('fills', {}))], sort_keys=True).encode()).hexdigest()[:24]
|
||||
intent['id'] = 'ROT_'+token
|
||||
if config['mode'] == 'paper':
|
||||
core.apply_paper_fill(account, intent, price, day, config['costs'],
|
||||
prices={c: q['price'] for c, q in quotes.items() if q.get('price')})
|
||||
done.append(intent)
|
||||
else:
|
||||
from app.services.rotation_execution import send_intent
|
||||
from app.db import session as db
|
||||
try:
|
||||
with db.savepoint():
|
||||
done.append(send_intent(intent, price, now, value['snapshot_version']))
|
||||
except Exception as exc:
|
||||
waits.append(c+'委托待重试:'+type(exc).__name__)
|
||||
if s['phase'] == 'entering_micro' and len(s['target']) == core.SIZE and not original and all(any(p['ts_code'] == c and p['total_qty'] >= s.get('entry_quantities', {}).get(c, 0) for p in micro) for c in s['target']) and not pending:
|
||||
s['phase'] = 'micro'
|
||||
state.update(last_tick=now.isoformat(), blocked=waits+errors, last_intents=intents, last_results=done,
|
||||
signal_healthy=bool(value.get('signal_ready') and value.get('basket_ready')),
|
||||
progress={'original_market_value': sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in original),
|
||||
'micro_market_value': sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in micro),
|
||||
'available_cash': cash, 'allowed_stock_budget': budget, 'original_count': len(original), 'micro_count': len(micro)})
|
||||
if config['mode'] == 'paper':
|
||||
state['board_permission_assumption'] = '纸面使用沪深全部板块,不是实际权限核实'
|
||||
state['nav'] = account['cash']+sum(p['qty']*quotes.get(c, {}).get('price', 0.) for b in account['books'].values() for c, p in b.items())
|
||||
if done:
|
||||
event = {'at': now.isoformat(), 'mode': config['mode'], 'phase': s['phase'], 'results': done, 'snapshot_version': value['snapshot_version']}
|
||||
store.put_once('execution:'+hashlib.sha256(json.dumps(event, sort_keys=True, default=str).encode()).hexdigest(), 'execution', event)
|
||||
return {'mode': config['mode'], 'phase': s['phase'], 'results': done, 'blocked': waits+errors}
|
||||
|
||||
|
||||
def original_buy_blocker():
|
||||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||||
return None
|
||||
value, _ = store.get('state:live')
|
||||
phase = (value or {}).get('rotation', {}).get('phase', 'original')
|
||||
return '账户正在转入或运行微盘策略,原策略停止新增投入' if phase in ('entering_micro', 'micro') else None
|
||||
|
||||
|
||||
|
||||
def closing_t0(parent):
|
||||
p = parent or {}
|
||||
return p.get('origin_type') == 'strategy' and p.get('action') == 'T0_ROUND' and (p.get('progress') or {}).get('leg') == 'close'
|
||||
|
||||
|
||||
def strategy_buy_blocker(book, parent=None):
|
||||
config = configuration()
|
||||
if book == books.ORIGINAL:
|
||||
if closing_t0(parent):
|
||||
return None
|
||||
return original_buy_blocker()
|
||||
if config['mode'] != 'auto' or config['control'] != 'run':
|
||||
return '微盘未在自动运行档或用户已停止新增'
|
||||
value, _ = store.get('state:live')
|
||||
if (value or {}).get('rotation', {}).get('phase') not in ('entering_micro', 'micro'):
|
||||
return '微盘阶段不允许新增买入'
|
||||
return None
|
||||
|
||||
|
||||
def reconcile_books():
|
||||
from app.services.ledger_service import positions_source
|
||||
from app.core.recon import diff_positions
|
||||
source = positions_source()
|
||||
totals = {}
|
||||
with books.scope('all'):
|
||||
rows = pms_repo.list_positions()
|
||||
for row in rows:
|
||||
code = row['ts_code']
|
||||
totals[code] = totals.get(code, 0)+int(row['total_qty'])
|
||||
if source['source'] != 'ws':
|
||||
return {'ok': False, 'diffs': [], 'fixes': [], 'errors': ['没有有效账户持仓事实源'], 'severity': 'ERROR'}
|
||||
differences = diff_positions([{'ts_code': c, 'total_qty': q} for c, q in totals.items()], source['rows'])
|
||||
return {'ok': not differences, 'diffs': differences, 'fixes': [], 'errors': [],
|
||||
'severity': 'ERROR' if differences else 'OK', 'source': source['source'],
|
||||
'note': '策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略'}
|
||||
|
||||
|
||||
def on_user_command(cmd_type, command_id, issued_by):
|
||||
if issued_by in ('rotation', 'macro') or str(issued_by).startswith('macro'):
|
||||
return
|
||||
if cmd_type in ('LIQUIDATE_ALL', 'HALT_ALL', 'HALT_BUY'):
|
||||
action = {'LIQUIDATE_ALL': 'exit_disable', 'HALT_ALL': 'pause_all', 'HALT_BUY': 'pause_new'}[cmd_type]
|
||||
result = param_store.set_param('PMS_ROTATION_CONTROL', action, issued_by)
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('全账户命令未同步到轮换控制')
|
||||
from app.services import executor
|
||||
with books.scope('micro30'):
|
||||
for ins in pms_repo.list_instructions(statuses=LIVE, limit=10000):
|
||||
if cmd_type == 'HALT_ALL' or ins['side'] == 'buy':
|
||||
result = executor.cancel_instruction(ins['instruction_id'], reason='用户全账户命令'+command_id, arbiter='user')
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('用户命令已停新增,既有委托撤销尚未确认')
|
||||
elif cmd_type in ('OPEN_TARGET', 'INCREASE_EXPOSURE', 'REDUCE_EXPOSURE', 'EXIT_STOCK', 'REDUCE_STOCK'):
|
||||
state, _ = store.get('state:live')
|
||||
if state and state['rotation']['phase'] != 'original':
|
||||
result = param_store.set_param('PMS_ROTATION_CONTROL', 'pause_all', issued_by)
|
||||
if not result.get('ok'):
|
||||
raise RuntimeError('用户命令冲突暂停未保存')
|
||||
cancel_control_orders('pause_all')
|
||||
store.put_once('conflict:'+command_id, 'command_conflict', {'command_id': command_id, 'reason': '用户命令优先,轮换已暂停'})
|
||||
|
||||
|
||||
def settle_day(now=None):
|
||||
now = now or dt.datetime.now(TZ)
|
||||
day = now.date().isoformat()
|
||||
if not documents_ready() or now.hour*60+now.minute < 15*60+20 or td.calendar_degraded(day) or not td.is_trade_day(day):
|
||||
return {'skipped': '未到有效交易日结算时间或观察表未启用'}
|
||||
config = configuration()
|
||||
if config['mode'] == 'auto':
|
||||
from app.services.rotation_accounting import view
|
||||
result = view()
|
||||
healthy = result['ready'] and result['cash_difference'] is not None and abs(result['cash_difference']) <= .02 and reconcile_books()['ok']
|
||||
record = {'date': day, 'rule_version': config['rule_version'], 'healthy': healthy, **result}
|
||||
store.put_once('live_day:'+day, 'live_day', record)
|
||||
return record
|
||||
if config['mode'] != 'paper':
|
||||
return {'skipped': '非纸面模式'}
|
||||
with store.locked('state:paper', 'state', {'rotation': core.initial_state()}) as state:
|
||||
account = state.get('account')
|
||||
if not account:
|
||||
return {'skipped': '纸面账户尚未初始化'}
|
||||
from app.core import rotation_account as capital
|
||||
values = {b: 0. for b in ('original','micro30')}
|
||||
missing = []
|
||||
for book, rows in account['books'].items():
|
||||
for code, p in rows.items():
|
||||
if not p['qty']:
|
||||
continue
|
||||
q = market.day_snapshot(code)
|
||||
stamp = str(q.get('bar_time') or '')
|
||||
try:
|
||||
at = dt.datetime.fromisoformat(stamp)
|
||||
valid = at.date().isoformat() == day and at.hour*60+at.minute >= 890
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid or not q.get('price'):
|
||||
missing.append(code)
|
||||
continue
|
||||
values[book] += p['qty']*q['price']
|
||||
healthy = bool(not missing and state.get('signal_healthy') and str(state.get('last_tick','')).startswith(day) and config['control'] != 'pause_all')
|
||||
metrics = capital.metrics(account['capital'], values) if account.get('capital') and not missing else None
|
||||
record = {'date': day, 'rule_version': config['rule_version'], 'healthy': healthy, 'missing_prices': missing,
|
||||
'metrics': metrics, 'fees': account['fees'], 'snapshot_version': state['rotation'].get('last_snapshot')}
|
||||
if metrics:
|
||||
state['metrics'] = metrics
|
||||
state['nav'] = metrics['account']['equity']
|
||||
store.put_once('paper_day:'+day, 'paper_day', record)
|
||||
return record
|
||||
|
||||
|
||||
def reset_micro_available(now=None):
|
||||
now = now or dt.datetime.now(TZ)
|
||||
if now.hour*60+now.minute >= 565:
|
||||
return {'skipped': '可卖数量只在盘前更新'}
|
||||
with books.scope('micro30'), store.locked('micro_available:'+now.date().isoformat(), 'daily_reset', {'done': False}) as marker:
|
||||
if marker['done']:
|
||||
return {'skipped': '当日已完成'}
|
||||
for p in pms_repo.list_positions(only_open=True):
|
||||
lots = pms_repo.list_lots(p['ts_code'])
|
||||
available = sum(int(r['qty']) for r in lots if str(r['open_date'])[:10] < now.date().isoformat())
|
||||
pms_repo.update_position(p['ts_code'], avail_qty=min(available, p['total_qty']))
|
||||
marker['done'] = True
|
||||
return {'done': True}
|
||||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ signal_digest / intraday_exec 互相覆盖 (与 portfolio.neg_streak_map 用独
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
|
||||
from app.core import tradedays as td
|
||||
|
|
@ -55,7 +56,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 批次
|
||||
|
|
@ -128,12 +129,36 @@ def _macro_gate_active() -> bool:
|
|||
|
||||
|
||||
# ================================================================ 指令 / 提议下发
|
||||
def _correction_id(st: dict):
|
||||
return ((st.get("state") or {}).get("trade_correction") or {}).get("correction_id")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _current_strategy(st: dict):
|
||||
"""只在落单阶段持账户锁;行情与策略求值不持锁、不跨线程。"""
|
||||
from app.services.execution_orders import account_guard
|
||||
with account_guard():
|
||||
fresh = pms_repo.get_strategy(st["strategy_id"])
|
||||
if not fresh or fresh.get("status") != "ACTIVE" or fresh.get("archived_at"):
|
||||
raise RuntimeError("策略已停用,停止生成新指令或提议")
|
||||
if (fresh.get("state") or {}).get("correction_hold"):
|
||||
raise RuntimeError("策略成交数量已更正,等待核对后续安排")
|
||||
if _correction_id(fresh) != _correction_id(st):
|
||||
raise RuntimeError("策略成交更正版本已变化,请按最新状态重新评估")
|
||||
yield fresh
|
||||
|
||||
|
||||
def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str:
|
||||
"""按决策发一张短窗口命令指令 (window_tdays=1, is_command=True), 交 run_tick 执行。
|
||||
|
||||
limit_price 不在这里定 —— 交由 run_tick 的择时按实时行情现算 (与 materialize_plans
|
||||
同口径: 那里也是 limit_price=None)。
|
||||
"""
|
||||
from config.settings import settings
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and dec.get('leg') != 'close':
|
||||
from app.services.rotation_service import original_buy_blocker
|
||||
if original_buy_blocker():
|
||||
raise ValueError('策略轮换期间停止原策略开新腿')
|
||||
code = st["ts_code"]
|
||||
now = datetime.now()
|
||||
iid = f"STR{_today()}{now.strftime('%H%M%S')}_{code.replace('.', '')}_{dec['leg'][:1]}"[:40]
|
||||
|
|
@ -141,11 +166,14 @@ def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str:
|
|||
# 网格/跟踪止盈到价即成交、当日没成交则作废, 不强制
|
||||
prog = {"is_command": is_cmd, "deadline": str(_today()), "children": [],
|
||||
"origin": "strategy", "strategy_id": st["strategy_id"], "stype": st.get("type"),
|
||||
"strategy_correction_id": _correction_id(st),
|
||||
"leg": dec["leg"], "reason": dec.get("reason"), "forced": bool(forced)}
|
||||
pms_repo.insert_instruction(
|
||||
with _current_strategy(st):
|
||||
if pms_repo.insert_instruction(
|
||||
instruction_id=iid, origin_type="strategy", origin_id=st["strategy_id"],
|
||||
ts_code=code, action=dec["action"], side=dec["side"], qty=int(dec["qty"]),
|
||||
limit_price=None, window_tdays=1, status="PROPOSED", progress=prog)
|
||||
limit_price=None, window_tdays=1, status="PROPOSED", progress=prog) != 1:
|
||||
raise RuntimeError("策略指令未成功保存")
|
||||
return iid
|
||||
|
||||
|
||||
|
|
@ -157,25 +185,32 @@ def _emit_proposal(st: dict, dec: dict) -> str:
|
|||
now = datetime.now()
|
||||
pid = f"STP{_today()}{now.strftime('%H%M%S')}_{code.replace('.', '')}"[:40]
|
||||
hard = {"kind": "strategy", "strategy_id": st["strategy_id"], "stype": st.get("type"),
|
||||
"strategy_correction_id": _correction_id(st),
|
||||
"side": dec["side"], "leg": dec["leg"], "action": dec["action"],
|
||||
"qty": int(dec["qty"]), "reason": dec.get("reason"), "entry": dec.get("entry")}
|
||||
expire = now.replace(hour=15, minute=0, second=0, microsecond=0)
|
||||
pms_repo.insert_proposal(proposal_id=pid, ts_code=code, action=dec["action"],
|
||||
with _current_strategy(st):
|
||||
if pms_repo.insert_proposal(proposal_id=pid, ts_code=code, action=dec["action"],
|
||||
qty=int(dec["qty"]), hard_numbers=hard, expire_at=expire,
|
||||
judge_verdict="STRATEGY",
|
||||
judge_reason=f"{st.get('type')} · {dec.get('reason')}")
|
||||
judge_reason=f"{st.get('type')} · {dec.get('reason')}") != 1:
|
||||
raise RuntimeError("策略提议未成功保存")
|
||||
return pid
|
||||
|
||||
|
||||
def emit_from_spec(spec: dict) -> dict:
|
||||
"""confirm 提议被采纳后的回调 (main._decide 调): 按 hard_numbers 里存的动作参数发指令。
|
||||
返回 {ok, instruction_id} 或 {ok:false, error}。"""
|
||||
from app.services.execution_orders import account_guard
|
||||
try:
|
||||
with account_guard():
|
||||
st = pms_repo.get_strategy(spec.get("strategy_id"))
|
||||
if not st:
|
||||
return {"ok": False, "error": "策略不存在或已撤下"}
|
||||
if st.get("status") != "ACTIVE":
|
||||
return {"ok": False, "error": f"策略处于 {st.get('status')}, 不再发指令"}
|
||||
if spec.get("strategy_correction_id") != _correction_id(st):
|
||||
return {"ok": False, "error": "提议对应的成交更正版本已变化,请按最新状态重新评估"}
|
||||
dec = {"side": spec["side"], "action": spec["action"], "qty": int(spec["qty"]),
|
||||
"leg": spec.get("leg") or "open", "reason": spec.get("reason"),
|
||||
"entry": spec.get("entry")}
|
||||
|
|
@ -183,7 +218,8 @@ def emit_from_spec(spec: dict) -> dict:
|
|||
state = dict(st.get("state") or {})
|
||||
state["pending"] = {"iid": iid, "leg": dec["leg"], "dir": spec.get("dir"),
|
||||
"qty": dec["qty"], "entry": dec.get("entry")}
|
||||
pms_repo.update_strategy(st["strategy_id"], state=state)
|
||||
if pms_repo.update_strategy(st["strategy_id"], state=state) != 1:
|
||||
raise RuntimeError("策略状态未成功保存")
|
||||
return {"ok": True, "instruction_id": iid}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("[strategy] 采纳提议发指令失败")
|
||||
|
|
@ -696,11 +732,14 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
|
||||
if dec:
|
||||
if not dry_run:
|
||||
with _current_strategy(st):
|
||||
_apply_grid_state(state, dec)
|
||||
if (st.get("autonomy") or "auto") == "confirm":
|
||||
pid = _emit_proposal(st, dec)
|
||||
state["pending"] = {"pid": pid, "leg": dec["leg"], "dir": dec.get("dir"),
|
||||
"qty": dec["qty"], "entry": dec.get("entry")}
|
||||
if pms_repo.update_strategy(st["strategy_id"], state=state) != 1:
|
||||
raise RuntimeError("策略状态未成功保存")
|
||||
out["queued"].append({"strategy_id": st["strategy_id"], "proposal_id": pid,
|
||||
"reason": dec["reason"]})
|
||||
else:
|
||||
|
|
@ -709,13 +748,15 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
"qty": dec["qty"], "entry": dec.get("entry"),
|
||||
"grid_sell_idx": dec.get("grid_sell_idx"),
|
||||
"grid_restore": dec.get("_grid_restore")}
|
||||
if pms_repo.update_strategy(st["strategy_id"], state=state) != 1:
|
||||
raise RuntimeError("策略状态未成功保存")
|
||||
out["fired"].append({"strategy_id": st["strategy_id"], "instruction_id": iid,
|
||||
"side": dec["side"], "qty": dec["qty"], "reason": dec["reason"]})
|
||||
else:
|
||||
out["fired"].append({"strategy_id": st["strategy_id"], "dry_run": True,
|
||||
"side": dec["side"], "qty": dec["qty"], "reason": dec["reason"]})
|
||||
|
||||
if not dry_run:
|
||||
if not dry_run and not dec:
|
||||
pms_repo.update_strategy(st["strategy_id"], state=state)
|
||||
except Exception as e: # noqa: BLE001 —— 单策略异常不拖垮整轮
|
||||
logger.exception("[strategy] 评估失败 %s", st.get("strategy_id"))
|
||||
|
|
@ -799,10 +840,12 @@ def force_t0_close(*, now=None) -> dict:
|
|||
if int(dec["qty"]) < LOT:
|
||||
out["skipped"].append({"strategy_id": st["strategy_id"], "why": "可平量不足 (avail 不够)"})
|
||||
continue
|
||||
with _current_strategy(st):
|
||||
iid = _emit_instruction(st, dec, forced=True)
|
||||
state["pending"] = {"iid": iid, "leg": "close", "dir": open_leg.get("dir"),
|
||||
"qty": dec["qty"], "entry": open_leg.get("entry")}
|
||||
pms_repo.update_strategy(st["strategy_id"], state=state)
|
||||
if pms_repo.update_strategy(st["strategy_id"], state=state) != 1:
|
||||
raise RuntimeError("策略状态未成功保存")
|
||||
out["closed"].append({"strategy_id": st["strategy_id"], "instruction_id": iid,
|
||||
"side": dec["side"], "qty": dec["qty"]})
|
||||
except Exception as e: # noqa: BLE001
|
||||
|
|
|
|||
|
|
@ -208,7 +208,9 @@ def cancel_by_code(ts_code: str, reason: str = "") -> dict:
|
|||
iid = i.get("instruction_id")
|
||||
try:
|
||||
r = executor.cancel_instruction(iid, reason=why, arbiter="system") or {}
|
||||
if r.get("ok"):
|
||||
if r.get('ok') and r.get('pending'):
|
||||
out.setdefault('pending_instructions', []).append(iid)
|
||||
elif r.get("ok"):
|
||||
out["instructions"].append(iid)
|
||||
else:
|
||||
out["ok"] = False
|
||||
|
|
|
|||
|
|
@ -444,3 +444,18 @@ def status() -> dict:
|
|||
"states": len(m.get("states") or {}), "fresh": bool(state_map(m)),
|
||||
"note": m.get("note"), "error": m.get("error"), "stale": m.get("stale")}
|
||||
return out
|
||||
|
||||
|
||||
def read_states_for(codes):
|
||||
"""盘中新加入的股票读取已有日线,按原规则合成立场,不重算行情或改写整份映射。"""
|
||||
codes = list(dict.fromkeys(codes))
|
||||
if not codes or not enabled():
|
||||
return {}
|
||||
p = _params()
|
||||
dd = tech_repo.latest_date()
|
||||
if not dd or _tdays_elapsed(dd, tradedays.ymd()) > int(p['stale_tdays']):
|
||||
return {}
|
||||
since = tradedays.ymd(tradedays.prev_trade_day(dd, tech_rules.CHOPPY_WINDOW + 5))
|
||||
history = tech_repo.history_multi(codes, since=since)
|
||||
return {code: _compact(tech_rules.synthesize(rows, params=p['rules']))
|
||||
for code, rows in history.items() if rows and int(rows[-1].get('data_date') or 0) == dd}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,500 @@
|
|||
"""两条QMT证据配对后的成交更正。原始成交不改写,投影与资金差额同成同败。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.core import command_spec, strategy_book as books, trade_correction as core, ws_codec
|
||||
from app.db import session as db
|
||||
from app.repo import pms_repo, qmt_repo, rotation_repo as store, trade_correction_repo as repo
|
||||
from config.settings import settings
|
||||
|
||||
TZ = ZoneInfo('Asia/Shanghai')
|
||||
IDENTITY = ('trade_no', 'instruction_id', 'broker_order_id', 'ts_code', 'side')
|
||||
ECONOMIC = ('qty', 'price', 'amount')
|
||||
LEGACY_NOTE = 'trade_correction 由通道进程消化, 不入账'
|
||||
|
||||
|
||||
class Waiting(Exception):
|
||||
"""配对或原成交尚未入账,原消息留在待处理,不把暂缺证据判成冲突。"""
|
||||
|
||||
|
||||
def _need(ok, reason):
|
||||
if not ok:
|
||||
raise ValueError(reason)
|
||||
|
||||
|
||||
def _d(value):
|
||||
_need(value is not None and not isinstance(value, bool), '金额或数量缺失')
|
||||
try:
|
||||
number = Decimal(str(value))
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
raise ValueError('金额或数量格式错误') from None
|
||||
_need(number.is_finite(), '金额或数量不是有限值')
|
||||
return number
|
||||
|
||||
|
||||
def _q(value):
|
||||
number = _d(value)
|
||||
_need(number >= 0 and number == number.to_integral_value(), '数量须为非负整数')
|
||||
return int(number)
|
||||
|
||||
|
||||
def _body(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, default=str, allow_nan=False)
|
||||
|
||||
|
||||
def _digest(value):
|
||||
return hashlib.sha256(_body(value).encode()).hexdigest()
|
||||
|
||||
|
||||
def _key(prefix, value):
|
||||
return prefix+hashlib.sha256(str(value).encode()).hexdigest()
|
||||
|
||||
|
||||
def _stamp(value):
|
||||
try:
|
||||
parsed = value if isinstance(value, dt.datetime) else dt.datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
return parsed.replace(tzinfo=TZ) if parsed.tzinfo is None else parsed.astimezone(TZ)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError('更正证据接收时间不可核实') from None
|
||||
|
||||
|
||||
def _values(payload):
|
||||
_need(isinstance(payload, dict) and all(k in payload for k in ECONOMIC), '成交数量价格金额不完整')
|
||||
return (_q(payload['qty']), _d(payload['price']), _d(payload['amount']))
|
||||
|
||||
|
||||
def _write(result, label):
|
||||
if not result:
|
||||
raise RuntimeError(label+'未写入,回滚本次更正')
|
||||
|
||||
|
||||
def _effective(row):
|
||||
original = copy.deepcopy(row['payload'])
|
||||
document, _ = store.get(_key('trade-effective:', original['trade_no']))
|
||||
if not document:
|
||||
return original
|
||||
_need(document.get('source_seq') == row['seq'] and document.get('original_digest') == _digest(original),
|
||||
'有效成交版本与原始成交证据不符')
|
||||
payload = document.get('effective')
|
||||
_need(isinstance(payload, dict) and all(payload.get(k) == original.get(k) for k in IDENTITY),
|
||||
'有效成交版本改变了成交身份')
|
||||
_need(all(payload.get(k) == original.get(k) for k in ('fee', 'fee_estimated', 'trade_time')),
|
||||
'有效成交版本改变了原费用或成交时间')
|
||||
_values(payload)
|
||||
return copy.deepcopy(payload)
|
||||
|
||||
|
||||
def _pair(row):
|
||||
payload = row.get('payload')
|
||||
_need(isinstance(payload, dict), '成交更正报文须为对象')
|
||||
cid, iid = payload.get('correction_id'), payload.get('instruction_id')
|
||||
_need(isinstance(cid, str) and 0 < len(cid) <= 128 and isinstance(iid, str) and iid,
|
||||
'成交更正缺少有效更正编号或子委托编号')
|
||||
_need(all(payload.get(k) not in (None, '') for k in IDENTITY), '更正缺少原成交身份')
|
||||
_need(isinstance(payload.get('before'), dict) and isinstance(payload.get('after'), dict)
|
||||
and set(payload['before']) == set(ECONOMIC) and set(payload['after']) == set(ECONOMIC),
|
||||
'更正前后只允许完整的数量、价格与金额')
|
||||
_need(isinstance(payload.get('reason'), str) and payload['reason'].strip(), '成交更正原因缺失')
|
||||
correct_time = payload.get('correct_time')
|
||||
_need(isinstance(correct_time, int) and not isinstance(correct_time, bool) and 0 < correct_time < 253402271999999,
|
||||
'更正时间须为正整数毫秒,不能替换原成交日期')
|
||||
originals = repo.corrections(cid, iid)
|
||||
_need(all(_digest(r['payload']) == _digest(payload) for r in originals), '同一更正编号对应不同更正内容')
|
||||
_need(not any(r['processed'] == qmt_repo.PROC_ORPHAN for r in originals), '同一更正编号已有待人工核实记录')
|
||||
amendments = repo.amendments(cid, iid)
|
||||
if not amendments:
|
||||
raise Waiting('等待同一更正编号的amended委托回报')
|
||||
amendment = amendments[0]
|
||||
other = amendment['payload']
|
||||
_need(isinstance(other, dict), '配套委托回报原文损坏,须人工核实后处理成交更正')
|
||||
_need(all(_digest(r['payload']) == _digest(other) for r in amendments), '同一更正编号对应不同委托累计回报')
|
||||
_need(not any(r['processed'] == qmt_repo.PROC_ORPHAN for r in amendments), '配对累计回报已有待人工核实记录')
|
||||
_need(other.get('amended') is True and other.get('reason') == 'trade_correction'
|
||||
and other.get('correction_id') == cid and other.get('instruction_id') == iid,
|
||||
'委托回报不是同一成交更正的配对证据')
|
||||
_need(other.get('broker_order_id') == payload['broker_order_id'], '更正与委托回报的券商委托号不一致')
|
||||
for name in ('ts_code', 'side'):
|
||||
_need(name not in other or other[name] == payload[name], '配对委托回报证券或方向冲突')
|
||||
return payload, amendment, originals, amendments
|
||||
|
||||
|
||||
def _load_evidence(original, order, parent):
|
||||
"""分别读取单表,在服务层按本端父指令归属组合完整证据。"""
|
||||
code, book = parent['ts_code'], parent['book_id']
|
||||
orders = repo.orders_for_code(code)
|
||||
parents, selected = {}, []
|
||||
with books.scope('all'):
|
||||
for child in orders:
|
||||
if qmt_repo.is_smoke(child.get('parent_id')):
|
||||
continue
|
||||
pid = child.get('parent_id')
|
||||
current = parents.get(pid) or pms_repo.get_instruction(pid)
|
||||
_need(current and current.get('book_id') in ('original', 'micro30'), '同股历史委托策略归属不完整')
|
||||
_need(current.get('ts_code') == code and current.get('side') == child.get('side'), '历史父子委托身份冲突')
|
||||
parents[pid] = current
|
||||
if current['book_id'] == book:
|
||||
selected.append(child)
|
||||
by_child = {r['instruction_id']: r for r in selected}
|
||||
_need(order['instruction_id'] in by_child, '目标子委托不在所属策略证据中')
|
||||
rows = repo.trades_for_orders(list(by_child))
|
||||
trades, links = [], {}
|
||||
for row in rows:
|
||||
if row['processed'] == qmt_repo.PROC_PENDING:
|
||||
raise Waiting('同股所属策略仍有原成交等待入账')
|
||||
_need(row['processed'] == qmt_repo.PROC_BOOKED, '同股所属策略存在未核实的原成交')
|
||||
raw = copy.deepcopy(row['payload'])
|
||||
child = by_child[raw['instruction_id']]
|
||||
_need(raw.get('broker_order_id') == child.get('broker_order_id') and raw.get('ts_code') == code
|
||||
and raw.get('side') == child.get('side'), '原成交与本端委托身份冲突')
|
||||
effective = _effective(row)
|
||||
effective['parent_id'] = raw['parent_id'] = child['parent_id']
|
||||
trades.append({**row, 'payload': effective, 'original_payload': raw, 'book_id': book})
|
||||
journal, _ = store.get(_key('trade-lineage:', raw['trade_no']))
|
||||
if journal:
|
||||
_need(journal.get('seq') == row['seq'] and journal.get('book_id') == book
|
||||
and journal.get('parent_id') == child['parent_id']
|
||||
and journal.get('original_payload_digest') == _digest(row['payload']), '成交批次来源凭据冲突')
|
||||
if raw['side'] == 'buy':
|
||||
_need(journal.get('lot_id'), '买入来源凭据缺少批次编号')
|
||||
links[raw['trade_no']] = journal['lot_id']
|
||||
_need(any(t['seq'] == original['seq'] for t in trades), '目标原成交不在完整入账证据中')
|
||||
return selected, parents, trades, links
|
||||
|
||||
|
||||
def _aggregate(trades, child_ids, replacement=None):
|
||||
qty, amount = 0, Decimal(0)
|
||||
for row in trades:
|
||||
payload = row['payload']
|
||||
if payload['instruction_id'] not in child_ids:
|
||||
continue
|
||||
value = replacement[1] if replacement and payload['trade_no'] == replacement[0] else payload
|
||||
q, _, money = _values(value)
|
||||
qty += q
|
||||
amount += money
|
||||
return qty, amount
|
||||
|
||||
|
||||
def _position_fields(position, projection):
|
||||
_need(_q(position.get('total_qty')) == projection['qty_before'], '持仓数量与批次投影不一致')
|
||||
_need(_d(position.get('realized_t_profit', 0)) == _d(projection['t_profit_before']), '持仓做T收益与原逐笔投影不一致')
|
||||
available = _q(position.get('avail_qty'))+int(projection['avail_delta'])
|
||||
quantity = projection['qty_after']
|
||||
_need(0 <= available <= quantity, '更正后的T+1可卖量越界')
|
||||
by_type = defaultdict(int)
|
||||
for lot in projection['lots']:
|
||||
by_type[lot['lot_type']] += int(lot['qty'])
|
||||
net = _d(projection['net_cost_after'])
|
||||
average = max(Decimal(0), net/quantity).quantize(Decimal('.001'), rounding=ROUND_HALF_UP) if quantity else None
|
||||
result = {'total_qty': quantity, 'avail_qty': available, 'base_qty': by_type['BASE'],
|
||||
'fill_qty': by_type['FILL'], 'add_qty': by_type['ADD'], 'dca_qty': by_type['DCA'], 't0_qty': by_type['T0'],
|
||||
'avg_cost': average, 'realized_t_profit': _d(position.get('realized_t_profit', 0))+_d(projection['t_profit_delta']),
|
||||
'cushion_pct': None, 'cushion_state': 'NONE', 'cushion_peak': 0, 'pct_of_scale': None}
|
||||
# 成本基准改变,旧峰值仅保留审计;等待正常行情重建,不借旧值产生动作。
|
||||
if quantity == 0:
|
||||
result.update(status='CLOSED', cushion_peak=0)
|
||||
elif position.get('status') == 'CLOSED':
|
||||
result['status'] = 'HOLDING'
|
||||
return result
|
||||
|
||||
|
||||
def _verify_physical(code, book, projection, received_at):
|
||||
if projection['qty_before'] == projection['qty_after']:
|
||||
return
|
||||
snap = qmt_repo.latest_snapshot('positions')
|
||||
if not snap or snap.get('age_sec') is None or not 0 <= snap['age_sec'] <= 60:
|
||||
raise Waiting('数量更正等待一分钟内QMT持仓快照')
|
||||
if _stamp(snap.get('received_at')) < received_at:
|
||||
raise Waiting('数量更正等待配对回报之后的新QMT持仓快照')
|
||||
payload = snap.get('payload') or {}
|
||||
items = next((payload[k] for k in ('items', 'positions', 'rows', 'data', 'list') if isinstance(payload.get(k), list)), None)
|
||||
_need(items is not None, 'QMT持仓快照没有完整列表,不能猜成空仓')
|
||||
for item in items:
|
||||
_need(isinstance(item, dict), 'QMT持仓快照行格式不合法')
|
||||
low = {str(k).lower(): v for k, v in item.items()}
|
||||
raw_qty = next((low[k] for k in ws_codec._SNAP_QTY if k in low and low[k] not in (None, '')), None)
|
||||
_q(raw_qty) # 不接受兼容解析器int(float(...))把小数数量截成整数。
|
||||
parsed = ws_codec.parse_positions_snapshot(payload)
|
||||
_need(not items or (parsed.get('columns', {}).get('qty') and len(parsed['rows']) == len(items)), 'QMT持仓快照数量或证券列无法识别')
|
||||
physical = 0
|
||||
seen = set()
|
||||
for row in parsed['rows']:
|
||||
normalized = command_spec.normalize_code(row.get('ts_code'))
|
||||
_need(normalized and normalized not in seen and row.get('qty') is not None, 'QMT持仓快照证券重复或数量缺失')
|
||||
seen.add(normalized)
|
||||
if normalized == code:
|
||||
physical = _q(row['qty'])
|
||||
with books.scope('all'):
|
||||
positions = [r for r in pms_repo.list_positions() if r['ts_code'] == code]
|
||||
_need(all(r.get('book_id') in ('original', 'micro30') for r in positions), '同股持仓策略归属不可核实')
|
||||
total = sum(_q(r['total_qty']) for r in positions if r['book_id'] != book)+projection['qty_after']
|
||||
_need(total == physical, '更正后双策略数量与QMT实际持仓不一致')
|
||||
|
||||
|
||||
def _cash_projection(original, book, side, projection, amended, order):
|
||||
value, _ = store.get('capital:live')
|
||||
_need(isinstance(value, dict) and isinstance(value.get('cash'), dict), '分策略现金尚未初始化')
|
||||
entry = value.get('fills', {}).get(str(original['seq']))
|
||||
raw = original['payload']
|
||||
fee = Decimal(0) if raw.get('fee') is None else _d(raw['fee'])
|
||||
amount = _d(raw['price'])*_q(raw['qty'])
|
||||
_need(entry and entry.get('book') == book and entry.get('side') == side
|
||||
and abs(_d(entry.get('amount'))-amount) <= Decimal('.000001')
|
||||
and abs(_d(entry.get('amount'))-_d(raw.get('amount'))) <= Decimal('.000001')
|
||||
and abs(_d(entry.get('fee'))-fee) <= Decimal('.000001'), '原成交本金或费用与策略现金凭据不符')
|
||||
updated = copy.deepcopy(value)
|
||||
cash = _d(value['cash'].get(book))+_d(projection['cash_delta'])
|
||||
_need(cash >= 0, '更正差额会使所属策略现金透支')
|
||||
active = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
|
||||
_need(len(active) < 10001, '在途委托超过资金核验上限')
|
||||
reserved = Decimal(0)
|
||||
from app.services.rotation_service import configuration
|
||||
from app.core.micro_rotation import fee as estimate_fee
|
||||
with books.scope('all'):
|
||||
for child in active:
|
||||
if child.get('side') != 'buy' or child['instruction_id'] == order['instruction_id'] and amended.get('final') is True:
|
||||
continue
|
||||
parent = pms_repo.get_instruction(child['parent_id'])
|
||||
_need(parent and parent.get('book_id') in ('original', 'micro30'), '在途资金策略归属未知')
|
||||
if parent['book_id'] != book:
|
||||
continue
|
||||
cum = amended['cum_qty'] if child['instruction_id'] == order['instruction_id'] else child.get('cum_qty', 0)
|
||||
remaining = _q(child['qty'])-_q(cum)
|
||||
_need(remaining >= 0, '在途委托剩余数量越界')
|
||||
if remaining:
|
||||
principal = _d(child['limit_price'])*remaining
|
||||
reserved += principal+_d(estimate_fee(float(principal), 'buy', **configuration()['costs']))
|
||||
_need(cash >= reserved, '更正后策略现金不足以覆盖既有在途买入占用')
|
||||
updated['cash'][book] = float(cash)
|
||||
return value, updated
|
||||
|
||||
|
||||
def _grid_updates(code, parent_map, orders, projection, quantity_changed, cid):
|
||||
strategies = pms_repo.list_strategies(ts_code=code, statuses=['ACTIVE', 'PAUSED'], include_archived=True, limit=1001)
|
||||
_need(len(strategies) < 1001, '同股策略数超过核验上限')
|
||||
result = []
|
||||
for strategy in strategies:
|
||||
_need(strategy.get('type') == 'GRID', '同股活动策略不是可重建网格,须人工核对后更正')
|
||||
state = copy.deepcopy(strategy.get('state') or {})
|
||||
previous_correction = state.get('trade_correction') or {}
|
||||
_need(isinstance(previous_correction, dict), '网格更正版本不可核实')
|
||||
_need(not state.get('pending'), '网格仍有待结算指令,须核对后更正')
|
||||
sid = strategy['strategy_id']
|
||||
related = {pid for pid, parent in parent_map.items() if parent.get('origin_id') == sid}
|
||||
_need(all(r['status'] in qmt_repo.FINAL for r in orders if r['parent_id'] in related), '网格仍有活动子委托,须核对后更正')
|
||||
levels = defaultdict(lambda: [0, Decimal(0)])
|
||||
for lot in projection['lots']:
|
||||
parent = parent_map.get(lot.get('instruction_id'))
|
||||
_need(parent, '批次缺少完整父指令来源')
|
||||
if parent.get('origin_id') != sid or not int(lot['qty']):
|
||||
continue
|
||||
leg = (parent.get('progress') or {}).get('leg', '')
|
||||
_need(isinstance(leg, str) and leg.startswith('grid_buy:') and leg.split(':', 1)[1].lstrip('-').isdigit(), '网格批次档位来源不可核实')
|
||||
level = leg.split(':', 1)[1]
|
||||
levels[level][0] += int(lot['qty'])
|
||||
levels[level][1] += int(lot['qty'])*_d(lot['open_price'])
|
||||
state['filled_levels'] = {k: {'qty': v[0], 'price': float(v[1]/v[0])} for k, v in levels.items()}
|
||||
state['invested'] = float(sum((v[1] for v in levels.values()), Decimal(0)))
|
||||
state['trade_correction'] = {'correction_id': cid, 'source': '已核实真实剩余批次'}
|
||||
fields = {'state': state, 'correction_expected': previous_correction.get('correction_id')}
|
||||
if quantity_changed:
|
||||
state['correction_hold'] = '成交数量已更正,网格档位须人工复核后恢复'
|
||||
fields['status'] = 'PAUSED'
|
||||
result.append((sid, fields))
|
||||
return result
|
||||
|
||||
|
||||
def _order_fields(order, amended, quantity, received):
|
||||
if any(k not in amended or amended[k] is None for k in ('status', 'final', 'leaves_qty')):
|
||||
raise Waiting('配对委托回报缺少状态、终态或剩余量,等待核实')
|
||||
status, final = amended['status'], amended['final']
|
||||
_need(status in ws_codec.PROTOCOL_STATUSES and isinstance(final, bool), '配对委托状态格式不合法')
|
||||
_need(final == (status in ws_codec.FINAL_STATUSES), '配对委托状态与终态标记冲突')
|
||||
leaves = _q(amended['leaves_qty'])
|
||||
_need(leaves == (0 if final else _q(order['qty'])-quantity), '配对委托剩余量与更正量冲突')
|
||||
fields = {'cum_qty': quantity, 'cum_avg_price': amended.get('cum_avg_price'), 'leaves_qty': leaves}
|
||||
if order['status'] in qmt_repo.FINAL:
|
||||
_need(final and leaves == 0, '已终态委托不能因更正重新进入在途')
|
||||
return fields # 对端可重分类终态;本地历史执行终态和final_at均保持。
|
||||
_need(order['status'] in qmt_repo.LIVE, '本端委托状态不可核实')
|
||||
_need(status != 'FILLED' or quantity == _q(order['qty']), '活动单转全成时累计数量未满')
|
||||
_need(status != 'REJECTED' or quantity == 0, '拒单终态不能带成交数量')
|
||||
_need(status != 'PARTIAL' or 0 < quantity < _q(order['qty']), '部分成交状态的累计量不合法')
|
||||
fields['status'] = status
|
||||
if final:
|
||||
fields['final_at'] = received.replace(tzinfo=None)
|
||||
return fields
|
||||
|
||||
|
||||
def _apply(row):
|
||||
state = qmt_repo.get_state() or {}
|
||||
watermark = state.get('last_seq')
|
||||
if not isinstance(watermark, int) or watermark < int(row['seq']):
|
||||
raise Waiting('更正回报等待连续持久水位追平')
|
||||
payload, amendment, corrections, amendments = _pair(row)
|
||||
if int(amendment['seq']) > watermark:
|
||||
raise Waiting('配对累计回报等待连续持久水位追平')
|
||||
cid, no, iid = payload['correction_id'], payload['trade_no'], payload['instruction_id']
|
||||
if repo.pending_for_trade(no, before_seq=row['seq']):
|
||||
raise Waiting('同一原成交的前序更正仍待完成或人工核实')
|
||||
fingerprint = _digest(payload)
|
||||
audit_key = _key('trade-correction:', cid)
|
||||
audit, _ = store.get(audit_key)
|
||||
if audit:
|
||||
_need(audit.get('payload_fingerprint') == fingerprint and audit.get('amendment_fingerprint') == _digest(amendment['payload']), '更正编号已处理但正文不同')
|
||||
duplicates = [r['seq'] for r in corrections+amendments if r['processed'] in (0, 2)]
|
||||
if duplicates:
|
||||
_write(qmt_repo.inbox_mark(duplicates, processed=qmt_repo.PROC_DIGESTED, note='同一更正已原子入账,重复消息不再改账'), '重复更正标记')
|
||||
return 'duplicate'
|
||||
_need(settings.INFRA_STRATEGY_BOOK_SCHEMA, '未启用分策略账本,成交更正须人工核对')
|
||||
original = repo.get_trade(no)
|
||||
if not original or original['processed'] == qmt_repo.PROC_PENDING:
|
||||
raise Waiting('等待原成交入账,更正不阻止原成交消费')
|
||||
_need(original['processed'] == qmt_repo.PROC_BOOKED, '原成交没有已入账凭据')
|
||||
_need(all(payload[k] == original['payload'].get(k) for k in IDENTITY), '更正身份与原成交不同')
|
||||
effective = _effective(original)
|
||||
_need(_values(payload['before']) == _values(effective), '更正before不是当前有效成交版本')
|
||||
order = qmt_repo.get_order(iid)
|
||||
_need(order and not qmt_repo.is_smoke(order.get('parent_id')), '更正子委托缺失或属于联调单')
|
||||
_need(all(order.get(k) == payload[k] for k in ('instruction_id', 'broker_order_id', 'ts_code', 'side')), '更正身份与出口委托不一致')
|
||||
with books.scope('all'):
|
||||
parent = pms_repo.get_instruction(order['parent_id'])
|
||||
_need(parent and parent.get('book_id') in ('original', 'micro30') and parent.get('ts_code') == payload['ts_code']
|
||||
and parent.get('side') == payload['side'], '父指令证券、方向或策略归属不可核实')
|
||||
book, code = parent['book_id'], parent['ts_code']
|
||||
with books.scope(book):
|
||||
orders, parents, trades, links = _load_evidence(original, order, parent)
|
||||
lots = pms_repo.list_lots(code, status=None, limit=20001)
|
||||
_need(len(lots) < 20001, '批次证据超过核验上限')
|
||||
projection = core.compile_correction(lots=lots, trades=trades, target_trade_no=no,
|
||||
after=payload['after'], today=dt.datetime.now(TZ).date(), lot_links=links)
|
||||
current = pms_repo.get_position(code)
|
||||
_need(current and not current.get('archived_at'), '目标策略持仓不存在或已归档')
|
||||
position_fields = _position_fields(current, projection)
|
||||
child_after, child_amount = _aggregate(trades, {iid}, (no, payload['after']))
|
||||
am = amendment['payload']
|
||||
_need(_q(am.get('cum_qty')) == child_after and child_after <= _q(order['qty']), '配对累计成交量与更正后逐笔合计不一致或超过子单')
|
||||
avg = child_amount/child_after if child_after else Decimal(0)
|
||||
# QMT旧协议累计均价为两位,新回报允许三位;仅接受正常舍入,不容忍任意差值。
|
||||
_need((not child_after and am.get('cum_avg_price') is None) or (am.get('cum_avg_price') is not None and _d(am['cum_avg_price']) in {avg, avg.quantize(Decimal('.01'), rounding=ROUND_HALF_UP), avg.quantize(Decimal('.001'), rounding=ROUND_HALF_UP)}), '配对累计均价与更正后逐笔金额不一致')
|
||||
order_fields = _order_fields(order, am, child_after, max(_stamp(row['received_at']), _stamp(amendment['received_at'])))
|
||||
children = {r['instruction_id'] for r in orders if r['parent_id'] == parent['instruction_id']}
|
||||
old_qty, _ = _aggregate(trades, children)
|
||||
new_qty, new_amount = _aggregate(trades, children, (no, payload['after']))
|
||||
_need(old_qty == _q(parent['exec_qty']) and new_qty <= _q(parent['qty']), '父指令执行量与旧逐笔合计不符或更正后超量')
|
||||
quantity_changed = _q(effective['qty']) != _q(payload['after']['qty'])
|
||||
received = max(_stamp(row['received_at']), _stamp(amendment['received_at']))
|
||||
_verify_physical(code, book, projection, received)
|
||||
cash_before, cash_after = _cash_projection(original, book, payload['side'], projection, am, order)
|
||||
projected_orders = [{**r, **order_fields} if r['instruction_id'] == iid else r for r in orders]
|
||||
strategy_updates = _grid_updates(code, parents, projected_orders, projection, quantity_changed, cid)
|
||||
progress = copy.deepcopy(parent.get('progress') or {})
|
||||
progress['trade_correction'] = {'correction_id': cid, 'before_exec_qty': old_qty, 'exec_qty': new_qty,
|
||||
'exec_amount': str(new_amount), 'received_at': received.isoformat()}
|
||||
if quantity_changed:
|
||||
progress['trade_correction_hold'] = '成交数量更正后停止自动续单,等待人工决定剩余目标'
|
||||
for child in progress.get('children', []):
|
||||
if child.get('ref') == iid:
|
||||
child.update(actual_exec_qty=child_after, actual_exec_amount=str(child_amount))
|
||||
# 所有事实核对完成后才开始写入;任何软失败必须抛出以回滚整个savepoint。
|
||||
for change in projection['changes']:
|
||||
_write(pms_repo.update_lot(change['id'], **{k: change['after'][k] for k in core.LOT_FIELDS}), '更正批次')
|
||||
_write(pms_repo.update_position(code, **position_fields), '更正持仓')
|
||||
_write(pms_repo.update_instruction(parent['instruction_id'], exec_qty=new_qty,
|
||||
exec_avg_price=float(new_amount/new_qty) if new_qty else 0, progress=progress), '更正父指令')
|
||||
if parent.get('origin_type') == 'plan':
|
||||
plans = pms_repo.list_plans(ts_code=code, limit=10001)
|
||||
_need(len(plans) < 10001 and any(p['plan_id'] == parent.get('origin_id') for p in plans), '来源方案不存在或超过核验上限')
|
||||
_write(pms_repo.update_plan(parent['origin_id'], filled_qty=new_qty), '更正方案进度')
|
||||
for sid, fields in strategy_updates:
|
||||
_write(pms_repo.update_strategy(sid, **fields), '更正网格状态')
|
||||
_write(qmt_repo.update_order(iid, **order_fields), '更正子委托累计量')
|
||||
with store.locked('capital:live', 'capital', {}) as capital:
|
||||
_need(_body(capital) == _body(cash_before), '资金核验后凭据已变化')
|
||||
capital.clear(); capital.update(cash_after)
|
||||
for trade_no, lot_id in projection['lot_links'].items():
|
||||
journal_key = _key('trade-lineage:', trade_no)
|
||||
if store.get(journal_key)[0]:
|
||||
continue
|
||||
trade = next(t for t in trades if t['payload']['trade_no'] == trade_no)
|
||||
raw = repo.get_trade(trade_no)
|
||||
store.put_once(journal_key, 'trade_lineage', {'trade_no': trade_no, 'seq': trade['seq'],
|
||||
'parent_id': trade['payload']['parent_id'], 'instruction_id': trade['payload']['instruction_id'],
|
||||
'book_id': book, 'ts_code': code, 'side': 'buy', 'lot_id': lot_id,
|
||||
'original_payload_digest': _digest(raw['payload'])})
|
||||
updated_effective = {**effective, **payload['after']}
|
||||
with store.locked(_key('trade-effective:', no), 'trade_effective', {}) as doc:
|
||||
doc.update(source_seq=original['seq'], original_digest=_digest(original['payload']), effective=updated_effective,
|
||||
last_correction_id=cid, lot_id=projection['lot_links'].get(no))
|
||||
with store.locked(_key('order-correction:', iid), 'order_correction', {}) as doc:
|
||||
doc.update(instruction_id=iid, cum_qty=child_after, correction_seq=row['seq'], amendment_seq=amendment['seq'], received_at=received.isoformat(),
|
||||
correction_id=cid, cum_avg_price_before=order.get('cum_avg_price'), cum_avg_price_after=am['cum_avg_price'])
|
||||
store.put_once(audit_key, 'trade_correction', {'correction_id': cid, 'payload_fingerprint': fingerprint,
|
||||
'amendment_fingerprint': _digest(am), 'original_seq': original['seq'], 'correction_seq': row['seq'],
|
||||
'amendment_seq': amendment['seq'], 'book_id': book, 'ts_code': code, 'before': projection['trade_before'],
|
||||
'after': projection['trade_after'], 'cash_delta': projection['cash_delta'], 'lot_changes': projection['changes'],
|
||||
'allocations_before': projection['allocations_before'], 'allocations_after': projection['allocations'],
|
||||
'parent_status_preserved': parent['status'], 'order_status_before': order['status'],
|
||||
'order_status_after': order_fields.get('status', order['status']), 'qmt_amended_status': am['status'], 'quantity_hold': quantity_changed, 'received_at': received.isoformat(),
|
||||
'position_before': {k: current.get(k) for k in position_fields}, 'position_after': position_fields,
|
||||
'cushion_note': '旧成本基准峰值失效,待正常行情重建',
|
||||
'cash_before': cash_before['cash'][book], 'cash_after': cash_after['cash'][book],
|
||||
'original_fee': original['payload'].get('fee'), 'original_fee_estimated': original['payload'].get('fee_estimated')})
|
||||
seqs = [r['seq'] for r in corrections+amendments if r['processed'] in (0, 2)]
|
||||
_write(qmt_repo.inbox_mark(seqs, processed=qmt_repo.PROC_BOOKED, note='成交更正及累计回报已按策略归属原子入账'), '更正回执标记')
|
||||
return 'applied'
|
||||
|
||||
|
||||
def _hold(row, reason):
|
||||
with store.account_guard(), db.transaction(), db.savepoint():
|
||||
current = repo.get_inbox(row['seq'], lock=True)
|
||||
if not current or current['processed'] not in (0, 2):
|
||||
return False
|
||||
payload = current.get('payload') if isinstance(current.get('payload'), dict) else {}
|
||||
raw = current.get('payload_json')
|
||||
raw = raw if isinstance(raw, str) else json.dumps(payload, ensure_ascii=False, default=str)
|
||||
raw_fingerprint = hashlib.sha256(raw.encode()).hexdigest()
|
||||
_write(qmt_repo.inbox_mark([row['seq']], processed=qmt_repo.PROC_ORPHAN,
|
||||
note='成交更正待人工核实:'+reason), '更正挂起标记')
|
||||
store.put_once(_key('trade-correction-hold:', str(row['seq'])), 'trade_correction_hold',
|
||||
{'seq': row['seq'], 'correction_id': payload.get('correction_id') if isinstance(payload.get('correction_id'), str) else None,
|
||||
'raw_payload_fingerprint': raw_fingerprint, 'reason': reason})
|
||||
return True
|
||||
|
||||
|
||||
def consume(limit=100):
|
||||
out = {'ok': True, 'applied': 0, 'waiting': 0, 'held': 0, 'errors': [], 'alerts': []}
|
||||
try:
|
||||
pending = repo.pending(limit=limit)
|
||||
except Exception as exc:
|
||||
out.update(ok=False, errors=['更正收件证据读取失败:'+type(exc).__name__])
|
||||
return out
|
||||
for candidate in pending:
|
||||
try:
|
||||
with store.account_guard(), db.transaction(), db.savepoint():
|
||||
row = repo.get_inbox(candidate['seq'], lock=True)
|
||||
if not row or not (row['processed'] == 0 or row['processed'] == 2 and row.get('process_note') == LEGACY_NOTE):
|
||||
continue
|
||||
result = _apply(row)
|
||||
if result == 'applied':
|
||||
out['applied'] += 1
|
||||
except Waiting:
|
||||
out['waiting'] += 1
|
||||
except ValueError as exc:
|
||||
reason = str(exc)
|
||||
try:
|
||||
if _hold(candidate, reason):
|
||||
out['held'] += 1
|
||||
out['alerts'].append({'type': 'TRADE_CORRECTION_HELD', 'seq': candidate['seq'], 'reason': reason})
|
||||
except Exception as failure:
|
||||
out['errors'].append('更正挂起审计未完成:'+type(failure).__name__)
|
||||
except Exception as exc:
|
||||
out['errors'].append('成交更正事务未完成,保留待重试:'+type(exc).__name__)
|
||||
out['ok'] = not out['errors'] and not out['held']
|
||||
return out
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
"""逐笔成交与批次的原子归属凭据。只记录真实入账,不重放或重写原回执。"""
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from app.repo import pms_repo, rotation_repo
|
||||
|
||||
|
||||
def key(trade_no):
|
||||
return 'trade-lineage:'+hashlib.sha256(str(trade_no).encode()).hexdigest()
|
||||
|
||||
|
||||
def lots(code):
|
||||
rows = pms_repo.list_lots(code, status=None, limit=2001)
|
||||
if len(rows) >= 2001:
|
||||
raise ValueError('批次超过完整核验上限,不能截断入账依据')
|
||||
return rows
|
||||
|
||||
|
||||
def record(act, instruction, seq, before, after):
|
||||
trade_no = act.get('order_id')
|
||||
if not trade_no:
|
||||
raise ValueError('逐笔入账缺少成交编号')
|
||||
old = {r['id']: r for r in before}
|
||||
new = {r['id']: r for r in after}
|
||||
fields = ('qty', 'closed_qty', 'open_price', 'close_avg_price', 'realized_pnl', 'status')
|
||||
changed = [i for i, row in new.items() if i not in old or
|
||||
any(str(row.get(f)) != str(old[i].get(f)) for f in fields)]
|
||||
lot_id = None
|
||||
if act['kind'] == 'BUY':
|
||||
added = set(new)-set(old)
|
||||
if len(added) != 1:
|
||||
raise ValueError('买入成交无法唯一对应新增批次')
|
||||
lot_id = next(iter(added))
|
||||
if int(new[lot_id]['qty']) != int(act['qty']):
|
||||
raise ValueError('新增批次数量与逐笔成交不符')
|
||||
source = act.get('source_payload')
|
||||
digest = (hashlib.sha256(json.dumps(source, ensure_ascii=False, sort_keys=True,
|
||||
separators=(',', ':'), default=str, allow_nan=False).encode()).hexdigest()
|
||||
if source else None)
|
||||
rotation_repo.put_once(key(trade_no), 'trade_lineage', {
|
||||
'trade_no': trade_no, 'seq': int(seq), 'parent_id': instruction['instruction_id'],
|
||||
'instruction_id': act.get('child_instruction_id'),
|
||||
'book_id': instruction['book_id'], 'ts_code': act['ts_code'],
|
||||
'side': 'buy' if act['kind'] == 'BUY' else 'sell', 'lot_id': lot_id,
|
||||
'original_payload_digest': digest,
|
||||
'changes': [{'lot_id': i, 'before': {f: old[i].get(f) for f in fields} if i in old else None,
|
||||
'after': {f: new[i].get(f) for f in fields}} for i in changed]})
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
# 页面目录规则
|
||||
|
||||
本文件补充`app/AGENTS.md`,适用于`app/web/`。
|
||||
|
||||
- 页面是Vue3与ElementPlus直接加载的HTML,无构建步骤。自定义标签必须显式闭合,例如`<el-alert></el-alert>`,不能写成自闭合标签。
|
||||
- `setup()`中供模板使用的变量与函数必须在返回值中导出。新增后端枚举要同时维护前端翻译及对应守卫名单。
|
||||
- 每次页面修改都跑`test_page_enum_guard.py`、`test_page_wiring_guard.py`、`test_page_copy_guard.py`,经仓库隔离入口执行。布局或交互变化还需浏览器检查相关桌面与窄屏尺寸、控制台、点击和关闭行为。
|
||||
- 使用真实只读响应重放页面时,明确这是浏览器复现,不称为真实登录验收。检查展示不得误触发写接口。
|
||||
- 用交易员能理解的短句。统一称基本面、技术面、择时,必要说明放悬停;表格操作列在页面内可见,不堆内部实现词。
|
||||
- 后续页面修改沿用现有布局、字号、间距、配色、组件和交互习惯。新增信息优先融入原有区域,不另起一套视觉样式;整体改版以用户明确要求为准。
|
||||
- 信号流沿用现有单行信息流的视觉和点击交互。左侧不另设关注专属分组、样式、身份标记或进度卡片,真实信号不得被等待记录替代。关注身份和详细进度放在原个股详情及选股页。
|
||||
- 看多红、看空绿、中性灰、无读数虚框。指标的冷暖阈值柱图沿用现有蓝、金、灰,不把阈值高低强行解释成看多看空。
|
||||
- 策略展示为“主观量化”和“微盘轮动”,持仓分别用标签页。数量和阈值来自当前规则,不能把30或50写死;策略详情新标签页打开,不替换当前管理页。
|
||||
- 明确区分计划数量、实际委托、受理、成交与入账。没有出口委托不能显示“已下单”,请求失败或旧行情不能显示成正常完成。
|
||||
|
|
@ -16,6 +16,7 @@ import json
|
|||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Body, FastAPI, Query, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
|
@ -39,6 +40,30 @@ STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
|
|||
|
||||
app = FastAPI(title="PMS 持仓管理系统", version=VERSION)
|
||||
|
||||
|
||||
@app.get('/rotation')
|
||||
def rotation_page():
|
||||
return FileResponse(os.path.join(STATIC_DIR, 'rotation.html'))
|
||||
|
||||
|
||||
@app.get('/api/rotation')
|
||||
def rotation_status():
|
||||
from app.services.rotation_service import status
|
||||
return ok(status)
|
||||
|
||||
|
||||
@app.get('/api/rotation/history')
|
||||
def rotation_history(end: str, limit: int = 60):
|
||||
from app.services.rotation_service import signal_history
|
||||
return ok(signal_history, end=end, limit=limit)
|
||||
|
||||
|
||||
@app.post('/api/ops/rotation/control')
|
||||
def rotation_control(request: Request, payload: dict = Body(...)):
|
||||
from app.services.rotation_service import control
|
||||
return ok_logged('rotation_control', control, mode=payload.get('mode'),
|
||||
action=payload.get('action'), actor=_actor(request, payload), by=_actor(request, payload), params=payload)
|
||||
|
||||
# 把 static 目录挂到 /static —— 内网隔离时的离线兜底:
|
||||
# 页面默认从 unpkg 取 Vue3 / ElementPlus / axios, 浏览器上不了外网就会白屏 (更准确地说是
|
||||
# 只剩一个光秃秃的头部, 因为 el-* 组件全渲染不出来)。把三个库放进 static/vendor/ 再把
|
||||
|
|
@ -406,21 +431,28 @@ def api_positions():
|
|||
"timing": tm.get("stance"), "nightly": tm.get("nightly")}
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("[持仓] 综合分析三票挂不上: %s", e)
|
||||
return {"ok": True, **v, "stock_params": sp}
|
||||
return {"ok": True, **v, "stock_params": sp,
|
||||
"strategy_groups": portfolio.position_groups(v)}
|
||||
return ok(_view)
|
||||
|
||||
|
||||
@app.get("/api/positions/{ts_code}/lots")
|
||||
def api_lots(ts_code: str, status: str = Query("OPEN")):
|
||||
return ok(pms_repo.list_lots, ts_code, status=(status or None))
|
||||
def api_lots(ts_code: str, status: str = Query("OPEN"),
|
||||
book_id: Literal["original", "micro30"] = Query("original")):
|
||||
return ok(portfolio.position_lots, ts_code, book_id, status=(status or None))
|
||||
|
||||
|
||||
@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
|
||||
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)
|
||||
|
|
@ -537,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)
|
||||
|
|
@ -760,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")
|
||||
|
|
@ -899,6 +941,14 @@ def _research_st(code):
|
|||
"company_review_text": r.get("company_review_text")}, "candidate"
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("[研究面] 取候选计划失败 %s: %s", code, e)
|
||||
try:
|
||||
from app.services import monitor_watch
|
||||
row = monitor_watch.research_row(code)
|
||||
if row and (row.get('company_review') or {}).get('overall'):
|
||||
return {"company_review": row['company_review'],
|
||||
"company_review_text": row.get('company_review_text')}, "watch"
|
||||
except Exception as e:
|
||||
logger.warning("[研究面] 人工关注评析读取失败 %s: %s", code, type(e).__name__)
|
||||
return None, "none"
|
||||
|
||||
|
||||
|
|
@ -987,6 +1037,36 @@ def api_strategy_attach_scan(dry_run: bool = Query(False)):
|
|||
params={"dry_run": dry_run})
|
||||
|
||||
|
||||
@app.get('/api/plan/user-candidates/search')
|
||||
def api_search_user_candidates(q: str = ''):
|
||||
from app.services import plan_candidates
|
||||
return ok(plan_candidates.request, query=q)
|
||||
|
||||
|
||||
@app.get('/api/plan/user-candidates')
|
||||
def api_user_candidates():
|
||||
from app.services import monitor_watch
|
||||
return ok(monitor_watch.listing)
|
||||
|
||||
|
||||
@app.post('/api/plan/user-candidates')
|
||||
def api_add_user_candidates(request: Request, payload: dict = Body(...)):
|
||||
from app.services import plan_candidates
|
||||
result = ok_logged('add_plan_candidates', plan_candidates.request, 'POST',
|
||||
payload=payload, actor=_actor(request), by=_actor(request),
|
||||
params={k: payload.get(k) for k in ('codes', 'reason', 'expires_on')})
|
||||
if not result.get('ok') and str(result.get('error') or '').startswith('ValueError: '):
|
||||
result['error'] = result['error'][12:]
|
||||
return result
|
||||
|
||||
|
||||
@app.post('/api/plan/user-candidates/{identity}/remove')
|
||||
def api_remove_user_candidate(identity: str, request: Request):
|
||||
from app.services import plan_candidates
|
||||
return ok_logged('remove_plan_candidate', plan_candidates.request, 'POST',
|
||||
identity=identity, actor=_actor(request), by=_actor(request), params={'id': identity})
|
||||
|
||||
|
||||
@app.get("/api/upstream/plan")
|
||||
def api_upstream_plan(limit: int = Query(30), date: str = Query(None),
|
||||
bucket: str = Query("main")):
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,65 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>策略轮换 · PMS</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182638;font:15px/1.6 system-ui,-apple-system,sans-serif}main{max-width:1240px;margin:28px auto;padding:0 24px}header{display:flex;align-items:center;justify-content:space-between}h1{font-size:25px;margin:0}h2{font-size:18px;margin:0 0 14px}.sub{color:#627185}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.card{background:white;border:1px solid #dde4eb;border-radius:10px;padding:20px;margin-top:18px}.metric{font-size:28px;font-weight:650}.label{font-size:13px;color:#627185}button,a{color:#194c79}button{border:1px solid #c5d3e0;border-radius:6px;background:#fff;padding:8px 12px;cursor:pointer;margin:4px}button:disabled{opacity:.45;cursor:not-allowed}.warning{color:#8c4e09;background:#fff8e8;padding:12px;border-radius:6px;white-space:pre-line}table{border-collapse:collapse;width:100%;font-size:13px}th,td{text-align:left;border-bottom:1px solid #e8edf2;padding:10px 8px}th{color:#627185}.scroll{overflow-x:auto}.positive{color:#b7252f}.negative{color:#208356}.empty{color:#627185;padding:18px}#errors:empty{display:none}.controls{display:flex;flex-wrap:wrap;gap:8px}.small{font-size:12px}@media(max-width:760px){.grid{grid-template-columns:1fr}main{padding:0 12px}.metric{font-size:24px}}
|
||||
.card{min-width:0}.small{overflow-wrap:anywhere}header{gap:12px;flex-wrap:wrap}header>div,.grid>div{min-width:0}th,td{white-space:nowrap}
|
||||
.section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px}.section-heading h2{margin:0}.section-heading button{font:inherit;font-size:12px;padding:4px 10px;margin:0;white-space:nowrap}.section-heading button:hover:not(:disabled){background:#f4f7fa}
|
||||
</style></head>
|
||||
<body><main>
|
||||
<header><div><h1>策略轮换</h1><div class="sub">主观量化与微盘轮动共用账户,分别记录。</div></div><div><a href="/">返回工作台</a><button id="refresh">刷新</button></div></header>
|
||||
<div class="card warning" id="errors"></div>
|
||||
<div class="grid"><section class="card"><div class="label">运行档位</div><div class="metric" id="mode">读取中</div><div class="sub" id="control"></div></section><section class="card"><div class="label">账户资金使用阶段</div><div class="metric" id="phase">读取中</div><div class="sub" id="reason"></div></section><section class="card"><div class="label">名单与数据日期</div><div class="metric" id="count">—</div><div class="sub" id="date"></div></section></div>
|
||||
<section class="card"><h2>宏观信号</h2><div class="grid"><div><div class="label">成长主线瓦解</div><div class="metric" id="growth">—</div></div><div><div class="label">微盘活跃度历史位置</div><div class="metric" id="percentile">—</div></div><div><div class="label">本次判断</div><div class="metric" id="signal">—</div></div></div><p class="sub" id="rule-summary">规则读取中。</p><div class="small sub" id="version"></div></section>
|
||||
<section class="card"><div class="section-heading"><h2>目标名单与实际进度</h2><button id="copy-members" type="button" title="复制目标股票的代码和名称" aria-live="polite" disabled>复制名单</button></div><p class="sub" id="basket-summary">目标数量读取中。</p><p id="progress" class="sub"></p><div class="scroll"><table><thead><tr><th>排名</th><th>代码</th><th>名称</th><th>总市值(亿元)</th><th>收盘价</th><th>全日成交额(万元)</th><th>资格</th><th>实际股数</th><th>名单变动</th><th>初始金额/日成交额</th></tr></thead><tbody id="members"></tbody></table></div><div class="warning" id="waits" hidden></div></section>
|
||||
<section class="card"><h2>资金与收益记录</h2><div id="account" class="sub">尚无纸面或自动执行账本。</div><div class="scroll"><table><thead><tr><th>策略</th><th>账面现金</th><th>资产</th><th>净投入</th><th>盈亏</th><th>单位净值</th><th>最大回撤</th><th>已入账费用</th></tr></thead><tbody id="summary"></tbody></table><table><thead><tr><th>策略</th><th>股票</th><th>股数</th><th>账面成本</th><th>持仓权重</th><th>估值</th></tr></thead><tbody id="positions"></tbody></table></div><div id="reconcile" class="small sub"></div><p class="small sub">历史研究收益不等于账户轮换收益。纸面结果单独记录,资金划拨不计为盈利。费用仅包含已入账金额,未回报费用不视为零。开盘窗口容量与实际成交偏差在执行后记录。</p></section>
|
||||
<section class="card"><h2>运行控制</h2><div class="warning" id="activation"></div><p class="sub" id="activation-policy"></p><div class="controls"><button data-mode="observe">观察</button><button data-mode="paper">纸面模拟</button><button data-mode="auto" id="automatic">自动执行</button><button data-action="pause_new">暂停新增</button><button data-action="pause_all">暂停全部</button><button data-action="run">恢复运行</button><button data-action="exit_disable">退出并停用</button></div><div class="small sub">控制操作需要系统管理员权限。退出并停用会产生卖出安排;观察和纸面档不会向QMT发单。</div></section>
|
||||
</main><script>
|
||||
const modes={observe:'观察',paper:'纸面模拟',auto:'自动执行'},phases={original:'主观量化运行',entering_micro:'转入微盘轮动',micro:'微盘轮动运行',returning_original:'转回主观量化'},controls={run:'运行',pause_new:'暂停新增',pause_all:'暂停全部',exit_disable:'退出并停用'};
|
||||
const el=id=>document.getElementById(id),fmt=(x,n=2)=>x==null?'—':Number(x).toLocaleString('zh-CN',{maximumFractionDigits:n});
|
||||
const cashAmount=x=>x==null?'—':Number(x).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2});
|
||||
let memberCopyText='',copyBusy=false,copyTimer;
|
||||
function prepareCopy(snapshot={}){
|
||||
clearTimeout(copyTimer);const rows=snapshot.members||[];
|
||||
memberCopyText=snapshot.basket_ready&&rows.length&&rows.every(m=>m.code&&m.name)?rows.map(m=>String(m.code).trim()+'\t'+String(m.name).trim()).join('\n'):'';
|
||||
el('copy-members').disabled=!memberCopyText||copyBusy;el('copy-members').textContent='复制名单';
|
||||
}
|
||||
function copyFallback(text){
|
||||
const focus=document.activeElement,selection=document.getSelection(),ranges=[];
|
||||
if(selection)for(let i=0;i<selection.rangeCount;i++)ranges.push(selection.getRangeAt(i).cloneRange());
|
||||
const input=document.createElement('textarea');input.value=text;input.readOnly=true;input.style.cssText='position:fixed;left:-9999px;top:0';document.body.append(input);
|
||||
try{input.select();if(!document.execCommand('copy'))throw Error('复制失败');}
|
||||
finally{input.remove();if(focus)focus.focus({preventScroll:true});if(selection){selection.removeAllRanges();ranges.forEach(r=>selection.addRange(r));}}
|
||||
}
|
||||
async function copyMembers(){
|
||||
if(!memberCopyText||copyBusy)return;
|
||||
const text=memberCopyText,b=el('copy-members');copyBusy=true;b.disabled=true;clearTimeout(copyTimer);
|
||||
try{
|
||||
if(navigator.clipboard&&window.isSecureContext){try{await navigator.clipboard.writeText(text);}catch(e){copyFallback(text);}}
|
||||
else copyFallback(text);
|
||||
b.textContent='已复制';
|
||||
}catch(e){b.textContent='复制失败,请重试';}
|
||||
finally{copyBusy=false;b.disabled=!memberCopyText;copyTimer=setTimeout(()=>{b.textContent='复制名单';},2500);}
|
||||
}
|
||||
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.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?'待冻结':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}}
|
||||
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)+'%分位时退出。股汇对冲指标只作用于主观量化。';
|
||||
el('basket-summary').textContent='目标'+fmt(size)+'只。未成交或残余持仓可能使实际数量暂时偏离目标。保留成员不重新等权。';
|
||||
el('activation-policy').textContent=v.simulation_direct?'模拟仓直接运行,不设观察或纸面等待期。每笔交易继续核对账户资金、持仓、数据和用户控制。':'观察至少3个交易日,再纸面运行至少10个交易日。自动档需要回测、容量、账本、资金占用及页面验收完成。';
|
||||
const names={original:'主观量化',micro30:'微盘轮动',account:'全账户'};
|
||||
const positions=a?Object.entries(a.books||{}).flatMap(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).map(([code,p])=>({book_id:book,code,qty:p.qty,cost:p.cost,market_value:null}))):(isPaper?[]:((v.accounting||{}).positions||[]));
|
||||
el('progress').textContent='股票预算上限 '+fmt(v.stock_budget)+' 元 · 主观量化剩余 '+fmt(p.original_market_value)+' 元 · 微盘轮动已建 '+fmt(p.micro_market_value)+' 元 · 可用现金 '+fmt(p.available_cash)+' 元'+(v.simulation_direct?'':(' · 观察 '+(v.observed_days||0)+' 日 · 健康纸面 '+(v.paper_days||0)+' 日'));
|
||||
el('members').replaceChildren();const target=new Set((s.members||[]).map(x=>x.code));
|
||||
(s.members||[]).forEach(m=>{const held=positions.find(x=>x.book_id==='micro30'&&x.code===m.code);line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),s.basket_ready&&m.eligible?'通过':'待核实',held?held.qty:'—',!positions.length?'待建仓':held?'保留':'调入',m.daily_amount_yuan?fmt(v.stock_budget/size/m.daily_amount_yuan*100)+'%':'未知']);});
|
||||
positions.filter(x=>x.book_id==='micro30'&&!target.has(x.code)).forEach(x=>line(el('members'),['—',x.code,'残余持仓','—','—','—','等待卖出',x.qty,'调出','—']));
|
||||
el('positions').replaceChildren();positions.forEach(x=>line(el('positions'),[names[x.book_id],x.code,x.qty,fmt(x.cost),x.market_value&&metrics[x.book_id]?.equity?fmt(x.market_value/metrics[x.book_id].equity*100)+'%':'—',fmt(x.market_value)]));
|
||||
el('summary').replaceChildren();Object.entries(metrics).forEach(([book,r])=>{let peak=0,dd=0;[...(v.daily||[])].reverse().forEach(x=>{const n=(x.value.metrics||{})[book]?.nav;if(n>0){peak=Math.max(peak,n);dd=Math.min(dd,n/peak-1);}});line(el('summary'),[names[book],cashAmount(r.cash),fmt(r.equity),fmt(r.net_capital),fmt(r.profit),fmt(r.nav,4),book==='account'||r.nav==null?'—':fmt(dd*100)+'%',fmt(r.fees)]);});
|
||||
if(!isPaper&&(v.accounting?.cash_ready??v.accounting?.ready))el('account').textContent='实际账本自 '+v.accounting.started_at+' 起记录 · 内部划拨 '+v.accounting.transfer_count+' 笔 · 账面现金 '+cashAmount(metrics.account?.cash)+' 元'+(v.accounting.valuation_ready===false?' · '+(v.accounting.reason||'等待持仓行情,估值暂缺。'):'');
|
||||
const diff=v.accounting?.cash_difference;el('reconcile').textContent=v.reconciliation?('持仓对账 '+(v.reconciliation.ok?'一致':'待核对')+' · 现金差异 '+fmt(diff)+' 元'):'交易账本尚未启用,当前仅观察。';
|
||||
}
|
||||
el('copy-members').onclick=copyMembers;el('refresh').onclick=load;document.querySelectorAll('[data-mode],[data-action]').forEach(b=>b.onclick=async()=>{try{if(b.dataset.mode==='auto'&&!confirm('将启用155模拟账户自动执行。确认启用?'))return;if(b.dataset.action==='exit_disable'&&!confirm('将停止新增并退出微盘持仓。确认执行?'))return;await request('/api/ops/rotation/control',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(b.dataset.mode?{mode:b.dataset.mode}:{action:b.dataset.action})});await load()}catch(e){el('errors').textContent=e.message}});load();setInterval(load,30000);
|
||||
</script></body></html>
|
||||
126
app/ws/runner.py
126
app/ws/runner.py
|
|
@ -512,12 +512,13 @@ class WsRunner:
|
|||
协议的补发机制正是为这种情况准备的, 用它比自己攒重试队列稳妥得多。
|
||||
"""
|
||||
type_, pl, seq = env["type"], env.get("payload") or {}, int(env["seq"])
|
||||
needs_ledger = type_ in wsc.NEEDS_LEDGER
|
||||
needs_ledger = wsc.needs_ledger(type_, pl)
|
||||
note = None if needs_ledger else f"{type_} 由通道进程消化, 不入账"
|
||||
try:
|
||||
r = await _db(qmt_repo.inbox_put, seq=seq, msg_id=str(env.get("msg_id") or ""),
|
||||
msg_type=type_, payload=pl, msg_ts=int(env.get("ts") or 0),
|
||||
corr_id=env.get("corr_id") or pl.get("instruction_id"),
|
||||
corr_id=(pl.get('instruction_id') if wsc.is_correction(type_, pl)
|
||||
else env.get("corr_id") or pl.get("instruction_id")),
|
||||
dedup_key=wsc.dedup_key(type_, pl),
|
||||
processed=0 if needs_ledger else 2, note=note)
|
||||
except Exception as e:
|
||||
|
|
@ -525,6 +526,8 @@ class WsRunner:
|
|||
if r == qmt_repo.PUT_DUP_KEY:
|
||||
logger.warning("成交 %s 重复推送 (seq=%s), 已占位不入账",
|
||||
pl.get("trade_no"), seq)
|
||||
elif r == qmt_repo.PUT_CONFLICT:
|
||||
logger.error('成交修正消息冲突或缺少身份,seq=%s,已挂起等待核对', seq)
|
||||
had_pending = bool(self._pending_seq)
|
||||
self._last_seq, self._pending_seq = wsc.next_watermark(
|
||||
self._last_seq, self._pending_seq, seq)
|
||||
|
|
@ -632,21 +635,43 @@ class WsRunner:
|
|||
type_, iid, self._stat["orphan_updates"])
|
||||
|
||||
async def _apply_side_effects(self, type_: str, pl: dict, env: dict):
|
||||
if (type_ in (wsc.T_ACK, wsc.T_REJECT, wsc.T_ORDER_UPDATE)
|
||||
and not wsc.is_correction(type_, pl)
|
||||
and (pl.get('instruction_id') or env.get('corr_id'))):
|
||||
try:
|
||||
await _db(self._apply_order_side_effects_locked, type_, pl, env)
|
||||
except Exception as exc:
|
||||
logger.warning('委托状态持锁更新失败 %s %s: %s', type_,
|
||||
pl.get('instruction_id') or env.get('corr_id'), _brief_err(exc))
|
||||
else:
|
||||
self._apply_side_effects_sync(type_, pl, env)
|
||||
|
||||
def _apply_order_side_effects_locked(self, type_, pl, env):
|
||||
from app.services import execution_orders
|
||||
# 必须在同一线程内完成事务,不能让ContextVar连接跨多个to_thread调用。
|
||||
with execution_orders.account_guard():
|
||||
self._apply_side_effects_sync(type_, pl, env)
|
||||
|
||||
def _apply_side_effects_sync(self, type_: str, pl: dict, env: dict):
|
||||
"""把上行消息落到 pms_qmt_order 的状态上。**只动通道状态, 不动账本**。"""
|
||||
iid = pl.get("instruction_id") or env.get("corr_id")
|
||||
if wsc.is_correction(type_, pl):
|
||||
# 包括终态后的 amended 回报。两条证据配对、记账和累计量变更由 worker 原子完成。
|
||||
logger.info('[trade_correction] %s seq=%s 已收取,等待修正核验入账', iid, env.get('seq'))
|
||||
return
|
||||
try:
|
||||
if type_ == wsc.T_ACK:
|
||||
# 终态保护 (2026-08-28 审查修, 与 _on_order_update 同一条纪律):
|
||||
# _boot 重发换来的 ack{duplicate:true} 是新 seq 的新消息, 不带 status 时
|
||||
# 这里的 ACCEPTED 兜底会把已 FILLED 的委托改回在途 —— 幻影单从此常驻
|
||||
# queue_depth 与撤单清单。已终态的委托, ack 一律只记日志不动状态。
|
||||
row = await _db(qmt_repo.get_order, iid) or {}
|
||||
row = qmt_repo.get_order(iid) or {}
|
||||
cur = str(row.get("status") or "").upper()
|
||||
if cur and wsc.is_final(cur):
|
||||
logger.info("[ack] %s 已是终态 %s, ack(duplicate=%s) 不回退状态",
|
||||
iid, cur, bool(pl.get("duplicate")))
|
||||
else:
|
||||
n = await _db(qmt_repo.update_order, iid,
|
||||
n = qmt_repo.update_order(iid,
|
||||
status=str(pl.get("status") or wsc.ST_ACCEPTED).upper(),
|
||||
broker_order_id=pl.get("broker_order_id"))
|
||||
self._note_orphan(n, type_, iid)
|
||||
|
|
@ -675,7 +700,22 @@ class WsRunner:
|
|||
n, json.dumps(pl, ensure_ascii=False)[:500])
|
||||
self._maybe_degrade_ack(pl)
|
||||
else:
|
||||
n = await _db(qmt_repo.update_order, iid, status=qmt_repo.OS_REJECTED,
|
||||
row = qmt_repo.get_order(iid) or {}
|
||||
cur = str(row.get('status') or '').upper()
|
||||
# 撤单拒绝不等于原委托拒绝。先记录拒绝原因,保留数量与原状态。
|
||||
cancelling = row.get('cancel_state') in ('REQUESTED', 'SENT')
|
||||
if wsc.is_final(cur) or cancelling or code == 'ALREADY_FINAL' or pl.get('cancel_id'):
|
||||
self._note_orphan(qmt_repo.update_order(iid,
|
||||
reject_code=code[:32], reject_reason=str(pl.get('reason') or '')[:300]),
|
||||
type_, iid)
|
||||
final_status = str(pl.get('status') or pl.get('current_status') or '').upper()
|
||||
if not wsc.is_final(cur) and wsc.is_final(final_status) and pl.get('cum_qty') is not None:
|
||||
self._on_order_update_sync(iid, {**pl, 'status': final_status, 'final': True}, sequence=env.get('seq'))
|
||||
else:
|
||||
logger.warning('[reject] %s 撤单或终态响应 %s,保留委托状态 %s 和成交数量,等待最终核对',
|
||||
iid, code, cur)
|
||||
return
|
||||
n = qmt_repo.update_order(iid, status=qmt_repo.OS_REJECTED,
|
||||
reject_code=code[:32],
|
||||
reject_reason=str(pl.get("reason") or "")[:300],
|
||||
final_at=datetime.now())
|
||||
|
|
@ -686,7 +726,7 @@ class WsRunner:
|
|||
lvl("[reject] %s %s: %s (retryable=%s, 不自动重发)", iid, code,
|
||||
pl.get("reason"), pl.get("retryable"))
|
||||
elif type_ == wsc.T_ORDER_UPDATE:
|
||||
await self._on_order_update(iid, pl)
|
||||
self._on_order_update_sync(iid, pl, sequence=env.get('seq'))
|
||||
elif type_ == wsc.T_TRADE:
|
||||
self._stat["trades"] += 1
|
||||
if not wsc.trade_amount_ok(pl):
|
||||
|
|
@ -718,10 +758,41 @@ class WsRunner:
|
|||
# 通道状态更新失败不该拖垮连接 —— 账本不靠它, 靠 inbox 里的 trade。
|
||||
logger.warning("通道状态更新失败 %s %s: %s", type_, iid, _brief_err(e))
|
||||
|
||||
async def _on_order_update(self, iid: str, pl: dict):
|
||||
async def _on_order_update(self, iid: str, pl: dict, sequence=None):
|
||||
if wsc.is_correction(wsc.T_ORDER_UPDATE, pl):
|
||||
return
|
||||
await _db(self._on_order_update_locked, iid, pl, sequence)
|
||||
|
||||
def _on_order_update_locked(self, iid, pl, sequence):
|
||||
from app.services import execution_orders
|
||||
with execution_orders.account_guard():
|
||||
self._on_order_update_sync(iid, pl, sequence)
|
||||
|
||||
def _on_order_update_sync(self, iid: str, pl: dict, sequence=None):
|
||||
if wsc.is_correction(wsc.T_ORDER_UPDATE, pl):
|
||||
return
|
||||
status = str(pl.get("status") or "").upper()
|
||||
row = await _db(qmt_repo.get_order, iid) or {}
|
||||
row = qmt_repo.get_order(iid) or {}
|
||||
cur = str(row.get("status") or "").upper()
|
||||
if row:
|
||||
from app.services import execution_orders
|
||||
audit = execution_orders.order_correction(row)
|
||||
if audit and (wsc.is_final(cur) or sequence is not None and int(sequence) <=
|
||||
max(int(audit['correction_seq']), int(audit.get('amendment_seq') or 0))):
|
||||
logger.info('[order_update] %s 已有已核实成交修正,普通终态回报不覆盖修正版本', iid)
|
||||
return
|
||||
done = pl.get('cum_qty')
|
||||
try:
|
||||
done = int(done)
|
||||
if done < int(row.get('cum_qty') or 0) or done > int(row['qty']) or done < 0:
|
||||
raise ValueError('累计成交倒退或超出委托数量')
|
||||
if status == wsc.ST_FILLED and done != int(row['qty']):
|
||||
raise ValueError('全成状态与累计成交数量不符')
|
||||
except (TypeError, ValueError, KeyError) as exc:
|
||||
self._stat['order_update_conflicts'] = self._stat.get('order_update_conflicts', 0) + 1
|
||||
self._stat['last_order_conflict'] = f'{iid}: {exc}'
|
||||
logger.error('[order_update] %s 累计成交不可核实,保留原委托占用: %s', iid, exc)
|
||||
return
|
||||
if wsc.is_final(cur) and status != cur:
|
||||
# §5.4/§7.1: 终态唯一、不可再变、只推一次。真收到第二条终态说明对端有 bug ——
|
||||
# 此时**保住第一条**: 账本记的是"到底成交了多少", 被一条迟到的 CANCELLED 覆盖掉
|
||||
|
|
@ -729,7 +800,7 @@ class WsRunner:
|
|||
logger.error("[order_update] %s 已是终态 %s, 又收到 %s —— 已忽略, 请核对对端实现",
|
||||
iid, cur, status)
|
||||
return
|
||||
fields = {"status": status, "cum_qty": int(pl.get("cum_qty") or 0)}
|
||||
fields = {"status": status, "cum_qty": done}
|
||||
if pl.get("cum_avg_price") is not None:
|
||||
fields["cum_avg_price"] = float(pl["cum_avg_price"])
|
||||
if pl.get("leaves_qty") is not None:
|
||||
|
|
@ -749,7 +820,7 @@ class WsRunner:
|
|||
"撤单可能在到期后才到, 按到期处理", iid)
|
||||
logger.info("[order_update] %s 终态 %s, 累计成交 %s 股", iid, status,
|
||||
fields["cum_qty"])
|
||||
self._note_orphan(await _db(qmt_repo.update_order, iid, **fields),
|
||||
self._note_orphan(qmt_repo.update_order(iid, **fields),
|
||||
wsc.T_ORDER_UPDATE, iid)
|
||||
|
||||
# ============================================================ 确认
|
||||
|
|
@ -865,8 +936,7 @@ class WsRunner:
|
|||
if int(r["valid_until"] or 0) <= now:
|
||||
# 排队期间就过期了。发出去只会立刻换回一个 EXPIRED, 白跑一趟还占对端一条
|
||||
# 记录 —— 本地作废更干净, executor 下一跳会按新行情重新出手。
|
||||
await _db(qmt_repo.abort_order, iid, "排队期间 valid_until 已过, 未发出即作废")
|
||||
logger.warning("[outbox] %s 有效期已过, 本地作废未发出", iid)
|
||||
await self._stop_outbox_order(iid, "排队期间 valid_until 已过")
|
||||
continue
|
||||
if not await _db(qmt_repo.claim_order, iid):
|
||||
continue # 被别的进程抢走了 (滚动重启的瞬间)
|
||||
|
|
@ -874,31 +944,43 @@ class WsRunner:
|
|||
# 排队后可能发生清仓或撤单。认领后再核对,未知状态保留重试。
|
||||
fresh = await _db(qmt_repo.get_order, iid)
|
||||
if not fresh or fresh.get('cancel_state') in ('REQUESTED', 'SENT'):
|
||||
await _db(qmt_repo.abort_order, iid, '发出前撤销')
|
||||
await self._stop_outbox_order(iid, '发出前撤销')
|
||||
continue
|
||||
from app.services.execution_conflicts import queued_buy_blocker
|
||||
from app.services.dispatcher import order_strategy_type
|
||||
try:
|
||||
blocked = await _db(queued_buy_blocker, fresh)
|
||||
if not blocked:
|
||||
strategy_type = await _db(order_strategy_type, fresh.get('parent_id'))
|
||||
except Exception as exc:
|
||||
await _db(qmt_repo.requeue_order, iid, f'买入依据暂不可核实: {exc}',
|
||||
self._p('max_attempts', 3), False)
|
||||
logger.warning('[outbox] %s 买入依据暂不可核实,保留队列', iid)
|
||||
continue
|
||||
if blocked:
|
||||
await _db(qmt_repo.abort_order, iid, blocked)
|
||||
await self._stop_outbox_order(iid, blocked)
|
||||
continue
|
||||
payload = wsc.place_order_payload(
|
||||
instruction_id=iid, ts_code=r["ts_code"], side=r["side"],
|
||||
qty=int(r["qty"]), limit_price=r["limit_price"],
|
||||
valid_until=int(r["valid_until"]), intent=r.get("intent") or "OPEN",
|
||||
note=r.get("note") or "")
|
||||
note=r.get("note") or "", strategy_type=strategy_type)
|
||||
from app.services import execution_orders
|
||||
send_check = await _db(execution_orders.prepare_send, iid)
|
||||
if send_check.get('blocked'):
|
||||
await self._stop_outbox_order(iid, send_check['blocked'])
|
||||
continue
|
||||
if not send_check['marked']:
|
||||
continue # 同时发生撤单或状态改变,不再发送。
|
||||
await self._send(wsc.T_PLACE, payload, seed, corr_id=iid)
|
||||
except Exception as e:
|
||||
# 连接断了不算这张单的"失败次数" —— 那是通道的问题不是这张单的问题,
|
||||
# 否则一次几秒的网络抖动就能把三张待发单全部烧成 SEND_FAILED。
|
||||
conn = _is_conn_error(e)
|
||||
# 已进入传输阶段则无法证明对端未收到,必须保留在途与幂等键。
|
||||
attempted = await _db(qmt_repo.get_order, iid)
|
||||
await _db(qmt_repo.requeue_order, iid, f"{type(e).__name__}: {e}",
|
||||
self._p("max_attempts", 3), not conn)
|
||||
self._p("max_attempts", 3), not conn and not bool((attempted or {}).get('sent_at')))
|
||||
logger.warning("[outbox] %s 发送失败%s: %s", iid,
|
||||
" (连接问题, 不计失败次数)" if conn else "", e)
|
||||
raise
|
||||
|
|
@ -906,11 +988,21 @@ class WsRunner:
|
|||
logger.info("[outbox] 已发出 %s %s %s %s股 @%.2f", iid, r["ts_code"],
|
||||
r["side"], r["qty"], float(r["limit_price"]))
|
||||
|
||||
async def _stop_outbox_order(self, iid: str, reason: str):
|
||||
row = await _db(qmt_repo.get_order, iid) or {}
|
||||
if row.get('sent_at'):
|
||||
# 包括重启恢复后的 QUEUED:曾尝试发送就必须向QMT撤单并等回报。
|
||||
n = await _db(qmt_repo.request_order_cancel, iid, wsc.new_cancel_id(_ymd()), reason)
|
||||
if not n and row.get('cancel_state') not in ('REQUESTED', 'SENT') and row.get('status') in qmt_repo.LIVE:
|
||||
raise RuntimeError('待撤意图未写入,保留委托占用')
|
||||
else:
|
||||
await _db(qmt_repo.abort_order, iid, reason)
|
||||
|
||||
async def _drain_cancels(self, seed: str):
|
||||
rows = await _db(qmt_repo.next_cancel_requests, 20)
|
||||
for r in rows:
|
||||
iid = r["instruction_id"]
|
||||
if r["status"] in (qmt_repo.OS_QUEUED, qmt_repo.OS_SENDING):
|
||||
if r["status"] in (qmt_repo.OS_QUEUED, qmt_repo.OS_SENDING) and not r.get('sent_at'):
|
||||
# 还没发出去就要撤 —— 直接本地作废, 不必跑一趟下游
|
||||
await _db(qmt_repo.abort_order, iid, "发出前撤销")
|
||||
await _db(qmt_repo.mark_cancel_sent, iid)
|
||||
|
|
|
|||
|
|
@ -17,6 +17,49 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
|
||||
|
||||
# 当日限制价缓存与独立采集。业务开关和预算统一从ParamStore读取。
|
||||
PMS_LIMIT_CACHE_ENABLED: bool = False
|
||||
PMS_LIMIT_COLLECT_ENABLED: bool = False
|
||||
PMS_LIMIT_FETCH_TIMEOUT_SEC: int = 5
|
||||
PMS_LIMIT_ROUND_BUDGET_SEC: int = 30
|
||||
PMS_LIMIT_ROUND_MAX_CODES: int = 25
|
||||
PMS_LIMIT_MIN_REQUEST_INTERVAL_SEC: float = 1.2
|
||||
PMS_LIMIT_RETRY_BASE_SEC: int = 60
|
||||
PMS_LIMIT_RETRY_MAX_SEC: int = 900
|
||||
PMS_LIMIT_MAX_FAILURES_PER_DAY: int = 32
|
||||
PMS_LIMIT_REFRESH_SEC: int = 900
|
||||
PMS_LIMIT_COLLECT_START: str = "08:55"
|
||||
PMS_LIMIT_COLLECT_END: str = "18:00"
|
||||
# 密钥只由采集容器专用.env.market-data注入,不得写入共享.env或ParamStore。
|
||||
PMS_TUSHARE_TOKEN: str = ""
|
||||
|
||||
# 异步研判与委托报价;业务运行值统一从ParamStore读取。
|
||||
PMS_EXEC_REJECT_COOLDOWN_SEC: int = 60
|
||||
PMS_EXEC_REJECT_MAX_COOLDOWN_SEC: int = 900
|
||||
PMS_EXEC_REPRICE_ENABLED: bool = False
|
||||
PMS_EXEC_BASIS_REFRESH_SEC: int = 60
|
||||
PMS_EXEC_BASIS_REFRESH_BUDGET_SEC: int = 20
|
||||
PMS_EXEC_BASIS_SOURCE_MAX_DAYS: int = 7
|
||||
PMS_EXEC_QUOTE_MAX_AGE_SEC: int = 15
|
||||
PMS_EXEC_ALLOW_MINUTE_QUOTE: bool = True
|
||||
PMS_EXEC_MINUTE_MAX_AGE_SEC: int = 90
|
||||
PMS_EXEC_PRICE_OFFSET_TICKS: int = 1
|
||||
PMS_EXEC_REPRICE_MIN_SEC: int = 60
|
||||
PMS_EXEC_REPRICE_TICKS: int = 2
|
||||
PMS_EXEC_REPRICE_MAX_ATTEMPTS: int = 0
|
||||
PMS_EXEC_MAX_SLIPPAGE_PCT: float = 0.01
|
||||
PMS_EXEC_MINUTE_SLIPPAGE_PCT: float = 0.002
|
||||
PMS_ROTATION_CANDIDATE_POOL_SIZE: int = 100
|
||||
PMS_JUDGE_ASYNC_ENABLED: bool = False
|
||||
PMS_JUDGE_ASYNC_HTTP_TIMEOUT: int = 3
|
||||
PMS_JUDGE_ASYNC_DEADLINE_SEC: int = 120
|
||||
PMS_JUDGE_ASYNC_CACHE_SEC: int = 120
|
||||
PMS_JUDGE_ASYNC_SCAN_BUDGET_SEC: int = 20
|
||||
|
||||
# 数据库基础设施能力位。迁移核验完成后才在部署环境打开,不是交易开关。
|
||||
INFRA_STRATEGY_BOOK_SCHEMA: bool = False
|
||||
INFRA_ROTATION_DOCUMENT_SCHEMA: bool = False
|
||||
|
||||
# =========================================================
|
||||
# 一、基础设施 (键名对齐 bionic_trader, 同一 .env 可共用)
|
||||
# =========================================================
|
||||
|
|
@ -152,11 +195,12 @@ class Settings(BaseSettings):
|
|||
# 若日后计划服务搬到别的机器, 这里直接填那台的 IP:端口。空=停用, 候选池恒为空。
|
||||
PMS_PLAN_API_BASE: str = "http://host.docker.internal:8300"
|
||||
PMS_PLAN_API_PATH: str = "/plan"
|
||||
PMS_PLAN_WRITE_KEY: str = "" # 仅环境注入;匹配桥侧写接口密钥,不进入参数中心。
|
||||
PMS_PLAN_TIMEOUT: int = 10 # 单次请求超时 (秒)
|
||||
PMS_PLAN_CACHE_SEC: int = 300 # 计划缓存秒数 (上游日频产出, 没必要每跳都拉)
|
||||
# 下面三个是**发给上游的请求参数** (对方 api.py: top=20/obs_top=10/theme_cap=5 都是
|
||||
# 可传的, 不是它的既定政策)。0 = 不传, 用上游默认。要个宽池子回来, 主题分散交给
|
||||
# PMS_PLAN_THEME_CAP_LOCAL 在候选阶段做 —— 理由见 plan_feed.select_candidates。
|
||||
# 可传的, 不是它的既定政策)。top/obs_top 为 0 使用上游默认;theme_cap 为 0 明确不限。
|
||||
# PMS_PLAN_THEME_CAP_LOCAL 单独控制 PMS 本地的主题限额。
|
||||
PMS_PLAN_TOP: int = 300 # 上游 top: 主榜要多少条
|
||||
PMS_PLAN_OBS_TOP: int = 100 # 上游 obs_top: 观察档要多少条
|
||||
PMS_PLAN_THEME_CAP: int = 999 # 上游 theme_cap: 让它别裁 (PMS 自己裁)
|
||||
|
|
@ -208,6 +252,7 @@ class Settings(BaseSettings):
|
|||
PMS_DISPATCH_MODE: str = "shadow" # 下发通道: shadow(影子,默认) / ws(直连QMT,待实现)
|
||||
PMS_EXEC_SLICES: int = 1 # 当日配额分几笔出手 (设计「分笔卖出配额」)
|
||||
PMS_ORDER_TTL_MIN: int = 10 # 单个下发分片的挂单有效期(交易分钟), 到点下游自动撤
|
||||
PMS_EXEC_QMT_DAY_ORDER: bool = False # 普通QMT限价单当日有效;微盘、网格等独立执行不受影响
|
||||
# --- 卖出分桶收口与紧急直通 (2026-08-17 清仓择时改造) ---
|
||||
# 「现价不低于均价才卖」是只在强势时放行的条件, 下跌日全天不满足, 全部数量会
|
||||
# 堆到 14:45 一笔打出。分桶: 桶内照旧择价, 桶收口无条件补齐该桶份额, 把跌日的
|
||||
|
|
@ -221,6 +266,7 @@ class Settings(BaseSettings):
|
|||
# 配额/兜底/停牌/一字板/不追高(当日涨幅) 这些检查始终留在 PMS 本地。
|
||||
# 不可用自动退实现B (设计 §13), 绝不因对端故障停出手。
|
||||
PMS_EXEC_IMPL: str = "B" # B=内置保守择时(默认) / A=委托决策系统
|
||||
PMS_EXEC_QMT_PRICE_MONITOR: bool = False # 已生成指令直接提交限价,由QMT等待价格;按实例启用
|
||||
PMS_EXEC_API_BASE: str = "" # 实现A接口根地址; 留空=沿用 PMS_JUDGE_API_BASE (同一个 bionic 服务)
|
||||
PMS_EXEC_PATH: str = "/api/intraday/pms_exec"
|
||||
PMS_EXEC_TIMEOUT_SEC: int = 8 # 咨询超时(秒)。盘中 tick 等不起长超时, 超了本轮退B
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
-- 轮换状态、快照、验收证据及独立纸面账本。与交易表分开存储。
|
||||
CREATE TABLE IF NOT EXISTS pms_rotation_document (
|
||||
doc_id VARCHAR(128) NOT NULL PRIMARY KEY,
|
||||
kind VARCHAR(32) NOT NULL,
|
||||
payload_json LONGTEXT NOT NULL,
|
||||
revision BIGINT NOT NULL DEFAULT 0,
|
||||
updated_at DATETIME NOT NULL,
|
||||
KEY idx_kind_updated (kind, updated_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='轮换持久状态与独立纸面记录';
|
||||
|
|
@ -9,10 +9,11 @@
|
|||
# PMS_WEB_PORT_HOST=38200 → 页面宿主机端口 (容器内固定 38100, 不用改)
|
||||
# COMPOSE_PROJECT_NAME=pms-real → compose 项目名 (网络/卷前缀), docker 原生支持
|
||||
# 这些键进容器环境也无害: settings 是 extra="ignore", 不声明就当不存在。
|
||||
# 三组服务:
|
||||
# 四组服务:
|
||||
# 默认 pms-web 管理页面 (38100)
|
||||
# --profile sched pms-beat / pms-worker Celery 调度与执行
|
||||
# --profile ws pms-ws QMT WebSocket 常驻连接 (协议 V1.0)
|
||||
# --profile market-data pms-market-data 独立限制价采集,不接交易通道
|
||||
#
|
||||
# pms-ws 与 worker 的关系: worker 里的 executor 把待发委托写进 pms_qmt_order 出口表,
|
||||
# pms-ws 亚秒轮询取走并发出。两者**只经数据库耦合**, 谁先起谁后起都不影响 —— pms-ws 没起
|
||||
|
|
@ -68,6 +69,27 @@ services:
|
|||
profiles: ["sched"]
|
||||
command: celery -A app.scheduler.celery_app worker -l info -c 2
|
||||
|
||||
# 独立单进程采集,专用密钥不注入其他服务。不要扩副本或同时启动第二个采集入口。
|
||||
pms-market-data:
|
||||
<<: *pms-base
|
||||
container_name: ${PMS_STACK_PREFIX:-}pms-market-data
|
||||
profiles: ["market-data"]
|
||||
env_file:
|
||||
- .env
|
||||
- path: .env.market-data
|
||||
required: false
|
||||
command: python -m app.market_data_worker
|
||||
volumes: []
|
||||
cpus: 0.5
|
||||
mem_limit: 256m
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=16m,mode=1777
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
stop_grace_period: 60s
|
||||
stop_signal: SIGTERM
|
||||
|
||||
# QMT WebSocket 常驻连接。协议 §1 规定 PMS 只开一条连接 (多开会让指令乱序),
|
||||
# 所以这个服务**绝不能扩副本** —— 不要 deploy.replicas, 不要 docker compose up --scale。
|
||||
# 退出流程见 app/ws/runner.py 的 _shutdown: 刷水位 → 最后一次 ack → 关连接 → 清心跳,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
# QMT下单策略类型
|
||||
|
||||
本次只给`place_order.payload`增加一个`strategy_type`字段,供QMT分类、展示及人工操作。其他业务字段、委托编号、价格、数量、有效期和备注保持原样,撤单及查询消息不变。
|
||||
|
||||
| strategy_type | 显示名称 | PMS内部账本 |
|
||||
| --- | --- | --- |
|
||||
| subjective_quant | 主观量化 | original |
|
||||
| micro_rotation | 微盘轮动 | micro30 |
|
||||
|
||||
标识不包含持股数量,微盘当前为50只。PMS按父指令的持久账本归属填值,不按备注、当前轮换阶段或调用上下文推断。主观量化减持为微盘腾出资金时,该卖单仍标为`subjective_quant`。微盘买入、日常换仓及退出均标为`micro_rotation`。
|
||||
|
||||
QMT读取并保存该字段,可用上述映射显示中文。旧订单或历史报文可能没有该字段,需要兼容保留;不要求重新下发或修改历史委托。新增字段参与完整payload签名,验签前不能用旧字段白名单重建payload。信封`v=1`、握手`protocol=1`和签名算法保持。完整定义见[QMT协议第4.2节](../QMT_WS_PROTOCOL.md)。
|
||||
|
||||
PMS策略来源无法核实时保留队列等待重试,不伪造另一策略名称;已有的用户命令、资金占用、跨日复核、到期与撤单回报处理保持。
|
||||
|
||||
## 验证与发布
|
||||
|
||||
源码提交578a2fa。新增8项隔离测试覆盖原字段不变、两类策略买卖归属、轮换筹资归属、策略读取故障、签名篡改及撤单格式。原签名测试向量未改,开发机全量断网回归通过。155候选镜像在断网、只读、1核512MiB下全量回归通过;没有修改生产依赖。
|
||||
|
||||
本对话的每日定时复核`30-pms`已按用户要求删除。这只取消本聊天的自动复核,不修改PMS业务调度或策略运行档位。
|
||||
|
||||
155于2026年11月2日09:07:31完成发布,仅将唯一`pms-ws`重建为`pms:strategy-type-578a2fa`,服务器补丁提交4059b6f。web、worker、beat与监控容器保持原进程;环境、挂载、业务参数、用户暂停及策略规则均未改变。首次发布前一致性检查中止在所有写操作之前,随后相同条件重新采样通过后才发布,没有通过重连规避检查。
|
||||
|
||||
09:08:20确认序号已推进至1569713,最新160条连续,缺口、新拒绝、额外重连、待入账和孤儿成交为0,资金年龄21.2秒;数量及现金对账差异0,无在途委托。当前没有新委托,字段的真实QMT接收、保存及显示尚待后续自然下单核实;本次不制造测试交易。隔离发送出口及签名测试通过,不冒充对端已落库。
|
||||
|
||||
发布证据见[155核验摘要](evidence/pms_qmt_strategy_type_20261102.json)。如需回退,先停止新增,保留账本及在途回报,再定向回退WS镜像;不删改历史委托或重置序号。
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
# 请协助排查QMT每30秒产生的SIG_INVALID及消息序号缺口
|
||||
|
||||
致QMT研发同事:
|
||||
|
||||
请协助定位目前持续出现的验签拒绝。**截至2026年10月27日16:29的复核,QMT仍约每30秒产生一条SIG_INVALID。这些拒绝占用了上行消息序号,但没有实时送到当前PMS连接,重连后才能补回,导致PMS无法连续确认已收消息。**
|
||||
|
||||
此前数分钟断线已确认与QMT系统重启有关,不作为本次故障判断依据。本次重点是重启后仍在产生的验签拒绝,以及这些拒绝的生成、存储和投递路径。
|
||||
|
||||
## 1. 对接环境和影响
|
||||
|
||||
| 项目 | 当前情况 |
|
||||
| --- | --- |
|
||||
| PMS | 155模拟环境,出口IP为192.168.16.155,只有一个pms-ws连接进程 |
|
||||
| QMT端点 | ws://192.168.18.182:9443/pms |
|
||||
| 曾使用的测试端点 | ws://192.168.16.98:9443/pms,是否仍有相关客户端或服务运行待核实 |
|
||||
| 连接和账户读取 | 握手、心跳、空仓及资金快照可正常取得 |
|
||||
| 当前影响 | 连续消息确认被序号缺口阻塞,交易暂停保留,尚未恢复自动执行 |
|
||||
| 排查期间操作 | 未发送测试委托,未修改密钥,未归零或降低消息序号 |
|
||||
|
||||
## 2. 请优先反查这条最新拒绝
|
||||
|
||||
请先根据下列字段,在QMT侧找到**触发拒绝的原始入站请求及其来源连接**。下面是已收到拒绝的定位字段节选,不是原始完整信封:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "reject",
|
||||
"seq": 1442087,
|
||||
"msg_id": "m-20261027-ba36fcf9",
|
||||
"ts": 1793089732694,
|
||||
"payload": {
|
||||
"instruction_id": null,
|
||||
"code": "SIG_INVALID",
|
||||
"reason": "signature verification failed",
|
||||
"retryable": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
其中msg_id是**拒绝消息自身的编号**,不能当作被拒原请求的编号。当前拒绝没有提供可用于定位原请求的关联字段。
|
||||
|
||||
最近7条拒绝如下。时间均为2026年10月27日北京时间,由QMT报文ts字段换算,并非PMS收到补发的时间。
|
||||
|
||||
| seq | QMT报文产生时间 |
|
||||
| --- | --- |
|
||||
| 1442045 | 16:25:52.428 |
|
||||
| 1442052 | 16:26:22.473 |
|
||||
| 1442059 | 16:26:52.521 |
|
||||
| 1442066 | 16:27:22.561 |
|
||||
| 1442073 | 16:27:52.607 |
|
||||
| 1442080 | 16:28:22.661 |
|
||||
| 1442087 | 16:28:52.694 |
|
||||
|
||||
这7条均为上述SIG_INVALID。PMS在16:28:58至16:28:59重连补发时收到它们,说明近期缺口已确认对应验签拒绝,并非仅根据跳号推测。
|
||||
|
||||
## 3. PMS侧已经核实的事实
|
||||
|
||||
1. 16:07:26至16:08:56曾停掉155唯一PMS连接约90秒。此期间对182和98的9443端口限定抓包为0,但QMT仍在16:07:50.635、16:08:20.671、16:08:50.707产生三条拒绝,序号为1441798、1441799、1441800,随后补发到PMS。这排除了当前PMS在停机期间发送新请求触发这三条拒绝;其他客户端、服务内部定时任务或延迟处理仍须QMT侧定位。
|
||||
2. 16:08:59恢复连接后的完整采样中,37条PMS下行和84条QMT上行共121条报文均可通过签名复核。PMS下行只有hello、query_positions、query_funds、ack_seq和ping,没有下单或撤单。心跳约5秒一次,账户查询配置为300秒一次。
|
||||
3. 上述结果不代表已经获得“真正验签失败的原始请求”,也不能替代核对QMT为该请求选用了哪把公钥。PMS收到的是QMT正确签名的失败通知,不是PMS验不过这条通知本身。
|
||||
4. 16:28:38,PMS连续确认停在1442044,已收最高1442083,暂存33条。一次受控重连从1442045起补发,补回上述近期拒绝后确认继续推进。问题不能仅用此前系统重启或当前ONLINE状态解释。
|
||||
|
||||
目前尚未证实这些失败请求来自98旧环境,也尚未证实来自当前155 PMS。请以原请求的来源地址、连接ID和运行进程为准。
|
||||
|
||||
## 4. 请QMT侧按以下顺序排查
|
||||
|
||||
**第一步:找到每30秒触发一次的来源。** 优先查16:25:40至16:29:10的日志,以seq=1442087或拒绝msg_id反向关联原请求。需要服务实例、PID、连接ID、远端IP及端口、原请求type和msg_id。检查是否存在旧客户端、健康探针、模拟客户端或30秒重试任务。若现场连接列表没有该来源,继续查历史接入日志,短连接可能已经退出。
|
||||
|
||||
**第二步:给出验签失败的直接原因。** 请保留一条失败原请求的v、type、msg_id、ts、nonce、payload、sig,以及实际使用的公钥指纹、payload序列化结果摘要、签名规范串摘要和异常类型。确认是签名缺失、公钥选择错误、规范化差异、实际签名不匹配,还是其他校验错误被统一映射成SIG_INVALID。
|
||||
|
||||
当前155 PMS签名公钥的指纹如下。计算口径是Ed25519裸公钥32字节的SHA-256,不是PEM文件文本的摘要:
|
||||
|
||||
```text
|
||||
d49def41f4362d59a07675f49dce2a1e1bacc706315de98c67a2f7e72c201a98
|
||||
```
|
||||
|
||||
双方签名规范为六段字符串,以单个换行连接,末尾没有换行:
|
||||
|
||||
```text
|
||||
v
|
||||
type
|
||||
msg_id
|
||||
ts
|
||||
nonce
|
||||
sha256(payload_json)
|
||||
```
|
||||
|
||||
payload_json使用键排序、紧凑JSON和UTF-8,不转义中文。seq和corr_id不属于现行协议的六段签名内容。请核对失败请求实际走的代码,而不仅核对握手成功时走的代码。
|
||||
|
||||
**第三步:核对序号和投递归属。** 对同一条拒绝串起“分配seq、写入回放存储、加入发送队列、实际发送”四个环节,记录各环节时间、队列所属连接和socket目标连接。需要解释:它为什么消耗了当前PMS接收序列中的号码,却没有实时送给这条连接,之后又能从该连接的回放记录里补回。
|
||||
|
||||
**第四步:检查182和98是否混用了状态。** 核对两端的运行入口、代码提交、服务及计划任务、可信PMS公钥、Redis主机和数据库编号,以及seq、回放记录、ack状态的键名或前缀。确认是否跨环境、账户或连接共用了本应分开的状态。另检查新连接是否在身份验证成功前替换旧连接,以及旧发送任务是否可能取到新连接的队列。
|
||||
|
||||
请先定位来源与原因,再决定修改方案。不要通过关闭验签、清空序号或反复重连来消除表面告警;这些操作不能说明故障已修复。无需提供私钥、密码或完整环境文件。
|
||||
|
||||
## 5. 如需双方一起看代码,请提供这些部分
|
||||
|
||||
请提供**当前实际运行版本**和提交号,文件名以QMT项目为准,不必提交整个仓库。
|
||||
|
||||
| 代码职责 | 需要的函数范围 |
|
||||
| --- | --- |
|
||||
| 连接生命周期 | 接入、hello认证、登记或替换活动连接、断开清理 |
|
||||
| 验签 | 公钥加载与选择、payload规范化、签名串生成、verify、异常映射 |
|
||||
| 拒绝发布 | SIG_INVALID生成、序号分配、存储及目标连接选择 |
|
||||
| 消息发送与回放 | 发送队列与socket绑定、任务取消、按last_seq补发、ack处理 |
|
||||
| 环境及周期任务 | Redis命名空间配置、30秒重试或探针任务及其启动入口 |
|
||||
|
||||
若现有日志缺少关联字段,可在测试环境短期补日志,至少覆盖三个30秒周期。原始失败帧留在QMT本机;如共享时修改了签名覆盖字段进行脱敏,请标注“已脱敏,不能直接验签”,同时提供原始规范串摘要供双方核对。
|
||||
|
||||
## 6. 请按此格式返回排查结论
|
||||
|
||||
```text
|
||||
排查时间及QMT运行版本:
|
||||
失败请求来源:主机/IP、进程或服务、连接ID。
|
||||
被拒请求:type、msg_id、ts;关联reject的seq/msg_id。
|
||||
每30秒触发的原因:
|
||||
验签失败的直接原因及证据:
|
||||
使用的公钥指纹及规范串摘要:
|
||||
该拒绝的存储位置和实际投递连接:
|
||||
为何造成当前PMS的序号缺口:
|
||||
182与98是否共用相关状态:
|
||||
拟修改的文件或配置及影响范围:
|
||||
修复后验证时间、日志和结果:
|
||||
```
|
||||
|
||||
修复后双方连续观察至少10分钟。预期不再出现同类拒绝,PMS消息确认连续推进,没有新缺口或连接被替换。PMS现有逻辑会在缺口持续300秒后跳过缺口并保留对账标记,因此只看到序号变大不能算验证通过。双方完成通道与账户对账后,再处理交易恢复。
|
||||
|
||||
PMS侧可补充已整理的119条原样协议报文、日志、公钥和离线复核脚本。该材料不含账户快照或私钥。如需交叉查原始证据,最新复核保存在155的/home/factor/project/tradingSystem/backups/qmt-current-reject-20261027,停连和抓包证据保存在同级qmt-joint-20261027目录。
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
# QMT修复后的联调核验
|
||||
|
||||
用户提供《QMT侧排查回复_SIG_INVALID_2026-10-27.md》,并确认QMT已修改、重启。本次核验155模拟PMS到ws://192.168.18.182:9443/pms的实际运行。以下时间均为2026年10月27日北京时间。QMT报文时间由epoch毫秒换算,PMS容器日志和本次数据库DATETIME读数直接按北京时间读取。
|
||||
|
||||
## 当前结论
|
||||
|
||||
真机见过:16:55:33至17:06:19连续10分46秒没有新SIG_INVALID、PMS本端验签失败、序号缺口、跳过缺口或被动断线。PMS收件表中1442461至1442595共135条消息逐号连续,确认水位为1442595。
|
||||
|
||||
17:06:20完成新账户快照对账并留痕,清除resync,按此前授权将本次清账设置的暂停买入、暂停执行恢复为false。微盘轮动仍为observe,策略交易账本开关仍关闭。这是本轮通道恢复核验,不表示微盘自动执行已验收。
|
||||
|
||||
## 对方回复说明了什么
|
||||
|
||||
对方报告已增加拒绝消息的原请求类型、编号、时间、来源IP和连接ID,增加异IP连接保护及发布失败日志,并调整签名规范化和ack_seq失败处理。回复中的PMS公钥指纹与155此前提供的指纹一致。
|
||||
|
||||
这些是对方报告的改动,不等于本次已经审查182实际运行源码。回复没有填写部署提交号,也没有给出失败请求的真实来源。98联调客户端使用不配对密钥、或182与98共用Redis序列,目前仍是待核实的解释。
|
||||
|
||||
ack_seq不要求回应,并不意味着验签失败可以算正常。若QMT仍记录来自155的ack_seq验签失败,需要继续解决,并确认通过验签的确认消息确实更新了QMT的已确认水位。PMS显示的acked_seq只证明本端已发送确认。
|
||||
|
||||
## 修复切换期间发生了什么
|
||||
|
||||
| 北京时间 | 真机记录及解释 |
|
||||
| --- | --- |
|
||||
| 16:49:40 | 连接断开,随后两次握手超时。用户已说明QMT重启,不将这段断线作为旧环境抢连的证据 |
|
||||
| 16:50:09 | 自动重连成功,补发历史消息并将连续水位补至1442390 |
|
||||
| 16:50:10 | 收到最近一条历史拒绝1442389,QMT报文产生时间为16:49:54.564。不能因接收时间较晚就认为是重连后新产生的拒绝 |
|
||||
| 16:50:29 | 新缺口出现,连续确认停在1442395 |
|
||||
| 16:52:05 | 确认仍为1442395,最高收到1442417,暂存20条。此时还不能判定修复成功 |
|
||||
| 16:55:29 | PMS现有300秒规则跳过两个未收到的序号,推进到1442460,并保留resync标记 |
|
||||
| 16:55:30至16:55:33 | 在两项暂停、无在途及待处理成交的条件下,对原有唯一pms-ws受控重连一次。没有新开第二个连接 |
|
||||
|
||||
本次受控重连原本用于取回新缺口报文,但执行前已触发300秒超时跳过,所以没有取得这两条报文。没有降低确认序号或反复重连补取。
|
||||
|
||||
逐条核对PMS收件表确认,1442390至1442460之间仅缺1442396、1442403。第一条位于16:50:24.642和16:50:29.642的两条心跳之间,第二条位于16:50:54.658和16:50:59.658之间。仅凭跳号不能确定它们就是SIG_INVALID,也不能确认来源IP。
|
||||
|
||||
因此,16:55:33之后的无缺口运行必须单独计时,不把此前自动跳过缺口当作恢复证据。本次新增的来源字段尚未在新拒绝中得到验证,因为重新连接后尚未收到新拒绝。
|
||||
|
||||
## 连续观察与账户复核
|
||||
|
||||
连续观察从16:55:33这次连接开始。每30秒读取通道状态,并用收件表逐号检查实际持久化消息。16:57:04至17:06:05共19次采样,所有新拒绝、本端验签失败、暂存缺口、超时跳号、被动重连以及确认降级计数均为0。
|
||||
|
||||
16:58:41已确认PMS持仓、批次、指令、命令及交易动作均为0行。旧通道委托364条、逐笔成交1275条继续保留,成交最新序号仍为1440744,没有新增历史成交回流。回放游标仍为15:15:09,已登记的3笔旧成交去重标识完整。
|
||||
|
||||
恢复前,两项暂停仍由sim_reset_20261027在15:10:20设置,没有新增用户命令。清理前备份中暂停执行为false;暂停买入没有数据库覆盖值,ParamStore默认值为false。
|
||||
|
||||
17:06:19的恢复检查使用17:05:33产生的持仓及资金快照,年龄46.5秒。QMT持仓0,总资产和可用资金各200万元,冻结及市值0。无在途委托、待处理成交或孤立成交,下游重叠窗口内成交0。只读对账source=ws、source_mode=ws_only、severity=OK,差异、修正及错误均为0。
|
||||
|
||||
17:06:20先在同一事务内写入qmt_postfix_reconcile操作审计,再清resync并经ParamStore恢复两项暂停。更新人是qmt_recovered_20261027。第一次恢复尝试在审计参数序列化时因datetime类型失败,事务未执行状态写入;将日期转换为字符串后重新通过全部检查并完成提交,没有绕过审计。
|
||||
|
||||
17:07:43恢复后复核:确认水位继续推进至1442612,新拒绝、在途及待处理成交仍为0,PMS持仓仍为0;resync为0,两项暂停为false,observe和ws_only保留。操作审计编号为296。
|
||||
|
||||
## 本轮操作和边界
|
||||
|
||||
只重启了一次155原有pms-ws,镜像仍为pms:micro30-c994409。web仍为pms:micro30-98a58d1,其余业务容器及188真实PMS没有操作。没有修改业务代码、签名密钥、签名校验、超时参数、消息序号或持仓账本,没有发送测试委托。
|
||||
|
||||
证据保存在155的/home/factor/project/tradingSystem/backups/qmt-postfix-20261027,包括before.json、after.json、precheck.json、monitor.jsonl、recovery-receipt.json、recover.py和ws.log。目录权限700,文件权限600。recover.py是带日期、账户、连续运行时长、完整序号、新快照及暂停归属检查的一次性运维脚本,不是定时恢复逻辑;执行后条件已变化,不应重复运行。运行核验使用155现有pms-web内的仓储和对账模块,通道日志来自唯一pms-ws。
|
||||
|
||||
本轮为运行核验和文档更新,没有业务代码或页面变更,不重复运行与本轮无关的全量回归和浏览器验收。
|
||||
|
||||
## 请QMT侧保留的收尾证据
|
||||
|
||||
1. 182实际运行提交号、启动时间和启动日志中的PMS公钥指纹。
|
||||
2. 1442396、1442403在QMT回放存储中的类型和原请求关联字段,以及其生成和投递实例。查询历史记录即可,不需要PMS下调水位。
|
||||
3. 修复后来自155的ack_seq是否通过验签并更新确认水位。不要只用“不再发reject”作为处理成功证据。
|
||||
4. 若最终归因为98或其他进程,补上来源地址和进程证据,以及182、98的Redis数据库及键前缀隔离结果。
|
||||
|
||||
这些材料用于确认历史根因和部署归属。未取得之前,不将“98干扰”写成已证实结论。
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
# QMT切回182核验
|
||||
|
||||
17:06更新:QMT修改重启后,155已完成连续10分46秒无新拒绝和缺口的核验,收到新空仓及200万元资金快照并对账一致。已清resync,将清账暂停恢复为false;微盘继续观察。下文故障和暂停为早前现场,最新结果见[修复后联调核验](QMT修复后联调核验_2026-10-27.md)。
|
||||
|
||||
后续排查见[周期性验签拒绝联调材料](联调材料/QMT验签与序号缺口_2026-10-27/README.md)。16:07至16:08的90秒停连实验确认,当前PMS停机期间对端仍产生三条拒绝,当前连接并非停机期间的发送来源。具体其他来源尚需QMT接入日志确认。
|
||||
|
||||
用户确认QMT环境切回原182,要求检查是否正常。2026-10-27 15:47:45,155模拟PMS经ParamStore把端点改为ws://192.168.18.182:9443/pms,并重启原有唯一pms-ws使新连接立即生效。只改运行参数,未改业务代码、密钥、委托或账本。以下均为北京时间。
|
||||
|
||||
## 已确认正常的部分
|
||||
|
||||
真机见过:15:47:49握手成功,持续收发心跳;观察到15:50的连接期间没有再出现被其他连接替换的被动断开。新持仓快照为空,总资产和可用资金均为200万元,冻结资金及账户市值均为0。PMS持仓0,无在途委托、待处理成交或孤立成交,下游已成交表为空。只读对账差异0。切换没有下发测试委托。
|
||||
|
||||
握手补回的3条SIG_INVALID拒绝消息,对端产生时刻分别为15:46:48、15:47:18、15:47:48,早于本次握手,不能直接称为本次握手验签失败。
|
||||
|
||||
## 尚未恢复的消息确认链路
|
||||
|
||||
15:48:19起,已收消息出现序号缺口。15:49:51已收到了1441568,但连续确认仍停在1441545,缺少1441546、1441553、1441560、1441567。后续心跳正常,暂存消息持续增加。因此ONLINE不能作为完整健康判据。
|
||||
|
||||
为核实补发,15:50进行一次受控重连,不重置序号、不清通道数据。15:50:18补回了上述4条消息,均为SIG_INVALID协议拒绝,没有instruction_id。其对端产生时刻分别为15:48:18.582、15:48:48.638、15:49:18.732、15:49:48.788。确认进度随之推进,但随后又发生新缺口。15:50:47连续确认停在1441576,已收最高1441582,暂存5条。
|
||||
|
||||
这说明约每30秒产生的拒绝消息没有实时投递到当前连接,重连才补回;不是PMS查询到一份空仓快照后就能消除的账本差异。具体连接来源仍未核实。QMT侧需要排查98测试服务或其他客户端是否仍共用消息序列,以及这些拒绝消息写入补发日志后实时发往了哪条连接。这里只提出待核实的来源,没有擅自停其他实例或绕过签名验证。
|
||||
|
||||
15:52:26最终核验仍为ONLINE,没有被动重连,已收最高1441606,但确认停在1441576、暂存25条。认证持仓接口返回主观量化0只、微盘轮动0只;健康检查status=ok、db_ok=true。故当前限制明确在连续消息确认,而非页面、数据库或空仓账本。
|
||||
|
||||
## 运行状态与证据
|
||||
|
||||
保持182地址、PMS_QMT_WS_ENABLED=true和唯一连接。全局暂停买入、暂停执行均保持true,resync_flag=1保留,微盘轮动仍为observe,对账来源仍为ws_only。连接与账户读取通过,连续消息确认未判收,不能恢复自动交易或称整体已正常。
|
||||
|
||||
证据位于155的/home/factor/project/tradingSystem/backups/qmt-return-182-20261027,文件权限600。before.json记录切换前状态,replay-before.json记录缺口,replay-after.json记录补发消息及对端时间,final-check.json记录最终状态及认证持仓接口,ws-transition.log记录本次日志。对端msg_ts按epoch毫秒转换为北京时间,received_at是容器北京时间,二者未混用。
|
||||
|
||||
后续先确认连续确认进度随心跳推进、暂存缺口为0、没有新验签拒绝或被动断线,再核对新账户快照和成交归属。全部满足且完成对账留痕后才能清resync并处理清账暂停。此次没有修改页面或交易代码,因此没有重跑离线回归和布局验收。188未操作。
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
# QMT成交修正接入与发布
|
||||
|
||||
2026年11月5日,北京时间。本次承接用户提供的工作台成交修正协议。原成交号不变,新增修正编号,并配套带修正标记的委托累计回报。
|
||||
|
||||
## 目标和边界
|
||||
|
||||
PMS负责按原策略归属修正数量、现金和成本解释。QMT原成交、历次修正及配套回报均保留。修正不是一笔新成交,不重放原成交,不重复计费,不生成委托,不改变真实持仓或费用数据。
|
||||
|
||||
修正和配套回报均先收存,再由原成交回放任务配对处理。原成交先入账,修正随后核验。待配对的消息不能占满普通成交消费批次,也不能释放旧委托占用。相同修正编号、相同正文只执行一次;正文冲突必须保留并告警。
|
||||
|
||||
修正前值必须等于当前有效成交版本。身份同时核对成交号、子委托、券商委托号、证券、方向及父指令账本。北交所不在范围内。单条SQL只访问一张表,跨表核验在服务层进行。所有写入同账户锁、同事务完成。
|
||||
|
||||
批次投影先用原有效逐笔重演,确认能还原当前批次,再应用修正重演后续卖出分配。只有完整证据才自动改账。缺失原成交、无法唯一对应的旧批次、外部或对账补入的起点、除权差异和归档旧仓不猜测归属。新普通成交原子记录成交与批次的关联,减少今后历史匹配歧义。
|
||||
|
||||
现金仅按已核实的本金差额调整原策略,不跨策略认领、透支或划拨。费用保持原事实,未知不改成零。历史报表和历史划拨净值不因此被宣称已重新计算。
|
||||
|
||||
终态保持终态,终结委托剩余量保持零。数量变化为原父指令留下续单阻断,不自动补差;价格更正不产生新的交易授权。网格等另有内部档位状态,须核实并同步,无法证明一致时整笔挂起,不只改一半账。
|
||||
|
||||
## 验证计划
|
||||
|
||||
开发机通过独立内存和隔离数据库检查价格与数量更正、买卖分配、多次更正、重复及乱序、冲突、事务失败回滚、双策略隔离和终态不复活。协议签名向量仍须通过。候选镜像断网全量检查后,只更新155实际受影响的PMS服务。WS始终只保留一个连接,不复位序号、不忽略验签。
|
||||
|
||||
发布后只读核对真实配置、镜像、连续确认、待入账和资金数量对账。没有自然修正报文时,明确记录未做自然修正判收,不发送测试成交或伪造修正补验收。188真实PMS不操作。
|
||||
|
||||
## 当前现场
|
||||
|
||||
08:54至08:55只读核验155,尚无trade_correction或带amended的委托回报。连续确认推进22条,最近200条连续,无暂存缺口、待入账或孤儿。数量和现金一致;盘前一只持仓尚缺估值行情,现金核对正常。
|
||||
|
||||
当时web为watch-flow-67b0277,worker和beat为watch-bf5e3ed,唯一WS为execution-2b1c447,行情采集为limits-0b3c50e。各服务源码与其镜像提交一致。以上为发布前事实,不代表本次功能已上线。
|
||||
|
||||
后续开发、候选检查、实际发布和自然判收分别追加,不把隔离回放算成真实业务处理。
|
||||
|
||||
## 实现补充
|
||||
|
||||
配套回报必须已越过连续持久水位,才可改变账本;同一成交的前一次更正尚未完成时,后一次留待顺序处理。数量变化还需一分钟内、且晚于两条修正回报的新QMT持仓快照,核对双策略数量合计。暂缺配对、原成交或新快照只等待;身份、前值、金额、归属或已入账证据冲突则挂起并留审计。
|
||||
|
||||
修正期间保守阻止新增买入及受影响证券的新委托,普通成交仍正常入账。终态委托不复活,旧累计回报不能覆盖已核实的修正,修正前的资金快照不能释放新的占用。数量更正永久阻断原父指令自动续单;网格同步重建档位,数量改变时暂停并等待人工安排。旧网格任务和旧提议通过修正版本校验失效,不能覆盖新状态或继续发单。
|
||||
|
||||
旧仓已经归零、后来另起持仓轮次时,不自动把旧轮修正计入新仓。旧历史只在完整重演能精确还原现账、批次唯一对应时处理;证据达到读取上限、缺少费用本金凭据或其它活动策略无法重建时挂起。更正不是费用后补入口,含手续费成本不能直接填作成交价。
|
||||
|
||||
本次复用既有收件和文档表,无表结构迁移、不新增业务开关。受影响发布目标为155的web、worker与唯一WS;beat、行情采集、微盘监控及188不在本次重建范围。
|
||||
|
||||
## 回退边界
|
||||
|
||||
只回退本次三个目标服务,保留账本、收件、修正审计和队列。尚无已应用修正时,可以恢复备份的三个原镜像和私有覆盖。若已经应用数量更正,旧版本仍可能把FILLED当作原委托全量,不能直接恢复旧执行代码;须先停止新增执行,保留接收与账本事实,核对未结委托,再发布理解修正版本的兼容修复。不得用恢复数据库或删除修正记录来回退。
|
||||
|
||||
## 开发验证
|
||||
|
||||
开发机独立环境全量回归末行为ALL SUITES PASS,日志/private/tmp/pms-correction-evidence-20261105/full-local-tests.log。最后坏回执隔离补审使用对应专项复验,最终候选须重新完成全量,不混用旧代码指纹。页面文件未修改,原页面三道护栏随全量通过。新增检查使用内存凭据、隔离SQLite事务和交错线程;不连接真实服务。
|
||||
|
||||
最终专项共134例:批次投影36、传输与执行29、服务事务36、普通成交凭据与仓储13、网格版本与并发20,全部通过。已有回放回归另增加6例,核对等待、挂起、正常成交和日终摘要;该套18例通过。
|
||||
|
||||
## 实际发布与接续(09:36核验)
|
||||
|
||||
代码f756344082fb3e48d8ef2c896b27aed1768d83de已提交推送并直接核对远程。155候选pms:trade-correction-f756344完成断网、无业务配置、只读根目录全量回归,末行ALL SUITES PASS;镜像sha256:89edb06ec0f14605f708525e037f05e1ae0e9e90180825bb6a5428eea2c1d041,代码指纹97764c9aeff1。服务器日志/tmp/pms-trade-correction-test-f756344.log,本地副本/private/tmp/pms-correction-evidence-20261105/full-candidate-tests.log。
|
||||
|
||||
09:32:42仅重建pms-web、pms-worker和pms-ws。旧worker仅暂停自身celery消费,活动、预取和预约任务均0后重建;没有强杀模型任务。WS原进程结束后启动唯一新进程。重建使用原Compose项目和私有覆盖,只改三个镜像,不带依赖、不重新构建。备份backups/qmt-trade-correction-20261105-f756344保存原镜像、配置、在途核验和15个非目标容器基线;其余15个标识、镜像与启动时间完全不变。环境、挂载、原.env、采集.env.market-data及私有scripts/deploy.sh摘要保持。初次配置核对因未加载ws配置分组停止在备份前,补齐只读配置分组后通过,未引起额外重建。
|
||||
|
||||
09:33:46确认及接收均1639151,最近200条连续,无resync、待入账或孤儿,资金与持仓快照年龄0.5秒;数量和现金一致、估值就绪。业务参数、两项用户暂停false、改价、异步与微盘v3保持。09:36三个容器代码指纹相同,环境与挂载和发布前一致;页面健康、数据库、交易日历正常。新worker恢复celery消费,已经自然完成三轮回放、执行、撤单确认、依据刷新和相关任务,三个容器无Traceback。唯一WS容器和Python连接进程均为1。
|
||||
|
||||
修正报文及修正审计当前均0,所以只证明接入已部署、隔离回放通过及原链路恢复,尚无真实修正的自然判收。没有注入测试成交、修正或模型请求。beat、行情采集、微盘监控和188未操作。脱敏证据见[成交修正发布核验](evidence/pms_trade_correction_release_20261105.json)。
|
||||
|
||||
用户发布过程中新增“上游选股计划过期”修复任务。消费端直接GET确认11-03原始数据日,过期保护正确;该问题由独立上游任务继续定位,不能以本次QMT发布健康结论代替选股修复结果。
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
# QMT测试地址切换
|
||||
|
||||
用户指定155模拟PMS改连192.168.16.98,并随后确认端口仍为9443、路径仍为/pms,QMT侧已经完成清空。本次只改运行参数和现有连接进程的启停,没有修改交易业务代码、密钥或188实例。以下为2026-10-27北京时间,按容器时钟记录。
|
||||
|
||||
15:29:25经ParamStore把PMS_QMT_WS_URL从ws://192.168.18.182:9443/pms改成ws://192.168.16.98:9443/pms。初次握手成功,但快照仍有14只持仓、8100股,冻结资金88092元,并持续发生连接被替换和验签拒绝。为避免反复争用,15:33暂时关闭连接开关并停止唯一pms-ws,没有改空仓账本。
|
||||
|
||||
用户确认端口无误且QMT方才清空后,15:35:20重新启用PMS_QMT_WS_ENABLED,并启动原pms-ws容器。其余三个PMS进程持续运行。没有重建镜像,没有重置序号,没有跳过签名验证,没有下测试委托。
|
||||
|
||||
## 复测结果
|
||||
|
||||
真机见过:155到98的9443端口连通,现有密钥可以完成握手并取得经过验签的持仓和资金快照。15:35:48的新快照为持仓0、账户市值0、总资产200万元、可用资金200万元、冻结资金0。PMS持仓0,未完成委托0,待处理成交和孤立成交均为0。下游已成交表也已经清空。只读全量对账返回severity=OK、差异0,没有执行补仓或修账。
|
||||
|
||||
未判收:连接持续稳定性。复测后仍多次收到关闭原因“replaced by new connection”。15:35:47、15:36:17、15:36:47有SIG_INVALID协议拒绝;本侧停止连接期间15:34:17、15:34:47、15:35:17也存在同类拒绝,随后由补发读取。这些是上行拒绝记录中的对端消息时间,按epoch毫秒转换为北京时间,并非本端落库时间。
|
||||
|
||||
上述周期性行为表明存在其他连接请求,具体来源IP尚未核实。155的docker top确认仅一个pms-ws Python进程,仓库运行代码也只有runner建立WebSocket。需要QMT侧从连接日志定位每30秒接入但验签失败的来源,并检查是否在验证新连接身份之前就替换了现有连接。后者是待核实的实现推断,没有据此改PMS或绕过认证。
|
||||
|
||||
15:39:12通道状态为OFFLINE,最后成功快照约105秒前,pms-ws仍按原退避规则重连。用户指定地址保持不变,连接开关为true。不能将偶尔ONLINE描述为已稳定接通。
|
||||
|
||||
## 当前保护与接续
|
||||
|
||||
全局暂停买入、暂停执行保持true,微盘轮动仍为observe,对账来源保持ws_only。历史补发曾触发resync_flag=1,尚未清除;虽然空仓对账已通过,仍等待连接稳定后复核。原清账回执的净值1.0000及空仓基线继续有效,没有认领首次看到的14只旧持仓。
|
||||
|
||||
后续不再询问用户测试端口。先排除重复连接,再确认新快照在60秒内、持仓及冻结均为0、无在途和待处理成交、序号无倒挂或缺口、旧测试成交不会回流。完成对账并留痕后才能清除resync标记。恢复本次清账设置的暂停前,还须确认用户没有新的暂停指令。微盘自动执行仍受既定观察和纸面验收约束。
|
||||
|
||||
备份与证据位于155的/home/factor/project/tradingSystem/backups/qmt-endpoint-98-20261027,文件权限600。before.json保留切换前状态,verification.json保留首次14只持仓的结果,retest.json保留清空后的复测,ws-transition.log保留连接变化日志。操作已记录pms_op_log。已有每日16:10复核任务应以本记录作为最新QMT接续,不再使用旧182地址。
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
# QMT限价等待与微盘分位展示
|
||||
|
||||
## 用户要求和实施范围
|
||||
|
||||
用户要求PMS给出价格和数量,把价格是否满足成交条件的监控交给QMT,同时恢复蓝、金、灰柱图配色,微盘只展示历史百分位,策略详情另开页面。本次范围为155模拟PMS。188真实实例不操作。
|
||||
|
||||
新增实例参数PMS_EXEC_QMT_PRICE_MONITOR,默认false。155启用后,已经形成的主观量化指令不再等待现价进入执行区间,也不再被盘中涨幅、距五日均线、开盘避让和封板价格判断留在PMS。PMS仍读取决策系统给出的区间,买入限价取上沿,卖出限价取下沿,通过既有place_order协议交给QMT。网格、跟踪止盈的策略触发和选股规则不变,已触发指令沿用策略定价。微盘日频执行原本就提交限价,不叠加主观量化区间。
|
||||
|
||||
这是一侧限价,不是上下界条件单。买入允许按限价或更低成交,卖出允许按限价或更高成交。现价低于买入区间下沿时也不再由PMS拦截。普通指令尾盘不再把限价改成追价完成;指定价格未成交可以继续等待或到期撤单。既有每日配额、分片、10个交易分钟有效期和次轮按剩余数量处理保留。600股多日计划不因此变为一次提交600股。
|
||||
|
||||
用户暂停、黑名单、总规模、仓位、资金保留、数量单位、可卖量、策略归属、相反方向在途及数据有效性检查保留。买入预算校验取现价与限价较大者,共用出口仍按委托金额保留资金。价格区间缺失、数据异常或服务不可用时等待补齐,不以现价追单。离场、回避和参考位漂移属于计划或数据问题,仍阻止买入。旧缓存没有今日离场字段时重新咨询。
|
||||
|
||||
## 展示调整
|
||||
|
||||
微盘活跃度是原始成交活跃程度,历史百分位是它在自身历史分布中的位置。入退场关注历史低位和高位,悬浮框只保留历史百分位柱图和当前8.33%的读数,移除原始活跃度重复图。原始值和冻结信号仍保留在数据及详情中,计算口径不变。成长主线瓦解仍作为另一个入场条件,简短显示触发状态。
|
||||
|
||||
股汇与微盘柱图统一蓝、金、灰:低位蓝色,高位金色,其余灰色;缺数虚框。微盘低于5%入场,高于95%退出。悬浮框的策略详情和顶栏微盘标签均使用独立标签页,设置noopener和noreferrer。
|
||||
|
||||
## 验证与部署
|
||||
|
||||
代码提交02837fa。新增第50批14项隔离测试,覆盖区间外限价提交、买卖方向、缺数和服务失败、非价格否决、缓存升级、分日配额、防重、暂停和资金限制、尾盘不追价及试算隔离。开发机全量断网回归ALL SUITES PASS,页面三道护栏通过。155干净归档候选镜像断网全量回归ALL SUITES PASS。
|
||||
|
||||
浏览器检查1440、1280、390宽度,确认只剩60根历史分位柱,蓝金阈值变色,0值和缺数不混淆。实际点击策略详情产生新标签页,关闭详情后主页面仍在;检查无脚本错误和写请求。
|
||||
|
||||
北京时间11:20:08完成部署,web和worker更新为pms:micro30-02837fa。beat短暂停止后恢复原容器,镜像仍为f1424f3;唯一pms-ws的容器编号与启动时间均未改变,仍为f1424f3。监控容器未更新。有效环境不变,两个用户暂停保持false。业务开关经ParamStore开启。首次参数写入因updated_by超出字段长度失败,自动回退旧镜像,改短运维标识后第二次部署通过;该失败没有生成委托。
|
||||
|
||||
部署前只读试算使用实际指令,得到盛弘200股、30.02元限价,无错误或规则拒绝。恢复worker后自然调度于11:20:16发送INS_20261028_300693SZ_OPEN_47b78b_D01,QMT回执序号1456511,accepted=true、duplicate=false,受理号DESK-bffb6ade07。11:20:29出口状态为ACCEPTED、成交0,父指令DISPATCHED,页面显示委托待成交。600股为总计划量,本日首笔200股来自原三日配额。没有人为运行非试算tick,没有测试委托或重复补单。
|
||||
|
||||
真机见过:QMT连接ONLINE,心跳年龄1.2秒,last_seq与acked_seq同为1456515,待入账0,resync=false,本连接拒绝和重连计数均为0。页面和数据库健康。盛弘是否成交仍以实际回报为准,不把受理当成交。
|
||||
|
||||
证据位置:155的backups/qmt-price-20261028-verified/receipt.json、execution-preview.json,以及/home/factor/project/pms-qmt-price-20261028/tests-02837fa.log。本机实际响应和浏览器证据在/tmp/pms-qmt-price-20261028。浏览器使用实际部署HTML和实际响应在隔离环境重放,真实登录会话的人工操作未判收。
|
||||
|
||||
验证命令在开发机执行,预期全量输出ALL SUITES PASS,包含三道页面护栏,实际通过:
|
||||
|
||||
```bash
|
||||
/tmp/pms-micro30-venv/bin/python scripts/run_tests.py
|
||||
```
|
||||
|
||||
镜像验证在155执行,预期同样输出ALL SUITES PASS,实际通过:
|
||||
|
||||
```bash
|
||||
docker run --rm --network none --cpus 1 --memory 512m --read-only --tmpfs /tmp:rw,size=128m pms:micro30-02837fa python scripts/run_tests.py
|
||||
```
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
# QMT验签拒绝即时复核
|
||||
|
||||
用户说明此前数分钟断线由QMT系统重启造成,本次只核实现在是否仍产生SIG_INVALID,不把重启断线当作其他连接干扰的证据。
|
||||
|
||||
**结论:截至2026-10-27北京时间16:29的复核,QMT仍在约每30秒产生SIG_INVALID。** 本次补回7条近期拒绝,报文产生时间从16:25:52.428至16:28:52.694,均晚于之前的重启中断。不是把16:08补发的旧拒绝重复当成新故障。
|
||||
|
||||
| seq | 对端报文产生时间,北京时间 | code |
|
||||
| --- | --- | --- |
|
||||
| 1442045 | 16:25:52.428 | SIG_INVALID |
|
||||
| 1442052 | 16:26:22.473 | SIG_INVALID |
|
||||
| 1442059 | 16:26:52.521 | SIG_INVALID |
|
||||
| 1442066 | 16:27:22.561 | SIG_INVALID |
|
||||
| 1442073 | 16:27:52.607 | SIG_INVALID |
|
||||
| 1442080 | 16:28:22.661 | SIG_INVALID |
|
||||
| 1442087 | 16:28:52.694 | SIG_INVALID |
|
||||
|
||||
七条均为instruction_id=null、reason=signature verification failed、retryable=false。报文时间来自msg_ts的epoch毫秒转换;PMS实际收到补发的时间是16:28:58至16:28:59,不能混用。这些近期缺失序号已由补发确认其类型,不再只是根据序号缺口推测。
|
||||
|
||||
16:28:38只读检查确认PMS仍停在1442044,最高已收1442083、暂存33条;最近收到的拒绝仍是16:08:50那条。因为拒绝未实时投递,仅查当前PMS日志不能回答是否仍在产生。确认交易暂停、无在途、无待处理或孤立成交后,只对原有唯一pms-ws做一次受控重连,保留原水位,从1442045起补发。没有打开第二条连接、重置序号、改变密钥或绕过验签,没有发测试委托。
|
||||
|
||||
16:29:18连接已恢复,补发后水位到1442095,resync仍为1,两项全局交易暂停保持true。补发后暂存短时归零只说明这批补发完成,不视为周期性故障已消失。
|
||||
|
||||
155真机证据保存在/home/factor/project/tradingSystem/backups/qmt-current-reject-20261027,before.json、after.json及ws.log权限600。QMT研发可优先按最新seq=1442087、msg_id=m-20261027-ba36fcf9、ts=1793089732694反查触发来源和失败请求。具体源IP与被拒原始帧仍未取得。所需代码与日志字段沿用之前联调材料,无需交换私钥。
|
||||
|
||||
本次仅诊断与原连接停启,没有业务代码或参数改动,未重建镜像,不需要业务回归或页面验收。开发机git diff --check通过。验签故障恢复仍未判收。
|
||||
|
|
@ -158,7 +158,16 @@ def strategies(include_archived: bool = False):
|
|||
|
||||
@app.get("/api/positions")
|
||||
def positions():
|
||||
rows = [{**p, "book_id": "original"} for p in POSITIONS]
|
||||
held = [p for p in rows if p["total_qty"] > 0]
|
||||
return {"ok": True, "positions": POSITIONS, "stock_params": {},
|
||||
"strategy_groups": [
|
||||
{"book_id": "original", "name": "主观量化", "positions": rows, "held": held,
|
||||
"ready": True, "price_missing": [], "totals": {"names_count": len(held),
|
||||
"market_value": sum(p["market_value"] for p in held),
|
||||
"pnl": sum(p["market_value"] - p["avg_cost"] * p["total_qty"] for p in held)}},
|
||||
{"book_id": "micro30", "name": "微盘轮动", "positions": [], "held": [],
|
||||
"ready": True, "price_missing": [], "totals": {"names_count": 0, "market_value": 0, "pnl": 0}}],
|
||||
"summary": {"total_scale": 2000000.0, "market_value": sum(p["market_value"] for p in POSITIONS)}}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,180 @@
|
|||
{
|
||||
"verified_at": "2026-11-04T11:16:31.967049+08:00",
|
||||
"scope": "155模拟PMS与选股桥,188仅三个Bionic服务",
|
||||
"code_commits": {
|
||||
"pms": "bf5e3edd91b98c3812e538a7e13b68ef2ecf29bb",
|
||||
"bridge": "e5696ee476d6815b4d0692b498ed4edb6cdbbc20",
|
||||
"bionic": "963196a0a228a0b7d99d09e5ad2b67e4cd773350"
|
||||
},
|
||||
"isolated_validation": {
|
||||
"pms_all_suites_pass": true,
|
||||
"bridge_suites_pass": 35,
|
||||
"bionic_suites_pass": 16,
|
||||
"browser_widths": [
|
||||
1440,
|
||||
390
|
||||
],
|
||||
"actual_response_replay": true,
|
||||
"live_login_acceptance": false,
|
||||
"browser_errors": 0,
|
||||
"browser_writes": 0,
|
||||
"browser_external_requests": 0
|
||||
},
|
||||
"qmt": {
|
||||
"ack_equals_persisted_watermark": true,
|
||||
"watermark_window_contiguous": true,
|
||||
"watermark_window_expected": 200,
|
||||
"pending_ledger_count": 0,
|
||||
"orphan_count": 0,
|
||||
"resync_flag": false
|
||||
},
|
||||
"reconciliation": {
|
||||
"accounting_ready": true,
|
||||
"cash_difference_known": true,
|
||||
"cash_matches_existing_settlement_tolerance": true,
|
||||
"cash_ready": true,
|
||||
"fix_count": 0,
|
||||
"quantity_diff_count": 0,
|
||||
"quantity_error_count": 0,
|
||||
"quantity_ok": true,
|
||||
"quantity_source": "ws",
|
||||
"valuation_missing_count": 0,
|
||||
"valuation_ready": true
|
||||
},
|
||||
"funds_age_sec": 3.1,
|
||||
"manual_watch": {
|
||||
"active_count": 6,
|
||||
"active_count_matches_expected": true,
|
||||
"coverage_capability": true,
|
||||
"coverage_note_count": 0,
|
||||
"daily": {
|
||||
"complete_with_display_fields_count": 1,
|
||||
"expired_count": 0,
|
||||
"states": {
|
||||
"COMPLETE": 1,
|
||||
"PENDING": 5
|
||||
}
|
||||
},
|
||||
"expected_active_count": 6,
|
||||
"history_date_present_count": 6,
|
||||
"history_dropped_count": 5,
|
||||
"intraday": {
|
||||
"complete_with_display_fields_count": 1,
|
||||
"expired_count": 0,
|
||||
"states": {
|
||||
"COMPLETE": 1,
|
||||
"PENDING": 5
|
||||
}
|
||||
},
|
||||
"ok": true,
|
||||
"registry_status": {
|
||||
"evaluated": 6
|
||||
},
|
||||
"review_error_count": 5,
|
||||
"review_status_active": {
|
||||
"completed": 1,
|
||||
"queued": 5
|
||||
},
|
||||
"row_count": 6
|
||||
},
|
||||
"upstream_review_queue": {
|
||||
"total": 66,
|
||||
"new_accepted_still_pending": 5,
|
||||
"source": "实际受理任务的只读Redis状态核对",
|
||||
"modified": false
|
||||
},
|
||||
"plan": {
|
||||
"first_policy_revision": 23,
|
||||
"current_revision": 24,
|
||||
"code_version": "e5696ee",
|
||||
"admission": {
|
||||
"accum_confirm_required": false,
|
||||
"accum_max_age": 30,
|
||||
"admission_rule": "accum-reference-v2-20261104",
|
||||
"require_started": false,
|
||||
"start_pct": 3.0
|
||||
},
|
||||
"quality_sort_unchanged": true,
|
||||
"candidate_before": 6,
|
||||
"candidate_after_policy": 21,
|
||||
"watch_before": 11,
|
||||
"watch_after_policy": 27,
|
||||
"historical_mornings_count": 15,
|
||||
"historical_mornings_unchanged": true,
|
||||
"manual_targets_present": 6
|
||||
},
|
||||
"natural_coverage": {
|
||||
"present": true,
|
||||
"redis_ttl_ms": 604766142,
|
||||
"updated_at": "2026-11-04T11:15:16.488261+08:00",
|
||||
"stored_rows_count": 1,
|
||||
"valid_identity_rows": 1,
|
||||
"mismatched_identity_rows": 0,
|
||||
"inactive_or_absent_rows_count": 0,
|
||||
"daily": {
|
||||
"states_for_valid_current_source": {
|
||||
"COMPLETE": 1
|
||||
},
|
||||
"analysis_date_counts": {
|
||||
"2026-11-04": 1
|
||||
},
|
||||
"data_date_counts": {
|
||||
"2026-11-03": 1
|
||||
},
|
||||
"complete_receipt_count": 1,
|
||||
"reused_true_count": 0,
|
||||
"new_model_true_count": 1,
|
||||
"overdue_waiting_count": 0,
|
||||
"time_ranges": {
|
||||
"queued_at": {
|
||||
"min": "2026-11-04T11:12:00.038249+08:00",
|
||||
"max": "2026-11-04T11:12:00.038249+08:00"
|
||||
},
|
||||
"started_at": {
|
||||
"min": "2026-11-04T11:12:00.052082+08:00",
|
||||
"max": "2026-11-04T11:12:00.052082+08:00"
|
||||
},
|
||||
"completed_at": {
|
||||
"min": "2026-11-04T11:13:38.327320+08:00",
|
||||
"max": "2026-11-04T11:13:38.327320+08:00"
|
||||
}
|
||||
}
|
||||
},
|
||||
"intraday": {
|
||||
"states_for_valid_current_source": {
|
||||
"COMPLETE": 1
|
||||
},
|
||||
"analysis_date_counts": {
|
||||
"2026-11-04": 1
|
||||
},
|
||||
"data_date_counts": {
|
||||
"2026-11-04": 1
|
||||
},
|
||||
"complete_receipt_count": 1,
|
||||
"reused_true_count": 0,
|
||||
"new_model_true_count": 1,
|
||||
"overdue_waiting_count": 0,
|
||||
"time_ranges": {
|
||||
"queued_at": {
|
||||
"min": "2026-11-04T11:15:00.107959+08:00",
|
||||
"max": "2026-11-04T11:15:00.107959+08:00"
|
||||
},
|
||||
"started_at": {
|
||||
"min": "2026-11-04T11:15:00.124133+08:00",
|
||||
"max": "2026-11-04T11:15:00.124133+08:00"
|
||||
},
|
||||
"completed_at": {
|
||||
"min": "2026-11-04T11:15:16.487044+08:00",
|
||||
"max": "2026-11-04T11:15:16.487044+08:00"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"remaining": "5条买方评析及其后续每日和盘中研究未完成;未新建长期观察",
|
||||
"final_container_check": {
|
||||
"155_other_unchanged": 14,
|
||||
"188_other_unchanged": 35,
|
||||
"other_changed": [],
|
||||
"pms_web_health": "healthy"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
{
|
||||
"deployment": {
|
||||
"started_at_utc": "2026-10-28T04:47:26.755838+00:00",
|
||||
"finished_at_utc": "2026-10-28T04:48:30.613266+00:00",
|
||||
"image": "pms:micro50-9e14f92",
|
||||
"monitor_image": "bionic-micro30:3e2a584",
|
||||
"new_rule": "micro50-v2-20261028",
|
||||
"parameters": {
|
||||
"entry_percentile": 0.08,
|
||||
"exit_percentile": 0.85,
|
||||
"basket_size": 50
|
||||
},
|
||||
"ws_unchanged": true,
|
||||
"beat_same_container": true,
|
||||
"environment_unchanged": true,
|
||||
"old_frozen_unchanged": true,
|
||||
"old_frozen_sha256": "1adf689cfc046bd4e0f3bb4f350ff78e4c5339ccd94a25bab64f7c19cbbf9735",
|
||||
"new_snapshot": "79ecf854796fd2b5c5058cdf31996a4b4ddf488ac3e5e4388c0515892ebfba3f",
|
||||
"frozen": false,
|
||||
"members": 50,
|
||||
"history_rows": 60,
|
||||
"params": {
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false
|
||||
},
|
||||
"health": {
|
||||
"status": "ok",
|
||||
"version": "0.2.0-dev",
|
||||
"service": "pms-web",
|
||||
"now": "2026-10-28 12:48:20",
|
||||
"trade_day": true,
|
||||
"calendar_degraded": false,
|
||||
"db_ok": true
|
||||
},
|
||||
"validation": {
|
||||
"display_errors": [],
|
||||
"execution_errors": [
|
||||
"执行快照尚未冻结"
|
||||
]
|
||||
}
|
||||
},
|
||||
"first_check": {
|
||||
"at": "2026-10-28T12:48:47.041008",
|
||||
"seq": 1457931
|
||||
},
|
||||
"final_check": {
|
||||
"at": "2026-10-28T12:49:37.210107",
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": -0.3,
|
||||
"last_seq": 1457943,
|
||||
"acked_seq": 1457943,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 1,
|
||||
"ACCEPTED": 1,
|
||||
"EXPIRED": 5,
|
||||
"FILLED": 357,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-10-28 09:28:10",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 3186,
|
||||
"tx": 5854,
|
||||
"trades": 1,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "12:49:35",
|
||||
"last_tx_at": "12:49:35",
|
||||
"hs_server_seq": 1454756,
|
||||
"hs_last_seq": 1454756,
|
||||
"snap_positions_at": "12:49:10",
|
||||
"snap_positions_n": 1,
|
||||
"snap_funds_at": "12:49:10",
|
||||
"seq_hwm": 1457943,
|
||||
"peer_skew_ms": -51,
|
||||
"peer_skew_min": -83,
|
||||
"peer_skew_max": 1876,
|
||||
"position_update_at": "09:59:40",
|
||||
"position_update_n": 1,
|
||||
"funds_update_at": "09:59:40",
|
||||
"funds_update_n": 1
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1997108.0,
|
||||
"total_asset": 2000020.0,
|
||||
"account_market_value": 2912.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 26.7,
|
||||
"why": ""
|
||||
},
|
||||
"reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"micro_inflight": 0
|
||||
},
|
||||
"snapshot": {
|
||||
"rule": "micro50-v2-20261028",
|
||||
"parameters": {
|
||||
"entry_percentile": 0.08,
|
||||
"exit_percentile": 0.85,
|
||||
"basket_size": 50
|
||||
},
|
||||
"data_date": "2026-10-27",
|
||||
"effective_date": "2026-10-28",
|
||||
"frozen": false,
|
||||
"signal": {
|
||||
"date": "2026-10-27",
|
||||
"ready": true,
|
||||
"growth_break": false,
|
||||
"low": false,
|
||||
"high": false,
|
||||
"activity": 0.7266321909882428,
|
||||
"activity_percentile": 0.08333333333333333,
|
||||
"low_threshold": 0.7233829566510594,
|
||||
"high_threshold": 1.58469612793713,
|
||||
"growth_recent_hot": false,
|
||||
"growth_price_damage": -0.2505291432159401,
|
||||
"group_percentiles": {
|
||||
"large": 0.09788359788359788,
|
||||
"growth": 0.08994708994708994,
|
||||
"small": 0.08333333333333333
|
||||
}
|
||||
},
|
||||
"members": 50,
|
||||
"snapshot_version": "79ecf854796fd2b5c5058cdf31996a4b4ddf488ac3e5e4388c0515892ebfba3f"
|
||||
},
|
||||
"browser": {
|
||||
"live": true,
|
||||
"viewports": [
|
||||
1440,
|
||||
1280,
|
||||
390
|
||||
],
|
||||
"target_rows": 50,
|
||||
"thresholds": [
|
||||
8,
|
||||
85
|
||||
],
|
||||
"capacity_denominator": 50,
|
||||
"new_tab": true,
|
||||
"unfrozen_not_execution_signal": true,
|
||||
"errors": [],
|
||||
"writes": []
|
||||
},
|
||||
"historical_signal_check": {
|
||||
"rows": 678,
|
||||
"growth_definition_unchanged": true
|
||||
},
|
||||
"tests": {
|
||||
"local": "ALL SUITES PASS",
|
||||
"155_image": "ALL SUITES PASS",
|
||||
"rotation_cases": 55,
|
||||
"monitor_cases": 12
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,296 @@
|
|||
{
|
||||
"scope": "155模拟PMS,只读复核",
|
||||
"at_beijing": "2026-10-28T16:12:22.292107",
|
||||
"images": {
|
||||
"pms-web": "pms:micro50-9e14f92",
|
||||
"pms-worker": "pms:micro50-9e14f92",
|
||||
"pms-beat": "pms:micro30-f1424f3",
|
||||
"pms-ws": "pms:micro30-f1424f3",
|
||||
"bionic-micro30-monitor": "bionic-micro30:3e2a584"
|
||||
},
|
||||
"source_mount_app": false,
|
||||
"params": {
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_QUERY_INTERVAL_SEC": 30,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true
|
||||
},
|
||||
"channel_checks": [
|
||||
{
|
||||
"at_beijing": "2026-10-28T16:10:04.405739",
|
||||
"last_seq": 1461183,
|
||||
"acked_seq": 1461183,
|
||||
"seq_hwm": 1461183,
|
||||
"resync": false,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"tail_min": 1461024,
|
||||
"tail_max": 1461183,
|
||||
"tail_count": 160,
|
||||
"tail_missing": []
|
||||
},
|
||||
{
|
||||
"at_beijing": "2026-10-28T16:12:22.292107",
|
||||
"last_seq": 1461221,
|
||||
"acked_seq": 1461221,
|
||||
"seq_hwm": 1461221,
|
||||
"resync": false,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"tail_min": 1461062,
|
||||
"tail_max": 1461221,
|
||||
"tail_count": 160,
|
||||
"tail_missing": []
|
||||
}
|
||||
],
|
||||
"new_rejects_since_124937": 0,
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1997108.0,
|
||||
"total_asset": 2000020.0,
|
||||
"account_market_value": 2912.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 10.8,
|
||||
"why": ""
|
||||
},
|
||||
"positions": {
|
||||
"original": [
|
||||
{
|
||||
"ts_code": "601126.SH",
|
||||
"status": "HOLDING",
|
||||
"total_qty": 100,
|
||||
"book_id": "original"
|
||||
}
|
||||
],
|
||||
"micro30": []
|
||||
},
|
||||
"orders": [
|
||||
{
|
||||
"book": "original",
|
||||
"parent": "INS_20261028_300693SZ_OPEN_47b78b",
|
||||
"code": "300693.SZ",
|
||||
"plan_qty": 600,
|
||||
"parent_status": "DISPATCHED",
|
||||
"child_states": {
|
||||
"EXPIRED": 13,
|
||||
"ABORTED": 1
|
||||
},
|
||||
"child_total_filled": 0,
|
||||
"active_children": 0
|
||||
}
|
||||
],
|
||||
"reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"monitor_health": {
|
||||
"state": "degraded",
|
||||
"last_success": "2026-10-28T12:48:06.203313+08:00",
|
||||
"error": "ValueError"
|
||||
},
|
||||
"monitor_snapshots": {
|
||||
"2026-10-28": {
|
||||
"status_code": 200,
|
||||
"data_date": "2026-10-27",
|
||||
"rule_version": "micro50-v2-20261028",
|
||||
"snapshot_version": "79ecf854796fd2b5c5058cdf31996a4b4ddf488ac3e5e4388c0515892ebfba3f",
|
||||
"frozen": false,
|
||||
"signal": {
|
||||
"date": "2026-10-27",
|
||||
"ready": true,
|
||||
"growth_break": false,
|
||||
"low": false,
|
||||
"high": false,
|
||||
"activity": 0.7266321909882428,
|
||||
"activity_percentile": 0.08333333333333333,
|
||||
"low_threshold": 0.7233829566510594,
|
||||
"high_threshold": 1.58469612793713,
|
||||
"growth_recent_hot": false,
|
||||
"growth_price_damage": -0.2505291432159401,
|
||||
"group_percentiles": {
|
||||
"large": 0.09788359788359788,
|
||||
"growth": 0.08994708994708994,
|
||||
"small": 0.08333333333333333
|
||||
}
|
||||
},
|
||||
"signal_ready": true,
|
||||
"basket_ready": true,
|
||||
"members": 50,
|
||||
"display_errors": [],
|
||||
"execution_errors": [
|
||||
"执行快照尚未冻结"
|
||||
],
|
||||
"error": null
|
||||
},
|
||||
"2026-10-29": {
|
||||
"status_code": 404,
|
||||
"data_date": null,
|
||||
"rule_version": null,
|
||||
"snapshot_version": null,
|
||||
"frozen": null,
|
||||
"signal": null,
|
||||
"signal_ready": null,
|
||||
"basket_ready": null,
|
||||
"members": 0,
|
||||
"display_errors": null,
|
||||
"execution_errors": null,
|
||||
"error": "指定执行日没有可用快照"
|
||||
}
|
||||
},
|
||||
"source_coverage": {
|
||||
"at_beijing": "2026-10-28T16:12:20.370142",
|
||||
"indices": {
|
||||
"large": [
|
||||
{
|
||||
"symbol": "000300.SH",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 383125565
|
||||
},
|
||||
{
|
||||
"symbol": "000300.SH",
|
||||
"timestamp": "2026-10-26",
|
||||
"amount": 456246629
|
||||
}
|
||||
],
|
||||
"growth": [
|
||||
{
|
||||
"symbol": "399006.SZ",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 149752373
|
||||
},
|
||||
{
|
||||
"symbol": "399006.SZ",
|
||||
"timestamp": "2026-10-26",
|
||||
"amount": 174604167
|
||||
}
|
||||
],
|
||||
"small": [
|
||||
{
|
||||
"symbol": "932000.CSI",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 328426717
|
||||
},
|
||||
{
|
||||
"symbol": "932000.CSI",
|
||||
"timestamp": "2026-10-26",
|
||||
"amount": 332005798
|
||||
}
|
||||
],
|
||||
"calendar": [
|
||||
{
|
||||
"symbol": "000001.SH",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 672414398
|
||||
},
|
||||
{
|
||||
"symbol": "000001.SH",
|
||||
"timestamp": "2026-10-26",
|
||||
"amount": 746528026
|
||||
}
|
||||
]
|
||||
},
|
||||
"stocks": {
|
||||
"bars": [
|
||||
{
|
||||
"trade_date": "2026-10-27",
|
||||
"n": 5570
|
||||
}
|
||||
],
|
||||
"risk": [
|
||||
{
|
||||
"trade_date": "2026-10-27",
|
||||
"n": 197
|
||||
}
|
||||
],
|
||||
"limits": [
|
||||
{
|
||||
"trade_date": "2026-10-27",
|
||||
"n": 5654
|
||||
}
|
||||
],
|
||||
"basic": [
|
||||
{
|
||||
"trade_date": "2026-10-27",
|
||||
"n": 5570
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"daily_record": [
|
||||
{
|
||||
"id": "live_day:2026-10-28",
|
||||
"value": {
|
||||
"cash_difference": 0.0,
|
||||
"date": "2026-10-28",
|
||||
"healthy": true,
|
||||
"metrics": {
|
||||
"account": {
|
||||
"cash": 1997108.0,
|
||||
"equity": 2000020.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 2912.0,
|
||||
"profit": 20.0
|
||||
},
|
||||
"micro30": {
|
||||
"cash": 0.0,
|
||||
"equity": 0.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 0.0,
|
||||
"nav": null,
|
||||
"net_capital": 0.0,
|
||||
"profit": 0.0
|
||||
},
|
||||
"original": {
|
||||
"cash": 1997108.0,
|
||||
"equity": 2000020.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 2912.0,
|
||||
"nav": 1.00001,
|
||||
"net_capital": 2000000.0,
|
||||
"profit": 20.0
|
||||
}
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"book_id": "original",
|
||||
"code": "601126.SH",
|
||||
"cost": 2892.0,
|
||||
"market_value": 2912.0,
|
||||
"price": 29.12,
|
||||
"qty": 100
|
||||
}
|
||||
],
|
||||
"ready": true,
|
||||
"rule_version": "micro50-v2-20261028",
|
||||
"started_at": "2026-10-28T09:29:06.569619",
|
||||
"transfer_count": 0
|
||||
},
|
||||
"updated_at": "2026-10-28 15:20:00"
|
||||
}
|
||||
],
|
||||
"actions": {
|
||||
"restart": false,
|
||||
"param_write": false,
|
||||
"trade_write": false,
|
||||
"source_write": false
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,536 @@
|
|||
{
|
||||
"scope": "155模拟PMS,只读复核",
|
||||
"at_beijing": "2026-10-29T16:18:38.144989",
|
||||
"images": {
|
||||
"pms-web": "pms:micro50-9e14f92",
|
||||
"pms-worker": "pms:micro50-9e14f92",
|
||||
"pms-beat": "pms:micro30-f1424f3",
|
||||
"pms-ws": "pms:micro30-f1424f3",
|
||||
"bionic-micro30-monitor": "bionic-micro30:3e2a584"
|
||||
},
|
||||
"source_mount_app": false,
|
||||
"table_prefix": "",
|
||||
"params": {
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_QUERY_INTERVAL_SEC": 30,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true
|
||||
},
|
||||
"channel_checks": [
|
||||
{
|
||||
"at_beijing": "2026-10-29T16:16:53.945199",
|
||||
"last_seq": 1484434,
|
||||
"acked_seq": 1484434,
|
||||
"resync_required": false,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"connected_at": "2026-10-29 11:54:04",
|
||||
"seq_hwm": 1484434,
|
||||
"rejects": 0,
|
||||
"reconnects": 3,
|
||||
"dropped": 0,
|
||||
"tail_min": 1484275,
|
||||
"tail_max": 1484434,
|
||||
"tail_count": 160,
|
||||
"tail_missing": []
|
||||
},
|
||||
{
|
||||
"at_beijing": "2026-10-29T16:18:38.144989",
|
||||
"last_seq": 1484463,
|
||||
"acked_seq": 1484463,
|
||||
"resync_required": false,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"connected_at": "2026-10-29 11:54:04",
|
||||
"seq_hwm": 1484463,
|
||||
"rejects": 0,
|
||||
"reconnects": 3,
|
||||
"dropped": 0,
|
||||
"tail_min": 1484304,
|
||||
"tail_max": 1484463,
|
||||
"tail_count": 160,
|
||||
"tail_missing": []
|
||||
}
|
||||
],
|
||||
"new_rejects_since": "2026-10-28 16:12:22",
|
||||
"new_reject_count": 0,
|
||||
"disconnect": {
|
||||
"from": "2026-10-29 11:53:36",
|
||||
"recovered": "2026-10-29 11:54:04",
|
||||
"duration_seconds": 28,
|
||||
"first_error": "ConnectionClosedError: no close frame received or sent",
|
||||
"subsequent_handshake_timeouts": 2,
|
||||
"root_cause_verified": false,
|
||||
"surrounding_sequence": [
|
||||
{
|
||||
"seq": 1480160,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:52:56",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480161,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:01",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480162,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:06",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480163,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:11",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480164,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:16",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480165,
|
||||
"msg_type": "snapshot",
|
||||
"received_at": "2026-10-29 11:53:19",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480166,
|
||||
"msg_type": "snapshot",
|
||||
"received_at": "2026-10-29 11:53:19",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480167,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:21",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480168,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:26",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480169,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:31",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480170,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:53:36",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480171,
|
||||
"msg_type": "hello_ack",
|
||||
"received_at": "2026-10-29 11:54:04",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480172,
|
||||
"msg_type": "snapshot",
|
||||
"received_at": "2026-10-29 11:54:04",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480173,
|
||||
"msg_type": "snapshot",
|
||||
"received_at": "2026-10-29 11:54:04",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480174,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:09",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480175,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:14",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480176,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:19",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480177,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:24",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480178,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:29",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480179,
|
||||
"msg_type": "pong",
|
||||
"received_at": "2026-10-29 11:54:34",
|
||||
"processed": 2
|
||||
},
|
||||
{
|
||||
"seq": 1480180,
|
||||
"msg_type": "snapshot",
|
||||
"received_at": "2026-10-29 11:54:34",
|
||||
"processed": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1923441.0,
|
||||
"total_asset": 1999581.0,
|
||||
"account_market_value": 76140.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 5.0,
|
||||
"why": ""
|
||||
},
|
||||
"positions": {
|
||||
"original": [
|
||||
{
|
||||
"ts_code": "601126.SH",
|
||||
"status": "HOLDING",
|
||||
"total_qty": 2700,
|
||||
"book_id": "original"
|
||||
}
|
||||
],
|
||||
"micro30": []
|
||||
},
|
||||
"orders": [
|
||||
{
|
||||
"book": "original",
|
||||
"parent": "INS_20261029_688100SH_OPEN_001_2d3808de0edd",
|
||||
"code": "688100.SH",
|
||||
"plan_qty": 800,
|
||||
"parent_status": "DISPATCHED",
|
||||
"child_states": {
|
||||
"EXPIRED": 4
|
||||
},
|
||||
"child_total_filled": 0
|
||||
},
|
||||
{
|
||||
"book": "original",
|
||||
"parent": "INS_20261028_300693SZ_OPEN_47b78b",
|
||||
"code": "300693.SZ",
|
||||
"plan_qty": 600,
|
||||
"parent_status": "DISPATCHED",
|
||||
"child_states": {
|
||||
"EXPIRED": 37,
|
||||
"ABORTED": 1
|
||||
},
|
||||
"child_total_filled": 0
|
||||
}
|
||||
],
|
||||
"active_children": [],
|
||||
"trades_today": [
|
||||
{
|
||||
"seq": 1479112,
|
||||
"received_at": "2026-10-29 10:48:28",
|
||||
"processed": 1,
|
||||
"instruction_id": "STR20261029094901_601126SH_g_D06",
|
||||
"ts_code": "601126.SH",
|
||||
"side": "buy",
|
||||
"qty": 2700,
|
||||
"price": 28.35,
|
||||
"amount": 76545.0,
|
||||
"fee": null
|
||||
},
|
||||
{
|
||||
"seq": 1481500,
|
||||
"received_at": "2026-10-29 13:16:22",
|
||||
"processed": 1,
|
||||
"instruction_id": "STR20261029105701_601126SH_g_D02",
|
||||
"ts_code": "601126.SH",
|
||||
"side": "sell",
|
||||
"qty": 100,
|
||||
"price": 28.78,
|
||||
"amount": 2878.0,
|
||||
"fee": null
|
||||
}
|
||||
],
|
||||
"capital_ledger": {
|
||||
"cash": {
|
||||
"micro30": 0.0,
|
||||
"original": 1923441.0
|
||||
},
|
||||
"fees": {
|
||||
"micro30": 0.0,
|
||||
"original": 0.0
|
||||
},
|
||||
"fills": {
|
||||
"1455217": {
|
||||
"amount": 2892.0,
|
||||
"book": "original",
|
||||
"fee": 0,
|
||||
"side": "buy"
|
||||
},
|
||||
"1479112": {
|
||||
"amount": 76545.0,
|
||||
"book": "original",
|
||||
"fee": 0,
|
||||
"side": "buy"
|
||||
},
|
||||
"1481500": {
|
||||
"amount": 2878.0,
|
||||
"book": "original",
|
||||
"fee": 0,
|
||||
"side": "sell"
|
||||
}
|
||||
},
|
||||
"net_capital": {
|
||||
"micro30": 0.0,
|
||||
"original": 2000000.0
|
||||
},
|
||||
"source_funds_seq": 1454759,
|
||||
"started_at": "2026-10-28T09:29:06.569619",
|
||||
"transfers": {},
|
||||
"units": {
|
||||
"micro30": 0.0,
|
||||
"original": 2000000.0
|
||||
}
|
||||
},
|
||||
"cash_flow_rows_today": 0,
|
||||
"reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"monitor_health": {
|
||||
"state": "degraded",
|
||||
"last_success": "2026-10-29T08:52:52.391912+08:00",
|
||||
"error": "ValueError"
|
||||
},
|
||||
"current_snapshot": {
|
||||
"calculated_at": "2026-10-28T21:32:14.502610+08:00",
|
||||
"rule_version": "micro50-v2-20261028",
|
||||
"rule_parameters": {
|
||||
"entry_percentile": 0.08,
|
||||
"exit_percentile": 0.85,
|
||||
"basket_size": 50
|
||||
},
|
||||
"basket_size": 50,
|
||||
"data_date": "2026-10-28",
|
||||
"effective_date": "2026-10-29",
|
||||
"signal_ready": true,
|
||||
"basket_ready": true,
|
||||
"signal": {
|
||||
"date": "2026-10-28",
|
||||
"ready": true,
|
||||
"growth_break": false,
|
||||
"low": false,
|
||||
"high": false,
|
||||
"activity": 0.7453087062839947,
|
||||
"activity_percentile": 0.09391534391534391,
|
||||
"low_threshold": 0.7233829566510594,
|
||||
"high_threshold": 1.58469612793713,
|
||||
"growth_recent_hot": false,
|
||||
"growth_price_damage": -0.22505467906370535,
|
||||
"group_percentiles": {
|
||||
"large": 0.1111111111111111,
|
||||
"growth": 0.09391534391534391,
|
||||
"small": 0.09391534391534391
|
||||
}
|
||||
},
|
||||
"source_hashes": {
|
||||
"indices": "d4307a5d38914b1a89c1c60085b83a9a40205053e619834df09e322134816791",
|
||||
"calendar": "6c9605e33f796c90fab81e4f304a972339123288e700020378abce00c989d6cf",
|
||||
"stocks": "f36948b9cb6183fae260132eb5aff17d45f4f3a889a59f72843ab49314939fab"
|
||||
},
|
||||
"errors": [],
|
||||
"snapshot_version": "278ccbb519992f5ae780bfd5c01b42989e44eb56fd8438978f0771c6fcabbb78",
|
||||
"frozen": true
|
||||
},
|
||||
"current_snapshot_checks": {
|
||||
"member_count": 50,
|
||||
"unique_count": 50,
|
||||
"all_eligible": true,
|
||||
"sorted_by_cap_and_code": true,
|
||||
"min_listed_trade_days": 635,
|
||||
"execution_errors": []
|
||||
},
|
||||
"frozen_file": {
|
||||
"frozen_file_mtime_beijing": "2026-10-29T08:50:12.356883+08:00",
|
||||
"snapshot_version": "278ccbb519992f5ae780bfd5c01b42989e44eb56fd8438978f0771c6fcabbb78",
|
||||
"calculated_at": "2026-10-28T21:32:14.502610+08:00",
|
||||
"members": 50
|
||||
},
|
||||
"recorded_snapshot": {
|
||||
"date": "2026-10-29",
|
||||
"rule_version": "micro50-v2-20261028",
|
||||
"snapshot_version": "278ccbb519992f5ae780bfd5c01b42989e44eb56fd8438978f0771c6fcabbb78"
|
||||
},
|
||||
"rotation_window": {
|
||||
"ticks": 30,
|
||||
"successful_no_action": 29,
|
||||
"first_tick_blocked": "09:30持仓行情不完整,601126.SH",
|
||||
"recovered_at": "09:31:01",
|
||||
"last_tick": "2026-10-29T09:59:00.240677+08:00",
|
||||
"phase": "original"
|
||||
},
|
||||
"next_snapshot": {
|
||||
"status_code": 404,
|
||||
"snapshot": {
|
||||
"error": "指定执行日没有可用快照"
|
||||
}
|
||||
},
|
||||
"source_coverage": {
|
||||
"at_beijing": "2026-10-29T16:16:52.319977",
|
||||
"indices": {
|
||||
"large": [
|
||||
{
|
||||
"symbol": "000300.SH",
|
||||
"timestamp": "2026-10-28",
|
||||
"amount": 419279466
|
||||
},
|
||||
{
|
||||
"symbol": "000300.SH",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 383125565
|
||||
}
|
||||
],
|
||||
"growth": [
|
||||
{
|
||||
"symbol": "399006.SZ",
|
||||
"timestamp": "2026-10-28",
|
||||
"amount": 183224638
|
||||
},
|
||||
{
|
||||
"symbol": "399006.SZ",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 149752373
|
||||
}
|
||||
],
|
||||
"small": [
|
||||
{
|
||||
"symbol": "932000.CSI",
|
||||
"timestamp": "2026-10-28",
|
||||
"amount": 360296264
|
||||
},
|
||||
{
|
||||
"symbol": "932000.CSI",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 328426717
|
||||
}
|
||||
],
|
||||
"calendar": [
|
||||
{
|
||||
"symbol": "000001.SH",
|
||||
"timestamp": "2026-10-28",
|
||||
"amount": 751019236
|
||||
},
|
||||
{
|
||||
"symbol": "000001.SH",
|
||||
"timestamp": "2026-10-27",
|
||||
"amount": 672414398
|
||||
}
|
||||
]
|
||||
},
|
||||
"stocks": {
|
||||
"bars": [
|
||||
{
|
||||
"trade_date": "2026-10-28",
|
||||
"n": 5570
|
||||
}
|
||||
],
|
||||
"risk": [
|
||||
{
|
||||
"trade_date": "2026-10-28",
|
||||
"n": 197
|
||||
}
|
||||
],
|
||||
"limits": [
|
||||
{
|
||||
"trade_date": "2026-10-28",
|
||||
"n": 5653
|
||||
}
|
||||
],
|
||||
"basic": [
|
||||
{
|
||||
"trade_date": "2026-10-28",
|
||||
"n": 5570
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"daily": {
|
||||
"id": "live_day:2026-10-29",
|
||||
"value": {
|
||||
"cash_difference": 0.0,
|
||||
"date": "2026-10-29",
|
||||
"healthy": true,
|
||||
"metrics": {
|
||||
"account": {
|
||||
"cash": 1923441.0,
|
||||
"equity": 1999581.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 76140.0,
|
||||
"profit": -419.0
|
||||
},
|
||||
"micro30": {
|
||||
"cash": 0.0,
|
||||
"equity": 0.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 0.0,
|
||||
"nav": null,
|
||||
"net_capital": 0.0,
|
||||
"profit": 0.0
|
||||
},
|
||||
"original": {
|
||||
"cash": 1923441.0,
|
||||
"equity": 1999581.0,
|
||||
"fees": 0.0,
|
||||
"market_value": 76140.0,
|
||||
"nav": 0.9997905,
|
||||
"net_capital": 2000000.0,
|
||||
"profit": -419.0
|
||||
}
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"book_id": "original",
|
||||
"code": "601126.SH",
|
||||
"cost": 76558.5,
|
||||
"market_value": 76140.0,
|
||||
"price": 28.2,
|
||||
"qty": 2700
|
||||
}
|
||||
],
|
||||
"ready": true,
|
||||
"rule_version": "micro50-v2-20261028",
|
||||
"started_at": "2026-10-28T09:29:06.569619",
|
||||
"transfer_count": 0
|
||||
},
|
||||
"updated_at": "2026-10-29 15:20:00"
|
||||
},
|
||||
"not_yet_accepted": [
|
||||
"自然微盘完整入退场、成交容量及残余退出",
|
||||
"QMT实际费用回报与费用入账,当前fee=null",
|
||||
"午间断线外部根因"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,503 @@
|
|||
{
|
||||
"deployment": {
|
||||
"at_beijing": "2026-10-30 10:16:14",
|
||||
"health": {
|
||||
"status": "ok",
|
||||
"version": "0.2.0-dev",
|
||||
"service": "pms-web",
|
||||
"now": "2026-10-30 10:16:14",
|
||||
"trade_day": true,
|
||||
"calendar_degraded": false,
|
||||
"db_ok": true
|
||||
},
|
||||
"source_commit": "8f8beba",
|
||||
"image": "pms:daily-review-8f8beba",
|
||||
"server_commit": "12b9c22",
|
||||
"page_sha256": "2b55496a0298e0ed86f9b6e5c4fde07212a41da910add08ba83e53b0b850990f",
|
||||
"worker_idle_before": {
|
||||
"celery@cdc01843e579": []
|
||||
},
|
||||
"recreated": [
|
||||
"pms-web",
|
||||
"pms-worker",
|
||||
"pms-ws"
|
||||
],
|
||||
"beat_unchanged": true,
|
||||
"environment_mounts_unchanged": true,
|
||||
"services": {
|
||||
"pms-web": {
|
||||
"image": "pms:daily-review-8f8beba",
|
||||
"started": "2026-10-30T02:16:09.657546766Z"
|
||||
},
|
||||
"pms-worker": {
|
||||
"image": "pms:daily-review-8f8beba",
|
||||
"started": "2026-10-30T02:16:09.656947918Z"
|
||||
},
|
||||
"pms-beat": {
|
||||
"image": "pms:micro30-f1424f3",
|
||||
"started": "2026-10-28T04:48:27.998315799Z"
|
||||
},
|
||||
"pms-ws": {
|
||||
"image": "pms:daily-review-8f8beba",
|
||||
"started": "2026-10-30T02:16:09.656555286Z"
|
||||
}
|
||||
}
|
||||
},
|
||||
"code_commits": [
|
||||
"f0a7e91",
|
||||
"c90d7b3",
|
||||
"8f8beba"
|
||||
],
|
||||
"tests": {
|
||||
"specialized_cases": 36,
|
||||
"local_full": "ALL SUITES PASS",
|
||||
"candidate_155_network_none": "ALL SUITES PASS",
|
||||
"browser": {
|
||||
"viewports": [
|
||||
1440,
|
||||
390
|
||||
],
|
||||
"actualRowsReplayed": true,
|
||||
"waitingAndSubmittedLimits": true,
|
||||
"cancelDialogClosed": true,
|
||||
"errors": [],
|
||||
"writes": []
|
||||
},
|
||||
"final_html_sha256": "2b55496a0298e0ed86f9b6e5c4fde07212a41da910add08ba83e53b0b850990f"
|
||||
},
|
||||
"samples": [
|
||||
{
|
||||
"at": "2026-10-30T10:16:42.049212",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028"
|
||||
},
|
||||
"channel": {
|
||||
"online": true,
|
||||
"last_seq": 1501727,
|
||||
"acked_seq": 1501727,
|
||||
"resync_required": false,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"connected_at": "2026-10-30 10:16:13"
|
||||
},
|
||||
"gap": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1998107.0,
|
||||
"account_market_value": 85886.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 29.4,
|
||||
"why": ""
|
||||
},
|
||||
"recon": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"accounting": {
|
||||
"ready": true,
|
||||
"cash_difference": 0.0
|
||||
},
|
||||
"instructions": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d",
|
||||
"ts_code": "688100.SH",
|
||||
"status": "DISPATCHED",
|
||||
"qty": 800,
|
||||
"exec_qty": 0,
|
||||
"limit_price": "24.16",
|
||||
"created_at": "2026-10-30 10:10:22",
|
||||
"updated_at": "2026-10-30 10:16:02",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"status": "ACCEPTED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-30 10:11:05",
|
||||
"updated_at": "2026-10-30 10:11:05",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": null,
|
||||
"review_reason": null,
|
||||
"execution_price_date": 20261030
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd",
|
||||
"ts_code": "688100.SH",
|
||||
"status": "EXPIRED",
|
||||
"qty": 800,
|
||||
"exec_qty": 0,
|
||||
"limit_price": null,
|
||||
"created_at": "2026-10-29 14:18:13",
|
||||
"updated_at": "2026-10-30 10:11:03",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D02",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:29:01",
|
||||
"updated_at": "2026-10-29 14:39:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D03",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:40:01",
|
||||
"updated_at": "2026-10-29 14:50:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D04",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:51:01",
|
||||
"updated_at": "2026-10-29 15:00:01",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D05",
|
||||
"status": "CANCELLED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-30 09:32:42",
|
||||
"updated_at": "2026-10-30 09:39:40",
|
||||
"cancel_state": "SENT",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": "ended",
|
||||
"review_reason": "当日复核未通过:已有在途指令 INS_20261030_688100SH_OPEN_001_39f88720f32d (PROPOSED)",
|
||||
"execution_price_date": 20261030
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b",
|
||||
"ts_code": "300693.SZ",
|
||||
"status": "EXPIRED",
|
||||
"qty": 600,
|
||||
"exec_qty": 0,
|
||||
"limit_price": null,
|
||||
"created_at": "2026-10-28 09:35:02",
|
||||
"updated_at": "2026-10-30 10:12:02",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D36",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:36:01",
|
||||
"updated_at": "2026-10-29 14:46:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D37",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:46:05",
|
||||
"updated_at": "2026-10-29 14:56:01",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D38",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:56:05",
|
||||
"updated_at": "2026-10-29 15:00:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D39",
|
||||
"status": "CANCELLED",
|
||||
"qty": 600,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-30 09:32:42",
|
||||
"updated_at": "2026-10-30 09:39:40",
|
||||
"cancel_state": "SENT",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": "ended",
|
||||
"review_reason": "当日复核未通过:三条门槛都过了,但吸筹只到「⚠️ 跌破吸筹区间」,没到明确吸筹这条线",
|
||||
"execution_price_date": 20261030
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"at": "2026-10-30T10:17:39.076079",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028"
|
||||
},
|
||||
"channel": {
|
||||
"online": true,
|
||||
"last_seq": 1501742,
|
||||
"acked_seq": 1501742,
|
||||
"resync_required": false,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"connected_at": "2026-10-30 10:16:13"
|
||||
},
|
||||
"gap": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1997952.0,
|
||||
"account_market_value": 85731.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 26.3,
|
||||
"why": ""
|
||||
},
|
||||
"recon": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"accounting": {
|
||||
"ready": true,
|
||||
"cash_difference": 0.0
|
||||
},
|
||||
"instructions": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d",
|
||||
"ts_code": "688100.SH",
|
||||
"status": "DISPATCHED",
|
||||
"qty": 800,
|
||||
"exec_qty": 0,
|
||||
"limit_price": "24.16",
|
||||
"created_at": "2026-10-30 10:10:22",
|
||||
"updated_at": "2026-10-30 10:17:04",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"status": "ACCEPTED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-30 10:11:05",
|
||||
"updated_at": "2026-10-30 10:11:05",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": null,
|
||||
"review_reason": null,
|
||||
"execution_price_date": 20261030
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd",
|
||||
"ts_code": "688100.SH",
|
||||
"status": "EXPIRED",
|
||||
"qty": 800,
|
||||
"exec_qty": 0,
|
||||
"limit_price": null,
|
||||
"created_at": "2026-10-29 14:18:13",
|
||||
"updated_at": "2026-10-30 10:11:03",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D02",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:29:01",
|
||||
"updated_at": "2026-10-29 14:39:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D03",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:40:01",
|
||||
"updated_at": "2026-10-29 14:50:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D04",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-29 14:51:01",
|
||||
"updated_at": "2026-10-29 15:00:01",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261029_688100SH_OPEN_001_2d3808de0edd_D05",
|
||||
"status": "CANCELLED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"created_at": "2026-10-30 09:32:42",
|
||||
"updated_at": "2026-10-30 09:39:40",
|
||||
"cancel_state": "SENT",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": "ended",
|
||||
"review_reason": "当日复核未通过:已有在途指令 INS_20261030_688100SH_OPEN_001_39f88720f32d (PROPOSED)",
|
||||
"execution_price_date": 20261030
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b",
|
||||
"ts_code": "300693.SZ",
|
||||
"status": "EXPIRED",
|
||||
"qty": 600,
|
||||
"exec_qty": 0,
|
||||
"limit_price": null,
|
||||
"created_at": "2026-10-28 09:35:02",
|
||||
"updated_at": "2026-10-30 10:12:02",
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D36",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:36:01",
|
||||
"updated_at": "2026-10-29 14:46:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D37",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:46:05",
|
||||
"updated_at": "2026-10-29 14:56:01",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D38",
|
||||
"status": "EXPIRED",
|
||||
"qty": 300,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-29 14:56:05",
|
||||
"updated_at": "2026-10-29 15:00:02",
|
||||
"cancel_state": "NONE",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261028_300693SZ_OPEN_47b78b_D39",
|
||||
"status": "CANCELLED",
|
||||
"qty": 600,
|
||||
"cum_qty": 0,
|
||||
"limit_price": "30.02",
|
||||
"created_at": "2026-10-30 09:32:42",
|
||||
"updated_at": "2026-10-30 09:39:40",
|
||||
"cancel_state": "SENT",
|
||||
"reject_code": null,
|
||||
"reject_reason": null
|
||||
}
|
||||
],
|
||||
"review_status": "ended",
|
||||
"review_reason": "当日复核未通过:三条门槛都过了,但吸筹只到「⚠️ 跌破吸筹区间」,没到明确吸筹这条线",
|
||||
"execution_price_date": 20261030
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"today_weisheng": {
|
||||
"parent": {
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d",
|
||||
"origin_id": "PRP_20261030_688100SH_OPEN",
|
||||
"created_at": "2026-10-30 10:10:22",
|
||||
"status": "DISPATCHED",
|
||||
"qty": 800
|
||||
},
|
||||
"proposal": {
|
||||
"proposal_id": "PRP_20261030_688100SH_OPEN",
|
||||
"created_at": "2026-10-30 09:40:41",
|
||||
"decided_at": "2026-10-30 10:10:22",
|
||||
"status": "ACCEPTED",
|
||||
"judge_verdict": "UNAVAILABLE",
|
||||
"judge_reason": "证据不足以判断, 交人: 吸筹与模组传导仍成立,但实时资金中性、PV双周期看空且无近期催化,多空冲突证据不足以从零建仓。",
|
||||
"expire_at": "2026-10-30 23:59:59"
|
||||
},
|
||||
"version_check_at": "2026-10-30T10:10:22.420687+08:00"
|
||||
},
|
||||
"limits": [
|
||||
"审批和通过后继续执行的全部异常路径经隔离测试;本次真机自然见到旧任务失效和当日独立确认,未制造模拟信号或测试委托。",
|
||||
"研究工作树及155已有实验容器不在本次发布目标内。"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,493 @@
|
|||
{
|
||||
"cause": {
|
||||
"at": "2026-10-30T10:40:35.812835",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ORDER_TTL_MIN": 10
|
||||
},
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793326860000,
|
||||
"created_at": "2026-10-30 10:11:05",
|
||||
"sent_at": "2026-10-30 10:11:05",
|
||||
"final_at": "2026-10-30 10:21:28",
|
||||
"updated_at": "2026-10-30 10:21:28",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-c4591a9c78",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793327520000,
|
||||
"created_at": "2026-10-30 10:22:02",
|
||||
"sent_at": "2026-10-30 10:22:02",
|
||||
"final_at": "2026-10-30 10:32:02",
|
||||
"updated_at": "2026-10-30 10:32:02",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-6d51935a96",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D03",
|
||||
"status": "ACCEPTED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": null,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793328180000,
|
||||
"created_at": "2026-10-30 10:33:01",
|
||||
"sent_at": "2026-10-30 10:33:02",
|
||||
"final_at": null,
|
||||
"updated_at": "2026-10-30 10:33:02",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-18347d4c92",
|
||||
"reject_code": null
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"seq": 1501990,
|
||||
"msg_type": "persist_result",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D03",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D03\", \"scope\": \"final\", \"trade_no\": null, \"ok\": true, \"tables\": {\"trading_order\": \"DESK-18347d4c92\"}, \"error\": null}",
|
||||
"received_at": "2026-10-30 10:33:02"
|
||||
},
|
||||
{
|
||||
"seq": 1501989,
|
||||
"msg_type": "ack",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D03",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D03\", \"accepted\": true, \"duplicate\": false, \"broker_order_id\": \"DESK-18347d4c92\", \"status\": \"ACCEPTED\"}",
|
||||
"received_at": "2026-10-30 10:33:02"
|
||||
},
|
||||
{
|
||||
"seq": 1501972,
|
||||
"msg_type": "order_update",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D02\", \"broker_order_id\": \"DESK-6d51935a96\", \"status\": \"EXPIRED\", \"final\": true, \"cum_qty\": 0, \"cum_avg_price\": null, \"leaves_qty\": 0, \"update_time\": 1793327521896, \"reason\": \"valid_until\"}",
|
||||
"received_at": "2026-10-30 10:32:02"
|
||||
},
|
||||
{
|
||||
"seq": 1501811,
|
||||
"msg_type": "persist_result",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D02\", \"scope\": \"final\", \"trade_no\": null, \"ok\": true, \"tables\": {\"trading_order\": \"DESK-6d51935a96\"}, \"error\": null}",
|
||||
"received_at": "2026-10-30 10:22:02"
|
||||
},
|
||||
{
|
||||
"seq": 1501810,
|
||||
"msg_type": "ack",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D02\", \"accepted\": true, \"duplicate\": false, \"broker_order_id\": \"DESK-6d51935a96\", \"status\": \"ACCEPTED\"}",
|
||||
"received_at": "2026-10-30 10:22:02"
|
||||
},
|
||||
{
|
||||
"seq": 1501798,
|
||||
"msg_type": "order_update",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D01\", \"broker_order_id\": \"DESK-c4591a9c78\", \"status\": \"EXPIRED\", \"final\": true, \"cum_qty\": 0, \"cum_avg_price\": null, \"leaves_qty\": 0, \"update_time\": 1793326879970, \"reason\": \"valid_until\"}",
|
||||
"received_at": "2026-10-30 10:21:28"
|
||||
},
|
||||
{
|
||||
"seq": 1501639,
|
||||
"msg_type": "persist_result",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D01\", \"scope\": \"final\", \"trade_no\": null, \"ok\": true, \"tables\": {\"trading_order\": \"DESK-c4591a9c78\"}, \"error\": null}",
|
||||
"received_at": "2026-10-30 10:11:05"
|
||||
},
|
||||
{
|
||||
"seq": 1501638,
|
||||
"msg_type": "ack",
|
||||
"corr_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"payload_json": "{\"instruction_id\": \"INS_20261030_688100SH_OPEN_001_39f88720f32d_D01\", \"accepted\": true, \"duplicate\": false, \"broker_order_id\": \"DESK-c4591a9c78\", \"status\": \"ACCEPTED\"}",
|
||||
"received_at": "2026-10-30 10:11:05"
|
||||
}
|
||||
]
|
||||
},
|
||||
"deployment": {
|
||||
"at_beijing": "2026-10-30 10:52:39",
|
||||
"health": {
|
||||
"status": "ok",
|
||||
"version": "0.2.0-dev",
|
||||
"service": "pms-web",
|
||||
"now": "2026-10-30 10:52:39",
|
||||
"trade_day": true,
|
||||
"calendar_degraded": false,
|
||||
"db_ok": true
|
||||
},
|
||||
"source_commit": "2eaec70",
|
||||
"image": "pms:day-order-2eaec70",
|
||||
"server_commit": "6702090",
|
||||
"page_sha256": "2b55496a0298e0ed86f9b6e5c4fde07212a41da910add08ba83e53b0b850990f",
|
||||
"worker_idle_before": {
|
||||
"celery@308c9752144e": []
|
||||
},
|
||||
"recreated": [
|
||||
"pms-web",
|
||||
"pms-worker",
|
||||
"pms-ws"
|
||||
],
|
||||
"parameter": {
|
||||
"ok": true,
|
||||
"key": "PMS_EXEC_QMT_DAY_ORDER",
|
||||
"value": true
|
||||
},
|
||||
"beat_unchanged": true,
|
||||
"environment_mounts_unchanged": true,
|
||||
"services": {
|
||||
"pms-web": {
|
||||
"image": "pms:day-order-2eaec70",
|
||||
"started": "2026-10-30T02:52:34.907638327Z"
|
||||
},
|
||||
"pms-worker": {
|
||||
"image": "pms:day-order-2eaec70",
|
||||
"started": "2026-10-30T02:52:34.905973353Z"
|
||||
},
|
||||
"pms-beat": {
|
||||
"image": "pms:micro30-f1424f3",
|
||||
"started": "2026-10-28T04:48:27.998315799Z"
|
||||
},
|
||||
"pms-ws": {
|
||||
"image": "pms:day-order-2eaec70",
|
||||
"started": "2026-10-30T02:52:34.905287589Z"
|
||||
}
|
||||
}
|
||||
},
|
||||
"verification": [
|
||||
{
|
||||
"at": "2026-10-30T10:53:00.840527",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ORDER_TTL_MIN": 10,
|
||||
"PMS_EXEC_QMT_DAY_ORDER": true
|
||||
},
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": 1.0,
|
||||
"last_seq": 1502289,
|
||||
"acked_seq": 1502289,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 2,
|
||||
"ACCEPTED": 1,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 57,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-10-30 10:52:37",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 6,
|
||||
"tx": 12,
|
||||
"trades": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "10:52:57",
|
||||
"last_tx_at": "10:52:57",
|
||||
"hs_server_seq": 1502282,
|
||||
"hs_last_seq": 1502282,
|
||||
"snap_positions_at": "10:52:37",
|
||||
"snap_positions_n": 2,
|
||||
"snap_funds_at": "10:52:37",
|
||||
"seq_hwm": 1502289,
|
||||
"peer_skew_ms": -56,
|
||||
"peer_skew_min": -59,
|
||||
"peer_skew_max": -44
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1997349.0,
|
||||
"account_market_value": 85128.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 24.0,
|
||||
"why": ""
|
||||
},
|
||||
"recon": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793326860000,
|
||||
"created_at": "2026-10-30 10:11:05",
|
||||
"sent_at": "2026-10-30 10:11:05",
|
||||
"final_at": "2026-10-30 10:21:28",
|
||||
"updated_at": "2026-10-30 10:21:28",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-c4591a9c78",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793327520000,
|
||||
"created_at": "2026-10-30 10:22:02",
|
||||
"sent_at": "2026-10-30 10:22:02",
|
||||
"final_at": "2026-10-30 10:32:02",
|
||||
"updated_at": "2026-10-30 10:32:02",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-6d51935a96",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D03",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793328180000,
|
||||
"created_at": "2026-10-30 10:33:01",
|
||||
"sent_at": "2026-10-30 10:33:02",
|
||||
"final_at": "2026-10-30 10:43:01",
|
||||
"updated_at": "2026-10-30 10:43:01",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-18347d4c92",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D04",
|
||||
"status": "ACCEPTED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": null,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793328780000,
|
||||
"created_at": "2026-10-30 10:43:06",
|
||||
"sent_at": "2026-10-30 10:43:06",
|
||||
"final_at": null,
|
||||
"updated_at": "2026-10-30 10:43:06",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-7eb3c789d8",
|
||||
"reject_code": null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"at": "2026-10-30T10:54:05.684820",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ORDER_TTL_MIN": 10,
|
||||
"PMS_EXEC_QMT_DAY_ORDER": true
|
||||
},
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": 1.8,
|
||||
"last_seq": 1502309,
|
||||
"acked_seq": 1502309,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 2,
|
||||
"ACCEPTED": 1,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 58,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-10-30 10:52:37",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 26,
|
||||
"tx": 44,
|
||||
"trades": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "10:54:02",
|
||||
"last_tx_at": "10:54:03",
|
||||
"hs_server_seq": 1502282,
|
||||
"hs_last_seq": 1502282,
|
||||
"snap_positions_at": "10:53:37",
|
||||
"snap_positions_n": 2,
|
||||
"snap_funds_at": "10:53:37",
|
||||
"seq_hwm": 1502309,
|
||||
"peer_skew_ms": -56,
|
||||
"peer_skew_min": -59,
|
||||
"peer_skew_max": -44
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1997299.0,
|
||||
"account_market_value": 85078.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 27.8,
|
||||
"why": ""
|
||||
},
|
||||
"recon": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"orders": [
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D01",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793326860000,
|
||||
"created_at": "2026-10-30 10:11:05",
|
||||
"sent_at": "2026-10-30 10:11:05",
|
||||
"final_at": "2026-10-30 10:21:28",
|
||||
"updated_at": "2026-10-30 10:21:28",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-c4591a9c78",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D02",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793327520000,
|
||||
"created_at": "2026-10-30 10:22:02",
|
||||
"sent_at": "2026-10-30 10:22:02",
|
||||
"final_at": "2026-10-30 10:32:02",
|
||||
"updated_at": "2026-10-30 10:32:02",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-6d51935a96",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D03",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793328180000,
|
||||
"created_at": "2026-10-30 10:33:01",
|
||||
"sent_at": "2026-10-30 10:33:02",
|
||||
"final_at": "2026-10-30 10:43:01",
|
||||
"updated_at": "2026-10-30 10:43:01",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-18347d4c92",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D04",
|
||||
"status": "EXPIRED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": 0,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793328780000,
|
||||
"created_at": "2026-10-30 10:43:06",
|
||||
"sent_at": "2026-10-30 10:43:06",
|
||||
"final_at": "2026-10-30 10:53:02",
|
||||
"updated_at": "2026-10-30 10:53:02",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-7eb3c789d8",
|
||||
"reject_code": null
|
||||
},
|
||||
{
|
||||
"instruction_id": "INS_20261030_688100SH_OPEN_001_39f88720f32d_D05",
|
||||
"status": "ACCEPTED",
|
||||
"qty": 400,
|
||||
"cum_qty": 0,
|
||||
"leaves_qty": null,
|
||||
"limit_price": "23.30",
|
||||
"valid_until": 1793343600000,
|
||||
"created_at": "2026-10-30 10:53:04",
|
||||
"sent_at": "2026-10-30 10:53:05",
|
||||
"final_at": null,
|
||||
"updated_at": "2026-10-30 10:53:05",
|
||||
"cancel_state": "NONE",
|
||||
"cancel_req_at": null,
|
||||
"broker_order_id": "DESK-9da5d84aa1",
|
||||
"reject_code": null
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"tests": {
|
||||
"local_special_cases": 22,
|
||||
"local_full_regression": "PASS before final cancel-read-failure follow-up",
|
||||
"server_final_image": "pms:day-order-2eaec70",
|
||||
"server_offline_full": "ALL SUITES PASS",
|
||||
"artificial_live_orders": 0,
|
||||
"cancel_fill_races": "isolated replay only"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
{
|
||||
"verified_at": "2026-11-03T15:17:00+08:00",
|
||||
"bionic": {
|
||||
"code": "00f678505a67447e6f3d6bffdf69fad7b47cd9fc",
|
||||
"image": "bionic:execution-00f6785",
|
||||
"image_id": "sha256:b3c7fa8f0c4fd4f349ad7fb96dda52b12ed9cc53f867863413c72e37e777faef",
|
||||
"started_at": "2026-11-03T15:12:01+08:00",
|
||||
"containers": {
|
||||
"trader_api": "e70c3d6016e7",
|
||||
"trader_worker_brain": "f1c8e9bfcdca",
|
||||
"trader_worker_pms": "57bf77127f3b"
|
||||
},
|
||||
"offline_checks": "15/15 passed",
|
||||
"api": "online",
|
||||
"async_result_readonly": "UNAVAILABLE/NOT_FOUND",
|
||||
"task_registered": "intraday.pms_judge_async",
|
||||
"flags": {
|
||||
"PMS_API_ENABLED": true,
|
||||
"PMS_EXEC_BASIS_ENABLED": true,
|
||||
"PMS_JUDGE_ASYNC_ENABLED": true,
|
||||
"PMS_JUDGE_QUEUE": "pms_queue"
|
||||
},
|
||||
"other_containers_unchanged": 45,
|
||||
"external_predeployment_change": {
|
||||
"name": "quant_ml_trainer",
|
||||
"started_at": "2026-11-03T15:08:01+08:00",
|
||||
"same_image": true
|
||||
},
|
||||
"original_shared_source": "e9681e413e8d139348106679f501c7f809713f12",
|
||||
"original_env_unchanged": true
|
||||
},
|
||||
"pms155": {
|
||||
"worker_code": "56db0fddda2769658c4f13f919061c9313dc211e",
|
||||
"async_enabled_at": "2026-11-03T15:16:06+08:00",
|
||||
"async_enabled": true,
|
||||
"reprice_enabled": false,
|
||||
"micro_version": "micro50-v2-20261028",
|
||||
"today_sh_sz_limits": 0,
|
||||
"verification_at": "2026-11-03T15:16:53+08:00",
|
||||
"last_seq": 1598615,
|
||||
"acked_seq": 1598615,
|
||||
"last160_gaps": 0,
|
||||
"pending_inbox": 0,
|
||||
"orphan_fills": 0,
|
||||
"active_orders": 0,
|
||||
"funds_age_seconds": 23.5,
|
||||
"cash_available": 1967927.74,
|
||||
"cash_difference": 0,
|
||||
"quantity_reconciliation": "OK",
|
||||
"async_requests": 0,
|
||||
"natural_scheduler_at": "2026-11-03T15:17:00+08:00",
|
||||
"natural_scheduler_result": "execution_cancel_confirm success; other three skipped not_in_session"
|
||||
},
|
||||
"unaccepted_natural_cases": [
|
||||
"async_model_completion_and_timeout",
|
||||
"repricing_fill_cancel_race",
|
||||
"micro_v3_rotation_and_substitution"
|
||||
],
|
||||
"automation": {
|
||||
"id": "bionic",
|
||||
"deleted": true
|
||||
},
|
||||
"activation_1540": {
|
||||
"at": "2026-11-03T15:40:40+08:00",
|
||||
"user_authorized": true,
|
||||
"reprice_enabled": true,
|
||||
"async_enabled": true,
|
||||
"micro_rule": "micro50-v3-20261103",
|
||||
"candidate_pool": 100,
|
||||
"monitor_container": "e96aa5a76188",
|
||||
"monitor_started_at": "2026-11-03T15:37:30+08:00",
|
||||
"v2_files_unchanged": 16,
|
||||
"current_snapshot": {
|
||||
"data_date": "2026-11-02",
|
||||
"effective_date": "2026-11-03",
|
||||
"signal_ready": true,
|
||||
"basket_ready": true,
|
||||
"frozen": false,
|
||||
"candidate_count": 100,
|
||||
"snapshot_version": "aadbc205599a28c902ab2e930e35e8e998705a5e7a19c4464a48172f4a1932c6"
|
||||
},
|
||||
"tomorrow_snapshot": "not_yet_generated_at_1538",
|
||||
"last_seq": 1598996,
|
||||
"acked_seq": 1598996,
|
||||
"funds_age_sec": 10.3,
|
||||
"cash_difference": 0,
|
||||
"quantity_reconciliation": "OK",
|
||||
"pending": 0,
|
||||
"orphan": 0,
|
||||
"daily_calculation_execution_fallback_implemented": false,
|
||||
"validation_automation": {
|
||||
"id": "v3",
|
||||
"scheduled_beijing": "2026-11-04T10:00:00+08:00",
|
||||
"runs": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
{
|
||||
"code_commit": "017ead5f778736ceab69be29b2f81a031a20464f",
|
||||
"image": "pms:funds-cost-017ead5",
|
||||
"image_id": "sha256:17c80fb323a10e73545cf52ccf5cec9a9629678aadd544d49c7f98651a99daed",
|
||||
"deployed_at_beijing": "2026-11-04T09:53:47+08:00",
|
||||
"targets": [
|
||||
"pms-web",
|
||||
"pms-worker"
|
||||
],
|
||||
"other_services_unchanged": 13,
|
||||
"other_project_recreated": {
|
||||
"project": "mtf-etf-155",
|
||||
"count": 3,
|
||||
"started_at_beijing": "2026-11-04T09:52:28+08:00",
|
||||
"operated_by_this_release": false
|
||||
},
|
||||
"private_files_unchanged": [
|
||||
".env",
|
||||
".env.market-data",
|
||||
"scripts/deploy.sh"
|
||||
],
|
||||
"candidate_offline_log": "155:/tmp/pms-funds-cost-test-017ead5.log",
|
||||
"local_full_log": "/private/tmp/pms-funds-cost-final-decimal-local-20261104.log",
|
||||
"new_tests": 37,
|
||||
"browser": {
|
||||
"fixtureOnly": true,
|
||||
"liveLogin": false,
|
||||
"checked": [
|
||||
{
|
||||
"width": 1440,
|
||||
"missingPriceKeptCash": true,
|
||||
"unknownValuationBlank": true,
|
||||
"oldPaperStateIgnored": true,
|
||||
"refreshRestoredValuation": true,
|
||||
"costAndLotThreeDecimals": true,
|
||||
"drawerClosed": true
|
||||
},
|
||||
{
|
||||
"width": 390,
|
||||
"missingPriceKeptCash": true,
|
||||
"unknownValuationBlank": true,
|
||||
"oldPaperStateIgnored": true,
|
||||
"refreshRestoredValuation": true,
|
||||
"costAndLotThreeDecimals": true,
|
||||
"drawerClosed": true
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"writes": [],
|
||||
"external": []
|
||||
},
|
||||
"fee_backfill_ready": false,
|
||||
"fees_changed": false,
|
||||
"real_pms_188_operated": false,
|
||||
"verification": {
|
||||
"as_of_beijing": "2026-11-04T09:54:36+08:00",
|
||||
"health": "ok",
|
||||
"quantity_reconciled": true,
|
||||
"cash_reconciled": true,
|
||||
"sequence_contiguous": true,
|
||||
"pending_trades": false,
|
||||
"orphan_trades": false,
|
||||
"funds_fresh": true,
|
||||
"actual_export_checked": true,
|
||||
"natural_business_receipt_replayed": true,
|
||||
"manual_trade_or_fee_mutations": false,
|
||||
"raw_financial_records_committed": false
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
{
|
||||
"checked_at_beijing": "2026-11-02T09:40:32.008023",
|
||||
"source_commit": "716e215",
|
||||
"server_code_commit": "381ddf8",
|
||||
"deployment_at": "2026-11-02 09:39:49",
|
||||
"image": "pms:instruction-books-716e215",
|
||||
"recreated": [
|
||||
"pms-web"
|
||||
],
|
||||
"other_containers_unchanged": true,
|
||||
"environment_mounts_unchanged": true,
|
||||
"services": {
|
||||
"pms-web": {
|
||||
"image": "pms:instruction-books-716e215",
|
||||
"started": "2026-11-02T01:39:44.413915761Z"
|
||||
},
|
||||
"pms-worker": {
|
||||
"image": "pms:close-boundary-47f5621",
|
||||
"started": "2026-10-30T08:22:00.413434371Z"
|
||||
},
|
||||
"pms-beat": {
|
||||
"image": "pms:micro30-f1424f3",
|
||||
"started": "2026-10-28T04:48:27.998315799Z"
|
||||
},
|
||||
"pms-ws": {
|
||||
"image": "pms:strategy-type-578a2fa",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
"bionic-micro30-monitor": {
|
||||
"image": "bionic-micro30:3e2a584",
|
||||
"started": "2026-10-28T04:48:05.471247248Z"
|
||||
}
|
||||
},
|
||||
"html_sha256": "fc906283185a3daf2ece8e0aaa7e57ada03e93218bd81fd93d375e5a397cd998",
|
||||
"tests": {
|
||||
"strategy_ui_api_cases": 14,
|
||||
"local_full_offline": "ALL SUITES PASS",
|
||||
"candidate_155_full_offline": "ALL SUITES PASS",
|
||||
"page_guards": [
|
||||
"enum",
|
||||
"wiring",
|
||||
"copy"
|
||||
]
|
||||
},
|
||||
"browser": {
|
||||
"actualRowsReplayed": true,
|
||||
"isolatedBothBooksSameCode": true,
|
||||
"rotationTerminalsVisible": true,
|
||||
"statusCounts": true,
|
||||
"scopedCancelDialogClosed": true,
|
||||
"feedJumpsToBookAndStatus": true,
|
||||
"failedReadIsNotEmpty": true,
|
||||
"viewports": [
|
||||
1440,
|
||||
390
|
||||
],
|
||||
"errors": [],
|
||||
"writes": [],
|
||||
"external": []
|
||||
},
|
||||
"instruction_api": {
|
||||
"original": {
|
||||
"ok": true,
|
||||
"rows": 7,
|
||||
"all_rows_in_requested_book": true
|
||||
},
|
||||
"micro30": {
|
||||
"ok": true,
|
||||
"rows": 0,
|
||||
"all_rows_in_requested_book": true
|
||||
}
|
||||
},
|
||||
"channel": {
|
||||
"online": true,
|
||||
"connected_at": "2026-11-02 09:27:08",
|
||||
"last_seq": 1570221,
|
||||
"acked_seq": 1570221,
|
||||
"resync_required": false,
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0
|
||||
},
|
||||
"channel_stat": {
|
||||
"seq_hwm": 1570221,
|
||||
"pending_gap": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 3
|
||||
},
|
||||
"new_reject_count": 0,
|
||||
"cash_age_sec": 24.2,
|
||||
"quantity_reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"active_child_count": 0,
|
||||
"natural_new_order_count": 0,
|
||||
"params_unchanged": true,
|
||||
"scope": "155模拟PMS,浏览器为真实只读数据及隔离场景重放;未触发生产写接口、未制造委托。"
|
||||
}
|
||||
|
|
@ -0,0 +1,248 @@
|
|||
{
|
||||
"checked_at_beijing": "2026-11-03T12:41:34+08:00",
|
||||
"problem": "批量粘贴名称被当成代码;名称检索仅使用部分行业池,遗漏正常沪深股票。",
|
||||
"release": {
|
||||
"at_utc": "2026-11-03T04:39:33.107881",
|
||||
"pms_source": "8e6ce09",
|
||||
"bridge_source": "c11ae65",
|
||||
"before": [
|
||||
{
|
||||
"name": "pms-web",
|
||||
"id": "9577a77c5d1f053aa4c337138dc4320ac2e3caabc56ef1710a9e89092ca435eb",
|
||||
"tag": "pms:plan-user-934d46f",
|
||||
"image": "sha256:df1b553c3192da33de548a356f1dc86e35dac32c5cc4f08a855b7508839b2313",
|
||||
"started": "2026-11-03T04:16:14.276040337Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-worker",
|
||||
"id": "ae6346dceab43cb00c696cd368578ae636d5793b8bd04fd895ad9baf026fb973",
|
||||
"tag": "pms:plan-user-934d46f",
|
||||
"image": "sha256:df1b553c3192da33de548a356f1dc86e35dac32c5cc4f08a855b7508839b2313",
|
||||
"started": "2026-11-03T04:16:14.275312711Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-ws",
|
||||
"id": "d20181a32007de55ff42de002b4315f940bfdc411e4d8b76bc092c788a2b9e2d",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-beat",
|
||||
"id": "f41a32d70e459d8406f695752318d893fb3fee3ad51a0f3c7579d3f950e726b7",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "akg_factor_bridge",
|
||||
"id": "9d2566e725fe86407d3a26b1c4bf6fd9939298431b2cf82e94c17fd957abbc26",
|
||||
"tag": "bridge:plan-user-04339be",
|
||||
"image": "sha256:020bec7f666f3da3a1e1dfcd390c5965e6ed6c1e3ae5820c3cf4bda9216529d7",
|
||||
"started": "2026-11-03T04:16:09.449489958Z"
|
||||
}
|
||||
],
|
||||
"pms_commit": "b8037d52b2d531d7bb125aacf8feb202474201e6",
|
||||
"bridge_commit": "d9c4b92640e5fbe5c2cb351436a3b849e9e6fb99",
|
||||
"after": [
|
||||
{
|
||||
"name": "pms-web",
|
||||
"id": "9c6fde0c90419418a477757581a07ade6b7afc2c5da2aef66a49a4ec46ae323a",
|
||||
"tag": "pms:plan-names-8e6ce09",
|
||||
"image": "sha256:b38bdcfba4b7f54fd82a22e45aa3b038aa222120e37699eea7d460961eb1a26d",
|
||||
"started": "2026-11-03T04:39:42.874919446Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-worker",
|
||||
"id": "ae6346dceab43cb00c696cd368578ae636d5793b8bd04fd895ad9baf026fb973",
|
||||
"tag": "pms:plan-user-934d46f",
|
||||
"image": "sha256:df1b553c3192da33de548a356f1dc86e35dac32c5cc4f08a855b7508839b2313",
|
||||
"started": "2026-11-03T04:16:14.275312711Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-ws",
|
||||
"id": "d20181a32007de55ff42de002b4315f940bfdc411e4d8b76bc092c788a2b9e2d",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-beat",
|
||||
"id": "f41a32d70e459d8406f695752318d893fb3fee3ad51a0f3c7579d3f950e726b7",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "akg_factor_bridge",
|
||||
"id": "108bdd0e49042f813a23cf5a4e676a4fa4317a936469e3350df5e6128dbec8e8",
|
||||
"tag": "bridge:plan-names-c11ae65",
|
||||
"image": "sha256:7dd5cc309b2d75d952d815e712bccbd490410bfdc60ce985cf6ac7f9e34e9c67",
|
||||
"started": "2026-11-03T04:39:38.07343585Z"
|
||||
}
|
||||
],
|
||||
"complete_at_utc": "2026-11-03T04:39:46.679904"
|
||||
},
|
||||
"verification": {
|
||||
"at": "2026-11-03T12:40:19.063338",
|
||||
"prefix": "",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_OPEN_AUTONOMY": "propose_only",
|
||||
"PMS_PLAN_VERSION_RECHECK": true
|
||||
},
|
||||
"fingerprint": "1d92e659f123",
|
||||
"html_sha256": "adbd12d451f62a1ebdbf9463ec3db1080b9dd1e5c157198b85da630bc3c71fee",
|
||||
"channel": {
|
||||
"conn_state": "ONLINE",
|
||||
"heartbeat_age_sec": 2.2,
|
||||
"last_seq": 1596110,
|
||||
"acked_seq": 1596110,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"ACCEPTED": 2,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null
|
||||
},
|
||||
"channel_counters": {
|
||||
"rejects": 0,
|
||||
"reconnects": 8,
|
||||
"pending_gap": 0,
|
||||
"ooo": 0
|
||||
},
|
||||
"funds_age_sec": 13.1,
|
||||
"latest_sequence_count": 160,
|
||||
"sequence_gaps": 0,
|
||||
"quantity_reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_ready": true,
|
||||
"cash_difference": 0,
|
||||
"user_candidates": {
|
||||
"ok": true,
|
||||
"revision": 0,
|
||||
"writable": true
|
||||
},
|
||||
"user_candidate_count": 0,
|
||||
"search_ok": true,
|
||||
"search_count": 1,
|
||||
"plan_status": {
|
||||
"ok": true,
|
||||
"date": "2026-11-02",
|
||||
"age_tdays": 1
|
||||
},
|
||||
"name_search": {
|
||||
"华策影视": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SZ300133",
|
||||
"name": "华策影视"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
},
|
||||
"中文在线": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SZ300364",
|
||||
"name": "中文在线"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
},
|
||||
"捷成股份": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SZ300182",
|
||||
"name": "捷成股份"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
},
|
||||
"掌阅科技": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SH603533",
|
||||
"name": "掌阅科技"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
},
|
||||
"百纳千成": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SZ300291",
|
||||
"name": "百纳千成"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
},
|
||||
"果麦文化": {
|
||||
"ok": true,
|
||||
"items": [
|
||||
{
|
||||
"code": "SZ301052",
|
||||
"name": "果麦文化"
|
||||
}
|
||||
],
|
||||
"writable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"read_only_resolution": {
|
||||
"resolved": [
|
||||
"SZ300133",
|
||||
"SZ300364",
|
||||
"SZ300182",
|
||||
"SH603533",
|
||||
"SZ300291",
|
||||
"SZ301052"
|
||||
],
|
||||
"registry_unchanged": true,
|
||||
"revision": 0,
|
||||
"registered_count": 0
|
||||
},
|
||||
"upstream_natural_refresh": {
|
||||
"checked_at": "2026-11-03T04:40:24+00:00",
|
||||
"error": null,
|
||||
"pending_codes": []
|
||||
},
|
||||
"validation": {
|
||||
"local": "PMS ALL SUITES PASS;上游64项OK;页面三道护栏通过。",
|
||||
"sim155_images": "pms:plan-names-8e6ce09、bridge:plan-names-c11ae65均通过断网、无业务环境、只读、1核512MiB回归。",
|
||||
"browser": "1440与390像素本机固定示例:六名称粘贴拆分、保存为六代码、未知名称整批不保存、窄屏无表单横向溢出,控制台错误和警告0。",
|
||||
"html_matches": true,
|
||||
"environment_and_mounts_unchanged": true,
|
||||
"worker_beat_ws_unchanged": true,
|
||||
"startup_note": "12:40:23高股息接口一次读取超时;后续只读调用恢复,返回182行。新增来源搜索、解析和自然刷新正常。"
|
||||
},
|
||||
"backup": "/home/factor/project/tradingSystem/backups/plan-names-20261103-043933",
|
||||
"boundaries": {
|
||||
"real_candidate_registered": false,
|
||||
"real_registry_revision": 0,
|
||||
"test_order_sent": false,
|
||||
"note": "没有代替用户提交;本机示例保存与155真实登记严格分开。"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,461 @@
|
|||
{
|
||||
"checked_at_beijing": "2026-11-03T12:20:39.756760+08:00",
|
||||
"natural_refresh_after_final_release": {
|
||||
"checked_at_utc": "2026-11-03T04:20:39.756760",
|
||||
"date": "2026-11-02",
|
||||
"plan_version": "4286705",
|
||||
"generated_at": "2026-11-03T04:15:19+00:00",
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27",
|
||||
"refresh_status": {
|
||||
"checked_at": "2026-11-03T04:20:15+00:00",
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27",
|
||||
"error": null,
|
||||
"pending_codes": []
|
||||
}
|
||||
},
|
||||
"target": "192.168.16.155 模拟PMS及上游akg-factor-bridge",
|
||||
"authorization": "用户明确回复:允许同步发布到155",
|
||||
"release": {
|
||||
"at_utc": "2026-11-03T04:15:29.266000",
|
||||
"pms_source": "934d46f",
|
||||
"bridge_source": "04339be",
|
||||
"before": [
|
||||
{
|
||||
"name": "pms-web",
|
||||
"id": "aa23f38f4b25afadd2300f5ea55745b094efab31e6fd2db099a8032b38d6e06c",
|
||||
"tag": "pms:plan-user-96b2ea2",
|
||||
"image": "sha256:50e9c4f02f407a5bd7c1318389696ef7ee77e30d93a90f747422b76ff8145716",
|
||||
"started": "2026-11-03T03:57:00.393167309Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-worker",
|
||||
"id": "e0cc9672c3416ae6024aa3512bb3379c890289c22c18aa383713107d1812dd25",
|
||||
"tag": "pms:plan-user-96b2ea2",
|
||||
"image": "sha256:50e9c4f02f407a5bd7c1318389696ef7ee77e30d93a90f747422b76ff8145716",
|
||||
"started": "2026-11-03T03:57:00.394795126Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-ws",
|
||||
"id": "d20181a32007de55ff42de002b4315f940bfdc411e4d8b76bc092c788a2b9e2d",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-beat",
|
||||
"id": "f41a32d70e459d8406f695752318d893fb3fee3ad51a0f3c7579d3f950e726b7",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "akg_factor_bridge",
|
||||
"id": "c82e6ba9effbbb1c303c6196d7883b6c9582c465762806ea0b0d703994f303c9",
|
||||
"tag": "bridge:plan-user-a9fc789",
|
||||
"image": "sha256:f118a0b543a1986e6aca6026e3e086499f297eadfba4dda327a5e362745bfb99",
|
||||
"started": "2026-11-03T03:56:55.181128293Z"
|
||||
}
|
||||
],
|
||||
"pms_commit": "5b75adea85cccedb0a79f892992c34b60b4c848c",
|
||||
"bridge_commit": "36b9e08ab93f52fcd8bd4f0fca9a49205967568b",
|
||||
"after": [
|
||||
{
|
||||
"name": "pms-web",
|
||||
"id": "9577a77c5d1f053aa4c337138dc4320ac2e3caabc56ef1710a9e89092ca435eb",
|
||||
"tag": "pms:plan-user-934d46f",
|
||||
"image": "sha256:df1b553c3192da33de548a356f1dc86e35dac32c5cc4f08a855b7508839b2313",
|
||||
"started": "2026-11-03T04:16:14.276040337Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-worker",
|
||||
"id": "ae6346dceab43cb00c696cd368578ae636d5793b8bd04fd895ad9baf026fb973",
|
||||
"tag": "pms:plan-user-934d46f",
|
||||
"image": "sha256:df1b553c3192da33de548a356f1dc86e35dac32c5cc4f08a855b7508839b2313",
|
||||
"started": "2026-11-03T04:16:14.275312711Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-ws",
|
||||
"id": "d20181a32007de55ff42de002b4315f940bfdc411e4d8b76bc092c788a2b9e2d",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "pms-beat",
|
||||
"id": "f41a32d70e459d8406f695752318d893fb3fee3ad51a0f3c7579d3f950e726b7",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "akg_factor_bridge",
|
||||
"id": "9d2566e725fe86407d3a26b1c4bf6fd9939298431b2cf82e94c17fd957abbc26",
|
||||
"tag": "bridge:plan-user-04339be",
|
||||
"image": "sha256:020bec7f666f3da3a1e1dfcd390c5965e6ed6c1e3ae5820c3cf4bda9216529d7",
|
||||
"started": "2026-11-03T04:16:09.449489958Z"
|
||||
}
|
||||
],
|
||||
"complete_at_utc": "2026-11-03T04:17:15.169413",
|
||||
"environment_check": "compose有效环境与备份一致,容器值在还原Compose美元符转义后相符;基底与候选镜像环境一致。列表顺序比较触发误报,未再次重建。"
|
||||
},
|
||||
"verification": {
|
||||
"at": "2026-11-03T12:17:27.453004",
|
||||
"prefix": "",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_OPEN_AUTONOMY": "propose_only",
|
||||
"PMS_PLAN_VERSION_RECHECK": true
|
||||
},
|
||||
"fingerprint": "e3e8dbb38c36",
|
||||
"html_sha256": "88d0fe421e558b2628f362f754a5bbc9805d3fe3ac43e218aef60d3afd1d654d",
|
||||
"channel": {
|
||||
"conn_state": "ONLINE",
|
||||
"heartbeat_age_sec": 1.6,
|
||||
"last_seq": 1595743,
|
||||
"acked_seq": 1595743,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"ACCEPTED": 2,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null
|
||||
},
|
||||
"channel_counters": {
|
||||
"rejects": 0,
|
||||
"reconnects": 8,
|
||||
"pending_gap": 0,
|
||||
"ooo": 0
|
||||
},
|
||||
"funds_age_sec": 21.5,
|
||||
"latest_sequence_count": 160,
|
||||
"sequence_gaps": 0,
|
||||
"quantity_reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_ready": true,
|
||||
"cash_difference": 0,
|
||||
"user_candidates": {
|
||||
"ok": true,
|
||||
"revision": 0,
|
||||
"writable": true
|
||||
},
|
||||
"user_candidate_count": 0,
|
||||
"search_ok": true,
|
||||
"search_count": 1,
|
||||
"plan_status": {
|
||||
"source": "plan_api",
|
||||
"base": "http://192.168.16.155:8300",
|
||||
"path": "/plan",
|
||||
"top_n": 50,
|
||||
"tiers": [],
|
||||
"min_upside": 0,
|
||||
"theme_cap_local": 0,
|
||||
"query": {
|
||||
"top": "300",
|
||||
"obs_top": "100",
|
||||
"theme_cap": "0"
|
||||
},
|
||||
"include_observe": false,
|
||||
"stale_tdays": 1,
|
||||
"theme_sync": null,
|
||||
"snapshot_on": true,
|
||||
"enabled": true,
|
||||
"ok": true,
|
||||
"date": "2026-11-02",
|
||||
"age_tdays": 1,
|
||||
"plan_version": "4286705",
|
||||
"generated_at": "2026-11-03T04:15:19+00:00",
|
||||
"route_by_verdict": true,
|
||||
"heat_date": "2026-11-02",
|
||||
"market_snapshot_days": [
|
||||
"2026-11-02"
|
||||
],
|
||||
"counts": {
|
||||
"main": 572,
|
||||
"observe": 652,
|
||||
"gate_covered": 3825
|
||||
},
|
||||
"returned": {
|
||||
"main": 300,
|
||||
"observe": 100
|
||||
},
|
||||
"funnel": {
|
||||
"scored_main": 572,
|
||||
"returned_main": 300,
|
||||
"scored_observe": 652,
|
||||
"returned_observe": 100
|
||||
},
|
||||
"requested": {
|
||||
"top": 300,
|
||||
"obs_top": 100,
|
||||
"theme_cap": 0
|
||||
},
|
||||
"truncated": {
|
||||
"main": true,
|
||||
"observe": true
|
||||
},
|
||||
"theme_cap": 0,
|
||||
"encoding": "主榜分=200+传导档位×20+组内分(还没热、还便宜);观察档分=100+0.6z(传导)+0.4z(−热度);名次按开关 PLAN_RANK_AXIS:quality 时质地带优先、传导只在带内作次级键,transmission 时按 09-14 的质地调整分序",
|
||||
"snapshot": {
|
||||
"digest": "4ca9a04285b4483188da8e40b068d66f08f57b6e",
|
||||
"rows": 400,
|
||||
"stored": false
|
||||
},
|
||||
"fetched_at": 1793679448.279967,
|
||||
"url": "http://192.168.16.155:8300/plan",
|
||||
"plan_source": "snapshot",
|
||||
"snapshot_generated_at": "2026-11-03T04:15:19+00:00",
|
||||
"gate_on": true,
|
||||
"hint": "计划 2026-11-02 已就绪 (日龄 1 交易日)"
|
||||
},
|
||||
"search_count_note": "搜索接口返回items,追加只读核对items长度为1。"
|
||||
},
|
||||
"read_only_plan_contracts": [
|
||||
{
|
||||
"explicit": false,
|
||||
"http": 200,
|
||||
"date": "2026-11-02",
|
||||
"main_count": 300,
|
||||
"observe_count": 100,
|
||||
"refresh_status": {
|
||||
"checked_at": "2026-11-03T04:15:25+00:00",
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27",
|
||||
"error": null,
|
||||
"pending_codes": []
|
||||
},
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27"
|
||||
},
|
||||
{
|
||||
"explicit": true,
|
||||
"http": 200,
|
||||
"date": "2026-11-02",
|
||||
"main_count": 300,
|
||||
"observe_count": 100,
|
||||
"refresh_status": {
|
||||
"checked_at": "2026-11-03T04:15:25+00:00",
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27",
|
||||
"error": null,
|
||||
"pending_codes": []
|
||||
},
|
||||
"decision_id": "2026-11-02_3768a6567bbb8c70066139a1739af5fe2c179397700c7798286cc928bcfa3c27"
|
||||
}
|
||||
],
|
||||
"validation": {
|
||||
"developer_machine": "最终PMS全量ALL SUITES PASS;用户候选9项;上游60项OK;页面三道护栏、1440/390浏览器固定示例验收通过。",
|
||||
"sim155_candidate_images": "最终镜像pms:plan-user-934d46f、bridge:plan-user-04339be;断网、无业务环境、只读、1核512MiB,分别ALL SUITES PASS和60项OK。",
|
||||
"fingerprints": "开发机、155源码、web和worker均为e3e8dbb38c36",
|
||||
"effective_environment_unchanged": true,
|
||||
"ws_and_beat_process_unchanged": true,
|
||||
"deployed_html_matches_browser_verified": true,
|
||||
"natural_worker_successful_tasks": 10,
|
||||
"final_service_error_count": 0,
|
||||
"natural_explicit_plan_request_seen": true
|
||||
},
|
||||
"backups": [
|
||||
"/home/factor/project/tradingSystem/backups/plan-user-20261103-035319",
|
||||
"/home/factor/project/tradingSystem/backups/plan-optin-20261103-041529"
|
||||
],
|
||||
"boundaries": {
|
||||
"real_candidate_registered": false,
|
||||
"test_order_created": false,
|
||||
"real_login_browser_acceptance": false,
|
||||
"waiting": "首次实际添加及其自然评估未制造测试记录"
|
||||
},
|
||||
"initial_release_history": {
|
||||
"checked_at_beijing": "2026-11-03T11:58:25.848957",
|
||||
"release": {
|
||||
"at": "20261103-035319 UTC",
|
||||
"pms_source": "96b2ea2",
|
||||
"bridge_source": "a9fc789",
|
||||
"plan_before": "2026-11-02_ea48de436ca086520e170e58315017c328c9de647d8ce6a2201bd81558e06d81",
|
||||
"containers": [
|
||||
{
|
||||
"name": "/pms-web",
|
||||
"id": "2555df501a6793b28ee4bd78b2d77a2b6c09b14e193571a8c5e7a8c77014cd73",
|
||||
"image": "sha256:3ef7d6b657f376fb269e0139d78e1d8680642cd106fdbbcaaed5e99832db9bd2",
|
||||
"tag": "pms:instruction-books-716e215",
|
||||
"started": "2026-11-02T01:39:44.413915761Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-worker",
|
||||
"id": "41ae032bfbfbbd0672e460d8082a7dc01ed8b5e23a470028e53a105917164fc7",
|
||||
"image": "sha256:273191b69ca0466ef0b316a80358293cbc80d14ce5a9a6fef4f6398a8a57ee3b",
|
||||
"tag": "pms:close-boundary-47f5621",
|
||||
"started": "2026-11-02T02:10:06.254009359Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-ws",
|
||||
"id": "d20181a32007de55ff42de002b4315f940bfdc411e4d8b76bc092c788a2b9e2d",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-beat",
|
||||
"id": "f41a32d70e459d8406f695752318d893fb3fee3ad51a0f3c7579d3f950e726b7",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "/akg_factor_bridge",
|
||||
"id": "970b0b8f82af2309722022af95a7948d698176e90001e39845e0e4e94e518580",
|
||||
"image": "sha256:9d526e51c2c890aaa27b70e00b77f5d8ba6a0d22a452e6f5ac7254dc83e6e01f",
|
||||
"tag": "akg-factor-bridge-akg-factor-bridge",
|
||||
"started": "2026-10-26T06:55:31.112283953Z"
|
||||
}
|
||||
],
|
||||
"bridge_commit": "4286705f819de406cb8d6dc8ae254a0654779c90",
|
||||
"pms_commit": "bd938b21aeba54737eb0baed01c9f5503174ea70",
|
||||
"after": [
|
||||
{
|
||||
"name": "/pms-web",
|
||||
"image": "sha256:50e9c4f02f407a5bd7c1318389696ef7ee77e30d93a90f747422b76ff8145716",
|
||||
"tag": "pms:plan-user-96b2ea2",
|
||||
"started": "2026-11-03T03:57:00.393167309Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-worker",
|
||||
"image": "sha256:50e9c4f02f407a5bd7c1318389696ef7ee77e30d93a90f747422b76ff8145716",
|
||||
"tag": "pms:plan-user-96b2ea2",
|
||||
"started": "2026-11-03T03:57:00.394795126Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-ws",
|
||||
"image": "sha256:12611317b3b92022badd3b4ac10bbb0c1dded188273af852b44dec7f1635d17f",
|
||||
"tag": "pms:strategy-type-578a2fa",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
{
|
||||
"name": "/pms-beat",
|
||||
"image": "sha256:72a98112ccde0f083b5e52d1f0c9d0b5ab0f2cfc1b38196745eee383a07f132a",
|
||||
"tag": "pms:micro30-f1424f3",
|
||||
"started": "2026-11-02T02:10:06.6712493Z"
|
||||
},
|
||||
{
|
||||
"name": "/akg_factor_bridge",
|
||||
"image": "sha256:f118a0b543a1986e6aca6026e3e086499f297eadfba4dda327a5e362745bfb99",
|
||||
"tag": "bridge:plan-user-a9fc789",
|
||||
"started": "2026-11-03T03:56:55.181128293Z"
|
||||
}
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"at": "2026-11-03T11:58:25.848957",
|
||||
"prefix": "",
|
||||
"params": {
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_OPEN_AUTONOMY": "propose_only",
|
||||
"PMS_PLAN_VERSION_RECHECK": true
|
||||
},
|
||||
"fingerprint": "e7b8ad60b10f",
|
||||
"html_sha256": "88d0fe421e558b2628f362f754a5bbc9805d3fe3ac43e218aef60d3afd1d654d",
|
||||
"channel": {
|
||||
"conn_state": "ONLINE",
|
||||
"heartbeat_age_sec": 1.1,
|
||||
"last_seq": 1595439,
|
||||
"acked_seq": 1595439,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"ACCEPTED": 2,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0
|
||||
},
|
||||
"channel_counters": {
|
||||
"rejects": 0,
|
||||
"reconnects": 8,
|
||||
"pending_gap": 0,
|
||||
"ooo": 0
|
||||
},
|
||||
"funds_age_sec": 18.2,
|
||||
"latest_sequence_count": 160,
|
||||
"sequence_gaps": 0,
|
||||
"quantity_reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_ready": true,
|
||||
"cash_difference": 0,
|
||||
"user_candidates": {
|
||||
"ok": true,
|
||||
"rows": [],
|
||||
"revision": 0,
|
||||
"writable": true
|
||||
},
|
||||
"search_ok": true,
|
||||
"search_count": 1,
|
||||
"plan_status": {
|
||||
"ok": true,
|
||||
"date": "2026-11-02",
|
||||
"hint": "计划 2026-11-02 已就绪 (日龄 1 交易日)",
|
||||
"age_tdays": 1
|
||||
}
|
||||
},
|
||||
"upstream": {
|
||||
"date": "2026-11-02",
|
||||
"decision_id": "2026-11-02_ea48de436ca086520e170e58315017c328c9de647d8ce6a2201bd81558e06d81",
|
||||
"health": {
|
||||
"checked_at": "2026-11-03T03:50:23+00:00",
|
||||
"decision_id": "2026-11-02_ea48de436ca086520e170e58315017c328c9de647d8ce6a2201bd81558e06d81",
|
||||
"error": null,
|
||||
"pending_codes": []
|
||||
},
|
||||
"registry_exists": false
|
||||
},
|
||||
"existing_dividend_source": {
|
||||
"high_dividend_read_ok": true,
|
||||
"keys": [
|
||||
"checked_at",
|
||||
"data_date",
|
||||
"decision",
|
||||
"eligible_count",
|
||||
"investment_approved",
|
||||
"policy_version",
|
||||
"rows",
|
||||
"schema_version",
|
||||
"source"
|
||||
]
|
||||
},
|
||||
"validation": {
|
||||
"developer_machine": "ALL SUITES PASS; 页面三道护栏通过;1440/390固定示例浏览器验收通过",
|
||||
"sim155_candidate_images": "PMS ALL SUITES PASS;上游59项OK;断网、无业务环境、只读运行"
|
||||
},
|
||||
"boundaries": {
|
||||
"real_candidate_registered": false,
|
||||
"test_order_created": false,
|
||||
"real_login_browser_acceptance": false,
|
||||
"waiting": "首次实际添加及其自然评估未制造测试记录"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
{
|
||||
"checked_at": "2026-11-03T16:47:37+08:00",
|
||||
"machine": "155模拟PMS",
|
||||
"source_commit": "0b3c50ef3478ccc415d5f81803fa5d8f7e93261d",
|
||||
"image": "pms:limits-0b3c50e",
|
||||
"image_id": "sha256:11fcd4868f48c512da2b8f2c018d5177ba4060deb238c67842f2c9fcc97b5b94",
|
||||
"started_at": "2026-11-03T16:31:49+08:00",
|
||||
"services": [
|
||||
"pms-web",
|
||||
"pms-worker",
|
||||
"pms-market-data"
|
||||
],
|
||||
"unchanged_other_services": 12,
|
||||
"original_env_unchanged": true,
|
||||
"secret_only_collector": true,
|
||||
"cache_enabled_at": "2026-11-03T16:38:04+08:00",
|
||||
"cache": {
|
||||
"trade_date": "2026-11-03",
|
||||
"target_count": 103,
|
||||
"valid_count": 103,
|
||||
"micro_candidates": 100,
|
||||
"source": "tushare.stk_limit",
|
||||
"errors": 0
|
||||
},
|
||||
"tests": {
|
||||
"new_offline_cases": 121,
|
||||
"local_full": "ALL SUITES PASS",
|
||||
"candidate_network_none_full": "ALL SUITES PASS",
|
||||
"server_log": "/tmp/pms-limits-test-0b3c50e.log"
|
||||
},
|
||||
"late_report": {
|
||||
"user_confirmed": true,
|
||||
"ts_code": "002979.SZ",
|
||||
"qty": 100,
|
||||
"price": 48.29,
|
||||
"received_at": "2026-11-03T16:16:12+08:00",
|
||||
"trade_seq": 1599510,
|
||||
"final_update_seq": 1599512,
|
||||
"original_expired_seq": 1598347,
|
||||
"desk_backfill": true,
|
||||
"book_id": "original",
|
||||
"parent_target": 300,
|
||||
"parent_filled": 100,
|
||||
"parent_remaining": 200,
|
||||
"child_status": "FILLED",
|
||||
"fee": null,
|
||||
"audit_keys": [
|
||||
"late-trade-booked:1599510",
|
||||
"late-order-correction:1599512"
|
||||
],
|
||||
"not_natural_validation": true
|
||||
},
|
||||
"qmt": {
|
||||
"last_seq": 1600016,
|
||||
"acked_seq": 1600016,
|
||||
"recent_count": 160,
|
||||
"gaps": 0,
|
||||
"resync": 0,
|
||||
"pending": 0,
|
||||
"orphan": 0,
|
||||
"active_orders": 0,
|
||||
"cash_avail": 1963098.74,
|
||||
"total_asset": 1967971.74,
|
||||
"market_value": 4873,
|
||||
"frozen_cash": 0,
|
||||
"funds_age_sec": 16.9,
|
||||
"cash_difference": 0,
|
||||
"position_difference_count": 0
|
||||
},
|
||||
"natural_judge_requests": 0,
|
||||
"next_validation": {
|
||||
"automation_id": "v3",
|
||||
"at": "2026-11-04T10:00:00+08:00",
|
||||
"once": true,
|
||||
"frozen_next_day_snapshot_pending": true
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,289 @@
|
|||
{
|
||||
"deployment": {
|
||||
"at_beijing": "2026-11-02 09:07:31",
|
||||
"source_commit": "578a2fa",
|
||||
"server_commit": "4059b6f",
|
||||
"image": "pms:strategy-type-578a2fa",
|
||||
"recreated": [
|
||||
"pms-ws"
|
||||
],
|
||||
"other_containers_unchanged": true,
|
||||
"environment_mounts_unchanged": true,
|
||||
"before": {
|
||||
"params": {
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false
|
||||
},
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": 1.4,
|
||||
"last_seq": 1569698,
|
||||
"acked_seq": 1569698,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-10-30 10:52:37",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 67415,
|
||||
"tx": 122909,
|
||||
"trades": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "09:07:23",
|
||||
"last_tx_at": "09:07:25",
|
||||
"hs_server_seq": 1502282,
|
||||
"hs_last_seq": 1502282,
|
||||
"snap_positions_at": "09:07:03",
|
||||
"snap_positions_n": 2,
|
||||
"snap_funds_at": "09:07:03",
|
||||
"seq_hwm": 1569698,
|
||||
"peer_skew_ms": 40,
|
||||
"peer_skew_min": -97,
|
||||
"peer_skew_max": 274,
|
||||
"ooo": 0,
|
||||
"pending_gap": 0
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1995983.0,
|
||||
"account_market_value": 83762.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 23.5,
|
||||
"why": ""
|
||||
},
|
||||
"schema": true,
|
||||
"active": []
|
||||
},
|
||||
"after": {
|
||||
"params": {
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false
|
||||
},
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": 0.7,
|
||||
"last_seq": 1569698,
|
||||
"acked_seq": 1569698,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-11-02 09:07:30",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 67415,
|
||||
"tx": 122909,
|
||||
"trades": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "09:07:23",
|
||||
"last_tx_at": "09:07:25",
|
||||
"hs_server_seq": 1502282,
|
||||
"hs_last_seq": 1502282,
|
||||
"snap_positions_at": "09:07:03",
|
||||
"snap_positions_n": 2,
|
||||
"snap_funds_at": "09:07:03",
|
||||
"seq_hwm": 1569698,
|
||||
"peer_skew_ms": 40,
|
||||
"peer_skew_min": -97,
|
||||
"peer_skew_max": 274,
|
||||
"ooo": 0,
|
||||
"pending_gap": 0
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1995983.0,
|
||||
"account_market_value": 83762.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 0.7,
|
||||
"why": ""
|
||||
},
|
||||
"schema": true,
|
||||
"active": []
|
||||
},
|
||||
"health": {
|
||||
"status": "ok",
|
||||
"version": "0.2.0-dev",
|
||||
"service": "pms-web",
|
||||
"now": "2026-11-02 09:07:31",
|
||||
"trade_day": true,
|
||||
"calendar_degraded": false,
|
||||
"db_ok": true
|
||||
},
|
||||
"services": {
|
||||
"pms-web": {
|
||||
"image": "pms:close-boundary-47f5621",
|
||||
"started": "2026-10-30T08:22:00.412778588Z"
|
||||
},
|
||||
"pms-worker": {
|
||||
"image": "pms:close-boundary-47f5621",
|
||||
"started": "2026-10-30T08:22:00.413434371Z"
|
||||
},
|
||||
"pms-beat": {
|
||||
"image": "pms:micro30-f1424f3",
|
||||
"started": "2026-10-28T04:48:27.998315799Z"
|
||||
},
|
||||
"pms-ws": {
|
||||
"image": "pms:strategy-type-578a2fa",
|
||||
"started": "2026-11-02T01:07:27.741851322Z"
|
||||
},
|
||||
"bionic-micro30-monitor": {
|
||||
"image": "bionic-micro30:3e2a584",
|
||||
"started": "2026-10-28T04:48:05.471247248Z"
|
||||
}
|
||||
}
|
||||
},
|
||||
"final_probe": {
|
||||
"at_beijing": "2026-11-02T09:08:20.959362",
|
||||
"params": {
|
||||
"PMS_ROTATION_MODE": "auto",
|
||||
"PMS_ROTATION_CONTROL": "run",
|
||||
"PMS_ROTATION_RULE_VERSION": "micro50-v2-20261028",
|
||||
"PMS_GLOBAL_EXEC_HALT": false,
|
||||
"PMS_GLOBAL_BUY_HALT": false,
|
||||
"PMS_QMT_WS_URL": "ws://192.168.18.182:9443/pms",
|
||||
"PMS_QMT_WS_ENABLED": true,
|
||||
"PMS_DISPATCH_MODE": "ws",
|
||||
"PMS_RECON_SOURCE": "ws_only",
|
||||
"PMS_EXEC_QMT_PRICE_MONITOR": true,
|
||||
"PMS_EXEC_QMT_DAY_ORDER": true,
|
||||
"PMS_DAILY_BUY_REVIEW": true,
|
||||
"PMS_ROTATION_SIM_DIRECT": true
|
||||
},
|
||||
"channel": {
|
||||
"process_alive": true,
|
||||
"conn_state": "ONLINE",
|
||||
"online": true,
|
||||
"heartbeat_age_sec": 0.1,
|
||||
"last_seq": 1569713,
|
||||
"acked_seq": 1569713,
|
||||
"resync_required": false,
|
||||
"queue": {
|
||||
"ABORTED": 3,
|
||||
"CANCELLED": 2,
|
||||
"EXPIRED": 59,
|
||||
"FILLED": 360,
|
||||
"REJECTED": 5
|
||||
},
|
||||
"inbox_pending": 0,
|
||||
"orphan_held": 0,
|
||||
"error": null,
|
||||
"connected_at": "2026-11-02 09:07:30",
|
||||
"last_error": "",
|
||||
"stat": {
|
||||
"rx": 14,
|
||||
"tx": 26,
|
||||
"trades": 0,
|
||||
"rejects": 0,
|
||||
"reconnects": 0,
|
||||
"dropped": 0,
|
||||
"last_rx_at": "09:08:20",
|
||||
"last_tx_at": "09:08:20",
|
||||
"hs_server_seq": 1569698,
|
||||
"hs_last_seq": 1569698,
|
||||
"snap_positions_at": "09:08:00",
|
||||
"snap_positions_n": 2,
|
||||
"snap_funds_at": "09:08:00",
|
||||
"seq_hwm": 1569713,
|
||||
"peer_skew_ms": 34,
|
||||
"peer_skew_min": 28,
|
||||
"peer_skew_max": 44
|
||||
}
|
||||
},
|
||||
"cash": {
|
||||
"source": "ws",
|
||||
"cash_avail": 1912221.0,
|
||||
"total_asset": 1995983.0,
|
||||
"account_market_value": 83762.0,
|
||||
"frozen_cash": 0.0,
|
||||
"age_sec": 21.2,
|
||||
"why": ""
|
||||
},
|
||||
"positions": {
|
||||
"original": [
|
||||
{
|
||||
"ts_code": "300124.SZ",
|
||||
"total_qty": 200,
|
||||
"book_id": "original"
|
||||
},
|
||||
{
|
||||
"ts_code": "601126.SH",
|
||||
"total_qty": 2700,
|
||||
"book_id": "original"
|
||||
}
|
||||
],
|
||||
"micro30": []
|
||||
},
|
||||
"reconciliation": {
|
||||
"ok": true,
|
||||
"diffs": [],
|
||||
"fixes": [],
|
||||
"errors": [],
|
||||
"severity": "OK",
|
||||
"source": "ws",
|
||||
"note": "策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略"
|
||||
},
|
||||
"cash_difference": 0.0,
|
||||
"new_rejects": [],
|
||||
"new_trades": [],
|
||||
"new_orders": [],
|
||||
"active_children": []
|
||||
},
|
||||
"latest_160_messages_contiguous": true,
|
||||
"verification": {
|
||||
"specific_cases": 8,
|
||||
"local_full": "ALL SUITES PASS",
|
||||
"candidate_full": "ALL SUITES PASS",
|
||||
"candidate_network": "none",
|
||||
"candidate_resource_limit": "1CPU/512MiB",
|
||||
"source_matches_running_ws": true,
|
||||
"new_strategy_field_seen_by_qmt": false,
|
||||
"no_synthetic_order": true
|
||||
},
|
||||
"automation": {
|
||||
"id": "30-pms",
|
||||
"status": "deleted",
|
||||
"tool_confirmed": true
|
||||
},
|
||||
"initial_deploy_preflight": "第一次一致性检查在任何发布写操作前中止;相同断言重新采样通过后发布,未主动重连绕过检查。"
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue