QMT下单报文增加所属策略类型

This commit is contained in:
baobao 2026-11-02 09:02:22 +08:00 committed by Codex deployment
parent 7ff397ba22
commit 4059b6f1ba
6 changed files with 154 additions and 6 deletions

View File

@ -1,6 +1,6 @@
# PMS ↔ QMT · WebSocket 指令与回报协议
> 版本:**V1.0.1**(2026-07-30)——V1.0 定稿(2026-07-28)+ 两处澄清,**消息集与状态机一字未动**,V1.0 的实现无需改动即合规。Q1~Q11 与 R1/R2 均已答复回填(见 §10),双方据此实现。
> 版本:**V1.0.2**(2026-11-02)——`place_order.payload`新增`strategy_type`策略类型,其他业务字段、信封版本及状态机保持。历史变更见§11。
> 后续变更一律版本号递增。**变更记录(§11)按版本号从旧到新排列,读到最后一行才是当前版本**——曾因 V1.0 排在 V0.9.2 之上,对端漏掉了 `ack_seq`(§4.5)。
> 双方:**PMS**(tradingSystem,持仓管理系统,指令发起方)· **QMT**(券商终端侧执行服务,指令执行方)
> 本文档取代 `QMT_INTERFACE_REQUIREMENTS.md` 中 B 部分的表通道方案。A 部分(只读数据)与 C 部分(切换约定)继续有效。
@ -174,6 +174,7 @@ def sign(seed_hex, canon):
"limit_price": 12.35,
"valid_until": 1769512500000,
"intent": "TRIM",
"strategy_type": "subjective_quant",
"note": "保垫减仓·垫厚先收"
}
```
@ -187,12 +188,17 @@ def sign(seed_hex, canon):
| `limit_price` | number | **必填**,2 位小数。PMS 的择时模块负责定价,QMT 不做价格决策。不接受 null |
| `valid_until` | int | 有效期截止,epoch 毫秒。到期仍未全成,QMT **自动撤单**并回 `EXPIRED` 终态 |
| `intent` | string | `OPEN`/`FILL`/`ADD`/`DCA`/`TRIM`/`EXIT`/`T0`,仅归类 |
| `strategy_type` | string | `subjective_quant`:主观量化;`micro_rotation`:微盘轮动。用于QMT分类、展示和人工操作,不改变价格、数量或执行规则。新PMS下单必带,历史报文可能没有此字段 |
| `note` | string | ≤ 200 字,人工看盘用,QMT 原样落库即可 |
`valid_until` 是这套设计里替代「10 秒轮询撤单」的关键:PMS 不必盯着撤,到点 QMT 自己收。
2026-10-28补充:155模拟实例可启用`PMS_EXEC_QMT_PRICE_MONITOR`。已生成的计划由PMS给出限价、数量和有效期,即可提交QMT等待成交,不再等待现价进入区间。买单限价为执行区间上沿,卖单为下沿;买入可在更低价格成交,卖出可在更高价格成交。这不是上下界条件单,协议字段没有增加。用户暂停、资金占用、配额、可卖量和回报入账仍由PMS负责。原执行模式默认保留,不改变其他实例。
2026-11-02补充:策略类型取自父指令的持久账本归属,适用于买入、卖出、补单及重发。主观量化为微盘筹资的卖单仍为`subjective_quant`,不能按当前轮换阶段或备注判断。内部账本`original`对应`subjective_quant`,`micro30`对应`micro_rotation`,50只版本不改变标识。`note`等原有字段原样保留,撤单与查询报文不加字段。策略来源暂时无法核实时保留队列,不误标为另一策略。
QMT需读取并保存该字段,可按上述映射显示中文;兼容既有无此字段的历史订单。验签仍按收到的完整payload规范化,包含新增字段,不能先按旧字段白名单重建payload后验签。信封`v=1`与握手`protocol=1`不变;历史签名测试向量保持原样。
### 4.3 `cancel_order` —— 撤单
```json
@ -540,3 +546,4 @@ QMT 侧如有本表未覆盖的拒绝场景,请在定稿时补充,**不要
| V0.9.2 | 2026-07-28 | 回填 QMT 侧 Q1~Q11 答复(§10),并据此补齐四处:①新增下行消息 **`ack_seq` 累积确认**(§4.5)——对方的「按最后未 ack 的消息续发」实现依赖它,原协议缺失 ②`trade_no` 定为 `{broker_order_id}#{n}`(§5.5)——券商原生只有委托号,一委托多成交时无法逐笔去重 ③手续费**不摊入持仓成本**、新增 `fee_estimated` 标志(§5.5)——对方明确逐笔费用可能有误差,避免污染安全垫 ④`CANCELLED`/`EXPIRED` 改由 PMS 侧自记(§7.2),不再要求下游区分。另记录 `total_filled` 口径存疑及规避方式(§10.2)。剩余阻塞项收敛为 R1/R2 两条(§10.1) |
| **V1.0** | 2026-07-28 | **定稿**。回填 R1/R2:旧通道**即刻停用**、端点定为 `ws://192.168.16.98:8080`;补 §10.1.1 部署前检查清单(白名单、公钥交换、Redis 持久化、密钥只走 `.env`);调整 §9 灰度策略(旧通道已停,无从并行,改为小仓位实跑) |
| V1.0.1 | 2026-07-30 | 依 07-30 联调实测澄清两处,**不改消息集与状态机**:①§7.3 `BAD_PARAM` 的含义由「价格精度超限」扩为「价格不合法(精度超限或限价越界)」,并补一段与 `LIMIT_UP`/`LIMIT_DOWN` 的分界说明——原表对「限价超出当日涨跌停区间」没有落点,实测该单既未被拒也未成交,一路挂到 `EXPIRED` ②本表顺序修正:V1.0 那行原排在 V0.9.2 之上,导致对端读到「定稿」即止、漏掉 V0.9.2 引入的 `ack_seq`(§4.5),进而形成 ack→reject 自激循环。**顺序修正不涉及任何条款变更** |
| V1.0.2 | 2026-11-02 | 下单业务体新增`strategy_type`,按父指令账本区分主观量化与微盘轮动;其余下单字段、撤单、信封与握手版本、签名算法及状态机不变。新增字段参与完整payload签名,历史测试向量不变 |

View File

@ -370,7 +370,7 @@ def parse(raw, *, peer_pubkey_b64: str) -> dict:
# ================================================================ 各类下行 payload
def place_order_payload(*, instruction_id: str, ts_code: str, side: str, qty: int,
limit_price, valid_until: int, intent: str = "OPEN",
note: str = "") -> dict:
note: str = "", strategy_type: str = None) -> dict:
"""§4.2。落地前把易错项一次性校验干净 —— 宁可在本地报错, 不要换 QMT 一个 BAD_PARAM。"""
side = str(side or "").lower()
if side not in ("buy", "sell"):
@ -395,9 +395,14 @@ def place_order_payload(*, instruction_id: str, ts_code: str, side: str, qty: in
intent = "OPEN"
if len(str(instruction_id or "")) > 64 or not instruction_id:
raise CodecError("BAD_PARAM", f"instruction_id 长度须在 1~64, 收到 {instruction_id!r}")
return {"instruction_id": str(instruction_id), "ts_code": str(ts_code), "side": side,
"qty": qty, "limit_price": px, "valid_until": int(valid_until),
"intent": intent, "note": str(note or "")[:200]}
payload = {"instruction_id": str(instruction_id), "ts_code": str(ts_code), "side": side,
"qty": qty, "limit_price": px, "valid_until": int(valid_until),
"intent": intent, "note": str(note or "")[:200]}
if strategy_type is not None:
if strategy_type not in ("subjective_quant", "micro_rotation"):
raise CodecError("BAD_PARAM", "未知策略类型")
payload["strategy_type"] = strategy_type
return payload
def cancel_order_payload(*, cancel_id: str, instruction_id: str) -> dict:

View File

@ -205,6 +205,21 @@ def _parent_of(instruction_id: str, parent_id=None) -> str:
return tail[0] if len(tail) == 2 and tail[1].isdigit() else iid
def order_strategy_type(parent_id: str) -> str:
"""下单报文按持久父指令的账本归类,不用备注、当前阶段或调用上下文猜测。"""
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
return "subjective_quant" # 未启用分策略账本的既有实例只有主观量化。
from app.core import strategy_book as books
from app.repo import pms_repo
with books.scope('all'):
parent = pms_repo.get_instruction(parent_id)
types = {books.ORIGINAL: "subjective_quant", books.MICRO: "micro_rotation"}
book = (parent or {}).get('book_id')
if book not in types:
raise RuntimeError('委托的策略来源无法核实')
return types[book]
def _ws(*, instruction_id, ts_code, side, qty, limit_price, valid_until, intent=None,
parent_id=None, note=None) -> dict:
"""ws 直连: 落出口队列即返回, 实际发送由 pms-ws 常驻进程完成。

View File

@ -900,8 +900,11 @@ class WsRunner:
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)
@ -914,7 +917,7 @@ class WsRunner:
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)
if not await _db(qmt_repo.mark_send_attempt, iid):
continue # 同时发生撤单或状态改变,不再发送。
await self._send(wsc.T_PLACE, payload, seed, corr_id=iid)

View File

@ -5,6 +5,7 @@
运行: docker compose run --rm pms-web python scripts/run_tests.py
包含 (例数按 2026-10-26 隔离回归实跑校正):
test_batch53_units.py QMT下单策略类型、原字段与签名、双策略买卖归属及读取故障保留队列 (8例)
test_batch52_units.py 当日限价、撤单拒绝、迟到成交、发送恢复与真实SQL状态保护 (22例)
test_batch51_units.py 跨日决策复核、撤单回报、数量约束、人工确认与真实SQL事务及完整选股接线 (36例)
test_batch50_units.py QMT限价等待、价格来源故障、用户暂停、配额防重、试算隔离及收盘边界 (17例)
@ -183,6 +184,7 @@ import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
SUITES = [
"test_batch53_units.py",
"test_batch52_units.py",
"test_batch51_units.py","test_core_units.py", "test_batch2_units.py", "test_batch3_units.py",
"test_batch4_units.py", "test_batch5_units.py", "test_batch6_units.py",

View File

@ -0,0 +1,116 @@
"""QMT策略类型扩展:保留原报文、签名覆盖及真实发送出口的策略归属。"""
import unit_test_guard
import asyncio
import copy
import os
import sys
import unittest
from contextlib import ExitStack
from unittest.mock import AsyncMock, patch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config.settings import settings
from app.core import ws_codec as wsc, strategy_book as books
from app.repo import pms_repo, qmt_repo
from app.services import dispatcher, execution_conflicts
from app.ws.runner import WsRunner
BASE = dict(instruction_id='P_D01', ts_code='600000.SH', side='buy', qty=200,
limit_price=12.35, valid_until=9999999999999, intent='OPEN', note='原始备注不变')
class StrategyPayloadTest(unittest.TestCase):
def test_only_adds_strategy_type(self):
self.assertEqual(wsc.place_order_payload(**BASE), BASE)
for kind in ('subjective_quant', 'micro_rotation'):
self.assertEqual(wsc.place_order_payload(**BASE, strategy_type=kind),
dict(BASE, strategy_type=kind))
def test_unknown_type_does_not_silently_mislabel(self):
for kind in ('original', 'micro30', '', 'unknown'):
with self.assertRaises(wsc.CodecError):
wsc.place_order_payload(**BASE, strategy_type=kind)
def test_strategy_type_is_signed(self):
seed = '01'*32 # 独立测试向量,不读取业务签名环境。
body = wsc.place_order_payload(**BASE, strategy_type='micro_rotation')
env = wsc.build('place_order', body, seed_hex=seed, msg_id='m-test')
self.assertEqual(wsc.parse(wsc.dumps(env), peer_pubkey_b64=wsc.public_key_b64(seed))['payload'], body)
env['payload']['strategy_type'] = 'subjective_quant'
with self.assertRaises(wsc.CodecError) as ctx:
wsc.parse(wsc.dumps(env), peer_pubkey_b64=wsc.public_key_b64(seed))
self.assertEqual(ctx.exception.code, 'SIG_INVALID')
def test_legacy_instance_stays_original_without_parent_read(self):
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
patch.object(pms_repo, 'get_instruction') as read:
self.assertEqual(dispatcher.order_strategy_type('P'), 'subjective_quant')
read.assert_not_called()
def test_cancel_payload_is_unchanged(self):
self.assertEqual(wsc.cancel_order_payload(cancel_id='C', instruction_id='P_D01'),
{'cancel_id': 'C', 'instruction_id': 'P_D01'})
class StrategyOutboxTest(unittest.TestCase):
def drain(self, parent, *, side='buy', lookup_error=None):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
runner = WsRunner()
row = dict(BASE, side=side, parent_id='P', status='SENDING', cancel_state='NONE')
scopes = []
def read(_):
scopes.append(books.CURRENT.get())
if lookup_error:
raise lookup_error
return copy.deepcopy(parent)
try:
with ExitStack() as stack:
for obj, name, kw in [
(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', {'new': True}),
(qmt_repo, 'next_queued', {'return_value': [row]}),
(qmt_repo, 'get_order', {'return_value': row}),
(qmt_repo, 'claim_order', {'return_value': True}),
(qmt_repo, 'mark_send_attempt', {'return_value': True}),
(qmt_repo, 'mark_sent', {}),
(pms_repo, 'get_instruction', {'side_effect': read}),
(execution_conflicts, 'queued_buy_blocker', {'return_value': None}),
]:
stack.enter_context(patch.object(obj, name, **kw))
send = stack.enter_context(patch.object(runner, '_send', new_callable=AsyncMock))
retry = stack.enter_context(patch.object(qmt_repo, 'requeue_order'))
loop.run_until_complete(runner._drain_outbox('unused'))
return send, retry, scopes
finally:
loop.close()
asyncio.set_event_loop(None)
def test_both_books_and_sides_use_parent_not_current_scope_or_profile(self):
for book, expected in [('original', 'subjective_quant'), ('micro30', 'micro_rotation')]:
for side in ('buy', 'sell'):
# 原策略减持筹资也可能采用rotation执行方式,仍归主观量化。
parent = {'book_id': book, 'progress': {'execution_profile': 'rotation'}}
with books.scope('micro30' if book == 'original' else 'original'):
send, retry, scopes = self.drain(parent, side=side)
send.assert_awaited_once()
self.assertEqual(send.call_args.args[:2],
('place_order', dict(BASE, side=side, strategy_type=expected)))
self.assertEqual(send.call_args.kwargs, {'corr_id': BASE['instruction_id']})
self.assertEqual(scopes, ['all'])
retry.assert_not_called()
def test_missing_or_unknown_parent_keeps_queue_without_send(self):
for parent in (None, {}, {'book_id': 'other'}):
send, retry, _ = self.drain(parent, side='sell')
send.assert_not_called()
retry.assert_called_once()
self.assertFalse(retry.call_args.args[-1])
def test_parent_lookup_failure_keeps_queue_without_send(self):
send, retry, _ = self.drain(None, lookup_error=RuntimeError('temporary read failure'))
send.assert_not_called()
retry.assert_called_once()
self.assertFalse(retry.call_args.args[-1])
if __name__ == '__main__':
unittest.main()