tradingSystem/app/services/execution_orders.py

152 lines
7.1 KiB
Python

"""共用报价及撤换。撤单请求不释放数量,实际终态及成交入账后才可重报。"""
from contextlib import nullcontext
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 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)
qty, done = int(order['qty']), int(order.get('cum_qty') or 0)
if qty <= 0 or done < 0 or done > qty:
raise ValueError('子单累计成交数量异常')
if order.get('status') == 'FILLED' and done != qty:
raise ValueError('全成子单累计成交不完整')
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
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)