用后续到期终态核验已平仓卖出更正

This commit is contained in:
baobao 2026-11-19 16:51:45 +08:00
parent fbe4fe68dc
commit d99d658e48
3 changed files with 44 additions and 3 deletions

View File

@ -338,6 +338,22 @@ def _order_fields(order, amended, quantity, received):
return fields
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')
@ -390,7 +406,9 @@ def _apply(row, *, recovery=None):
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']))
@ -451,7 +469,8 @@ def _apply(row, *, recovery=None):
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

@ -72,8 +72,15 @@ def plan():
'无法完整证明迁移后的当前平仓轮次')
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 = data(amendment_seq, 'order_update', code)
terminal = data(terminal_seq, 'order_update', code)
require(amendment['payload']['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
@ -95,7 +102,7 @@ def plan():
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}),
'balancing_trade_seq':late_seq,'balancing_sell':quantity}})
'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}

View File

@ -236,6 +236,21 @@ class ServiceTests(unittest.TestCase):
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)