tradingSystem/app/services/daily_buy_review.py

316 lines
16 KiB
Python
Raw Permalink Normal View History

"""跨日买入复核:停止旧单、等待真实回报、重走当日决策,再开放当日额度。"""
from copy import deepcopy
from datetime import datetime
import hashlib
from app.db.session import transaction
from app.repo import pms_repo, qmt_repo
from app.services import param_store
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
def _day(value):
try:
return int(str(value)[:10].replace('-', ''))
except (TypeError, ValueError):
return 0
def applies(ins):
return bool(ins and ins.get('side') == 'buy'
and (ins.get('progress') or {}).get('execution_profile') != 'rotation')
def _command_blocker(ins):
cid = (ins.get('progress') or {}).get('command_id')
if cid:
cmd = pms_repo.get_command(cid)
if not cmd or cmd['status'] not in ('EXECUTING', 'PARTIAL'):
return '来源命令已经结束,不能恢复旧买入安排'
return None
def blocker(ins, *, now=None):
if not applies(ins):
return None
if ins.get('status') == 'WAIT_REVIEW':
return '跨日买入尚未完成当日决策复核'
if not param_store.get_bool('PMS_DAILY_BUY_REVIEW', False):
return None
stopped = _command_blocker(ins)
if stopped:
return stopped
today = _day(now or datetime.now())
prog = ins.get('progress') or {}
if prog.get('deadline') and _day(prog['deadline']) < today:
return '买入安排已过有效期,不能继续续单'
review = prog.get('daily_review') or {}
if review.get('ymd') == today and review.get('status') == 'approved':
return None
decision_day = prog.get('decision_ymd') or _day(ins.get('created_at'))
if decision_day != today:
return '旧买入安排需按当日候选、研判、数量和价格重新复核'
return None
def _orders(ins):
"""不把终态当作零成交;出口与账本尚未一致时禁止重开额度。"""
rows = qmt_repo.orders_for_parent(ins['instruction_id'])
if len({r['instruction_id'] for r in rows}) != len(rows):
raise ValueError('出口子单重复,等待核对')
filled = 0
for row in rows:
qty, done = int(row['qty']), int(row.get('cum_qty') or 0)
if qty <= 0 or not 0 <= done <= qty:
raise ValueError('出口数量无效,等待核对')
filled += qty if row['status'] == qmt_repo.OS_FILLED else done
return rows, filled
def allowance(ins, *, now=None):
if not applies(ins):
return max(0, int(ins['qty']) - int(ins.get('exec_qty') or 0))
if blocker(ins, now=now):
return 0
review = (ins.get('progress') or {}).get('daily_review') or {}
if review.get('ymd') != _day(now or datetime.now()) or review.get('status') != 'approved':
return max(0, int(ins['qty']) - int(ins.get('exec_qty') or 0))
rows, filled = _orders(ins)
pending = sum(int(r['qty']) - int(r.get('cum_qty') or 0)
for r in rows if r['status'] not in qmt_repo.FINAL)
consumed = max(filled, int(ins.get('exec_qty') or 0)) - int(review['start_filled'])
return max(0, int(review['qty']) - max(0, consumed) - pending)
def _save(old, progress, status, reason, *, proposal=None, decision=None, arbiter='system'):
"""所有状态推进均比较旧状态、旧进度及成交量;不能复活用户已撤销的指令。"""
with transaction():
changed = pms_repo.compare_review_instruction(old, progress, status)
if not changed:
return False
if proposal and decision:
if not pms_repo.decide_proposal(proposal['proposal_id'], decision,
expected_hard=proposal['hard_numbers_json']):
raise RuntimeError('确认建议已变化,本次复核推进已回滚')
recorded = pms_repo.insert_ledger(ts_code=old['ts_code'], action='DAILY_REVIEW', arbiter=arbiter,
verdict='PASS' if status == 'PROPOSED' else 'WAIT' if status == 'WAIT_REVIEW' else 'REJECT',
price_at=0, hard_numbers=progress.get('daily_review'), reason=reason,
ref_id=old['instruction_id'])
if not recorded:
raise RuntimeError('复核留痕失败,状态推进已回滚')
if status == 'PROPOSED' and arbiter == 'system' and (progress['daily_review'].get('self_decide') or {}).get('decision') == 'accept':
counted = pms_repo.insert_ledger(ts_code=old['ts_code'], action=old['action'], arbiter='system',
verdict='PASS', price_at=0, hard_numbers=progress['daily_review'],
reason=pms_repo.SYSTEM_ACCEPT_REASON_PREFIX + '跨日完整复核通过', ref_id=old['instruction_id'])
if not counted:
raise RuntimeError('当日自动采纳计数失败,状态推进已回滚')
return True
def _hold(ins, now, reason):
prog = deepcopy(ins.get('progress') or {})
previous = prog.get('daily_review') or {}
if previous:
prog['daily_review_history'] = (prog.get('daily_review_history', []) + [previous])[-20:]
prog['daily_review'] = {'ymd': _day(now), 'status': 'pending', 'reason': reason}
# 同一日人工维护后重核也不能复用旧执行价。
for key in ('exec_advice', 'ref_lock', 'last_decision'):
prog.pop(key, None)
if _save(ins, prog, 'WAIT_REVIEW', reason):
return pms_repo.get_instruction(ins['instruction_id'])
return None
def _end(ins, reason, now, *, proposal=None, decision=None, arbiter='system'):
prog = deepcopy(ins.get('progress') or {})
prog['daily_review'] = {'ymd': _day(now), 'status': 'ended', 'reason': reason}
return _save(ins, prog, 'EXPIRED', reason, proposal=proposal, decision=decision, arbiter=arbiter)
def _basis(candidate):
h = candidate.get('hard_numbers') or {}
# 价格由执行层重新咨询;成交前仍过实时规则闸。研究/账户变化不能复用人工确认。
from app.core.plan_revision import fingerprint
return fingerprint({'qty': candidate['qty'], 'action': candidate['action'],
'code': candidate['ts_code'], 'basis': h.get('plan_basis'),
'params': h.get('scan_params_hash'), 'portfolio': h.get('portfolio_context_hash'),
'risk': h.get('risk'), 'consensus': h.get('consensus')})
def _invalidate_confirmation(ins, p, now):
prog = deepcopy(ins.get('progress') or {})
reason = '当日依据已变化,后台重新准备买入建议'
prog['daily_review'] = {'ymd': _day(now), 'status': 'pending', 'reason': reason}
return _save(ins, prog, 'WAIT_REVIEW', reason, proposal=p, decision='EXPIRED')
def _approve(ins, result, now, *, proposal=None, arbiter='system', reason=None):
if _command_blocker(ins):
return False
rows, filled = _orders(ins)
if any(r['status'] not in qmt_repo.FINAL for r in rows) or filled != int(ins.get('exec_qty') or 0):
return False
c = result['candidate']
qty = min(int(c['qty']), int(ins['qty']) - int(ins.get('exec_qty') or 0))
if qty <= 0:
return False
prog = deepcopy(ins.get('progress') or {})
reason = reason or '已通过当日完整决策复核,执行前重新确定限价'
prog['daily_review'] = {'ymd': _day(now), 'status': 'approved', 'qty': qty,
'start_filled': int(ins.get('exec_qty') or 0), 'at': now.isoformat(), 'reason': reason,
'basis': _basis(c), 'candidate': c, 'verdict': result['verdict'],
'self_decide': result.get('self_decide')}
for key in ('exec_advice', 'ref_lock', 'last_decision'):
prog.pop(key, None)
return _save(ins, prog, 'PROPOSED', reason, proposal=proposal,
decision='ACCEPTED' if proposal else None, arbiter=arbiter)
def _queue(ins, result, now):
c, verdict = result['candidate'], result['verdict']
prog = deepcopy(ins.get('progress') or {})
# 按当次准备内容编号;重启复用,依据变化可以生成新版本。
digest = hashlib.sha256((ins['instruction_id'] + _basis(c)).encode()).hexdigest()[:18]
pid = f'PRP_DAILY_{_day(now)}_{digest}'
reason = c.get('confirm_why') or verdict.get('reason') or '今日买入需按原确认规则重新确认'
hard = dict(c.get('hard_numbers') or {}, kind='daily_review', daily_parent=ins['instruction_id'],
daily_basis=_basis(c), daily_ymd=_day(now), daily_verdict=verdict,
preparation={'status': 'ready'}, proposal_revision=digest, reason=reason)
prog['daily_review'] = {'ymd': _day(now), 'status': 'confirmation', 'proposal_id': pid,
'reason': reason}
with transaction():
if not _save(ins, prog, 'WAIT_REVIEW', reason):
return False
if not pms_repo.get_proposal(pid):
inserted = pms_repo.insert_proposal(proposal_id=pid, ts_code=ins['ts_code'], action=ins['action'],
qty=c['qty'], hard_numbers=hard, expire_at=now.replace(hour=15, minute=0, second=0),
judge_verdict=verdict.get('verdict'), judge_reason=reason[:500])
if not inserted:
raise RuntimeError('复核确认建议未保存,状态推进已回滚')
return True
def process(*, now=None):
from app.services import dispatcher, proposal_service
now = now or datetime.now()
out = {'held': [], 'approved': [], 'queued': [], 'ended': [], 'waiting': [], 'errors': []}
if not param_store.get_bool('PMS_DAILY_BUY_REVIEW', False):
return out
# 先停完所有旧任务,再进行可能耗时的研判;未处理到的也不能从下发出口绕过。
for row in pms_repo.list_instructions(statuses=list(LIVE), side='buy', limit=500):
if not applies(row) or not blocker(row, now=now):
continue
try:
review = (row.get('progress') or {}).get('daily_review') or {}
if row['status'] != 'WAIT_REVIEW' or review.get('ymd') != _day(now):
held = _hold(row, now, blocker(row, now=now))
if held:
out['held'].append(row['instruction_id'])
except Exception as e:
out['errors'].append(f"{row['instruction_id']}: {e}")
reviewed = 0
for row in pms_repo.list_instructions(statuses=['WAIT_REVIEW'], side='buy', limit=500):
if not applies(row):
continue
iid = row['instruction_id']
try:
orders, filled = _orders(row)
if any(o['status'] not in qmt_repo.FINAL for o in orders):
cancelled = dispatcher.cancel(instruction_id=iid, dispatch_ref=row.get('dispatch_ref'))
if not cancelled.get('ok'):
out['errors'].append(f'{iid}: 旧委托撤销未受理')
out['waiting'].append(iid)
continue
if filled != int(row.get('exec_qty') or 0):
out['waiting'].append(iid) # 等回放,不将通道累计数写成账本成交。
continue
prog = row.get('progress') or {}
stopped = _command_blocker(row)
if stopped:
if _end(row, stopped, now):
out['ended'].append(iid)
continue
if (prog.get('deadline') and _day(prog['deadline']) < _day(now)) or prog.get('origin') == 'strategy':
if _end(row, '昨日买入安排结束;后续按当日策略重新生成', now):
out['ended'].append(iid)
continue
state = prog.get('daily_review') or {}
if state.get('status') == 'confirmation' and state.get('ymd') == _day(now):
p = pms_repo.get_proposal(state['proposal_id'])
if p and p['status'] == 'WAIT_USER' and not proposal_service.is_expired(p, now):
continue
if _end(row, '当日复核确认未完成,旧买入安排结束', now):
out['ended'].append(iid)
continue
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False) or param_store.get_bool('PMS_GLOBAL_BUY_HALT', False):
out['waiting'].append(iid)
continue
if reviewed >= 1:
break
reviewed += 1
result = proposal_service.scan_and_route(now=now, review_instruction=row)
if result.get('errors') or not result.get('ok'):
out['errors'].extend(result.get('errors') or [f'{iid}: 当日决策资料未就绪'])
continue
if any(x.get('by') == 'judge_pending' for x in result.get('skipped', [])):
out['waiting'].append(iid)
continue
fresh = result.get('review')
if fresh:
# 模型响应期间上游可能换榜或账户成交。再走同一候选流程,不能只验证旧票仍有报告。
checked = proposal_service.scan_and_route(now=now, review_instruction=row,
prepared_verdict=fresh['verdict'])
current = checked.get('review')
if checked.get('errors') or not current or _basis(current['candidate']) != _basis(fresh['candidate']):
out['waiting'].append(iid)
continue
fresh = current
changed = _approve(row, fresh, now) if fresh['auto_exec'] else _queue(row, fresh, now)
if changed:
out['approved' if fresh['auto_exec'] else 'queued'].append(iid)
else:
# 未通过不带昨日任务继续。后续条件转好仍由正常扫描产生新建议。
reasons = [r.get('why') or ';'.join(r.get('failed') or [])
for r in result.get('rejected', []) + result.get('skipped', [])
if r.get('ts_code') in (None, row['ts_code']) and not r.get('informational')]
reason = '当日复核未通过:' + (';'.join(filter(None, reasons)) or '不在当日可执行候选中')
if _end(row, reason[:500], now):
out['ended'].append(iid)
except Exception as e:
out['errors'].append(f'{iid}: {e}')
return out
def decide_confirmation(p, decision, reason, revision=None, *, now=None):
"""人工入口不调用模型,只在当前候选/账户依据未变时使用当日已准备结论。"""
from app.services import proposal_service
now = now or datetime.now()
h = p.get('hard_numbers') or {}
ins = pms_repo.get_instruction(h.get('daily_parent'))
if decision == 'ACCEPTED' and p['status'] == 'ACCEPTED':
return {'ok': True, 'already_accepted': True, 'instruction_id': h['daily_parent']}
if (not ins or ins['status'] != 'WAIT_REVIEW' or p['status'] != 'WAIT_USER'
or h.get('daily_ymd') != _day(now) or proposal_service.is_expired(p, now)
or revision != h.get('proposal_revision')):
return {'ok': False, 'error': '今日复核建议已变化或过期,请刷新'}
orders, filled = _orders(ins)
if any(o['status'] not in qmt_repo.FINAL for o in orders) or filled != int(ins.get('exec_qty') or 0):
return {'ok': False, 'error': '旧委托或成交尚未核对完成'}
if decision == 'DECLINED':
changed = _end(ins, reason, now, proposal=p, decision=decision, arbiter='user')
else:
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False) or param_store.get_bool('PMS_GLOBAL_BUY_HALT', False):
return {'ok': False, 'error': '用户已暂停买入或执行'}
result = proposal_service.scan_and_route(now=now, review_instruction=ins,
prepared_verdict=h['daily_verdict'])
fresh = result.get('review')
if result.get('errors'):
return {'ok': False, 'error': '当日资料暂不可用,恢复后再确认'}
if not fresh or _basis(fresh['candidate']) != h['daily_basis']:
pending = _invalidate_confirmation(ins, p, now)
return {'ok': False, 'pending': pending, 'error': '当日依据已变化,后台重新准备买入建议'}
changed = _approve(ins, fresh, now, proposal=p, arbiter='user', reason=reason)
return {'ok': bool(changed), 'decision': decision, 'instruction_id': ins['instruction_id'],
**({} if changed else {'error': '指令已变化,本次未恢复买入'})}