tradingSystem/app/services/rotation_day_orders.py

113 lines
5.9 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.

"""本日盘中授权的一篮子保护限价委托。每笔独立核对后交唯一QMT执行。"""
from decimal import Decimal
from app.core import strategy_book as books
from app.repo import pms_repo, qmt_repo, rotation_repo as store
from app.services import intraday_rotation as entry, param_store
def policy_for(progress):
ticket = progress.get('ticket')
if not ticket:
return None
policy, _ = store.get('qmt-day-orders:'+ticket)
if not policy:
return None
if policy['binding'] != entry.metadata(progress) or policy.get('account') != '155模拟':
raise ValueError('委托执行方式与盘中授权不一致')
return policy
def protected_price(parent, line, limits):
"""核对已授权价格边界与当日涨跌停。原价仅作保护,不作实时行情。"""
if any(parent[k] != line[k] for k in ('ts_code','book_id','side','qty')):
raise ValueError('保护限价与原指令不匹配')
price = Decimal(str(line['price']))
low = Decimal(str(limits.get('down_limit') or 0))
high = Decimal(str(limits.get('up_limit') or 0))
if (not all(v.is_finite() for v in (price,low,high)) or not 0 < low <= price <= high
or price != price.quantize(Decimal('.01'))):
raise ValueError('保护限价或当日价格上下限不可核实')
boundary = (parent.get('progress') or {}).get('user_limit_price') or parent.get('limit_price')
if boundary is not None:
limit = Decimal(str(boundary))
if not limit.is_finite() or (parent['side']=='buy' and price>limit) or (parent['side']=='sell' and price<limit):
raise ValueError('保护限价越过原指令价格边界')
return float(price)
def cancel_reason(parent, release, rotation, controls):
p = parent['progress']
if not release or entry.metadata(release) != entry.metadata(p):
return '本批授权已撤销或到期'
if rotation.get('consumed_entry') != release['snapshot_version']:
return '买入篮子所属轮次已结束'
if controls['halt_all'] or controls['mode'] != 'auto' or controls['control'] == 'pause_all':
return '用户暂停本批执行'
if parent['side']=='buy':
if controls['halt_buy'] or controls['control'] != 'run':
return '用户停止新增买入'
if entry.repo.buy_ban(parent['ts_code']):
return '该股已冻结或列入黑名单'
if parent['ts_code'] not in rotation.get('target',[]) or rotation.get('phase') not in ('micro','entering_micro'):
return '已调出当日买入篮子'
elif not release.get('funding_sales') or rotation.get('phase') != 'entering_micro' or controls['control'] != 'run':
return '本批筹资卖出已停止'
return ''
def execute(work):
from app.services import rotation_execution as trade, rotation_service as service, executor
results, waits = [], []
# 先处理筹资卖出;买入额度始终按QMT实际回款和账户资金保留核验。
for book, iid in sorted(work['parents'], key=lambda item: item[0] != books.ORIGINAL):
code = iid
try:
with store.account_guard(), books.scope(book):
now = entry.local_now()
parent = pms_repo.get_instruction(iid)
if not parent or parent['status'] not in service.LIVE or parent['progress'].get('cancel_requested'):
continue
code = parent['ts_code']
policy = policy_for(parent['progress'])
if not policy or iid not in policy['lines']:
continue
release = entry.read_release(now)
rotation = (store.get('state:live')[0] or {}).get('rotation',{})
reason = cancel_reason(parent, release, rotation, param_store.execution_controls())
if not reason:
reason = work['unavailable'].get(code) if parent['side']=='buy' else None
if reason:
if not executor.cancel_instruction(iid, reason=reason, arbiter='system').get('ok'):
raise RuntimeError('撤单等待确认')
continue
history = qmt_repo.orders_for_parent(iid)
if any(o['status'] not in qmt_repo.FINAL for o in history):
continue
if history and history[-1]['status']=='CANCELLED' and history[-1].get('cancel_state') not in ('REQUESTED','SENT'):
waits.append(code+'下游已撤单,等待重新授权')
continue
if not entry.session_open(now) or now.date().isoformat()!=work['day']:
continue
# 盘口时效不影响保护价;持仓与真实可用资金仍须核实。
if not service.reconcile_books()['ok']:
waits.append(code+'等待策略持仓与QMT对齐')
continue
line = policy['lines'][iid]
limits = work['limits'].get(code,{})
price = protected_price(parent,line,limits)
intent = dict(id=iid,book_id=book,ts_code=code,side=parent['side'],qty=parent['qty'],
reason='盘中篮子保护限价委托',rule_version=release['rule_version'],
quote_basis={'source':'当日授权保护限价','limit_price':price,'source_ref':line['source_ref']},
day_limits=limits,limits_date=work['day'])
result = trade.send_intent(intent,price,now,release['snapshot_version'])
if (result.get('result') or {}).get('ok'):
results.append(result)
elif result.get('state'):
waits.append(code+result['state'])
except Exception as exc:
why = str(exc)[:160] if isinstance(exc, (ValueError,RuntimeError)) else type(exc).__name__
waits.append(code+'等待执行:'+why)
return results, waits