501 lines
30 KiB
Python
501 lines
30 KiB
Python
"""两条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
|