# -*- coding: utf-8 -*- """ 个股交易方案 (策略) 运行器 —— PER_STOCK_STRATEGY_PLAN.md §四/§六/§七/§七B ============================================================================ 每分钟一跳 (挂在 scheduler.intraday_exec 里, 与 run_tick 并列)。载入 ACTIVE 策略, 按类型 评估 (做T / 网格 / 跟踪止盈), 触发就**发一张短窗口指令** (window_tdays=1, is_command=True, origin_type='strategy'), 交 executor.run_tick 用现有管线执行 —— 择时 / 规则闸 / T+1 可卖封顶 / 下发 / 账本一道不重写; autonomy=confirm 的落一条提议进「等我拍板」, 人点采纳后再由本层发指令。 **只做加法**: 本模块不改 executor / rule_gate / action_engine 任何一行, 唯一的引擎触点是 action_engine.scan 早已加好的「有 ACTIVE 策略的票跳过」那一条 skip (设计 §四)。 一条铁律定了整个框架 —— T+1 (设计 §三) -------------------------------------------------- 当日买入不可当日卖出, 所以做T / 网格 / 跟踪止盈本质都是「在一只**底仓**上、用 T+1 可卖的存量股 做买卖」= 同一自动机的三种配置。卖出一律经 run_tick 按 avail_qty 封顶, T+1 天然被挡在那里。 批次口径 (与 app/core/recon.ACTION_TO_LOT 对齐, 不另立) -------------------------------------------------- 做T —— 买入与卖出都用 action='T0_ROUND' → 记 T0 批次; 卖出核销次序 T0→ADD→DCA→FILL→BASE 先把 T0 批次对冲掉, 底仓与摊薄成本不动, 做T利润自然摊入 realized_t_profit。 网格 —— 买入 action='ADD' (记 ADD 批次), 卖出 action='TRIM' (从 avail 卖)。 跟踪止盈 —— 卖出 action='TRIM' (部分) / 'EXIT' (全清)。只卖不买。 安全 (设计 §九) -------------------------------------------------- * 全局开关 PMS_STRATEGY_ENABLED (默认 False) —— 关着时本模块整体空转、一条指令都不发。 * 挂了 ACTIVE 策略的票由 action_engine.scan 排除 (两个大脑不抢同一只)。 * 策略动作走命令口径 (is_command=True, 过规则闸、不过研判闸)。 * scheduler 的 @guard(session=True) 兜住: 非交易时段 / 休假模式不跑。 * 影子/实盘由 PMS_DISPATCH_MODE 决定, 与本层无关、自动继承。 * **双保险**: 本层 rails 先拦 (熔断 / 当日次数 / 上限 / 平回 / 下界), 规则闸再拦一道 (合规)。 * **关键路径禁止丢弃返回值**: 发不出指令 / 落不了库一律进 out["errors"], 绝不静默当成功。 决策系统对策略票的边界 (2026-08-11 用户定) -------------------------------------------------- 挂了策略的票, 决策系统的风控卖出信号只提示、不自动清仓 (强制离场会推翻你特意设的策略); `signal_service` 会把它落成提议、并把该票策略的**买入这一侧暂停** (不平仓、不动卖出、可页面恢复)。 暂停标记存在运行参数 `PMS_STRATEGY_BUYPAUSE` (按 ts_code 映射), 由 strategy_service 维护、 本模块只读 —— 特意不放进策略 state_json: 那份 state 每跳都被本模块重写, 放进去会被并发的 signal_digest / intraday_exec 互相覆盖 (与 portfolio.neg_streak_map 用独立参数同一个道理)。 暂停只挡「开新仓 / 加仓」这一侧, 卖出、平回、跟踪止盈照常 —— 挡的是"资金在流出、网格还在 逢跌买入", 不替你做清仓这种不可逆的事。 """ from __future__ import annotations import logging from contextlib import contextmanager, nullcontext from copy import deepcopy from datetime import datetime from app.core import tradedays as td from app.core.grid_inventory import price_tick from app.core.sizer import LOT from app.repo import pms_repo from app.services import market, param_store, portfolio logger = logging.getLogger("pms.strategy") # 指令在途 (未终态) 的状态集 —— 与 executor.LIVE 一致; 本层据此判断「上一笔还没走完, 先别再发」。 LIVE_INS = ("PROPOSED", "RULE_PASSED", "DISPATCHED", "WAIT_REVIEW") # 批次动作 (与 recon.ACTION_TO_LOT 对齐) A_T0 = "T0_ROUND" # 做T 买入与卖出 → T0 批次 A_GRID_BUY = "ADD" # 网格买入 → ADD 批次 A_SELL = "TRIM" # 网格 / 跟踪止盈 部分卖 A_EXIT = "EXIT" # 跟踪止盈 全清 (允许零股一次性清出) # 触发用的小额贴近带 (设计只说「近支撑 / 近压力 / 滞涨」, 未给具体数; 这里取保守小带并写明)。 NEAR_BAND = 0.005 # 现价距支撑/压力 0.5% 以内算「贴近」 OFF_HIGH_BAND = 0.003 # 距当日高点回落 0.3% 以上算「滞涨」(反T 用) # ================================================================ 取数小工具 def _f(v, d=0.0): try: return float(v) except (TypeError, ValueError): return d def _pos_of(view: dict, code: str) -> dict: for x in view.get("positions") or []: if x.get("ts_code") == code: return x return {} def _round_lot(qty) -> int: """向下取整到一手 (100 股)。不足一手返回 0。""" n = int(_f(qty)) return (n // LOT) * LOT def _min_lot(code) -> int: """最小申报数量: 科创板 (688/689 开头) 买卖都是 200 股起, 其余 100 股。 2026-08-25 补: 持仓里出现科创板票后发现全库取整都按 100 股, 而科创板 100 股的申报 会被券商直接拒掉。规则还有一条例外: 持仓不足 200 股时允许**一次性全部卖出**, 网格与止盈的各卖出落点分别处理了这一条。做T是命令授权的手工策略, 科创板做T的 开腿与平回数量怎么处理需要单独拍板, 本次不动 (见 DEVLOG)。""" return 200 if str(code or "").startswith(("688", "689")) else 100 def _today() -> int: return td.ymd() def _buypause_codes() -> set: """当前被暂停买入的证券集合;读失败返回未知,停止新增买入。""" try: from app.services import strategy_service return set(strategy_service.buypause_map().keys()) except Exception as e: # noqa: BLE001 logger.warning("[strategy] 读取买入暂停集失败 (停止新增买入): %s", e) return None def _macro_gate_active() -> bool: """宏观偏热闸 (MACRO_TIMING_PLAN.md §5.2): 生效时策略的买入开腿一并暂停。 与 buypause 走同一个判定点 (ctx.buy_paused), 天然继承「只挡开新仓/加仓腿, 卖出/平回/跟踪止盈照常」的既有语义 —— 反T 的买回是平回腿, 不会被拦。 读不到按不生效: 闸的安全方向是不额外拦。""" try: from app.services import macro_service return bool((macro_service.gate_state() or {}).get("active")) except Exception as e: # noqa: BLE001 logger.warning("[strategy] 读宏观闸状态失败 (按不生效): %s", e) return False # ================================================================ 指令 / 提议下发 def _correction_id(st: dict): return ((st.get("state") or {}).get("trade_correction") or {}).get("correction_id") @contextmanager def _current_strategy(st: dict): """保护策略快照与落单;网格批次读取和状态更新也在同一账户锁内。""" from app.services.execution_orders import account_guard with account_guard(): fresh = pms_repo.get_strategy(st["strategy_id"]) if not fresh or fresh.get("status") != "ACTIVE" or fresh.get("archived_at"): raise RuntimeError("策略已停用,停止生成新指令或提议") if (fresh.get("state") or {}).get("correction_hold"): raise RuntimeError("策略成交数量已更正,等待核对后续安排") if _correction_id(fresh) != _correction_id(st): raise RuntimeError("策略成交更正版本已变化,请按最新状态重新评估") if fresh.get('params', {}) != st.get('params', {}) or fresh.get('state', {}) != st.get('state', {}): raise RuntimeError('策略参数或状态已变化,请按最新状态重新评估') yield fresh def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str: """按决策发一张短窗口命令指令 (window_tdays=1, is_command=True), 交 run_tick 执行。 网格保留买入上限、卖出下限;最终合法限价仍由执行层按新鲜行情计算。 """ from config.settings import settings if settings.INFRA_STRATEGY_BOOK_SCHEMA and dec.get('side') == 'buy' and dec.get('leg') != 'close': from app.services.rotation_service import original_buy_blocker if original_buy_blocker(): raise ValueError('策略轮换期间停止原策略开新腿') code = st["ts_code"] now = datetime.now() iid = f"STR{_today()}{now.strftime('%H%M%S')}_{code.replace('.', '')}_{dec['leg'][:1]}"[:40] is_cmd = (st.get("type") == "T0") # 做T必须当日轧平→命令口径(含14:45强制平回); # 网格/跟踪止盈到价即成交、当日没成交则作废, 不强制 prog = {"is_command": is_cmd, "deadline": str(_today()), "children": [], "origin": "strategy", "strategy_id": st["strategy_id"], "stype": st.get("type"), "strategy_correction_id": _correction_id(st), "leg": dec["leg"], "reason": dec.get("reason"), "forced": bool(forced)} if st.get('type') == 'GRID': prog.update({k: deepcopy(dec.get(k)) for k in ('grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) with _current_strategy(st): if st.get('type') == 'GRID': _validate_grid_decision(st, dec) if pms_repo.insert_instruction( instruction_id=iid, origin_type="strategy", origin_id=st["strategy_id"], ts_code=code, action=dec["action"], side=dec["side"], qty=int(dec["qty"]), limit_price=dec.get("limit_price"), window_tdays=1, status="PROPOSED", progress=prog) != 1: raise RuntimeError("策略指令未成功保存") return iid def _emit_proposal(st: dict, dec: dict) -> str: """autonomy=confirm: 落一条提议进「等我拍板」。hard_numbers 里带完整动作参数, 人采纳后由 main._decide 识别 kind=strategy 再回调本层发指令 (不走通用物化, 因为 T0 买卖同 action、 side 无法由 action 反推)。""" code = st["ts_code"] now = datetime.now() pid = f"STP{_today()}{now.strftime('%H%M%S')}_{code.replace('.', '')}"[:40] hard = {"kind": "strategy", "strategy_id": st["strategy_id"], "stype": st.get("type"), "strategy_correction_id": _correction_id(st), "side": dec["side"], "leg": dec["leg"], "action": dec["action"], "qty": int(dec["qty"]), "reason": dec.get("reason"), "entry": dec.get("entry")} hard.update({k: deepcopy(dec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) expire = now.replace(hour=15, minute=0, second=0, microsecond=0) with _current_strategy(st): if pms_repo.insert_proposal(proposal_id=pid, ts_code=code, action=dec["action"], qty=int(dec["qty"]), hard_numbers=hard, expire_at=expire, judge_verdict="STRATEGY", judge_reason=f"{st.get('type')} · {dec.get('reason')}") != 1: raise RuntimeError("策略提议未成功保存") return pid def emit_from_spec(spec: dict) -> dict: """confirm 提议被采纳后的回调 (main._decide 调): 按 hard_numbers 里存的动作参数发指令。 返回 {ok, instruction_id} 或 {ok:false, error}。""" from app.services.execution_orders import account_guard try: with account_guard(): st = pms_repo.get_strategy(spec.get("strategy_id")) if not st: return {"ok": False, "error": "策略不存在或已撤下"} if st.get("status") != "ACTIVE": return {"ok": False, "error": f"策略处于 {st.get('status')}, 不再发指令"} if spec.get("strategy_correction_id") != _correction_id(st): return {"ok": False, "error": "提议对应的成交更正版本已变化,请按最新状态重新评估"} dec = {"side": spec["side"], "action": spec["action"], "qty": int(spec["qty"]), "leg": spec.get("leg") or "open", "reason": spec.get("reason"), "entry": spec.get("entry")} dec.update({k: deepcopy(spec.get(k)) for k in ('dir', 'limit_price', 'grid_entry', 'grid_exit', 'grid_params', 'grid_lot_id', 'grid_lots')}) iid = _emit_instruction(st, dec) state = dict(st.get("state") or {}) state["pending"] = {"iid": iid, "leg": dec["leg"], "dir": spec.get("dir"), "qty": dec["qty"], "entry": dec.get("entry")} if pms_repo.update_strategy(st["strategy_id"], state=state) != 1: raise RuntimeError("策略状态未成功保存") return {"ok": True, "instruction_id": iid} except Exception as e: # noqa: BLE001 logger.exception("[strategy] 采纳提议发指令失败") return {"ok": False, "error": f"{type(e).__name__}: {e}"} # ================================================================ 在途委托的收敛 def _pending_terminal(pending: dict): """上一笔委托是否已终态。返回 (已终态?, 指令行 or None)。无 pending 视为已终态。""" if not pending: return True, None iid = pending.get("iid") if not iid: # confirm 提议还没被采纳 —— 看提议是否还在等 pid = pending.get("pid") if not pid: return True, None pr = pms_repo.get_proposal(pid) if pr and pr.get("status") == "WAIT_USER": return False, None # 还在等人拍板, 先别再发 return True, None # 已采纳(转指令,另有pending.iid)/驳回/过期 ins = pms_repo.get_instruction(iid) if not ins: raise ValueError("在途父指令无法核实,保留策略等待核对") return (ins.get("status") not in LIVE_INS), ins def _reconcile(st: dict, state: dict, pos: dict): """把已终态的上一笔并进 state: 开仓成交 → 记 open_leg; 平回成交 → 记一次完成、清 open_leg。 网格库存另从真实批次重建;跟踪止盈按终态父指令实际成交扣减目标。 """ pending = state.get("pending") done, ins = _pending_terminal(pending) if not done: return False # 上一笔未走完 state["pending"] = None if not ins or not pending or not pending.get("iid"): if pending and pending.get('pid') and st.get('type') == 'TRAIL': # 人工未采纳的提议不能当成交;同日同一触发不反复催确认。 due = state.pop('trail_due', None) if due: state['trail_declined'] = {'day': _today(), 'leg': due['leg'], 'high_water': due['high_water']} return True filled = int(ins.get("exec_qty") or 0) > 0 leg = pending.get("leg") if st.get('type') == 'GRID': # 委托终态不等于已入账;新库存由真实批次投影,不恢复发单时的假设库存。 from config.settings import settings if settings.INFRA_STRATEGY_BOOK_SCHEMA and param_store.get('PMS_DISPATCH_MODE', '') == 'ws': from app.services import execution_orders if not execution_orders.replacement_state(pending['iid'])['ready']: state['pending'] = pending return False if st.get('type') == 'TRAIL' and state.get('trail_due'): due = dict(state['trail_due']) due['qty'] = max(0, int(due['qty']) - int(ins.get('exec_qty') or 0)) if due['qty']: state['trail_due'] = due else: if due.get('partial'): state['trail_fired_hw'] = due['high_water'] state.pop('trail_due', None) if st.get("type") == "T0": if leg == "open" and filled: state["open_leg"] = {"dir": pending.get("dir"), "qty": int(ins.get("exec_qty") or 0), "entry": _f(pending.get("entry")) or _f(ins.get("limit_price")), "opened_at": ins.get("updated_at") and str(ins["updated_at"])} elif leg == "close": # 平回终态: 只有真成交才算一轮完成; 一股没成 (到期/被拒) 要**保留 open_leg**, # 让下一跳与 14:50 平回继续补平 —— 绝不能把一条还开着的 T 仓静默丢掉。 filled_qty = int(ins.get("exec_qty") or 0) ol = dict(state.get("open_leg") or {}) rem = _round_lot(_f(ol.get("qty")) - filled_qty) if rem >= LOT: ol["qty"] = rem state["open_leg"] = ol if filled_qty > 0: logger.info("[strategy] %s 平回部分成交 %s, 余 %s 股待续平", st.get("strategy_id"), filled_qty, rem) else: state["t_count_today"] = int(state.get("t_count_today") or 0) + 1 state["open_leg"] = None return True # ================================================================ 评估器: 做T (设计 §六) def _eval_t0(st, pos, day, now, ctx): """做T: 正T (回落近支撑 → 买, 目标价差高卖) / 反T (近压力或滞涨 → 卖, 低买回)。 rails: 当日 ≤ 3 次; 单票 / 全局当日T亏熔断后当日禁开新T (仍允许平回已开的仓); 买入暂停 (决策系统风控预警) 时同样禁开新T, 但平回照常; 14:50 强制平回由 force_t0_close 走。 """ state = ctx["state"] price = _f(day.get("price")) if price <= 0: return None total = int(pos.get("total_qty") or 0) avail = int(pos.get("avail_qty") or 0) params = st.get("params") or {} t_ratio = min(_f(params.get("t_ratio")), param_store.get_float("PMS_T0_RATIO_MAX", 0.333)) t_qty = _round_lot(total * t_ratio) open_leg = state.get("open_leg") round_target = param_store.get_float("PMS_T0_ROUND_TARGET", 0.015) # ---- 有未平的仓 → 只找平回机会 (熔断 / 买入暂停都不挡平回) ---- if open_leg: entry = _f(open_leg.get("entry")) or price q = _round_lot(open_leg.get("qty")) if open_leg.get("dir") == "long": # 正T: 已买, 等高卖 pressure = _f(pos.get("pressure_ref")) hit = price >= entry * (1 + round_target) or (pressure > 0 and price >= pressure * (1 - NEAR_BAND)) if hit and q > 0: # 平回数量取整 (2026-08-28 审查修): avail 可能是零股 (其它卖出把可卖量 # 消耗成 137 之类), 非整百的部分卖出会被券商拒单并每跳重发。整百部分先平, # 尾巴交 14:50 兜底与对账。 q_close = min(q, avail) if q_close % LOT and q_close != int(pos.get("total_qty") or 0): q_close = _round_lot(q_close) if q_close <= 0: return None return {"side": "sell", "action": A_T0, "qty": q_close, "leg": "close", "reason": f"正T平回: 现价 {price} 达目标 {entry * (1 + round_target):.2f}(买价 {entry})"} else: # 反T: 已卖, 等低买回 support = _f(pos.get("support_ref")) hit = price <= entry * (1 - round_target) or (support > 0 and price <= support * (1 + NEAR_BAND)) if hit and q > 0: return {"side": "buy", "action": A_T0, "qty": q, "leg": "close", "reason": f"反T平回: 现价 {price} 回到目标 {entry * (1 - round_target):.2f}(卖价 {entry})"} return None # ---- 无未平的仓 → 看要不要开新的一轮 (受熔断 / 买入暂停 / 3 次 / 存量约束) ---- if ctx.get("halted") or ctx.get("buy_paused") or int(state.get("t_count_today") or 0) >= 3: return None if t_qty < LOT: return None high = _f(day.get("high")) support = _f(pos.get("support_ref")) pressure = _f(pos.get("pressure_ref")) pull = param_store.get_float("PMS_T0_PULLBACK_PCT", 0.03) rally = param_store.get_float("PMS_T0_RALLY_PCT", 0.05) dayup = _f(day.get("day_chg_from_open")) # 正T: 距当日高点回落 ≥ 回落阈 且 (近支撑 或 无支撑参照时仅凭回落, 写明) if high > 0 and price <= high * (1 - pull): near_sup = support > 0 and price <= support * (1 + NEAR_BAND) if near_sup or support <= 0: note = "近支撑" if near_sup else "无支撑参照, 仅凭回落(偏保守)" return {"side": "buy", "action": A_T0, "qty": t_qty, "leg": "open", "dir": "long", "entry": price, "reason": f"正T开仓: 距高点 {high} 回落 {1 - price / high:.1%} 且{note}, 买 {t_qty} 股"} # 反T: 近压力 或 (日内涨 ≥ 反T阈 且 已从高点滞涨) —— 卖 avail 的 t_qty, 待低买回 near_pre = pressure > 0 and price >= pressure * (1 - NEAR_BAND) stalled = dayup >= rally and high > 0 and price <= high * (1 - OFF_HIGH_BAND) if (near_pre or stalled) and avail >= LOT: q = min(t_qty, _round_lot(avail)) if q >= LOT: why = "近压力" if near_pre else f"日内涨 {dayup:.1%} 滞涨" return {"side": "sell", "action": A_T0, "qty": q, "leg": "open", "dir": "short", "entry": price, "reason": f"反T开仓: {why}, 卖 {q} 股待低买回"} return None # ================================================================ 评估器: 网格 (设计 §七) def _grid_levels(params: dict) -> list: """按 中枢/档距/上下界 生成一组网格价位 (由低到高)。档距支持百分比(step_pct)或绝对值(step)。""" lo, hi = _f(params.get("lower")), _f(params.get("upper")) center = _f(params.get("center")) step = _f(params.get("step")) step_pct = _f(params.get("step_pct")) if lo <= 0 or hi <= lo: return [] base = center if center > 0 else (lo + hi) / 2 if step <= 0 and step_pct > 0: step = base * step_pct if step <= 0: return [] levels, p, guard = [], lo, 0 while p <= hi + 1e-9 and guard < 200: levels.append(round(p, 3)) p += step guard += 1 return levels def _band(levels: list, price: float) -> int: """现价所处的档位下标: 满足 levels[i] <= price 的最大 i; 低于最低档返回 -1。""" b = -1 for i, lv in enumerate(levels): if lv <= price: b = i else: break return b def _eval_grid(st, pos, day, now, ctx): """持续检查已成交余量;买入跨过的边界与下一卖出边界相隔完整一档。""" state, params = ctx['state'], st.get('params') or {} price = _f(day.get('price')) levels = _grid_levels(params) if price <= 0 or not levels: return None filled = state.get('filled_levels') or {} avail, actual_add = int(pos.get('avail_qty') or 0), int(pos.get('add_qty') or 0) if sum(int(v.get('qty') or 0) for v in filled.values()) > actual_add: raise ValueError('网格库存超过实际增量,等待批次核对') per_lot = max(_min_lot(st.get('ts_code')), _round_lot(params.get('per_lot')) or LOT) cur, last = _band(levels, price), state.get('last_band') # 按账本实际核销顺序取连续批次,可合并零散成交,但不借用底仓凑申报数量。 from app.core.grid_inventory import sell_slice offered = sell_slice(filled, min(per_lot, actual_add, avail), price=price) q = _round_lot(offered['qty']) if q >= _min_lot(st.get('ts_code')): selected = sell_slice(filled, q, price=price) state['last_band'] = cur first = selected['lots'][0]['lot_id'] target = selected['limit_price'] return {'side':'sell', 'action':A_SELL, 'qty':q, 'leg':f'grid_sell:{first}', 'grid_lot_id':first, 'grid_lots':selected['lots'], 'grid_params':deepcopy(params), 'limit_price':target, 'reason':f'网格卖: 现价 {price} 达实际核销批次卖出线 {target},本次卖 {q} 股'} if offered['qty'] > 0: return None if price < levels[0]: state['below_floor'] = True state['last_band'] = cur return None state['below_floor'] = False if last is None or cur >= last: state['last_band'] = cur return None # 一次只取实际跨过的最近买入边界;跳空不追补多档。 k = cur + 1 state['last_band'] = cur if k >= len(levels)-1 or levels[k] >= _f(params.get('center')) or ctx.get('buy_paused'): return None entry, exit_price = levels[k], levels[k+1] if any(v.get('entry_level') == entry and int(v.get('qty') or 0) > 0 for v in filled.values()): return None ceiling = price_tick(entry) need = per_lot * ceiling if _f(state.get('invested')) + need > _f(params.get('max_capital')) + 1e-6: state['cap_hit'] = True return None state['cap_hit'] = False return {'side': 'buy', 'action': A_GRID_BUY, 'qty': per_lot, 'leg': f'grid_buy:{k}', 'grid_entry': entry, 'grid_exit': exit_price, 'grid_params': deepcopy(params), 'limit_price': ceiling, 'reason': f'网格买: 现价 {price} 跌破买入线 {entry},相邻卖出线 {exit_price},买 {per_lot} 股'} def _validate_grid_decision(st, dec): """落单前在账户锁内重读批次,拦截旧提议、旧参数和已经被其他动作卖出的库存。""" from app.services import grid_inventory if dec.get('grid_params') != (st.get('params') or {}) or _f(dec.get('limit_price')) <= 0: raise ValueError('网格报价依据已变化或缺失,停止下发') if pms_repo.list_instructions(ts_code=st['ts_code'], statuses=LIVE_INS, limit=1001): raise ValueError('同股已有在途安排,不能重复下发网格') from config.settings import settings if settings.INFRA_STRATEGY_BOOK_SCHEMA and param_store.get('PMS_DISPATCH_MODE', '') == 'ws': from app.services import execution_orders blocker = execution_orders.code_settlement_blocker(st['ts_code']) if blocker: raise ValueError(blocker) pos = pms_repo.get_position(st['ts_code']) or {} inventory = grid_inventory.snapshot(st, pos) qty = int(dec['qty']) ceiling_qty = max(_min_lot(st['ts_code']), _round_lot(st['params'].get('per_lot'))) if qty <= 0 or qty > ceiling_qty: raise ValueError('网格委托数量无效') if dec['side'] == 'sell': from app.core.grid_inventory import sell_slice selected = sell_slice(inventory['filled_levels'], qty) # 旧单批提议仅在仍然恰好核销同一批次时兼容;不能自动扩展到另一批。 expected = dec.get('grid_lots') or [{'lot_id':dec.get('grid_lot_id'), 'qty':qty}] if (qty > int(pos.get('avail_qty') or 0) or qty % LOT or qty < _min_lot(st['ts_code']) or selected['qty'] != qty or selected['lots'] != expected or _f(dec['limit_price']) < selected['limit_price']): raise ValueError('网格卖出批次、数量或价格下限已变化') else: paused = _buypause_codes() if paused is None or st['ts_code'] in paused or _macro_gate_active(): raise ValueError('网格买入当前已暂停或暂停状态不可核实') entry = _f(dec.get('grid_entry')) levels = _grid_levels(st['params']) entries = {levels[k]: levels[k+1] for k in range(1, len(levels)-1) if levels[k] < _f(st['params'].get('center'))} if (entry not in entries or dec.get('grid_exit') != entries[entry] or _f(dec['limit_price']) != price_tick(entry) or qty < _min_lot(st['ts_code']) or qty % LOT): raise ValueError('网格买入档位、相邻卖出线或价格上限无法核实') if any(v.get('entry_level') == entry for v in inventory['filled_levels'].values()): raise ValueError('该档已有实际库存,不能重复买入') if inventory['invested'] + qty * _f(dec['limit_price']) > _f(st['params'].get('max_capital')) + 1e-6: raise ValueError('网格买入超过剩余资金上限') def _tick_grid(st, pos, now, dry_run, out, buy_paused): from app.services import execution_orders, grid_inventory from app.core.execution_policy import local_now day = market.day_snapshot(st['ts_code']) or {} try: at = datetime.fromisoformat(str(day.get('bar_time')).replace('Z', '+00:00')) except (ValueError, TypeError): at = None age = (local_now(now)-local_now(at)).total_seconds() if at else None if age is None or age < 0 or age > param_store.get_int('PMS_EXEC_MINUTE_MAX_AGE_SEC', 90): out['skipped'].append({'strategy_id': st['strategy_id'], 'why': '网格分钟行情过期或时间不可核实,等待新行情'}) return emitted = None with (nullcontext(st) if dry_run else _current_strategy(st)): state = deepcopy(st.get('state') or {}) if not dry_run: pos = pms_repo.get_position(st['ts_code']) or {} live = pms_repo.list_instructions(ts_code=st['ts_code'], statuses=LIVE_INS, limit=1001) if any(i['instruction_id'] != (state.get('pending') or {}).get('iid') for i in live): out['skipped'].append({'strategy_id': st['strategy_id'], 'why': '同股已有其他在途安排,网格让路'}) return if not _reconcile(st, state, pos): out['skipped'].append({'strategy_id': st['strategy_id'], 'why': '上一笔委托或成交尚未结算'}) return from config.settings import settings if settings.INFRA_STRATEGY_BOOK_SCHEMA and param_store.get('PMS_DISPATCH_MODE', '') == 'ws': blocker = execution_orders.code_settlement_blocker(st['ts_code']) if blocker: out['skipped'].append({'strategy_id': st['strategy_id'], 'why': blocker}) return state.update(grid_inventory.snapshot(st, pos)) dec = EVALUATORS['GRID'](st, pos, day, now, {'state': state, 'notes': out['notes'], 'buy_paused': buy_paused}) if dec: if dry_run: out['fired'].append({'strategy_id': st['strategy_id'], 'dry_run': True, **dec}) return if (st.get('autonomy') or 'auto') == 'confirm': pid = _emit_proposal(st, dec) state['pending'] = {'pid': pid, 'leg': dec['leg'], 'qty': dec['qty']} emitted = ('queued', {'strategy_id': st['strategy_id'], 'proposal_id': pid, 'reason': dec['reason']}) else: iid = _emit_instruction(st, dec) state['pending'] = {'iid': iid, 'leg': dec['leg'], 'qty': dec['qty']} emitted = ('fired', {'strategy_id': st['strategy_id'], 'instruction_id': iid, **dec}) if not dry_run and pms_repo.update_strategy(st['strategy_id'], state=state) != 1: raise RuntimeError('网格状态未成功保存') if emitted: out[emitted[0]].append(emitted[1]) # ================================================================ 评估器: 跟踪止盈 (设计 §七B) def _eval_trail(st, pos, day, now, ctx): """止盈意图在实际成交后扣减;撤单、部分成交、T+1不能消耗整次减持。""" state, params = ctx['state'], st.get('params') or {} price, avg = _f(day.get('price')), _f(pos.get('avg_cost')) if price <= 0: return None avail = int(pos.get('avail_qty') or 0) total = int(pos.get('total_qty') or avail) profit = price / avg - 1 if avg > 0 else _f(pos.get('cushion_pct')) start = _f(params.get('start_line')) or param_store.get_float('PMS_CUSHION_SOLID', .03) giveback, ratio, hard = _f(params.get('giveback')), _f(params.get('sell_ratio')) or 1., _f(params.get('hard_target')) hw = max(_f(state.get('high_water')), price) state['high_water'] = round(hw, 3) if profit >= start: state['armed'] = True due = state.get('trail_due') sar = _f(params.get('sar_line')) sar_exit = (sar > 0 and now is not None and now.hour*100+now.minute >= 945 and param_store.get_bool('PMS_TECH_SAR_STOP_ON_TRAIL', True) and price <= sar*(1-param_store.get_float('PMS_TECH_SAR_STOP_BUFFER', .003))) hard_exit = hard > 0 and profit >= hard if not due or (due.get('partial') and (sar_exit or hard_exit)): leg, qty, partial, why = '', 0, False, '' if sar_exit: leg, qty, why = 'trail_sar', total, f'现价 {price} 跌破SAR止损线 {sar}' elif hard_exit: leg, qty, why = 'trail_hard', total, f'浮盈 {profit:.1%} 达硬目标 {hard:.1%}' elif state.get('armed') and giveback > 0 and price <= hw*(1-giveback) and (ratio >= 1 or hw > _f(state.get('trail_fired_hw'))+1e-9): partial = ratio < 1 qty = _round_lot(total*ratio) if partial else total if partial and _min_lot(st.get('ts_code')) > LOT and total >= _min_lot(st.get('ts_code')): qty = min(total, max(qty, _min_lot(st.get('ts_code')))) leg, why = 'trail_sell', f'现价 {price} 自高点 {hw} 回落 {1-price/hw:.1%},达到 {giveback:.1%}' declined = state.get('trail_declined') or {} if declined.get('day') == _today() and declined.get('leg') == leg and hw <= _f(declined.get('high_water')): return None if qty > 0: due = {'qty': qty, 'leg': leg, 'partial': partial, 'high_water': round(hw, 3), 'reason': why} state['trail_due'] = due if not due: return None remaining = min(int(due['qty']), total) raw = min(remaining, avail) whole_exit = not due['partial'] and raw == total q = raw if whole_exit else _round_lot(raw) if q <= 0 or (q < _min_lot(st.get('ts_code')) and not whole_exit): return None return {'side': 'sell', 'action': A_SELL if due['partial'] else A_EXIT, 'qty': q, 'leg': due['leg'], 'reason': f"跟踪止盈: {due['reason']},尚待减持 {remaining} 股,本次卖 {q} 股"} EVALUATORS = {"T0": _eval_t0, "GRID": _eval_grid, "TRAIL": _eval_trail} # ================================================================ 供 action_engine 排除 def active_codes() -> set: """有 ACTIVE 策略的 ts_code —— 供 action_engine 排除。读库失败按空集 (不误排除全体持仓)。""" try: return pms_repo.active_strategy_codes() except Exception as e: # noqa: BLE001 logger.warning("[strategy] 读取 ACTIVE 策略集失败 (按空集): %s", e) return set() # ================================================================ 每分钟主跳 def _roll_day(state: dict, pos: dict, today: int) -> dict: """做T 的按日重置: 当日次数归零, 记下当日 realized_t_profit 基线 (算当日T盈亏用)。 网格 filled_levels / 跟踪止盈 high_water 是跨日的, 不在这里动。""" if int(state.get("day") or 0) != today: state["day"] = today state["t_count_today"] = 0 state["rt_base"] = _f(pos.get("realized_t_profit")) # 未平腿必须跨日保留,不能因日切抹掉未完成的平回义务。 return state def _day_t_pnl(state: dict, pos: dict) -> float: return _f(pos.get("realized_t_profit")) - _f(state.get("rt_base")) def tick(*, now=None, dry_run: bool = False) -> dict: """盘中每分钟一跳: 载入 ACTIVE 策略 → 逐只评估 → 触发就发短窗口指令 / 落提议 → 更新 state。 dry_run=True 只算不发不落库 (页面「试算」用)。 """ now = now or datetime.now() out = {"enabled": False, "checked": 0, "fired": [], "queued": [], "skipped": [], "notes": [], "errors": [], "dry_run": dry_run} if not param_store.get_bool("PMS_STRATEGY_ENABLED", False): out["skipped"].append("PMS_STRATEGY_ENABLED=False, 策略层整体停用") return out out["enabled"] = True try: strategies = pms_repo.active_strategies() except Exception as e: # noqa: BLE001 logger.exception("[strategy] 载入 ACTIVE 策略失败") return {**out, "ok": False, "errors": [f"载入失败: {type(e).__name__}: {e}"]} if not strategies: out["ok"] = True return out try: view = portfolio.positions_view() except Exception as e: # noqa: BLE001 logger.exception("[strategy] 取持仓快照失败") return {**out, "ok": False, "errors": [f"取持仓失败: {type(e).__name__}: {e}"]} scale = _f(view.get("totals", {}).get("scale")) today = _today() paused_codes = _buypause_codes() # 决策系统风控预警暂停买入的票 (本模块只读) macro_gated = _macro_gate_active() # 宏观偏热闸: 全体策略买开腿暂停, 闸解除自动恢复 if macro_gated: out["notes"].append("宏观偏热闸生效: 策略买入开腿本轮暂停 (卖出与平回照常)") # 全局当日T亏熔断: 汇总所有做T策略的当日T盈亏 (realized_t_profit 相对日初基线的增量) global_t_pnl = 0.0 for st in strategies: if st.get("type") == "T0" and int((st.get("state") or {}).get("day") or 0) == today: global_t_pnl += _day_t_pnl(st.get("state") or {}, _pos_of(view, st["ts_code"])) global_loss_cap = param_store.get_float("PMS_T0_GLOBAL_DAY_LOSS", 0.01) * scale global_halt = scale > 0 and global_t_pnl <= -global_loss_cap if global_halt: out["notes"].append(f"全局当日T亏 {global_t_pnl:.0f} 元 达熔断线 {global_loss_cap:.0f} 元, 今日不再开新T") for st in strategies: out["checked"] += 1 code = st.get("ts_code") from app.core.execution_policy import supported_code if not supported_code(code): continue fn = EVALUATORS.get(st.get("type")) if not fn: out["skipped"].append({"strategy_id": st.get("strategy_id"), "why": f"未知策略类型 {st.get('type')}"}) continue try: pos = _pos_of(view, code) if not pos or int(pos.get("total_qty") or 0) <= 0: out["skipped"].append({"strategy_id": st.get("strategy_id"), "why": f"{code} 已无持仓, 策略空转 (可撤下)"}) continue if st.get('type') == 'GRID': paused = paused_codes is None or code in paused_codes or macro_gated from app.services import timing_state, consensus_service if timing_state.enabled() and str(st.get('note') or '').startswith('自动挂载'): allowed, blocks = consensus_service.holding_buy_consensus(code, now=now) paused = paused or not allowed if not allowed: out['notes'].append(f"{code} 自动网格买入等待三源合议放行:" + str(blocks['consensus'].get('route_reason') or blocks['consensus'].get('reason'))) _tick_grid(st, pos, now, dry_run, out, paused) continue state = deepcopy(st.get("state") or {}) if st.get("type") == "T0": state = _roll_day(state, pos, today) # 上一笔还没走完就别再发; 走完了先把结果并进 state if not _reconcile(st, state, pos): if not dry_run: pms_repo.update_strategy(st["strategy_id"], state=state) out["skipped"].append({"strategy_id": st["strategy_id"], "why": "上一笔还在途, 等它走完"}) continue day = market.day_snapshot(code) if not day or not day.get("price"): out["skipped"].append({"strategy_id": st["strategy_id"], "why": f"{code} 无实时行情 (停牌/盘前), 顺延"}) if not dry_run: pms_repo.update_strategy(st["strategy_id"], state=state) continue # 单票当日T亏熔断 (做T) halted = global_halt if st.get("type") == "T0" and scale > 0: stock_cap = param_store.get_float("PMS_T0_STOCK_DAY_LOSS", 0.003) * scale if _day_t_pnl(state, pos) <= -stock_cap: halted = True out["notes"].append(f"{code} 当日T亏达单票熔断线 {stock_cap:.0f} 元, 今日不再开新T") ctx = {"state": state, "scale": scale, "halted": halted, "notes": out["notes"], "buy_paused": paused_codes is None or (code in paused_codes) or macro_gated} dec = fn(st, pos, day, now, ctx) if dec: if not dry_run: with _current_strategy(st): if (st.get("autonomy") or "auto") == "confirm": pid = _emit_proposal(st, dec) state["pending"] = {"pid": pid, "leg": dec["leg"], "dir": dec.get("dir"), "qty": dec["qty"], "entry": dec.get("entry")} if pms_repo.update_strategy(st["strategy_id"], state=state) != 1: raise RuntimeError("策略状态未成功保存") out["queued"].append({"strategy_id": st["strategy_id"], "proposal_id": pid, "reason": dec["reason"]}) else: iid = _emit_instruction(st, dec, forced=False) state["pending"] = {"iid": iid, "leg": dec["leg"], "dir": dec.get("dir"), "qty": dec["qty"], "entry": dec.get("entry"), "grid_sell_idx": dec.get("grid_sell_idx"), "grid_restore": dec.get("_grid_restore")} if pms_repo.update_strategy(st["strategy_id"], state=state) != 1: raise RuntimeError("策略状态未成功保存") out["fired"].append({"strategy_id": st["strategy_id"], "instruction_id": iid, "side": dec["side"], "qty": dec["qty"], "reason": dec["reason"]}) else: out["fired"].append({"strategy_id": st["strategy_id"], "dry_run": True, "side": dec["side"], "qty": dec["qty"], "reason": dec["reason"]}) if not dry_run and not dec: pms_repo.update_strategy(st["strategy_id"], state=state) except Exception as e: # noqa: BLE001 —— 单策略异常不拖垮整轮 logger.exception("[strategy] 评估失败 %s", st.get("strategy_id")) out["errors"].append(f"{st.get('strategy_id')}: {type(e).__name__}: {e}") out["ok"] = not out["errors"] return out # ================================================================ 14:50 强制平回 (设计 §六 rails) def force_t0_close(*, now=None) -> dict: """做T 强制平回 (scheduler.t0_close 在 PMS_T0_CLOSE_TIME 调): 对每只有未平仓的做T策略, 立刻发反方向的平回委托把当日T仓打平, 绝不过夜。已在途的不重复 —— 这里只补「还没平」的。 平回不受买入暂停影响: 暂停挡的是开新仓, 平回是把已开的打平, 必须放行 (反T 平回是买回)。""" out = {"closed": [], "skipped": [], "errors": []} if not param_store.get_bool("PMS_STRATEGY_ENABLED", False): out["skipped"].append("PMS_STRATEGY_ENABLED=False") return out try: strategies = [s for s in pms_repo.active_strategies() if s.get("type") == "T0"] except Exception as e: # noqa: BLE001 return {**out, "errors": [f"载入做T策略失败: {type(e).__name__}: {e}"]} if not strategies: return out try: view = portfolio.positions_view() except Exception as e: # noqa: BLE001 return {**out, "errors": [f"取持仓失败: {type(e).__name__}: {e}"]} for st in strategies: code = st["ts_code"] try: state = dict(st.get("state") or {}) pos = _pos_of(view, code) _reconcile(st, state, pos) open_leg = state.get("open_leg") if not open_leg: out["skipped"].append({"strategy_id": st["strategy_id"], "why": "无未平仓"}) pms_repo.update_strategy(st["strategy_id"], state=state) continue if state.get("pending"): out["skipped"].append({"strategy_id": st["strategy_id"], "why": "平回委托已在途"}) continue q = _round_lot(open_leg.get("qty")) if q < LOT: out["skipped"].append({"strategy_id": st["strategy_id"], "why": "残量不足一手"}) continue if open_leg.get("dir") == "long": # 正T 已买 → 卖平 avail_now = int(pos.get("avail_qty") or 0) q_close = min(q, avail_now) if q_close % LOT and q_close != int(pos.get("total_qty") or 0): q_close = _round_lot(q_close) # 零股平回会被拒单, 整百部分先平 (2026-08-28) dec = {"side": "sell", "action": A_T0, "qty": q_close, "leg": "close", "reason": "14:50 强制平回(正T)"} else: # 反T 已卖 → 买平 dec = {"side": "buy", "action": A_T0, "qty": q, "leg": "close", "reason": "14:50 强制平回(反T)"} if int(dec["qty"]) < LOT: out["skipped"].append({"strategy_id": st["strategy_id"], "why": "可平量不足 (avail 不够)"}) continue with _current_strategy(st): iid = _emit_instruction(st, dec, forced=True) state["pending"] = {"iid": iid, "leg": "close", "dir": open_leg.get("dir"), "qty": dec["qty"], "entry": open_leg.get("entry")} if pms_repo.update_strategy(st["strategy_id"], state=state) != 1: raise RuntimeError("策略状态未成功保存") out["closed"].append({"strategy_id": st["strategy_id"], "instruction_id": iid, "side": dec["side"], "qty": dec["qty"]}) except Exception as e: # noqa: BLE001 logger.exception("[strategy] 强制平回失败 %s", st.get("strategy_id")) out["errors"].append(f"{st.get('strategy_id')}: {type(e).__name__}: {e}") out["ok"] = not out["errors"] return out