"""原策略持仓的退出纪律。事件先入账,暂停买入与清仓按实际回报持续收尾。""" from datetime import datetime from config.settings import settings from app.core import risk_exit as rules, strategy_book as books from app.repo import pms_repo, rotation_repo from app.services import param_store KIND = 'risk_exit' PAUSED = {'STOP_BUY', 'EXIT_PENDING', 'EXITING', 'CLOSED', 'MANUAL'} LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW') def enabled(): return (settings.INFRA_STRATEGY_BOOK_SCHEMA and books.CURRENT.get() == books.ORIGINAL and param_store.get_bool('PMS_RISK_EXIT_ENABLED', False)) def _key(code): return 'risk-exit:original:' + code def _code_ok(code): from app.core.command_spec import is_stock_code return is_stock_code(code) and str(code).endswith(('.SH', '.SZ')) def buy_blocker(code): if not enabled() or not _code_ok(code): return None state, _ = rotation_repo.get(_key(code)) if state and state.get('phase') in PAUSED: return state.get('reason') or '该股退出纪律已生效,停止新增买入' return None def decorate_positions(rows): """只读展示退出纪律,非方案持仓也不能把停买误写成等待补仓。""" if not enabled(): return labels = {'STOP_BUY': '只卖不买', 'EXIT_PENDING': '等待清仓', 'EXITING': '清仓中', 'MANUAL': '退出待处理', 'CLOSED': '退出待核实'} for row in rows: if int(row.get('total_qty') or 0) <= 0 or not _code_ok(row.get('ts_code')): continue try: state, _ = rotation_repo.get(_key(row['ts_code'])) if state and state.get('phase') in labels: row['exit_status_text'] = labels[state['phase']] row['exit_status_reason'] = state.get('reason') or '退出纪律已生效,停止新增买入' except Exception: row['exit_status_text'] = '退出状态待核实' row['exit_status_reason'] = '暂时无法读取退出纪律,请稍后刷新' def _holding(code): pos = pms_repo.get_position(code) or {} rows = pms_repo.list_lots(code, status='OPEN', limit=2001) if len(rows) >= 2001: raise ValueError('持仓批次超过完整核验上限') lots = {str(r['id']) for r in rows if int(r.get('qty') or 0) > 0} if sum(int(r.get('qty') or 0) for r in rows) != int(pos.get('total_qty') or 0): raise ValueError('持仓与批次数量不一致,等待对账后执行退出纪律') pos['_risk_lots'] = rows return pos, lots def _ledger(code, action, reason, hard, ref): if pms_repo.insert_ledger(ts_code=code, action=action, arbiter='system', verdict='PASS', price_at=0, hard_numbers=hard, reason=reason[:500], ref_id=ref) != 1: raise RuntimeError('退出纪律依据未入账') def _sync(state, code, pos, lots, now): """以真实未平批次衔接持仓轮次,清空后再开仓不继承上轮信号。""" if not lots: return late = any(r.get('instruction_id') in (state.get('stopped_parents') or []) for r in pos.get('_risk_lots', [])) same = bool((state.get('opened_date') == str(pos.get('opened_date')) and set(state.get('lot_ids') or []) & lots) or late) if not same: # 没有批次交集时不猜是同一轮,旧证据绝不用于新批次清仓。 state.clear() state.update(code=code, book_id=books.ORIGINAL, opened_date=str(pos.get('opened_date')), round_id=rules.digest([code, str(pos.get('opened_date')), sorted(lots)])[:20], phase='WATCH', events=[], lot_ids=sorted(lots), count=0, exit_seq=0, initialized_at=rules.stamp(now).isoformat()) from app.services import logic_state_service entry = logic_state_service.entry_view(code) or {} baseline = rules.review_snapshot(entry.get('company_review'), now=now, stale_days=param_store.get_int('PMS_FUND_STALE_DAYS', 120)) if baseline: state['review'] = baseline _seed_legacy_first(state, code, pos, now) else: state['lot_ids'] = sorted(set(state['lot_ids']) | lots) if state.get('phase') == 'CLOSED' and late: state['phase'] = 'EXIT_PENDING' state['stopped_parents'] = sorted(set(state.get('stopped_parents') or []) | {r['instruction_id'] for r in pos.get('_risk_lots', []) if r.get('instruction_id')}) def _seed_legacy_first(state, code, pos, now): """只承接已有的真实停买及待确认清仓,不回扫历史凑第二次信号。""" from app.services import strategy_service pause = strategy_service.buypause_map().get(code) or {} sources = pause.get('sources') or {pause.get('source'): pause} candidates = pms_repo.list_proposals(statuses=('WAIT_USER',), limit=501) if len(candidates) >= 501: raise ValueError('待确认提议过多,不能截断迁移退出依据') for p in candidates: if p.get('ts_code') != code or p.get('action') != 'EXIT' or p.get('judge_verdict') != 'STRATEGY_RISK': continue hard = p.get('hard_numbers') or {} source = hard.get('signal_source') at, paused = rules.stamp(p.get('created_at')), sources.get(source) or {} pat = rules.stamp(paused.get('at')) if (not at or not pat or at.date() != rules.stamp(now).date() or abs((at-pat).total_seconds()) > 120 or not hard.get('on_strategy') or float(hard.get('confidence') or 0) < param_store.get_float('PMS_SIGNAL_AUTO_EXIT_CONF', .85)): continue reason = str(paused.get('reason') or '') if not reason or reason not in str(hard.get('reason') or ''): continue original = reason.split(' —— ', 1)[-1] event = {'key': rules.digest(['legacy', p['proposal_id']]), 'source': source, 'source_id': p['proposal_id'], 'msg_id': 'legacy:'+p['proposal_id'], 'at': pat.isoformat(), 'reason': original, 'content': rules.digest([code, original]), 'confidence': float(hard['confidence']), 'legacy_proposal': p['proposal_id']} state.update(events=[event], count=1, phase='STOP_BUY', reason='第一次清仓信号已确认,停止新增买入,等待第二次独立信号') _ledger(code, 'SIGNAL', state['reason'], {'legacy_proposal': p['proposal_id'], 'event': event, 'round_id': state['round_id']}, p['proposal_id']) return def on_signal(sig, *, now=None, dry_run=False): if not enabled(): return None now = now or datetime.now() event, why = rules.signal_event(sig, now=now, since=param_store.get('PMS_RISK_EXIT_START_AT', ''), threshold=param_store.get_float('PMS_SIGNAL_AUTO_EXIT_CONF', .85), max_age=param_store.get_int('PMS_RISK_SIGNAL_MAX_AGE_SEC', 300)) if not event: return {'accepted': False, 'reason': why} code = sig['ts_code'] if dry_run: state, _ = rotation_repo.get(_key(code)) return {'accepted': True, 'dry_run': True, 'count': (state or {}).get('count', 0), 'reason': '只读预览,不登记次数、不改变委托'} with rotation_repo.account_guard(), rotation_repo.locked(_key(code), KIND, {}) as state: pos, lots = _holding(code) if not lots: return {'accepted': False, 'reason': '当前没有原策略持仓'} _sync(state, code, pos, lots, now) reset = rules.stamp(state.get('reset_at')) if reset and rules.stamp(event['at']) <= reset: return {'accepted': False, 'reason': '信号早于本次恢复买入'} # 持仓买入前的消息不能用来清这轮新仓。 opened = rules.stamp(pos.get('opened_date')) if opened and rules.stamp(event['at']) < opened: return {'accepted': False, 'reason': '信号早于当前持仓轮次'} duplicate = rules.duplicate(state['events'], event, mirror_seconds=param_store.get_int('PMS_RISK_SIGNAL_MIRROR_SEC', 120)) if not duplicate and state['phase'] not in ('EXIT_PENDING', 'EXITING', 'CLOSED', 'MANUAL'): state['events'].append(event) state['count'] = int(state.get('count') or 0) + 1 state['phase'] = 'STOP_BUY' if state['count'] == 1 else 'EXIT_PENDING' state['reason'] = ('第一次清仓信号已确认,停止新增买入,等待第二次独立信号' if state['count'] == 1 else '第二次独立清仓信号已确认,开始清仓') _ledger(code, 'SIGNAL', state['reason'], {'event': event, 'count': state['count'], 'round_id': state['round_id']}, event['key'][:64]) count, phase = state['count'], state['phase'] drive(code, now=now) return {'accepted': True, 'duplicate': duplicate, 'count': count, 'phase': phase} def recover_on_buy(code, event, *, now=None): """新的有效转多只解除本轮第一次系统停买,不重开已撤指令。""" from app.services import timing_state, strategy_service, consensus_service, logic_state_service now = now or datetime.now() wait = {'recovered': False} if (not enabled() or not timing_state.enabled() or not _code_ok(code) or not timing_state.valid(event, now) or event.get('action') != 'BUY' or float(event.get('confidence') or 0) < param_store.get_float('PMS_SIGNAL_AUTO_EXIT_CONF', .85)): return wait if any(param_store.get_bool(k, False) for k in ('PMS_GLOBAL_BUY_HALT', 'PMS_GLOBAL_EXEC_HALT')): return wait review = (logic_state_service.state_map().get(code) or {}).get('company_review') snapshot = rules.review_snapshot(review, now=now, stale_days=param_store.get_int('PMS_FUND_STALE_DAYS', 120)) if not snapshot: return wait blocks = consensus_service.assemble({'ts_code': code, 'company_review': review}, nightly=consensus_service.nightly_map([code]).get(code), tech_states=consensus_service.state_map(), intraday_event=event, now=now) con = blocks['consensus'] if con.get('route') != '放行' or con.get('direction') != '看多': return wait with rotation_repo.account_guard(), rotation_repo.locked(_key(code), KIND, {}) as state: current = timing_state.latest(code, now) if not current or current['key'] != event['key']: return wait if (state.get('phase') != 'STOP_BUY' or state.get('count') != 1 or state.get('review_exit') or state.get('exit_iid')): return wait pos, lots = _holding(code) if (not lots or not set(state.get('lot_ids') or []) & lots or state.get('opened_date') != str(pos.get('opened_date'))): return wait change = rules.review_change(state.get('review'), snapshot) if change not in ('same', 'updated'): return wait at = rules.stamp(event['at']) prior = [rules.stamp(e.get('at')) for e in state.get('events', [])] prior.append(rules.stamp(state.get('reset_at'))) if any(t and at <= t for t in prior): return wait if pms_repo.list_strategies(ts_code=code, statuses=['PAUSED'], limit=1): return wait pause = strategy_service.buypause_map().get(code) or {} sources = pause.get('sources') or ({pause['source']: pause} if pause.get('source') else {}) allowed = {'risk_exit', 'intraday', 'risk_sell', 'accum'} if (not sources or set(sources) - allowed or any(not rules.stamp(v.get('at')) or rules.stamp(v['at']) >= at for v in sources.values())): return wait reason = '新的有效看多信号通过三源合议,解除首次系统停买' evidence = {'round_id': state['round_id'], 'event': event, 'previous_events': list(state.get('events') or []), 'consensus': consensus_service.hard_keys(blocks), 'sources': sorted(sources)} _ledger(code, 'SIGNAL', reason, {'buy_recovery': evidence}, event['key'][:64]) for source in sorted(sources): result = strategy_service.clear_buypause(code, only_source=source) if not result.get('ok') or not result.get('cleared'): raise RuntimeError('系统恢复买入未保存,保留原暂停') state.update(phase='WATCH', count=0, reset_at=event['at'], reason=reason, review=snapshot, last_recovery=evidence) return {'recovered': True, 'reason': reason} def observe_review(code, review, *, now=None): if not enabled() or not _code_ok(code): return None now = now or datetime.now() snapshot = rules.review_snapshot(review, now=now, stale_days=param_store.get_int('PMS_FUND_STALE_DAYS', 120)) with rotation_repo.account_guard(), rotation_repo.locked(_key(code), KIND, {}) as state: pos, lots = _holding(code) if not lots: return None _sync(state, code, pos, lots, now) change = rules.review_change(state.get('review'), snapshot) if change in ('baseline', 'updated', 'downgrade'): before = state.get('review') state['review'] = snapshot if change == 'downgrade' and state['phase'] not in ('EXIT_PENDING', 'EXITING', 'MANUAL'): state.update(phase='EXIT_PENDING', reason=f"买方评析整体评级由{before['grade']}降为{snapshot['grade']},开始清仓") state['review_exit'] = {'before': before, 'after': snapshot} _ledger(code, 'SIGNAL', state['reason'], {'review_exit': state['review_exit'], 'round_id': state['round_id']}, snapshot['ref']) return change def _stop_buys(code, state): """先持久化逐指令停止依据,再请求撤单;未确认撤销的量继续保留。""" from app.services import executor, strategy_service reason = state['reason'] strategy_service.pause_buy(code, reason=reason, source='risk_exit') pause = strategy_service.buypause_map().get(code) or {} if 'risk_exit' not in (pause.get('sources') or {}): raise RuntimeError('退出纪律暂停买入未保存') rows = pms_repo.list_instructions(statuses=list(LIVE), side='buy', ts_code=code, limit=501) if len(rows) >= 501: raise ValueError('在途买入过多,不能截断处理') for ins in rows: iid = ins['instruction_id'] state['stopped_parents'] = sorted(set(state.get('stopped_parents') or []) | {iid}) if not pms_repo.instruction_buy_stop(iid): _ledger(code, 'BUY_STOP', reason, {'risk_exit': True}, iid) result = executor.cancel_instruction(iid, reason=reason, arbiter='system') or {} if not result.get('ok'): raise RuntimeError('退出纪律撤单失败,保留停买并等待重试') def drive(code, *, now=None): """同账户串行收尾。T+1、迟到成交、部分成交继续沿已有执行与回报链处理。""" if not enabled() or not _code_ok(code) or param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False): return now = now or datetime.now() from app.services import execution_conflicts, execution_orders, strategy_service with rotation_repo.account_guard(), rotation_repo.locked(_key(code), KIND, {}) as state: if not state or state.get('phase') not in PAUSED: return _stop_buys(code, state) if state['phase'] in ('STOP_BUY', 'CLOSED', 'MANUAL'): return # 旧网格卖单也需明确撤销,不能只撤策略后让旧父单永久等待来源状态。 from app.services import executor all_live = pms_repo.list_instructions(statuses=list(LIVE), ts_code=code, limit=501) if len(all_live) >= 501: raise ValueError('在途指令过多,不能截断处理') for old in all_live: if old.get('origin_type') == 'strategy' and old.get('side') == 'sell': result = executor.cancel_instruction(old['instruction_id'], reason=state['reason'], arbiter='system') or {} if not result.get('ok'): raise RuntimeError('旧策略卖出撤单失败,等待重试') # 撤掉网格等自动策略,避免旧卖单与整票清仓并发占用可卖量。 result = strategy_service.cancel_by_code(code, reason=state['reason']) or {} if not result.get('ok'): raise RuntimeError('清仓前策略撤销未完成,等待重试') if pms_repo.list_strategies(ts_code=code, statuses=['ACTIVE', 'PAUSED'], limit=1): raise RuntimeError('清仓前仍有未撤下的交易方案,等待重试') # 同一账户锁和文档事务覆盖清仓指令、计数、报告版本与审计。 current = state pos, lots = _holding(code) from app.repo import qmt_repo children = qmt_repo.list_orders(ts_code=code, statuses=list(qmt_repo.LIVE), limit=1001) if len(children) >= 1001: raise ValueError('在途委托超过核验上限') owned = [] for child in children: with books.scope('all'): parent = pms_repo.get_instruction(child['parent_id']) if not parent or parent.get('book_id') not in (books.ORIGINAL, books.MICRO): raise ValueError('在途委托策略归属无法核实') if parent['book_id'] == books.ORIGINAL: owned.append(child) if any(c.get('side') == 'sell' for c in owned): return if qmt_repo.inbox_pending_count() or qmt_repo.inbox_orphan_count(): return rows = pms_repo.list_instructions(statuses=list(LIVE), side='sell', ts_code=code, limit=501) if len(rows) >= 501: raise ValueError('在途卖出过多,不能截断处理') if rows: return # 已有真实卖出先收尾,不叠加超卖,也不覆盖用户指令。 if current.get('exit_iid'): prev = pms_repo.get_instruction(current['exit_iid']) if not prev or prev.get('status') in ('CANCELLED', 'REJECTED'): current.update(phase='MANUAL', reason='清仓安排已撤销、拒绝或无法核实,等待人工处理') return # 等所有回报入账后才确认清仓完成;迟到买入仍归本轮退出收尾。 qty = int(pos.get('total_qty') or 0) if qty <= 0: live_buy = pms_repo.list_instructions(statuses=list(LIVE), side='buy', ts_code=code, limit=1) if not live_buy and not owned: current.update(phase='CLOSED', closed_at=rules.stamp(now).isoformat()) return blocker = execution_orders.correction_blocker(ts_code=code, side='sell') if blocker: raise RuntimeError(blocker) seq = int(current.get('exit_seq') or 0) + 1 iid = f"RX_{current['round_id']}_{seq}" progress = {'is_command': False, 'urgent': True, 'from_signal': True, 'risk_exit': {'round_id': current['round_id'], 'events': current['events'], 'review_exit': current.get('review_exit')}, 'reason': current['reason'], 'children': [], 'deadline': str(now.date())} if pms_repo.insert_instruction(instruction_id=iid, origin_type='system', origin_id='risk_exit', ts_code=code, action='EXIT', side='sell', qty=qty, limit_price=None, window_tdays=1, status='PROPOSED', progress=progress) != 1: raise RuntimeError('清仓指令未成功落表') _ledger(code, 'EXIT', current['reason'], progress['risk_exit'], iid) current.update(phase='EXITING', exit_iid=iid, exit_seq=seq) # 旧风控/目标价提议被新清仓覆盖,避免再被采纳为重复委托。 proposals = pms_repo.list_proposals(statuses=('WAIT_USER',), limit=501) if len(proposals) >= 501: raise ValueError('提议过多,不能完整清理退出冲突') for p in proposals: if p.get('ts_code') == code and p.get('action') in ('EXIT', 'TRIM', 'OPEN', 'FILL', 'ADD', 'DCA'): if not pms_repo.decide_proposal(p['proposal_id'], 'EXPIRED'): raise RuntimeError('清仓冲突提议未成功收尾') result = execution_conflicts.enforce_exit(pms_repo.get_instruction(iid)) if not result.get('ok'): raise RuntimeError('清仓已落表,买入侧仍待收尾') def resume_buy(code): """仅响应用户明确恢复;清仓已启动时不能用恢复买入撤销卖出安排。""" if not enabled(): return with rotation_repo.account_guard(), rotation_repo.locked(_key(code), KIND, {}) as state: if state.get('phase') in ('EXIT_PENDING', 'EXITING'): raise ValueError('该股已进入清仓流程,请先处理清仓安排') if state.get('phase') == 'MANUAL': from app.repo import qmt_repo if (pms_repo.list_instructions(statuses=list(LIVE), side='sell', ts_code=code, limit=1) or qmt_repo.list_orders(ts_code=code, statuses=list(qmt_repo.LIVE), limit=1) or qmt_repo.inbox_pending_count() or qmt_repo.inbox_orphan_count()): raise ValueError('该股委托或回报仍待收尾,暂不能恢复买入') if state: state.update(phase='WATCH', count=0, reset_at=rules.stamp(datetime.now()).isoformat(), reason='用户明确恢复买入') state.pop('exit_iid', None) from app.services import strategy_service result = strategy_service.clear_buypause(code) or {} if not result.get('ok'): raise RuntimeError('用户恢复买入未保存,保留原暂停') _ledger(code, 'SIGNAL', state['reason'], {'round_id': state['round_id'], 'reset_at': state['reset_at']}, state['round_id']) def scan(*, now=None): out = {'enabled': enabled(), 'reviews': {}, 'errors': []} if not out['enabled']: return out now = now or datetime.now() from app.services import logic_state_service states = logic_state_service.state_map() positions = pms_repo.list_positions(only_open=True) codes = {p['ts_code'] for p in positions if _code_ok(p['ts_code'])} pending = rotation_repo.recent(KIND, limit=1000) if len(pending) >= 1000: raise RuntimeError('退出纪律记录超过核验上限') codes.update(r['value']['code'] for r in pending if r['value'].get('phase') in PAUSED) for code in sorted(codes): try: out['reviews'][code] = observe_review(code, (states.get(code) or {}).get('company_review'), now=now) from app.services import timing_state event = timing_state.latest(code, now) if event and event['action'] == 'BUY': out.setdefault('recoveries', {})[code] = recover_on_buy(code, event, now=now) drive(code, now=now) except Exception as exc: out['errors'].append(f'{code}: {type(exc).__name__}: {exc}') out['ok'] = not out['errors'] return out def refresh_reviews(*, now=None): """在独立刷新任务中批量只读持仓评析;执行任务不等待外部请求或模型。""" out = {'enabled': enabled(), 'ok': True, 'reviews': {}, 'errors': []} if not out['enabled']: return out now = now or datetime.now() current = rules.stamp(now) from app.services import plan_feed positions = pms_repo.list_positions(only_open=True) codes = sorted({p['ts_code'] for p in positions if _code_ok(p['ts_code'])}) if not codes: return out if len(codes) > 200: raise ValueError('持仓评级批量查询超过完整核验上限') with rotation_repo.locked('risk-review-refresh:original', 'risk_review_refresh', {}) as state: previous = rules.stamp(state.get('attempt_at')) if previous and (current-previous).total_seconds() < param_store.get_int('PMS_RISK_REVIEW_REFRESH_SEC', 300): return {**out, 'skipped': '尚未到持仓评析刷新时间'} state['attempt_at'] = current.isoformat() try: states = plan_feed.fetch_logic_states(codes, timeout=param_store.get_int('PMS_RISK_REVIEW_TIMEOUT_SEC', 3)) except Exception as exc: out.update(ok=False, errors=[f'持仓评析补读失败,保留原评级:{type(exc).__name__}']) return out for code in codes: try: out['reviews'][code] = observe_review(code, (states.get(code) or {}).get('company_review'), now=now) except Exception as exc: out['errors'].append(f'{code}: {type(exc).__name__}: {exc}') out['ok'] = not out['errors'] return out