Compare commits

..

5 Commits

Author SHA1 Message Date
baobao 1fd640bffb 记录155补账发布验收和换机接续 2026-11-19 17:01:38 +08:00
baobao 6a10784019 保留抵销晚到卖出的逐笔序号 2026-11-19 16:54:42 +08:00
baobao b687a39230 按委托标识关联到期回报 2026-11-19 16:53:52 +08:00
baobao d99d658e48 用后续到期终态核验已平仓卖出更正 2026-11-19 16:51:45 +08:00
baobao fbe4fe68dc 按关联卖出逐笔核对模拟仓剩余资金差 2026-11-19 16:40:40 +08:00
7 changed files with 262 additions and 12 deletions

View File

@ -1,5 +1,11 @@
# 开发节点记录(三系统量化交易)
## 2026年11月19日 155恢复累计盈亏、委托防重与账本对齐
16:58完成两组卖出补账并启动最终worker `6a10784`,网页和唯一QMT连接为`7d2cc0e`。实际三个角色候选各通过92组断网回归。17:00:46复核50只持仓零差异、现金同为284,704.74元,待入账、孤儿和PMS在途均为零。仅替换155对应三个容器,原执行开关已恢复,未访问188。
14笔工作台晚到买入按原策略补记,奥精医疗两笔共8,600股;累计盈亏恢复显示为-20,746.00元。微盘建仓当日有效,已发同股同向当日撤销或过期不自动重报;盘中自然样本和QMT工作台操作审计待核。证据、资金差推导和换机指引见[155模拟仓重复成交与导出验收](docs/155模拟仓重复成交与导出验收_2026-11-19.md#盘后补账和运行验收)。
## 2026年11月19日 155模拟仓差异与公示导出
16:07 仅重建155网页容器,运行 `pms:publish-xlsx-13028a1-web`。候选镜像在155断网回归90组通过,实际导出文件和图表均核验。16:08 只读复核仍有14项超批准数量的真实成交差异,未改账或发单,未访问188。逐股明细和发布回执见[155模拟仓重复成交与导出验收](docs/155模拟仓重复成交与导出验收_2026-11-19.md)。

View File

@ -142,7 +142,7 @@ def _float(v):
# ================================================================ trading_order
def sim_buy_fill_evidence(child_id, broker_id):
def sim_fill_evidence(child_id, broker_id):
"""仅模拟委托的源记录;不改下游数据库。"""
if T_ORDER != 'trading_order' or T_POSITION != 'trading_position':
raise ValueError('不能从非模拟表读取补账证据')

View File

@ -125,7 +125,7 @@ def _pair(row):
return payload, amendment, originals, amendments
def _load_evidence(original, order, parent):
def _load_evidence(original, order, parent, *, recovery=None):
"""分别读取单表,在服务层按本端父指令归属组合完整证据。"""
code, book = parent['ts_code'], parent['book_id']
orders = repo.orders_for_code(code)
@ -136,6 +136,10 @@ def _load_evidence(original, order, parent):
continue
pid = child.get('parent_id')
current = parents.get(pid) or pms_repo.get_instruction(pid)
if recovery and not current and child.get('status') in qmt_repo.FINAL and child.get('final_at'):
finalized = _stamp(child['final_at'])
if finalized < recovery['cutover'] and pid not in recovery['lot_parents']:
continue
_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
@ -146,6 +150,8 @@ def _load_evidence(original, order, parent):
rows = repo.trades_for_orders(list(by_child))
trades, links = [], {}
for row in rows:
if recovery and row['seq'] == recovery.get('balancing_trade_seq') and row['processed'] == qmt_repo.PROC_PENDING:
continue
if row['processed'] == qmt_repo.PROC_PENDING:
raise Waiting('同股所属策略仍有原成交等待入账')
_need(row['processed'] == qmt_repo.PROC_BOOKED, '同股所属策略存在未核实的原成交')
@ -204,8 +210,8 @@ def _position_fields(position, projection):
return result
def _verify_physical(code, book, projection, received_at):
if projection['qty_before'] == projection['qty_after']:
def _verify_physical(code, book, projection, received_at, *, balancing_sell=0):
if projection['qty_before'] == projection['qty_after'] and not balancing_sell:
return
snap = qmt_repo.latest_snapshot('positions')
if not snap or snap.get('age_sec') is None or not 0 <= snap['age_sec'] <= 60:
@ -233,7 +239,7 @@ def _verify_physical(code, book, projection, received_at):
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']
total = sum(_q(r['total_qty']) for r in positions if r['book_id'] != book)+projection['qty_after']-balancing_sell
_need(total == physical, '更正后双策略数量与QMT实际持仓不一致')
@ -332,7 +338,23 @@ def _order_fields(order, amended, quantity, received):
return fields
def _apply(row):
def _closed_recovery_terminal(amendment, terminal, order, watermark):
amended = amendment['payload']
final = terminal['payload']
_need(amendment['seq'] < terminal['seq'] <= watermark and terminal['msg_type'] == 'order_update'
and final.get('status') == 'EXPIRED' and final.get('final') is True and final.get('leaves_qty') == 0
and amended.get('status') == 'PARTIAL' and amended.get('final') is False
and _q(amended.get('leaves_qty')) == _q(order['qty']) - _q(amended.get('cum_qty'))
and 0 < _q(amended.get('cum_qty')) < _q(order['qty'])
and final.get('cum_qty') == amended.get('cum_qty')
and final.get('cum_avg_price') == amended.get('cum_avg_price')
and final.get('instruction_id') == amended.get('instruction_id') == order['instruction_id']
and final.get('broker_order_id') == amended.get('broker_order_id') == order['broker_order_id'],
'配对部分成交后没有一致的已确认到期终态')
return final
def _apply(row, *, recovery=None):
state = qmt_repo.get_state() or {}
watermark = state.get('last_seq')
if not isinstance(watermark, int) or watermark < int(row['seq']):
@ -369,7 +391,8 @@ def _apply(row):
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)
options = {'recovery': recovery} if recovery else {}
orders, parents, trades, links = _load_evidence(original, order, parent, **options)
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,
@ -383,7 +406,9 @@ def _apply(row):
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'])))
closed_terminal = (recovery or {}).get('closed_terminals', {}).get(row['seq'])
order_am = _closed_recovery_terminal(amendment, closed_terminal, order, watermark) if closed_terminal else am
order_fields = _order_fields(order, 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']))
@ -395,7 +420,8 @@ def _apply(row):
'父指令执行量与旧逐笔合计不符或更正后超量')
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)
physical_options = {'balancing_sell': recovery['balancing_sell']} if recovery else {}
_verify_physical(code, book, projection, received, **physical_options)
cash_options = {'verified_price_only': True} if price_only_overfill else {}
cash_before, cash_after = _cash_projection(original, book, payload['side'], projection, am, order, **cash_options)
projected_orders = [{**r, **order_fields} if r['instruction_id'] == iid else r for r in orders]
@ -443,7 +469,8 @@ def _apply(row):
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'],
'amendment_seq': amendment['seq'], 'confirmed_terminal_seq': closed_terminal['seq'] if closed_terminal else None,
'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'],

View File

@ -44,3 +44,25 @@
恢复边界:PMS命令仍约束下发数量;实际成交必须按原券商委托和原策略入账,即使超出授权也不能删除事实、扩大授权或再派单。防重同时作用于入队前和发往QMT前。同股同向已发委托当日报撤销或过期,不自动另发;未发即作废、其他股票与方向不因此被拦。同编号的幂等恢复仍使用原编号。微盘新建仓买单最长至北京时间当日15:00,不因分钟报价变化撤换,不突破更早的独立授权,用户撤销、标的调出和明确风控要求仍有效。
累计盈亏使用有效QMT账户总资产减已建立的账户净投入;账户收益不再因两策略内部现金差异而隐藏,不把策略现金差异当成策略收益。无可核实基线或估值时,页面提示暂不可用。补账仅在明确指定的155模拟范围内使用`reconcile_qmt_late_buys.py`,默认只读。待入账逐笔须与券商委托号、原始委托和成交记录、旧终态与随后全成、有效实际持仓、同方向及已确认父指令交叉吻合。校验只读证据的摘要后方允许写入,原始回报、授权数量和旧终态不覆盖。策略现金可反映实际超支,但不隐式划拨、不编造费用、不改初始本金。其余回报继续走既有更正机制。
## 盘后补账和运行验收
16:38(北京时间)限定在155模拟实例进行维护。排空并暂停下发后只替换网页、交易工作进程和唯一的QMT连接;先停旧连接再启新连接。网页和连接使用`pms:order-pnl-7d2cc0e-web`和`pms:order-pnl-7d2cc0e-ws`。未访问或改变188,没有发测试单,没有修改QMT原始事实。
按原始回报补入14笔晚到买入,共34,700股;奥精医疗由4,300股对齐到8,600股。随后按已核实的微盘成交更正调整11笔价格(含已入账和晚到记录),释放合计1,221元,14笔晚到买入最终本金362,209元。股数对齐后仍少3,037元,不能用数量通过代替资金核对。
两组原策略已平仓卖出解释全部3,037元。601126.SH 原记2,700股×27.04元,QMT的最终记录为2,000股×27.06元,加同父指令晚到的700股×31.32元,净增加3,036元;002979.SZ 的100股卖价由44.32元更正至44.33元,净增加1元。601126.SH 的差额更正先报部分成交,再报剩余量到期;首次尝试因为普通更正规则拒绝把已终态本地子单重新置成在途,整笔回滚。专用脚本核对同一券商委托号、成交累计量、均价、连续序号及后续到期终态后,才允许在同一事务应用更正和补记晚到卖出。普通更正仍拒绝重开已终态委托。
16:58:46,两组卖出及其累计量在同一事务入账;16:58:47 启动最终交易工作进程`pms:order-pnl-6a10784-worker`,其余18个运行容器的标识和镜像均未改变。实际使用的三个角色镜像在155各完成92组断网回归,卖出更正专项39例通过。自然调度已送达新工作进程;盘中任务按规则在收盘后跳过,没有人为触发成交或交易任务。
17:00:46(北京时间)重新核验:网页及数据库健康;QMT单连接在线,连续接收和确认水位从1,969,950推进至1,969,955,未请求重同步;QMT的50只持仓与PMS数量逐股无差异,奥精医疗两批均为4,300股、成本价6.080元,两只已平仓卖出数量仍为零。PMS与QMT现金均为284,704.74元,冻结为零,待入账、孤儿回报和PMS在途委托均为零。维护暂停已撤销,恢复原来的执行开关、买入开关和轮动控制。原策略账本现金为621,699.96元,微盘账本现金为-336,995.22元,是超预算成交后反映实际发生额;没有自动跨策略划款,不应把账户余额当成微盘可用预算。
155线上网页处理器返回的实际响应,用桌面和窄屏Chrome复核:累计盈亏显示为-20,746.00元(-1.05%),账户总资产1,947,181.74元,账户净投入1,967,927.74元;缺有效估值或基线时显示“暂不可用”。浏览器核验为实际响应的离线回放,不是登录在线账户点击。累计盈亏不等同于当前持仓浮盈亏,也不等同于单策略收益。
## 换机接续
代码与文档在 Git 分支`codex/pms-order-pnl-fix`。在另一台开发机进入同一仓库,执行`git fetch origin codex/pms-order-pnl-fix`;本地没有同名分支时使用`git switch --track origin/codex/pms-order-pnl-fix`。原始回报、账户快照、私有部署配置和写入回执只留在155的`backups/order-pnl-7d2cc0e-20261119-163833`,不跟入Git。事件补账脚本默认只读;不用旧摘要或已完成的回执重放生产写入,不把换机取代码当成发版授权。
优先看备份里的`acceptance-restored.json`、`buy-apply.json`、`buy-prices-apply.json`、`closed-sell-apply-6a10784.json`和各角色断网回归日志。需要重新部署时按发布技能选择当前实际角色镜像、核验私有覆盖和环境。代码回退不等于财务回退;不得用备份覆盖当前账本,也不要恢复到会重复下单的旧代码后直接放行。
下一交易时段只观察自然委托:检查新微盘买入的授权截止不晚于北京时间当日15:00、未发子单可正常触发、已下发的当日撤销或过期旧单不会换编号自动重报、退出和人工撤单仍可进入既有流程。若QMT继续出现工作台补记,请QMT方以券商委托号调取柜台撤单确认、工作台操作审计与补记来源,核清谁在什么环节写入;不要为验收造单或回灌已归档仓位。

View File

@ -0,0 +1,155 @@
"""155模拟仓:在同一事务复核并补齐2026年11月19日两组已平仓卖出事实。"""
import argparse
import json
from datetime import date
from decimal import Decimal
from reconcile_qmt_late_buys import check_scope, digest, require, raw_values
from app.core import recon, strategy_book as books, ws_codec
from app.repo import downstream_repo, pms_repo, qmt_repo, rotation_repo, trade_correction_repo
from app.services import ledger_service, param_store, rotation_execution, rotation_service, trade_correction
def data(seq, kind, code):
row = trade_correction_repo.get_inbox(seq)
require(row and row['msg_type'] == kind and row['payload']['ts_code'] == code
and row['payload']['side'] == 'sell', '卖出证据身份不匹配')
return row
def source(payload, effective):
child, broker, code = (payload[key] for key in ('instruction_id','broker_order_id','ts_code'))
orders, logs = downstream_repo.sim_fill_evidence(child, broker)
require(len(orders) == len(logs) == 1, 'QMT原始委托或逐笔缺失、重复')
order, record = orders[0], logs[0]
log = json.loads(record['extra_data'])
require(order['order_id'] == child and order['qmt_order_id'] == record['order_id'] == broker
and order['order_side'] == log['trade_direction'] == 'sell'
and all(downstream_repo.to_dot(row['stock_code']) == code for row in (order, record))
and log['trade_no'] == payload['trade_no']
and raw_values({'qty': log['traded_volume'], 'price': log['traded_price'],
'amount': log['traded_amount']}) == raw_values(effective)
and int(order['filled_quantity']) == int(effective['qty']), 'QMT原始卖出与有效逐笔不互证')
return order, record
def plan():
require(not qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=1), '有在途委托,不能恢复已平仓卖出')
snapshot = ledger_service.positions_source()
require(snapshot['source'] == 'ws' and 0 <= snapshot['age_sec'] <= 60
and rotation_service.reconcile_books()['ok'], '先核实完整的QMT实际持仓并消除已有数量差')
funds = qmt_repo.latest_snapshot('funds')
require(funds and 0 <= funds['age_sec'] <= 60, 'QMT资金快照过期')
physical = ws_codec.parse_funds_snapshot(funds['payload'])
capital, _ = rotation_repo.get('capital:live')
cutover = trade_correction._stamp(capital['started_at'])
expected_cash = Decimal(str(physical['available_cash'])) + Decimal(str(physical['frozen_cash']))
expected_delta = expected_cash - sum(Decimal(str(value)) for value in capital['cash'].values())
require(physical['frozen_cash'] == 0, '仍有资金冻结,暂缓补账')
evidence, amount = [], Decimal(0)
for code, correction_seqs, late_seq in (('601126.SH', (1965760,1965780),1965841), ('002979.SZ',(1965803,),None)):
corrections = [data(seq, 'trade_correction', code) for seq in correction_seqs]
require(all(row['processed'] in (qmt_repo.PROC_PENDING, qmt_repo.PROC_ORPHAN) for row in corrections)
and all(row['processed'] != qmt_repo.PROC_ORPHAN or '历史委托策略归属不完整' in row['process_note']
for row in corrections), '卖出更正状态变化或另有阻塞')
payloads = [row['payload'] for row in corrections]
original = trade_correction_repo.get_trade(payloads[0]['trade_no'])
require(original and original['processed'] == qmt_repo.PROC_BOOKED, '原卖出未入账')
first, last = payloads[0], payloads[-1]
require(raw_values(original['payload']) == raw_values(first['before']) and
all(raw_values(previous['after']) == raw_values(current['before']) for previous,current in zip(payloads,payloads[1:])),
'更正记录并非连续版本')
raw = source(original['payload'], last['after'])
order = qmt_repo.get_order(first['instruction_id'])
with books.scope(books.ORIGINAL):
parent = pms_repo.get_instruction(order['parent_id'])
position = pms_repo.get_position(code)
lots = pms_repo.list_lots(code,status=None,limit=2001)
require(parent and parent['status'] == 'CONFIRMED' and parent['book_id'] == books.ORIGINAL
and position and position['status'] == 'CLOSED' and not position.get('archived_at')
and not position['total_qty'] and lots and len(lots) < 2001
and all(lot['instruction_id'] and lot['status'] == 'CLOSED' and lot['open_date'] > cutover.date() for lot in lots),
'无法完整证明迁移后的当前平仓轮次')
late = data(late_seq,'trade',code) if late_seq else None
late_order = late_raw = final = None
closed_terminals = {}
quantity = int(first['before']['qty']) - int(last['after']['qty'])
if late:
for correction, amendment_seq, terminal_seq in zip(corrections, (1965761,1965781), (1965764,1965783), strict=True):
amendment = trade_correction_repo.get_inbox(amendment_seq)
terminal = trade_correction_repo.get_inbox(terminal_seq)
require(amendment and terminal and amendment['msg_type'] == 'order_update'
and amendment['payload'].get('correction_id') == correction['payload']['correction_id'],
'对应更正配对序号变化')
trade_correction._closed_recovery_terminal(amendment, terminal, order, qmt_repo.get_state()['last_seq'])
closed_terminals[correction['seq']] = terminal
late_trade = late['payload']
late_order = qmt_repo.get_order(late_trade['instruction_id'])
require(late['processed'] == qmt_repo.PROC_PENDING and late_trade.get('desk_backfill') is True
and late_trade['fee'] is None and quantity == raw_values(late_trade)[0]
and late_order['parent_id'] == order['parent_id'] and late_order['broker_order_id'] == late_trade['broker_order_id']
and late_order['status'] == 'CANCELLED' and int(late_order['cum_qty']) == 0,
'晚到卖出不是同一父指令可验证的补量')
late_raw = source(late_trade, late_trade)
final = [row for row in qmt_repo.inbox_list(msg_type='order_update',corr_id=late_order['instruction_id'],limit=51)
if row['seq'] > late_seq and row['payload'].get('final') is True]
require(len(final) == 1 and final[0]['payload']['status'] == 'EXPIRED'
and int(final[0]['payload']['cum_qty']) == quantity and final[0]['payload']['broker_order_id'] == late_trade['broker_order_id']
and Decimal(str(final[0]['payload']['cum_avg_price'])) == raw_values(late_trade)[1]
and final[0]['payload']['leaves_qty'] == 0, '晚到卖出终态和真实累计量不一致')
amount += raw_values(late_trade)[2]
else:
require(quantity == 0, '仅价格更正不能改变持仓数量')
amount += raw_values(last['after'])[2] - raw_values(first['before'])[2]
evidence.append({'code':code,'corrections':corrections,'raw':raw,'late':late,'late_order':late_order,
'late_raw':late_raw,'late_final':final,'position':position,'lots':lots,'parent':parent,
'recovery':{'cutover':cutover,'lot_parents':sorted({lot['instruction_id'] for lot in lots}),
'closed_terminals':closed_terminals,'balancing_trade_seq':late_seq,
'balancing_sell':quantity}})
require(abs(expected_delta - amount) <= Decimal('.02'), '逐笔本金不能解释全部剩余资金差,不写入')
return {'evidence': evidence, 'cash_before':capital['cash'], 'qmt_cash':expected_cash, 'cash_delta':amount}
def apply(plan_result):
for item in plan_result['evidence']:
for event in item['corrections']:
if event['processed'] == qmt_repo.PROC_ORPHAN:
require(qmt_repo.inbox_mark([event['seq']], processed=qmt_repo.PROC_PENDING,
note='仅经已平仓轮次核实,重新处理原始更正'), '更正挂起标记未变更')
require(trade_correction._apply(trade_correction_repo.get_inbox(event['seq'],lock=True),
recovery=item['recovery']) == 'applied', '更正没有实际入账')
late = item['late']
if late:
parent = item['parent']
mapped = recon.map_trades_to_book([late], {parent['instruction_id']:parent['action']})
require(len(mapped['actions']) == 1 and not mapped['alerts'] and not mapped['fees'], '晚到卖出映射异常')
action = dict(mapped['actions'][0], verified_trade_date=date(2026,11,19))
require(rotation_execution.book_trade(action, [], late['seq']), '晚到卖出没有原子入账')
require(qmt_repo.update_order(item['late_order']['instruction_id'], cum_qty=action['qty'],
cum_avg_price=action['price'], leaves_qty=0), '晚到卖出累计量未保存')
rotation_repo.put_once('verified-closed-sell:20261119:'+item['code'], 'verified_closed_sell', item)
require(rotation_service.reconcile_books()['ok'], '已平仓数量核对未通过,全部回滚')
capital, _ = rotation_repo.get('capital:live')
cash = sum(Decimal(str(value)) for value in capital['cash'].values())
require(abs(cash - plan_result['qmt_cash']) <= Decimal('.02'), '补记后资金仍与QMT不符,全部回滚')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply-evidence-sha256')
requested = parser.parse_args().apply_evidence_sha256
check_scope()
if not requested:
result = plan()
print(rotation_repo.encode({'sha256':digest(result), **result}))
return
with rotation_repo.account_guard():
require(param_store.get_bool('PMS_GLOBAL_EXEC_HALT',False), '先暂停交易执行')
result = plan()
require(digest(result) == requested, '卖出证据或资金较预演变化,不写入')
apply(result)
print(rotation_repo.encode({'applied':len(result['evidence']),'cash_delta':result['cash_delta'],'sha256':requested}))
if __name__ == '__main__':
main()

View File

@ -24,7 +24,8 @@ def require(condition, message):
def check_scope():
require(not settings.PMS_TABLE_PREFIX and settings.INFRA_STRATEGY_BOOK_SCHEMA
and dispatcher.mode() == 'ws' and downstream_repo.T_ORDER == 'trading_order'
and downstream_repo.T_POSITION == 'trading_position', '仅允许在155模拟PMS运行')
and downstream_repo.T_POSITION == 'trading_position'
and param_store.get('PMS_MONITOR_WATCH_SCOPE') == 'pms-sim-155', '仅允许在155模拟PMS运行')
def raw_values(payload):
@ -99,7 +100,7 @@ def plan(codes, trade_day):
with books.scope('all'):
parent = pms_repo.get_instruction(order['parent_id'])
require(parent, '待核父指令不存在')
orders, logs = downstream_repo.sim_buy_fill_evidence(child, broker)
orders, logs = downstream_repo.sim_fill_evidence(child, broker)
events = qmt_repo.inbox_list(msg_type='order_update', corr_id=child, limit=51)
require(len(events) < 51, '同一子委托的回报超出完整检查上限')
events = sorted((item for item in events if item['payload'].get('final') is True

View File

@ -212,6 +212,45 @@ class ServiceTests(unittest.TestCase):
self.assertEqual((lot['qty'],lot['realized_pnl']),(60,40.))
self.assertAlmostEqual(pms_repo.get_position(CODE)['avg_cost'],10.333)
def test_closed_recovery_excludes_only_unlinked_pre_cutover_terminal(self):
self.insert('pms_qmt_order',dict(id=90,instruction_id='PRE_D01',parent_id='PRE',ts_code=CODE,
side='buy',status='FILLED',final_at='2026-10-30T12:00:00+08:00'))
original=service.repo.get_trade('BUY')
order=qmt_repo.get_order('P_BUY_D01')
parent=pms_repo.get_instruction('P_BUY')
recovery={'cutover':NOW-dt.timedelta(days=3),'lot_parents':['P_BUY'],'balancing_sell':0}
with self.assertRaisesRegex(ValueError,'历史委托'):
service._load_evidence(original,order,parent)
rows, _, trades, _ = service._load_evidence(original,order,parent,recovery=recovery)
self.assertEqual([row['instruction_id'] for row in rows],['P_BUY_D01'])
self.assertEqual([row['seq'] for row in trades],[original['seq']])
with self.assertRaisesRegex(ValueError,'历史委托'):
service._load_evidence(original,order,parent,recovery=dict(recovery,lot_parents=['PRE']))
def test_balancing_sell_requires_final_actual_quantity(self):
self.snapshot['payload']['items']=[]
projection={'qty_before':0,'qty_after':70}
with self.assertRaisesRegex(ValueError,'实际持仓不一致'):
service._verify_physical(CODE,'original',projection,NOW)
service._verify_physical(CODE,'original',projection,NOW,balancing_sell=70)
with self.assertRaisesRegex(ValueError,'实际持仓不一致'):
service._verify_physical(CODE,'original',projection,NOW,balancing_sell=69)
def test_closed_recovery_requires_matching_later_terminal(self):
order = {'status':'FILLED','qty':100,'instruction_id':'D01','broker_order_id':'B01'}
matched = {'instruction_id':'D01','broker_order_id':'B01','cum_qty':70,'cum_avg_price':10}
amended = {'seq':11,'payload':dict(matched,status='PARTIAL',final=False,leaves_qty=30)}
terminal = {'seq':12,'msg_type':'order_update','payload':dict(matched,status='EXPIRED',final=True,leaves_qty=0)}
with self.assertRaisesRegex(ValueError,'重新进入在途'):
service._order_fields(order, amended['payload'], 70, NOW)
fields = service._order_fields(order, service._closed_recovery_terminal(amended, terminal, order, 12), 70, NOW)
self.assertEqual(fields, {'cum_qty':70,'cum_avg_price':10,'leaves_qty':0})
for mismatch in ({'broker_order_id':'other'},{'cum_qty':69},{'cum_avg_price':11}):
with self.assertRaisesRegex(ValueError,'已确认到期终态'):
service._closed_recovery_terminal(amended, dict(terminal,payload=dict(terminal['payload'],**mismatch)), order, 12)
with self.assertRaisesRegex(ValueError,'已确认到期终态'):
service._closed_recovery_terminal(amended, terminal, order, 11)
def test_other_book_same_code_is_not_modified(self):
self.insert('pms_position',dict(id=2,book_id='micro30',ts_code=CODE,total_qty=50,avail_qty=50,status='HOLDING'))
self.modify_payload(10,after=economic(150,'10'));self.modify_payload(11,cum_qty=150,cum_avg_price=10)