tradingSystem/app/services/execution_orders.py

245 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""共用报价及撤换。撤单请求不释放数量,实际终态及成交入账后才可重报。"""
from contextlib import nullcontext
import hashlib
from datetime import datetime
from app.core import execution_policy as policy, strategy_book as books
from app.repo import pms_repo, qmt_repo, execution_repo
from app.services import param_store
from config.settings import settings
def enabled():
return param_store.get_bool('PMS_EXEC_REPRICE_ENABLED', False)
def account_guard():
if settings.INFRA_STRATEGY_BOOK_SCHEMA:
from app.repo import rotation_repo
return rotation_repo.account_guard()
return nullcontext()
def _receipt_time(value):
try:
parsed = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace('Z', '+00:00'))
return policy.local_now(parsed) # 本端数据库 DATETIME 按已核实的北京时间解释。
except (ValueError, TypeError):
return None
def order_correction(order, *, require_current=False):
"""只接受修正事务已保存且与出口累计数一致的审计投影。"""
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
return None
from app.repo import rotation_repo
iid = order['instruction_id']
value, _ = rotation_repo.get('order-correction:'+hashlib.sha256(iid.encode()).hexdigest())
if value is None:
return None
if (not isinstance(value, dict) or value.get('instruction_id') != iid or
not 0 <= int(value.get('cum_qty', -1)) <= int(order['qty']) or
(require_current and int(value['cum_qty']) != int(order.get('cum_qty') or 0)) or
int(value.get('correction_seq') or 0) <= 0 or _receipt_time(value.get('received_at')) is None):
raise ValueError('委托成交修正审计与当前累计量不一致,等待核对')
return value
def effective_filled(order):
qty, done = int(order['qty']), int(order.get('cum_qty') or 0)
if qty <= 0 or not 0 <= done <= qty:
raise ValueError('子单累计成交数量异常')
if order.get('status') == 'FILLED' and done != qty and not order_correction(order, require_current=True):
raise ValueError('全成子单累计成交不完整,且没有已核实的成交修正')
return done
def settlement_cutoff(order):
"""释放资金必须使用修正消息之后的快照,不能沿用早于修正的原终态时间。"""
final = _receipt_time(order.get('final_at'))
if final is None:
return None
audit = order_correction(order)
if audit:
return max(final, _receipt_time(audit['received_at']))
return final
def correction_blocker(parent=None, *, ts_code=None, side=None):
parent = parent or {}
if (parent.get('progress') or {}).get('trade_correction_hold'):
return '父指令成交数量已修正,停止自动续单和改价;后续须另行明确安排'
progress = parent.get('progress') or {}
if parent.get('origin_type') == 'strategy' and parent.get('origin_id'):
with books.scope('all'):
strategy = pms_repo.get_strategy(parent['origin_id'])
if progress.get('stype') == 'GRID' or (strategy or {}).get('type') == 'GRID':
if not strategy or strategy.get('status') != 'ACTIVE' or strategy.get('archived_at'):
return '来源网格策略已停止或不可核实,旧指令不再下发'
state = strategy.get('state') or {}
if state.get('correction_hold'):
return '来源网格正在核实成交修正,停止旧指令下发'
epoch = (state.get('trade_correction') or {}).get('correction_id')
if epoch != progress.get('strategy_correction_id'):
return '来源网格的成交已修正,旧版本指令不能继续下发'
side = side or parent.get('side')
code = ts_code or parent.get('ts_code')
if not execution_repo.pending_corrections():
return ''
if side == 'buy':
return '账户存在待核实成交修正,暂停新增买入和释放资金占用'
else:
if not code:
return '成交修正涉及证券无法核实,暂停新增委托'
# 修正原文证券字段缺失或冲突时,仍按本端出口身份拦住该股的新父指令。
children = qmt_repo.list_orders(ts_code=code, limit=10001)
if len(children) >= 10001:
return '该股出口历史超过核验上限,等待成交修正核对'
if execution_repo.pending_corrections(ts_code=code, child_ids=[r['instruction_id'] for r in children]):
return '该证券存在待核实成交修正,暂停新增委托和改价'
return ''
def prepare_send(instruction_id):
"""与修正收件串行检查,成功标记之后才允许WS实际发送。"""
with account_guard(), books.scope('all'):
order = qmt_repo.get_order(instruction_id)
if not order:
return {'marked': False, 'blocked': '委托不存在'}
parent = pms_repo.get_instruction(order['parent_id'])
blocked = correction_blocker(parent, ts_code=order['ts_code'], side=order['side'])
if blocked:
return {'marked': False, 'blocked': blocked}
return {'marked': qmt_repo.mark_send_attempt(instruction_id), 'blocked': ''}
def quote_order(side, quote, now=None, user_limit=None, anchor_price=None):
return policy.price_order(side=side, quote=quote, now=now, user_limit=user_limit,
anchor_price=anchor_price, params={
'allow_minute': param_store.get_bool('PMS_EXEC_ALLOW_MINUTE_QUOTE', True),
'quote_max_age_sec': param_store.get_int('PMS_EXEC_QUOTE_MAX_AGE_SEC', 15),
'minute_max_age_sec': param_store.get_int('PMS_EXEC_MINUTE_MAX_AGE_SEC', 90),
'offset_ticks': param_store.get_int('PMS_EXEC_PRICE_OFFSET_TICKS', 1),
'max_slippage_pct': param_store.get_float('PMS_EXEC_MAX_SLIPPAGE_PCT', .01),
'minute_slippage_pct': param_store.get_float('PMS_EXEC_MINUTE_SLIPPAGE_PCT', .002)})
def replacement_state(parent_id):
with books.scope('all'):
parent = pms_repo.get_instruction(parent_id)
if not parent:
raise ValueError('父指令不存在')
orders = qmt_repo.orders_for_parent(parent_id)
filled, live, seen = 0, [], set()
for order in orders:
iid = order['instruction_id']
if iid in seen:
raise ValueError('重复子单编号')
seen.add(iid)
done = effective_filled(order)
filled += done
if order.get('status') not in qmt_repo.FINAL:
live.append(order)
booked, target = int(parent.get('exec_qty') or 0), int(parent['qty'])
if max(booked, filled) > target:
raise ValueError('已成交数量超出父指令,等待核对')
pending_trades = execution_repo.pending_trades(list(seen))
remaining = max(0, target-max(booked, filled))
missing = [c.get('ref') for c in (parent.get('progress') or {}).get('children', [])
if c.get('ref') and c.get('ref') not in seen]
ready = not live and booked >= filled and not pending_trades and not missing
return {'ready': ready, 'pending': not ready, 'confirmed_filled': max(booked, filled),
'remaining': remaining, 'active': live, 'orders': orders,
'pending_trades': pending_trades, 'booked': booked, 'missing_orders': missing}
def code_settlement_blocker(ts_code):
"""跨父指令与策略检查迟到成交,不因旧父指令本地终态而再次建仓。"""
with books.scope('all'):
parents = pms_repo.list_instructions(ts_code=ts_code, limit=10001, include_archived=True)
if len(parents) >= 10001:
return '该股历史指令超过核验上限,等待核对'
for parent in parents:
state = replacement_state(parent['instruction_id'])
if state['pending_trades'] or state['booked'] < state['confirmed_filled'] or state['missing_orders']:
return '该股已有成交或旧委托尚未核实入账'
return ''
def next_child_id(parent_id):
numbers = [0]
prefix = parent_id+'_D'
for row in qmt_repo.orders_for_parent(parent_id):
iid = row['instruction_id']
if not iid.startswith(prefix) or not iid[len(prefix):].isdigit():
raise ValueError('父指令存在无法核实序号的子单')
numbers.append(int(iid[len(prefix):]))
return prefix+str(max(numbers)+1).zfill(2)
def retry_reason(parent_id, now=None):
"""拒单和发送失败退避;普通到期及正常撤换不消耗此预算。"""
history = qmt_repo.orders_for_parent(parent_id)
if not history or history[-1].get('status') not in ('REJECTED', 'SEND_FAILED'):
return ''
last = history[-1]
code, count = last.get('reject_code'), 0
for row in reversed(history):
if row.get('status') not in ('REJECTED', 'SEND_FAILED') or row.get('reject_code') != code:
break
count += 1
at = last.get('final_at') or last.get('sent_at') or last.get('created_at')
if not hasattr(at, 'tzinfo'):
at = policy.timestamp(at)
if at is None:
return '拒单时间不可核实,等待核对'
base = max(1, param_store.get_int('PMS_EXEC_REJECT_COOLDOWN_SEC', 60))
cap = max(base, param_store.get_int('PMS_EXEC_REJECT_MAX_COOLDOWN_SEC', 900))
wait = min(cap, base*2**min(max(0, count-1), 8))
left = wait-(policy.local_now(now)-policy.local_now(at)).total_seconds()
return f'委托连续拒绝或发送失败,退避等待 {max(0, int(left))} 秒:{code or "原因见回执"}' if left > 0 else ''
def request_replace(parent_id, reason, now=None):
from app.services import dispatcher
with account_guard(), books.scope('all'):
parent = pms_repo.get_instruction(parent_id)
if not parent:
raise ValueError('父指令不存在')
progress = dict(parent.get('progress') or {})
if not progress.get('replacement_requested'):
progress['replacement_requested'] = {'at': policy.local_now(now).isoformat(), 'reason': reason}
if not pms_repo.update_instruction(parent_id, progress=progress):
raise RuntimeError('撤换请求没有写入父指令')
result = dispatcher.cancel(instruction_id=parent_id, dispatch_ref=parent.get('dispatch_ref'))
if not result.get('ok'):
raise RuntimeError('撤换请求未成功落表:'+str(result.get('error')))
state = replacement_state(parent_id)
return {'requested': True, **state}
def should_replace(parent, desired, now=None):
"""仅比较同轮报价;失败重试次数和间隔由实际子单历史决定。"""
if desired.get('action') != 'FIRE':
return False
if correction_blocker(parent):
return False
orders = qmt_repo.orders_for_parent(parent['instruction_id'])
live = [o for o in orders if o.get('status') not in qmt_repo.FINAL]
if not live or any(o.get('cancel_state') in ('REQUESTED', 'SENT') for o in live):
return False
cap = max(0, param_store.get_int('PMS_EXEC_REPRICE_MAX_ATTEMPTS', 0))
if cap and len(orders) >= cap:
return False
gap = max(1, param_store.get_int('PMS_EXEC_REPRICE_TICKS', 2))*.01
min_age = max(0, param_store.get_int('PMS_EXEC_REPRICE_MIN_SEC', 60))
current = policy.local_now(now)
for order in live:
at = order.get('sent_at') or order.get('created_at')
if at is None:
return False
if not hasattr(at, 'tzinfo'):
at = policy.timestamp(at)
if at is None or (current-policy.local_now(at)).total_seconds() < min_age:
return False
return any(abs(float(o['limit_price'])-desired['limit_price'])+1e-8 >= gap for o in live)