"""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_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()