diff --git a/app/repo/pms_repo.py b/app/repo/pms_repo.py index c94c31d..1c9bba5 100644 --- a/app/repo/pms_repo.py +++ b/app/repo/pms_repo.py @@ -486,6 +486,17 @@ def add_instruction_exec(instruction_id: str, qty: int) -> int: {"q": int(qty), "iid": instruction_id, "ts": _NOW()}) +def compare_review_instruction(old, progress, status): + """单表条件更新;复核与用户撤销、回放成交互斥,不覆盖并发变化。""" + return execute('UPDATE pms_instruction SET status=:st, progress_json=:pg, ' + 'limit_price=NULL, updated_at=:ts WHERE instruction_id=:iid ' + 'AND status=:old_st AND exec_qty=:eq AND progress_json=:old_pg', + {'st': status, 'pg': _dumps(progress), 'ts': _NOW(), + 'iid': old['instruction_id'], 'old_st': old['status'], + 'eq': int(old.get('exec_qty') or 0), + 'old_pg': old.get('progress_json') or _dumps(old.get('progress') or {})}) + + # ================================================================ pms_proposal def insert_proposal(*, proposal_id, ts_code, action, qty, hard_numbers, expire_at, judge_verdict=None, judge_reason=None, status="WAIT_USER") -> int: diff --git a/app/scheduler.py b/app/scheduler.py index 4d4f3d2..590a585 100644 --- a/app/scheduler.py +++ b/app/scheduler.py @@ -244,6 +244,8 @@ def intraday_exec(): """ from app.services import executor, proposal_service, strategy_runner r = {"materialized": executor.materialize_plans()} + from app.services import daily_buy_review + r["daily_buy_review"] = daily_buy_review.process() r["proposals"] = proposal_service.scan_and_route() r["strategies"] = strategy_runner.tick() # 个股交易方案: 触发即发短窗口指令, 由下面 run_tick 执行 # 过期收口改为每分钟一次 (原来只在 15:10 日结跑) —— 让过了窗口/deadline 的单当即作废, diff --git a/app/services/daily_buy_review.py b/app/services/daily_buy_review.py new file mode 100644 index 0000000..da87a65 --- /dev/null +++ b/app/services/daily_buy_review.py @@ -0,0 +1,293 @@ +"""跨日买入复核:停止旧单、等待真实回报、重走当日决策,再开放当日额度。""" +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 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 + 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): + 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 {} + 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 + 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': '指令已变化,本次未恢复买入'})} diff --git a/app/services/dispatcher.py b/app/services/dispatcher.py index bda206f..75b3043 100644 --- a/app/services/dispatcher.py +++ b/app/services/dispatcher.py @@ -156,7 +156,9 @@ def dispatch(*, instruction_id: str, ts_code: str, side: str, qty: int, limit_pr pid = _parent_of(instruction_id, parent_id) parent = pms_repo.get_instruction(pid) stopped = pms_repo.instruction_buy_stop(pid) - blocked = ('清仓已终止原买入安排' if stopped or ((parent or {}).get('progress') or {}).get('stopped_by_exit') else buy_blocker(ts_code)) + from app.services import daily_buy_review + review_block = daily_buy_review.blocker(parent) if parent else None + blocked = review_block or ('清仓已终止原买入安排' if stopped or ((parent or {}).get('progress') or {}).get('stopped_by_exit') else buy_blocker(ts_code)) if parent and parent.get('status') not in ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED'): blocked = '来源买入指令已结束,不再发单' if blocked: diff --git a/app/services/execution_conflicts.py b/app/services/execution_conflicts.py index a5da2d8..1ea5a09 100644 --- a/app/services/execution_conflicts.py +++ b/app/services/execution_conflicts.py @@ -1,7 +1,7 @@ """统一执行方向检查。只消解既有指令冲突,不重做研究或择时。""" from app.repo import pms_repo, qmt_repo -LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED') +LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') BUY_ACTIONS = ('OPEN', 'FILL', 'ADD', 'DCA') @@ -51,7 +51,8 @@ def _queued_parent_check(row, parent): return '清仓已终止原买入安排' if parent.get('status') not in LIVE: return '来源买入指令已结束,未发出的委托作废' - return buy_blocker(row['ts_code']) + from app.services import daily_buy_review + return daily_buy_review.blocker(parent) or buy_blocker(row['ts_code']) def enforce_exit(ins): @@ -141,6 +142,14 @@ def instruction_progress(rows): label = '等待买入条件' if row.get('side') == 'buy' else '等待卖出条件' else: label = '等待执行' + review = (row.get('progress') or {}).get('daily_review') or {} + if row.get('status') == 'WAIT_REVIEW' and not active: + label = '待确认今日买入' if review.get('status') == 'confirmation' else '跨日复核中' + stage = 'review' + live_prices = {str(o.get('limit_price')) for o in active if o.get('limit_price') is not None} + row['execution_limit'] = next(iter(live_prices)) if len(live_prices) == 1 else None + row['execution_note'] = review.get('reason') if stage == 'review' else ( + ((row.get('progress') or {}).get('last_decision') or {}).get('reason')) row['execution_label'] = label row['execution_stage'] = stage except Exception: diff --git a/app/services/executor.py b/app/services/executor.py index 50dc84d..a49641e 100644 --- a/app/services/executor.py +++ b/app/services/executor.py @@ -36,7 +36,7 @@ logger = logging.getLogger("pms.exec") ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED = "PROPOSED", "RULE_PASSED", "DISPATCHED" ST_CONFIRMED, ST_REJECTED, ST_EXPIRED, ST_CANCELLED = ("CONFIRMED", "REJECTED", "EXPIRED", "CANCELLED") -LIVE = (ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED) +LIVE = (ST_PROPOSED, ST_RULE_PASSED, ST_DISPATCHED, "WAIT_REVIEW") # 方案状态: GATED = 建仓的补足/加仓批, 等动作引擎按条件解锁 (DDL 注释已同步) PLAN_PENDING, PLAN_GATED, PLAN_EXEC, PLAN_DONE = "PENDING", "GATED", "EXECUTING", "DONE" @@ -104,6 +104,9 @@ def materialize_plans(limit: int = 100) -> dict: or param_store.get_int("PMS_EXEC_WINDOW_TDAYS", 3)) prog0 = {"deadline": str(p.get("deadline") or ""), "command_id": cid, "is_command": True, "children": []} + # 旧方案今天才物化也不能冒充当日决策。 + from app.services.daily_buy_review import _day + prog0['decision_ymd'] = _day(p.get('created_at') or cmd.get('issued_at')) provenance = next((x for x in (cmd.get('progress') or {}).get('plan_provenance', []) if x.get('plan_id') == p['plan_id']), None) if provenance: @@ -209,7 +212,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: if not cancelled.get('ok'): out['errors'].append(cancelled.get('message') or '清仓停止买入尚未完成') continue - blocked = execution_conflicts.buy_blocker(code) + from app.services import daily_buy_review + blocked = daily_buy_review.blocker(ins, now=now) or execution_conflicts.buy_blocker(code) if blocked: prog['last_decision'] = {'at': now.strftime('%H:%M'), 'action': 'WAIT', 'reason': blocked} if not dry_run: @@ -219,6 +223,8 @@ def run_tick(*, now=None, dry_run: bool = False) -> dict: # 回放与下发是两个任务。出口已成交时,exec_qty 可能还没更新, # 不能把「已终态、不在途」误当成「父指令还有额度」。 available = _parent_available(ins, children) + if side == 'buy': + available = min(available, daily_buy_review.allowance(ins, now=now)) if available <= 0: reason = '父指令额度已由成交或在途委托占用,等待回报入账或撤单确认' prog['last_decision'] = {'at': now.strftime('%H:%M'), 'action': 'WAIT', 'reason': reason} @@ -437,6 +443,8 @@ def sweep_windows(*, now=None) -> dict: pms_repo.update_plan(ins["origin_id"], filled_qty=exec_qty, status=PLAN_DONE if remaining <= 0 else None) out["synced"] += 1 + if ins.get('status') == 'WAIT_REVIEW': + continue # 复核任务自行处理截止日及撤单,不能提前释放在途数量。 if remaining <= 0: pms_repo.update_instruction(ins["instruction_id"], status=ST_CONFIRMED) continue diff --git a/app/services/param_store.py b/app/services/param_store.py index 830771d..93480ba 100644 --- a/app/services/param_store.py +++ b/app/services/param_store.py @@ -40,6 +40,7 @@ SECRET_KEYS = ("PMS_QMT_SIGN_SEED_HEX", "PMS_QMT_PEER_PUBKEY_B64", "PMS_SESSION_ # 运行态开关: key -> (默认值, 类型, 说明) RUNTIME_EXTRA = { + "PMS_DAILY_BUY_REVIEW": (False, bool, "跨日买入先撤旧委托,再按当日候选、研判、数量和价格完整复核;未通过不得续单"), 'PMS_ROTATION_MODE': ('observe', str, '微盘轮换模式:observe观察、paper独立纸面、auto自动。自动须通过验收门槛'), 'PMS_ROTATION_SIM_DIRECT': (False, bool, '155模拟仓直接启用,取消观察及纸面等待;保留账本、资金、数据、权限和用户控制检查'), 'PMS_ROTATION_MONITOR_URL': ('', str, '微盘监控只读接口根地址,留空停用拉取'), diff --git a/app/services/plan_recheck.py b/app/services/plan_recheck.py index 4ace2e9..29d144b 100644 --- a/app/services/plan_recheck.py +++ b/app/services/plan_recheck.py @@ -193,6 +193,8 @@ def refresh_pending(*, now=None, deadline=None): legacy_on = param_store.get_bool('PMS_PLAN_VERSION_RECHECK', False) rows = pms_repo.list_proposals(statuses=('WAIT_USER',), limit=200) for p in rows: + if (p.get('hard_numbers') or {}).get('kind') == 'daily_review': + continue # 关联旧父指令的当日复核由 daily_buy_review 维护。 if not legacy_on and (p.get('hard_numbers') or {}).get('candidate_source') != 'dividend': continue if p.get('action') != 'OPEN' or (p.get('hard_numbers') or {}).get('kind') == 'strategy' or ps.is_expired(p, now): diff --git a/app/services/proposal_service.py b/app/services/proposal_service.py index 142907d..27cb478 100644 --- a/app/services/proposal_service.py +++ b/app/services/proposal_service.py @@ -63,9 +63,11 @@ def _macro_gate() -> dict: return {} -def scan_and_route(*, now=None, dry_run: bool = False) -> dict: +def scan_and_route(*, now=None, dry_run: bool = False, review_instruction=None, prepared_verdict=None) -> dict: """自主提议扫描一轮。dry_run=True 只出候选与判定, 不落任何表。""" now = now or datetime.now() + if review_instruction is not None: + dry_run = True out = {"ok": True, "autonomy": None, "open_autonomy": None, "candidates": 0, "open_candidates": 0, "executed": [], "queued": [], "rejected": [], "skipped": [], "errors": [], "degraded": False, "dry_run": dry_run, @@ -137,7 +139,8 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: # 「今日系统已判放弃,明日重评」。off 时 _system_declined_today_keys 返回空, 逐字回旧。 skip = {**_jk, **_rejected_today_keys(), **_declined_today_keys(), **_system_declined_today_keys(), - **_inflight_keys()} + **(_inflight_keys(exclude_instruction=review_instruction["instruction_id"]) + if review_instruction else _inflight_keys())} # 挂了 ACTIVE 交易方案(策略)的票交策略层接管, 动作引擎不再对它自动提议 # (读库失败按空集 —— 宁可这轮不排除, 也不能因读不到把全体持仓都排除) try: @@ -215,7 +218,8 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: else: try: open_cands = _scan_open(view, params, stock_params, skip, mkt, out, now=now, - record_consumption=not dry_run) + record_consumption=not dry_run, + **({'review_instruction': review_instruction} if review_instruction else {})) except Exception as e: logger.exception("新建仓扫描失败") out["errors"].append(f"新建仓扫描失败: {type(e).__name__}: {e}") @@ -234,6 +238,26 @@ def scan_and_route(*, now=None, dry_run: bool = False) -> dict: deadline = time.monotonic() + max( 0, param_store.get_int("PMS_JUDGE_TICK_BUDGET_SEC", 150)) + if review_instruction is not None: + old = review_instruction + fresh = next((c for c in list(scanned['candidates']) + open_cands + if c['ts_code'] == old['ts_code'] and c['action'] == old['action']), None) + if not fresh: + return {**out, 'review': None} + remaining = max(0, int(old['qty']) - int(old.get('exec_qty') or 0)) + fresh['qty'] = min(int(fresh['qty']), remaining) + if fresh['qty'] <= 0: + return {**out, 'review': None} + fresh['_plan_recheck'] = True + fresh['judge_required'] = True + fresh.setdefault('hard_numbers', {}).update(qty=fresh['qty'], daily_parent=old['instruction_id']) + result = _route_one(fresh, view, params, stock_params, brake_active, now, True, out, + deadline=deadline, review_only=True, prepared_verdict=prepared_verdict) + if result: + result['candidate']['qty'] = min(int(result['candidate']['qty']), remaining) + result['candidate']['hard_numbers']['qty'] = result['candidate']['qty'] + return {**out, 'review': result} + for group_index, group in enumerate((list(scanned['candidates']), open_cands)): if group_index == 1 and not dry_run: from app.services.plan_recheck import refresh_pending @@ -315,7 +339,8 @@ def _save_tech_exit_done(codes) -> None: # ================================================================ 新建仓的取数与筛选 def _scan_open(view, params, stock_params, skip, mkt, out, now=None, - review_code=None, exclude_proposal=None, record_consumption=True, candidate_source='plan') -> list: + review_code=None, exclude_proposal=None, record_consumption=True, candidate_source='plan', + review_instruction=None) -> list: """候选池 → 新建仓候选。产出的候选数天生不超过剩余名额 (名额与金额在纯逻辑里边走边扣)。 与命令驱动那条路 (command_service._candidates) 有意不同的两点: @@ -358,6 +383,8 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, # 拿不到 ≠ 今天没票可买。显式留痕, 本轮不产新建仓候选, 已有持仓的四类照常。 logger.error("[新建仓] 候选池取数失败, 本轮不建仓: %s", e) out["skipped"].append({"action": ae.A_OPEN, "why": f"候选池取不到, 本轮不建仓: {e}"}) + if review_instruction: + out['errors'].append('当日候选资料未就绪,跨日任务继续等待') return [] # 仅展示的票逐只写跳过原因: disposition_snapshot 复用本函数, 页面「系统在盯的候选」 # 由此显示「选股系统判为仅展示」而不是一个说不清的空白。 @@ -367,6 +394,12 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, out["skipped"].append({"ts_code": row.get("ts_code"), "action": ae.A_OPEN, "why": ae.display_only_why(row)}) items = list(sel.get("items") or []) + if review_instruction: + code = review_instruction['ts_code'] + pending = (sel.get('refresh_status') or {}).get('pending_codes') or [] + if not (sel.get('decision') or {}).get('id') or code in pending or code.replace('.', '') in pending: + out['errors'].append('当前研究资料未就绪,跨日买入继续等待') + return [] if review_code: items = [x for x in items if x['ts_code'] == review_code] if not items: @@ -375,6 +408,9 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, codes = [x["ts_code"] for x in items] prices = market.get_prices(codes) + if review_instruction and review_instruction['ts_code'] in codes and not prices.get(review_instruction['ts_code']): + out['errors'].append('当日有效行情缺失,跨日买入继续等待') + return [] # 行业名一次批量取, 本轮复用。滚动扣减要算行业集中度, 所以必须先有它 —— # caps_ctx 对**从没持仓过**的票带不出行业名, 不显式传的话 sizer.check_caps 遇到 # sector 为空会整段跳过, 行业集中度那道硬拦截就静默失效了。 @@ -401,8 +437,9 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, inflight = _inflight_open_commitments(view, exclude_proposal=exclude_proposal, strict=True) cands = [c for c in cands if c['ts_code'] not in inflight['names']] else: - inflight = (_inflight_open_commitments(view, exclude_proposal=exclude_proposal) - if exclude_proposal else _inflight_open_commitments(view)) + inflight = (_inflight_open_commitments(view, exclude_proposal=exclude_proposal, + exclude_instruction=review_instruction['instruction_id'], strict=True) + if review_instruction else _inflight_open_commitments(view, exclude_proposal=exclude_proposal)) slots = int(p["max_names"] or 0) - int(t["names_count"] or 0) - len(inflight["names"]) room = float(p["portfolio_cap"] or 0) * float(p["scale"] or 0) \ - float(t["portfolio_mv"] or 0) - inflight["amount"] @@ -418,6 +455,8 @@ def _scan_open(view, params, stock_params, skip, mkt, out, now=None, if str(t.get("cash_source") or "") == portfolio.CASH_WS and t.get("cash_avail") is not None: room = min(room, float(t["cash_avail"])) elif param_store.get_bool("PMS_OPEN_REQUIRE_WS_CASH", True): + if review_instruction: + out['errors'].append('最新账户资金未就绪,跨日买入继续等待') out["skipped"].append({"action": ae.A_OPEN, "why": f"读不到券商账户的可用资金,这一轮不开新仓;" f"已持有的票照常处理。" @@ -610,7 +649,7 @@ def _no_candidate_why(sel) -> str: return head + ":" + ",".join(parts) + "。" -def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dict: +def _inflight_open_commitments(view, exclude_proposal=None, strict=False, exclude_instruction=None) -> dict: """在途的新建仓承诺: names 为代码集合,amount 为预估占用,basis 为稳定核验依据。 口径: 在途 (LIVE) 的 OPEN 指令 + 等拍板 (WAIT_USER) 的 OPEN 提议, 只算**尚未持有** @@ -623,6 +662,8 @@ def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dic rows = [] try: for i in pms_repo.list_instructions(statuses=list(executor.LIVE), limit=300): + if exclude_instruction and i['instruction_id'] == exclude_instruction: + continue if i.get("action") == ae.A_OPEN and i["ts_code"] not in held: rows.append((i["ts_code"], int(i.get("qty") or 0), None)) basis.append(('instruction', str(i.get('instruction_id') or ''), @@ -635,6 +676,8 @@ def _inflight_open_commitments(view, exclude_proposal=None, strict=False) -> dic for pr in pms_repo.list_proposals(statuses=("WAIT_USER",), limit=200): if exclude_proposal and pr.get('proposal_id') == exclude_proposal: continue + if exclude_instruction and (pr.get('hard_numbers') or {}).get('daily_parent') == exclude_instruction: + continue if pr.get("action") == ae.A_OPEN and pr["ts_code"] not in held: hn = pr.get("hard_numbers") or {} rows.append((pr["ts_code"], int(pr.get("qty") or 0), @@ -1040,7 +1083,8 @@ def _route_one(c, view, params, stock_params, brake_active, now, dry_run, out, c['hard_numbers'].update(judge_verdict=verdict.get('verdict'), judge_conf=verdict.get('confidence'), price=price, reason=c['reason']) - return {'candidate': c, 'verdict': verdict} + return {'candidate': c, 'verdict': verdict, 'auto_exec': auto_exec, 'force_queue': force_queue, + 'self_decide': sd} if dry_run: (out["executed"] if auto_exec else out["queued"]).append( @@ -1659,7 +1703,7 @@ def _declined_today_keys() -> dict: return keys -def _inflight_keys() -> dict: +def _inflight_keys(exclude_instruction=None) -> dict: """已有在途提议或在途指令的 {(代码, 动作): 原因} —— 同一件事不重复提。 提议与指令分开写原因, 并且**指令写在后面覆盖提议**: 一条提议被采纳之后会变成指令, @@ -1679,14 +1723,22 @@ def _inflight_keys() -> dict: keys.setdefault((code, buy), '该股有减持安排待处理,暂不新增买入提议') try: for p in pms_repo.list_proposals(statuses=("WAIT_USER",), limit=200): + if exclude_instruction and (p.get('hard_numbers') or {}).get('daily_parent') == exclude_instruction: + continue _mark(p["ts_code"], p["action"], f"已有在途提议 {p.get('proposal_id')} 在等人确认") except Exception as e: + if exclude_instruction: + raise logger.warning("读提议队列失败: %s", e) try: for i in pms_repo.list_instructions(statuses=list(executor.LIVE), limit=300): + if i['instruction_id'] == exclude_instruction: + continue _mark(i["ts_code"], i.get("action"), f"已有在途指令 {i.get('instruction_id')} ({i.get('status')})") except Exception as e: + if exclude_instruction: + raise logger.warning("读在途指令失败: %s", e) return keys diff --git a/app/web/main.py b/app/web/main.py index 18aab30..cd200cc 100644 --- a/app/web/main.py +++ b/app/web/main.py @@ -564,6 +564,9 @@ def api_decide(request: Request, proposal_id: str, payload: dict = Body(default= p = pms_repo.get_proposal(proposal_id) if not p: return {"ok": False, "error": "提议不存在"} + if (p.get('hard_numbers') or {}).get('kind') == 'daily_review': + from app.services.daily_buy_review import decide_confirmation + return decide_confirmation(p, decision, reason, payload.get('proposal_revision')) if (decision == 'ACCEPTED' and p['status'] == 'ACCEPTED' and p['action'] == 'OPEN' and (p.get('hard_numbers') or {}).get('kind') != 'strategy'): existing = pms_repo.accepted_open_instruction(proposal_id) diff --git a/app/web/static/index.html b/app/web/static/index.html index c2bb161..bf359f1 100644 --- a/app/web/static/index.html +++ b/app/web/static/index.html @@ -1186,7 +1186,7 @@ body.dock-r:not(.r-fold) .side-r .strip{display:none;}