改用4%网格并按真实成交续卖余量
This commit is contained in:
parent
6c553d3d19
commit
2d673b0c0c
|
|
@ -2927,3 +2927,8 @@ PMS最终代码56db0fd已推送,155 web/WS/beat为execution-2b1c447,worker
|
|||
总览只保留持仓盈亏策略悬浮,提议卡片复用消息中心分类并支持再次收起,避免原右浮层盖住卡片。开发机80批及最终三道页面护栏通过,1920/1440/390/320只读真实响应重放验证开合、键盘和刷新,错误0。雷赛只读查实11月4日网格1600股中仅卖100,剩1500恢复后未被后续高档游标检查;断网纯函数复现漏卖。两票日线波动表明2%较细,但未做参数收益回测。本次仅拟发布网页,网格逻辑和在途保持,详见[接续](docs/卡片交互精简与网格幅度核验_2026-11-09.md)。
|
||||
|
||||
11:36补记:11:35:13仅pms-web发布`pms:card-cleanup-d1e4f21`,候选80批断网通过,其余18容器不变,私有配置保留。发布后实际页面哈希匹配,确认1733296与落库一致,数量/现金对账通过、待入账和孤儿0。雷赛11:36仍有网格余量1500,未生成新卖出指令;本次网格仅分析,交易缺陷待实施。
|
||||
|
||||
|
||||
## 2026-11-09 4%网格与实际成交余量修复(开发)
|
||||
|
||||
用户授权将档距改为4%并修复实际执行。当前两条网格核验发现四方同线往返、雷赛部分成交后余量漏卖。改为真实入账批次、完整卖出档及父指令限价约束,补充并发和迁移事务保护;跟踪止盈保留未完成目标,做T保留跨日未平腿。四方旧700股卖单12:01正常确认撤销、成交0。开发机81批隔离回归及37项专项通过;候选与实机判收待续。详见[接续](docs/网格档距与成交余量修复_2026-11-09.md)。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,50 @@
|
|||
"""网格只认已入账的剩余批次;几何档位与实际成交价各司其职。"""
|
||||
from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR
|
||||
|
||||
|
||||
def price_tick(value, *, sell=False):
|
||||
value = Decimal(str(value))
|
||||
if not value.is_finite() or value <= 0:
|
||||
raise ValueError('网格价格必须为有限正数')
|
||||
return float(value.quantize(Decimal('.01'), rounding=ROUND_CEILING if sell else ROUND_FLOOR))
|
||||
|
||||
|
||||
def project(strategy, lots, parents):
|
||||
"""输入同证券、同账本剩余批次及父指令,输出本网格真实库存。无网络与写入。"""
|
||||
sid, code = strategy['strategy_id'], strategy['ts_code']
|
||||
params = strategy.get('params') or {}
|
||||
pct = Decimal(str(params.get('step_pct') or 0))
|
||||
step = Decimal(str(params.get('step') or 0))
|
||||
if not pct.is_finite() or not step.is_finite() or (pct <= 0 and step <= 0):
|
||||
raise ValueError('网格档距无法核实')
|
||||
filled, invested = {}, Decimal(0)
|
||||
for lot in lots:
|
||||
qty = int(lot.get('qty') or 0)
|
||||
if qty <= 0 or lot.get('lot_type') != 'ADD':
|
||||
continue
|
||||
parent = parents.get(lot.get('instruction_id'))
|
||||
if (lot.get('ts_code') != code or not parent or parent.get('ts_code') != code
|
||||
or parent.get('origin_type') != 'strategy' or parent.get('origin_id') != sid
|
||||
or parent.get('side') != 'buy' or parent.get('action') != 'ADD'):
|
||||
raise ValueError('同股存在无法归属本网格的增量批次,停止网格动作等待核对')
|
||||
if lot.get('book_id', 'original') != 'original' or parent.get('book_id', 'original') != 'original':
|
||||
raise ValueError('网格批次账本归属不一致')
|
||||
progress = parent.get('progress') or {}
|
||||
if not str(progress.get('leg', '')).startswith('grid_buy:'):
|
||||
raise ValueError('网格批次缺少买入来源')
|
||||
cost = Decimal(str(lot['open_price']))
|
||||
if not cost.is_finite() or cost <= 0:
|
||||
raise ValueError('网格实际成交成本不可核实')
|
||||
target = cost + step if step > 0 else cost * (1 + pct)
|
||||
# 旧档距的目标不继承;存量采用本次已批准档距和实际买价。
|
||||
entry = progress.get('grid_entry')
|
||||
if progress.get('grid_params') == params and entry is not None:
|
||||
target = max(target, Decimal(str(progress['grid_exit'])))
|
||||
key = str(lot['id'])
|
||||
if key in filled:
|
||||
raise ValueError('网格批次重复')
|
||||
filled[key] = {'qty': qty, 'price': float(cost), 'sell_target': price_tick(target, sell=True),
|
||||
'entry_level': entry if progress.get('grid_params') == params else None,
|
||||
'buy_instruction_id': parent['instruction_id'], 'lot_id': lot['id']}
|
||||
invested += qty * cost
|
||||
return {'filled_levels': filled, 'invested': float(invested), 'inventory_source': 'booked_lots'}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
"""网格库存从原策略真实批次读取;不靠触发价或委托数量推定成交。"""
|
||||
from app.core import grid_inventory as core, strategy_book as books
|
||||
from app.repo import pms_repo
|
||||
|
||||
|
||||
def snapshot(strategy, position):
|
||||
with books.scope('original'):
|
||||
lots = pms_repo.list_lots(strategy['ts_code'], limit=10001)
|
||||
if len(lots) >= 10001:
|
||||
raise ValueError('网格批次数超过核验上限')
|
||||
parents = {}
|
||||
for lot in lots:
|
||||
if int(lot.get('qty') or 0) > 0 and lot.get('lot_type') == 'ADD':
|
||||
iid = lot.get('instruction_id')
|
||||
if iid not in parents:
|
||||
parents[iid] = pms_repo.get_instruction(iid) if iid else None
|
||||
result = core.project(strategy, lots, parents)
|
||||
actual = sum(r['qty'] for r in result['filled_levels'].values())
|
||||
if actual != int(position.get('add_qty') or 0) or actual > int(position.get('total_qty') or 0):
|
||||
raise ValueError('网格批次数量与持仓增量不一致,等待正常成交入账或对账')
|
||||
return result
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
"""已授权网格档距迁移:先预览,暂停策略调度后原子更新,不改成交与持仓。"""
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from app.core import strategy_book as books
|
||||
from app.core.execution_policy import supported_code
|
||||
from app.repo import pms_repo, rotation_repo
|
||||
from app.services import execution_orders, grid_inventory, param_store
|
||||
from app.services.strategy_runner import LIVE_INS
|
||||
|
||||
MIGRATION = 'grid-four-percent-20261109'
|
||||
KEY = 'strategy-migration:' + MIGRATION
|
||||
|
||||
|
||||
def _scope():
|
||||
from config.settings import settings
|
||||
if (settings.PMS_TABLE_PREFIX != '' or param_store.get('PMS_MONITOR_WATCH_SCOPE', '') != 'pms-sim-155'
|
||||
or param_store.get('PMS_DISPATCH_MODE', '') != 'ws'):
|
||||
raise ValueError('本次迁移仅允许155模拟PMS原策略')
|
||||
|
||||
|
||||
def _plan(strategy_ids):
|
||||
rows = pms_repo.active_strategies()
|
||||
targets = [s for s in rows if s.get('type') == 'GRID']
|
||||
if {s['strategy_id'] for s in targets} != set(strategy_ids):
|
||||
raise ValueError('当前生效网格集合与发布预览不一致')
|
||||
changes = []
|
||||
for old in sorted(targets, key=lambda x:x['strategy_id']):
|
||||
code = old['ts_code']
|
||||
if not supported_code(code) or (old.get('state') or {}).get('correction_hold'):
|
||||
raise ValueError('证券范围或成交更正状态不允许迁移')
|
||||
if (old.get('params') or {}).get('step'):
|
||||
raise ValueError('绝对价格档距需单独核实,不能直接覆盖')
|
||||
if pms_repo.list_instructions(ts_code=code, statuses=LIVE_INS, limit=1001):
|
||||
raise ValueError(code+'仍有在途父指令')
|
||||
pending = (old.get('state') or {}).get('pending') or {}
|
||||
if pending.get('pid'):
|
||||
raise ValueError(code+'仍有人工待确认提议')
|
||||
if pending.get('iid'):
|
||||
parent = pms_repo.get_instruction(pending['iid'])
|
||||
if not parent or not execution_orders.replacement_state(pending['iid'])['ready']:
|
||||
raise ValueError(code+'旧委托或成交尚未结算')
|
||||
blocker = execution_orders.code_settlement_blocker(code)
|
||||
if blocker:
|
||||
raise ValueError(code+': '+blocker)
|
||||
new = deepcopy(old)
|
||||
new['params']['step_pct'] = .04
|
||||
state = deepcopy(new.get('state') or {})
|
||||
state.update(grid_inventory.snapshot(new, pms_repo.get_position(code) or {}))
|
||||
state.update(pending=None, last_band=None, grid_revision=MIGRATION)
|
||||
new['state'] = state
|
||||
# 保留“自动挂载”身份和原决策说明,只替换其过时档距描述。
|
||||
note = str(old.get('note') or '').replace('步长2.0%', '步长4.0%').replace('步长 2.0%', '步长 4.0%').replace('档距 2.0%', '档距 4.0%')
|
||||
new['note'] = note + ';2026-11-09经用户批准改为4%,库存按已入账批次核验'
|
||||
changes.append({'before':old, 'after':new})
|
||||
return {'migration':MIGRATION, 'old_default':param_store.get_float('PMS_AUTO_GRID_STEP_PCT', .04), 'new_default':.04, 'changes':changes}
|
||||
|
||||
|
||||
def _fingerprint(plan):
|
||||
return sha256(rotation_repo.encode(plan).encode()).hexdigest()
|
||||
|
||||
|
||||
def migrate(strategy_ids, *, apply=False, expected=None):
|
||||
"""默认只读。apply需策略调度已停、预览未变化;重复调用只读原审计。"""
|
||||
_scope()
|
||||
with books.scope('original'):
|
||||
done, _ = rotation_repo.get(KEY)
|
||||
if done:
|
||||
return {'applied':False, 'already_applied':True, 'audit':done}
|
||||
if not apply:
|
||||
plan = _plan(strategy_ids)
|
||||
return {'applied':False, 'fingerprint':_fingerprint(plan), 'plan':plan}
|
||||
if param_store.get_bool('PMS_STRATEGY_ENABLED', True):
|
||||
raise ValueError('迁移前须温和排空worker并暂停个股策略调度')
|
||||
try:
|
||||
with rotation_repo.account_guard():
|
||||
done, _ = rotation_repo.get(KEY)
|
||||
if done:
|
||||
return {'applied':False, 'already_applied':True, 'audit':done}
|
||||
plan = _plan(strategy_ids)
|
||||
if not expected or _fingerprint(plan) != expected:
|
||||
raise ValueError('迁移预览后策略或成交状态发生变化,须重新只读核对')
|
||||
for row in plan['changes']:
|
||||
old, new = row['before'], row['after']
|
||||
if pms_repo.update_strategy(old['strategy_id'], params=new['params'], state=new['state'], note=new['note']) != 1:
|
||||
raise RuntimeError('网格迁移状态保存失败')
|
||||
result = param_store.set_param('PMS_AUTO_GRID_STEP_PCT', .04, updated_by=MIGRATION)
|
||||
if not result.get('ok') or float(pms_repo.get_param('PMS_AUTO_GRID_STEP_PCT')) != .04:
|
||||
raise RuntimeError('4%默认档距未成功落库')
|
||||
audit = {**plan, 'at':datetime.now().isoformat(), 'fingerprint':expected}
|
||||
rotation_repo.put_once(KEY, 'strategy_migration', audit)
|
||||
return {'applied':True, 'audit':audit}
|
||||
finally:
|
||||
# 事务失败不能让内存缓存留下未提交的新默认值。
|
||||
param_store._cache['loaded'] = False
|
||||
|
|
@ -121,8 +121,13 @@ def grid_params(*, price, support, pressure, band, step_pct, cap_room, cap_ratio
|
|||
if not (0 < lower < p < upper):
|
||||
return None, (f"区间不成立 (下界 {lower} / 现价 {p} / 上界 {upper}), "
|
||||
f"支撑压力形态不适合网格, 本轮放弃")
|
||||
step = max(0.005, _f(step_pct, 0.02))
|
||||
n_below = max(1, int((p - lower) / (p * step)))
|
||||
step = max(0.005, _f(step_pct, 0.04))
|
||||
# 与实际运行档位一致:必须有中枢以下买入线,且其上还有完整卖出档。
|
||||
from app.services.strategy_runner import _grid_levels
|
||||
levels = _grid_levels({'lower':lower, 'upper':upper, 'center':p, 'step_pct':step})
|
||||
n_below = sum(1 for k in range(1, len(levels)-1) if levels[k] < p)
|
||||
if not n_below:
|
||||
return None, '区间内容不下一组完整低买高卖档位,本轮不挂网格'
|
||||
per_lot = int(max_capital / n_below / p / 100) * 100
|
||||
if per_lot < lot:
|
||||
per_lot = lot
|
||||
|
|
@ -345,7 +350,7 @@ def _params() -> dict:
|
|||
"daily_max": g.get_int("PMS_AUTO_STRATEGY_DAILY_MAX", 2),
|
||||
"accum_stale_tdays": g.get_int("PMS_AUTO_ACCUM_STALE_TDAYS", 3),
|
||||
"grid_band": g.get_float("PMS_AUTO_GRID_BAND", 0.08),
|
||||
"grid_step_pct": g.get_float("PMS_AUTO_GRID_STEP_PCT", 0.02),
|
||||
"grid_step_pct": g.get_float("PMS_AUTO_GRID_STEP_PCT", 0.04),
|
||||
"grid_cap_ratio": g.get_float("PMS_AUTO_GRID_CAP_RATIO", 0.5),
|
||||
"heat_th": g.get_float("PMS_AUTO_HEAT_TH", 0.80),
|
||||
"trail_giveback": g.get_float("PMS_AUTO_TRAIL_GIVEBACK", 0.05),
|
||||
|
|
|
|||
|
|
@ -45,10 +45,12 @@ signal_digest / intraday_exec 互相覆盖 (与 portfolio.neg_streak_map 用独
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
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
|
||||
|
|
@ -105,13 +107,13 @@ def _today() -> int:
|
|||
|
||||
|
||||
def _buypause_codes() -> set:
|
||||
"""当前被暂停买入的 ts_code 集合 (决策系统对策略票的风控预警触发)。读失败按空集。"""
|
||||
"""当前被暂停买入的证券集合;读失败返回未知,停止新增买入。"""
|
||||
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 set()
|
||||
logger.warning("[strategy] 读取买入暂停集失败 (停止新增买入): %s", e)
|
||||
return None
|
||||
|
||||
|
||||
def _macro_gate_active() -> bool:
|
||||
|
|
@ -135,7 +137,7 @@ def _correction_id(st: dict):
|
|||
|
||||
@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"])
|
||||
|
|
@ -145,17 +147,18 @@ def _current_strategy(st: dict):
|
|||
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 执行。
|
||||
|
||||
limit_price 不在这里定 —— 交由 run_tick 的择时按实时行情现算 (与 materialize_plans
|
||||
同口径: 那里也是 limit_price=None)。
|
||||
网格保留买入上限、卖出下限;最终合法限价仍由执行层按新鲜行情计算。
|
||||
"""
|
||||
from config.settings import settings
|
||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and dec.get('leg') != 'close':
|
||||
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('策略轮换期间停止原策略开新腿')
|
||||
|
|
@ -168,11 +171,15 @@ def _emit_instruction(st: dict, dec: dict, *, forced: bool = False) -> str:
|
|||
"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')})
|
||||
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=None, window_tdays=1, status="PROPOSED", progress=prog) != 1:
|
||||
limit_price=dec.get("limit_price"), window_tdays=1, status="PROPOSED", progress=prog) != 1:
|
||||
raise RuntimeError("策略指令未成功保存")
|
||||
return iid
|
||||
|
||||
|
|
@ -188,6 +195,7 @@ def _emit_proposal(st: dict, dec: dict) -> str:
|
|||
"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')})
|
||||
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"],
|
||||
|
|
@ -214,6 +222,7 @@ def emit_from_spec(spec: dict) -> dict:
|
|||
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')})
|
||||
iid = _emit_instruction(st, dec)
|
||||
state = dict(st.get("state") or {})
|
||||
state["pending"] = {"iid": iid, "leg": dec["leg"], "dir": spec.get("dir"),
|
||||
|
|
@ -242,14 +251,14 @@ def _pending_terminal(pending: dict):
|
|||
return True, None # 已采纳(转指令,另有pending.iid)/驳回/过期
|
||||
ins = pms_repo.get_instruction(iid)
|
||||
if not ins:
|
||||
return True, None
|
||||
raise ValueError("在途父指令无法核实,保留策略等待核对")
|
||||
return (ins.get("status") not in LIVE_INS), ins
|
||||
|
||||
|
||||
def _reconcile(st: dict, state: dict, pos: dict):
|
||||
"""把已终态的上一笔并进 state: 开仓成交 → 记 open_leg; 平回成交 → 记一次完成、清 open_leg。
|
||||
|
||||
做T 用; 网格 / 跟踪止盈 的 filled_levels / high_water 在各自评估器里按现价推进, 不依赖这里。
|
||||
网格库存另从真实批次重建;跟踪止盈按终态父指令实际成交扣减目标。
|
||||
"""
|
||||
pending = state.get("pending")
|
||||
done, ins = _pending_terminal(pending)
|
||||
|
|
@ -257,23 +266,31 @@ def _reconcile(st: dict, state: dict, pos: dict):
|
|||
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" and str(leg or "").startswith("grid_sell"):
|
||||
# 网格卖单当日未成交作废 → 把发单时弹掉的档位放回去 (2026-08-28 审查修)。
|
||||
# 部分成交则按剩余量放回; 全成交不放。invested 同步加回放回部分。
|
||||
exec_qty = int(ins.get("exec_qty") or 0)
|
||||
info = dict(pending.get("grid_restore") or {})
|
||||
idx = pending.get("grid_sell_idx")
|
||||
left = int(_f(info.get("qty"))) - exec_qty
|
||||
if idx is not None and info and left >= LOT:
|
||||
fl = dict(state.get("filled_levels") or {})
|
||||
fl[str(idx)] = {"price": _f(info.get("price")), "qty": left}
|
||||
state["filled_levels"] = fl
|
||||
state["invested"] = _f(state.get("invested")) + _f(info.get("price")) * left
|
||||
logger.info("[strategy] %s 网格卖档 %s 未全成交 (成 %s), 档位按余量 %s 放回",
|
||||
st.get("strategy_id"), idx, exec_qty, left)
|
||||
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),
|
||||
|
|
@ -410,205 +427,202 @@ def _band(levels: list, price: float) -> int:
|
|||
|
||||
|
||||
def _eval_grid(st, pos, day, now, ctx):
|
||||
"""网格(逐档穿越): 价每向下跌破一个新档买一手(只买中枢下方), 向上涨破一个档就把下面对应
|
||||
档买的那手卖掉(从 avail)。一跳只走一档; 跌破下界=继续持有不再买; 买入暂停只停买、卖出照常;
|
||||
filled_levels 每跳与真实 ADD 持仓对账, 被对账冲销后收敛 —— 绝不卖幻影档(误卖底仓)。"""
|
||||
state = ctx["state"]
|
||||
params = st.get("params") or {}
|
||||
price = _f(day.get("price"))
|
||||
if price <= 0:
|
||||
return None
|
||||
"""持续检查已成交余量;买入跨过的边界与下一卖出边界相隔完整一档。"""
|
||||
state, params = ctx['state'], st.get('params') or {}
|
||||
price = _f(day.get('price'))
|
||||
levels = _grid_levels(params)
|
||||
if not levels:
|
||||
if price <= 0 or not levels:
|
||||
return None
|
||||
lo = levels[0]
|
||||
mlot = _min_lot(st.get("ts_code"))
|
||||
per_lot = _round_lot(params.get("per_lot")) or LOT
|
||||
if per_lot < mlot:
|
||||
per_lot = mlot # 科创板 200 股起: 手工挂的 100 股档在这里抬成合法数量
|
||||
max_capital = _f(params.get("max_capital"))
|
||||
filled = {int(k): dict(v) for k, v in (state.get("filled_levels") or {}).items()}
|
||||
invested = _f(state.get("invested"))
|
||||
avail = int(pos.get("avail_qty") or 0)
|
||||
actual_add = int(pos.get("add_qty") or 0) # 网格买入记 ADD 批次, 这是真实网格持仓
|
||||
|
||||
# —— 对账收敛: filled 声称的网格股 > 真实(被 RECON 冲销) → 收敛; 真实为0则清空重来 ——
|
||||
claimed = sum(int(v.get("qty") or 0) for v in filled.values())
|
||||
if claimed > actual_add:
|
||||
if actual_add <= 0:
|
||||
if filled:
|
||||
ctx["notes"].append(f"{st['ts_code']} 网格持仓已被对账冲销(真实网格股0), 清空网格档位重来")
|
||||
filled, invested = {}, 0.0
|
||||
state["last_band"] = None
|
||||
else:
|
||||
for k in sorted(filled.keys()):
|
||||
if claimed <= actual_add:
|
||||
break
|
||||
q = int(filled[k].get("qty") or 0)
|
||||
invested = max(0.0, invested - _f(filled[k].get("price")) * q)
|
||||
claimed -= q
|
||||
del filled[k]
|
||||
ctx["notes"].append(f"{st['ts_code']} 网格档位与真实持仓对齐(真实网格股 {actual_add})")
|
||||
state["filled_levels"] = {str(k): v for k, v in filled.items()}
|
||||
state["invested"] = invested
|
||||
|
||||
cur = _band(levels, price)
|
||||
last = state.get("last_band")
|
||||
|
||||
# 跌破下界: 停买、保留已买、告警; 记基准档但不交易
|
||||
if price < lo:
|
||||
if not state.get("below_floor"):
|
||||
state["below_floor"] = True
|
||||
ctx["notes"].append(f"{st['ts_code']} 跌破网格下界 {lo}, 已停止网格买入(继续持有已买档)")
|
||||
state["last_band"] = cur
|
||||
return None
|
||||
state["below_floor"] = False
|
||||
|
||||
# 首跳: 只记基准档, 不交易 (等价格真正穿越档位才动)
|
||||
if last is None:
|
||||
state["last_band"] = cur
|
||||
return None
|
||||
|
||||
# —— 上行: 价涨破 → 卖掉离开的这一档买的那手 (从 avail, 且确有网格股, 才卖) ——
|
||||
if cur > last:
|
||||
k = last
|
||||
if k in filled and avail >= LOT and actual_add >= LOT:
|
||||
info = filled[k]
|
||||
# 部分成交恢复的档位可能小于配置档量;不能借底仓补齐一档。
|
||||
# 同时守住实际网格股和可卖量,最小申报口径继续沿用下面的检查。
|
||||
q = min(per_lot, _round_lot(info.get("qty")),
|
||||
_round_lot(actual_add), _round_lot(avail))
|
||||
if q >= mlot: # 科创板部分卖低于 200 股不合法, 量不足先不推进
|
||||
state["last_band"] = last + 1
|
||||
return {"side": "sell", "action": A_SELL, "qty": q, "leg": f"grid_sell:{k}",
|
||||
"grid_sell_idx": k,
|
||||
"reason": f"网格卖: 现价 {price} 涨破档{k}(买价 {info.get('price')}), 卖 {q} 股"}
|
||||
return None # 有档可卖但量不足, 先不推进, 下跳再试
|
||||
state["last_band"] = last + 1 # 该档无网格持仓可卖, 只随价上移
|
||||
return None
|
||||
|
||||
# —— 下行: 价跌破新档 → 买这一档 (只买中枢下方; 受下界/暂停/上限约束) ——
|
||||
if cur < last:
|
||||
k = last - 1 # 刚跌破的这一档
|
||||
if k < 0:
|
||||
state["last_band"] = cur
|
||||
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')
|
||||
# 批次按账本FIFO顺序处理,避免TRIM核销另一档尚未到价的库存。
|
||||
for key, info in filled.items():
|
||||
qty = int(info.get('qty') or 0)
|
||||
if not qty:
|
||||
continue
|
||||
target = _f(info.get('sell_target'))
|
||||
if target <= 0:
|
||||
raise ValueError('网格批次缺少实际成本对应的卖出下限')
|
||||
if price < target:
|
||||
break
|
||||
q = min(per_lot, _round_lot(qty), _round_lot(actual_add), _round_lot(avail))
|
||||
if q < _min_lot(st.get('ts_code')):
|
||||
return None
|
||||
# **只买中枢下方** (2026-08-28 审查修): 档位表覆盖整个区间, 原实现对跌破的任何档
|
||||
# 都买 —— 价格先涨向上界再回落一档, 就在中枢上方接了一手; 上半区震荡还会把预算
|
||||
# (按中枢以下档数摊的 per_lot) 先吃光, 真跌回吸筹区反而触顶停买。恰好高买低不买。
|
||||
center = _f(params.get("center")) or ((lo + _f(params.get("upper"))) / 2
|
||||
if _f(params.get("upper")) > 0 else 0.0)
|
||||
if center > 0 and k < len(levels) and levels[k] >= center:
|
||||
state["last_band"] = last - 1 # 中枢上方: 只随价下移, 不买
|
||||
return None
|
||||
if k in filled:
|
||||
state["last_band"] = last - 1 # 已买, 只推进
|
||||
return None
|
||||
if ctx.get("buy_paused"):
|
||||
return None # 暂停买入: 原地等, 不推进
|
||||
need = per_lot * price
|
||||
if max_capital > 0 and invested + need > max_capital + 1e-6:
|
||||
if not state.get("cap_hit"):
|
||||
state["cap_hit"] = True
|
||||
ctx["notes"].append(f"{st['ts_code']} 网格已达最大投入 {max_capital:.0f} 元, 暂停买入")
|
||||
return None # 触顶: 不推进, 下次重试
|
||||
state["cap_hit"] = False
|
||||
state["last_band"] = last - 1
|
||||
return {"side": "buy", "action": A_GRID_BUY, "qty": per_lot, "leg": f"grid_buy:{k}",
|
||||
"grid_buy_idx": k, "grid_buy_price": price,
|
||||
"reason": f"网格买: 现价 {price} 跌破档{k}(档价 {levels[k]}), 买 {per_lot} 股"}
|
||||
state['last_band'] = cur
|
||||
return {'side': 'sell', 'action': A_SELL, 'qty': q, 'leg': f'grid_sell:{key}',
|
||||
'grid_lot_id': info.get('lot_id'), 'grid_params': deepcopy(params),
|
||||
'limit_price': target,
|
||||
'reason': f'网格卖: 现价 {price} 达已成交批次卖出线 {target},余量 {qty} 股,本次卖 {q} 股'}
|
||||
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} 股'}
|
||||
|
||||
return None # cur == last, 同档不动
|
||||
|
||||
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':
|
||||
first = next(iter(inventory['filled_levels'].values()), {})
|
||||
if (first.get('lot_id') != dec.get('grid_lot_id') or qty > int(first.get('qty') or 0)
|
||||
or _f(dec['limit_price']) < _f(first.get('sell_target'))):
|
||||
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):
|
||||
"""跟踪止盈: 创新高抬止盈线, 从高点回落 ≥ giveback 就卖 (从 avail); 命中硬止盈目标直接全清。
|
||||
只卖不买 —— 纯离场保护, 不受买入暂停影响。"""
|
||||
state = ctx["state"]
|
||||
params = st.get("params") or {}
|
||||
price = _f(day.get("price"))
|
||||
"""止盈意图在实际成交后扣减;撤单、部分成交、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
|
||||
avg = _f(pos.get("avg_cost"))
|
||||
avail = int(pos.get("avail_qty") or 0)
|
||||
profit = _f(pos.get("cushion_pct")) if pos.get("cushion_pct") is not None else (
|
||||
(price / avg - 1) if avg > 0 else 0.0)
|
||||
|
||||
start_line = _f(params.get("start_line")) or param_store.get_float("PMS_CUSHION_SOLID", 0.03)
|
||||
giveback = _f(params.get("giveback"))
|
||||
sell_ratio = _f(params.get("sell_ratio")) or 1.0
|
||||
hard_target = _f(params.get("hard_target"))
|
||||
|
||||
# 高水位每跳只抬不降
|
||||
hw = max(_f(state.get("high_water")), price)
|
||||
state["high_water"] = round(hw, 3)
|
||||
if not state.get("armed") and profit >= start_line:
|
||||
state["armed"] = True
|
||||
ctx["notes"].append(f"{st['ts_code']} 跟踪止盈已启动(浮盈 {profit:.1%} ≥ 启动线 {start_line:.1%})")
|
||||
|
||||
total = int(pos.get("total_qty") or 0)
|
||||
mlot = _min_lot(st.get("ts_code"))
|
||||
if avail < LOT:
|
||||
# 零股尾巴的出口 (2026-08-28 审查修): 主板整百取整后剩的 <100 股, 原来在这里
|
||||
# 永远 return None, 挂着策略又被动作引擎排除 —— 尾巴永久滞留。A股规则允许
|
||||
# 零股**一次性全部卖出**, 所以当尾巴就是全部持仓、且硬目标或回落条件仍成立时,
|
||||
# 按全清把尾巴一次清掉; 其余情形照旧只更新高水位。
|
||||
tail_hit = (hard_target > 0 and profit >= hard_target) or (
|
||||
state.get("armed") and hw > 0 and giveback > 0 and price <= hw * (1 - giveback))
|
||||
if avail > 0 and avail == total and tail_hit:
|
||||
return {"side": "sell", "action": A_EXIT, "qty": avail, "leg": "trail_hard",
|
||||
"reason": f"跟踪止盈-零股收尾: 余 {avail} 股为全部持仓, 一次性清出"}
|
||||
return None # 无 T+1 可卖 (或尾巴暂不能清), 只更新高水位
|
||||
|
||||
def _all_out():
|
||||
# 全清数量: 科创板持仓不足 200 股时按交易所例外一次性全卖, 否则整百
|
||||
return avail if avail < mlot else (_round_lot(avail) or avail)
|
||||
|
||||
# 盘中 SAR 止损线 (2026-09-11 工作包三 part 3): 09:45 后现价跌破昨日 SAR 值的缓冲即全清, 当日只触发一次。
|
||||
# SAR 值由 09:40 的 strategy_advisor.scan 刷进 params["sar_line"] (工作包三 part 3 的刷新腿);
|
||||
# 没刷进 (技术面无读数、首日、映射停更) 就跳过这道线 —— 加不改, 拿不到 SAR 绝不当"跌破"。
|
||||
# 与 giveback/hard_target 并列的一道硬止损, 不看 armed (SAR 翻空是趋势破位, 不必先武装)。
|
||||
sar_line = _f(params.get("sar_line"))
|
||||
if sar_line > 0 and now is not None and param_store.get_bool("PMS_TECH_SAR_STOP_ON_TRAIL", True):
|
||||
hm = now.hour * 100 + now.minute
|
||||
if hm >= 945 and int(state.get("sar_stop_day") or 0) != td.ymd(now):
|
||||
buf = param_store.get_float("PMS_TECH_SAR_STOP_BUFFER", 0.003)
|
||||
if price <= sar_line * (1 - buf):
|
||||
state["sar_stop_day"] = td.ymd(now) # 当日只触发一次
|
||||
return {"side": "sell", "action": A_EXIT, "qty": _all_out(), "leg": "trail_sar",
|
||||
"reason": f"跟踪止盈-SAR 止损: 现价 {price} 跌破昨日 SAR {sar_line}"
|
||||
f"×(1-{buf:.1%}), 全清 {_all_out()} 股"}
|
||||
|
||||
# 硬止盈目标: 直接全清
|
||||
if hard_target > 0 and profit >= hard_target:
|
||||
return {"side": "sell", "action": A_EXIT, "qty": _all_out(), "leg": "trail_hard",
|
||||
"reason": f"跟踪止盈-硬目标: 浮盈 {profit:.1%} ≥ {hard_target:.1%}, 全清 avail {avail} 股"}
|
||||
|
||||
# 已武装且从高点回落到设定比例 → 卖。
|
||||
# **部分卖有一次性闩锁** (2026-08-28 审查修): "回撤 5% 卖 50%" 的本意是这轮回撤卖一次。
|
||||
# 原来高水位只抬不降、armed 永不复位, 卖完上一单后条件仍成立, 每隔一单再卖剩余的一半,
|
||||
# 几何级联直到卖光。闩锁记"已按哪个高水位卖过" (trail_fired_hw), 只有高水位**再创新高**
|
||||
# 之后的下一轮回撤才允许再卖; 全清路径 (sell_ratio≥1 与硬目标) 不上锁 —— 清仓意图
|
||||
# 失败了就该重试。
|
||||
fired_hw = _f(state.get("trail_fired_hw"))
|
||||
if state.get("armed") and hw > 0 and price <= hw * (1 - giveback) and giveback > 0 \
|
||||
and (sell_ratio >= 1 or hw > fired_hw + 1e-9):
|
||||
if sell_ratio < 1:
|
||||
q = _round_lot(avail * sell_ratio)
|
||||
if mlot > LOT:
|
||||
# 科创板: 部分卖低于 200 股不合法 —— 量够就抬到 200 (方向是保利润, 多卖
|
||||
# 一点偏保守), 可卖的本来就不足 200 则这条部分卖路径放弃, 等硬目标或人工
|
||||
q = 0 if avail < mlot else min(max(q, mlot), _round_lot(avail))
|
||||
else:
|
||||
q = _all_out()
|
||||
if q >= mlot or (sell_ratio >= 1 and q > 0):
|
||||
act = A_EXIT if sell_ratio >= 1 else A_SELL
|
||||
if sell_ratio < 1:
|
||||
state["trail_fired_hw"] = round(hw, 3)
|
||||
return {"side": "sell", "action": act, "qty": q, "leg": "trail_sell",
|
||||
"reason": f"跟踪止盈: 现价 {price} 自高点 {hw} 回落 {1 - price / hw:.1%} ≥ {giveback:.1%}, 卖 {q} 股"}
|
||||
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')
|
||||
if not due:
|
||||
leg, qty, partial, why = '', 0, False, ''
|
||||
sar = _f(params.get('sar_line'))
|
||||
if (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))):
|
||||
leg, qty, why = 'trail_sar', total, f'现价 {price} 跌破SAR止损线 {sar}'
|
||||
elif hard > 0 and profit >= hard:
|
||||
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}
|
||||
|
|
@ -632,8 +646,7 @@ def _roll_day(state: dict, pos: dict, today: int) -> dict:
|
|||
state["day"] = today
|
||||
state["t_count_today"] = 0
|
||||
state["rt_base"] = _f(pos.get("realized_t_profit"))
|
||||
# 隔夜后原则上不该留未平的仓 (14:50 已平回); 万一留了, 清掉 open_leg 交对账兜底
|
||||
state["open_leg"] = None
|
||||
# 未平腿必须跨日保留,不能因日切抹掉未完成的平回义务。
|
||||
return state
|
||||
|
||||
|
||||
|
|
@ -678,7 +691,7 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
# 全局当日T亏熔断: 汇总所有做T策略的当日T盈亏 (realized_t_profit 相对日初基线的增量)
|
||||
global_t_pnl = 0.0
|
||||
for st in strategies:
|
||||
if st.get("type") == "T0":
|
||||
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
|
||||
|
|
@ -688,6 +701,9 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
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"),
|
||||
|
|
@ -699,7 +715,10 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
out["skipped"].append({"strategy_id": st.get("strategy_id"),
|
||||
"why": f"{code} 已无持仓, 策略空转 (可撤下)"})
|
||||
continue
|
||||
state = dict(st.get("state") or {})
|
||||
if st.get('type') == 'GRID':
|
||||
_tick_grid(st, pos, now, dry_run, out, paused_codes is None or code in paused_codes or macro_gated)
|
||||
continue
|
||||
state = deepcopy(st.get("state") or {})
|
||||
if st.get("type") == "T0":
|
||||
state = _roll_day(state, pos, today)
|
||||
|
||||
|
|
@ -727,13 +746,12 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
out["notes"].append(f"{code} 当日T亏达单票熔断线 {stock_cap:.0f} 元, 今日不再开新T")
|
||||
|
||||
ctx = {"state": state, "scale": scale, "halted": halted, "notes": out["notes"],
|
||||
"buy_paused": (code in paused_codes) or macro_gated}
|
||||
"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):
|
||||
_apply_grid_state(state, dec)
|
||||
if (st.get("autonomy") or "auto") == "confirm":
|
||||
pid = _emit_proposal(st, dec)
|
||||
state["pending"] = {"pid": pid, "leg": dec["leg"], "dir": dec.get("dir"),
|
||||
|
|
@ -766,28 +784,6 @@ def tick(*, now=None, dry_run: bool = False) -> dict:
|
|||
return out
|
||||
|
||||
|
||||
def _apply_grid_state(state: dict, dec: dict):
|
||||
"""网格发单同时更新 filled_levels / invested (买入占用一档, 卖出释放一档)。
|
||||
|
||||
卖出弹掉的档位信息随手塞回 dec (_grid_restore): 委托当日一股没成交时,
|
||||
_reconcile 要把这档**放回去** —— 原来发单即弹档、未成交不回滚, 股票还在档位
|
||||
记录没了, 下次跌破同档会再买一手 (同档双份), invested 也被提前扣掉导致上限
|
||||
实际被突破一档 (2026-08-28 审查修)。"""
|
||||
if "grid_buy_idx" in dec:
|
||||
filled = dict(state.get("filled_levels") or {})
|
||||
filled[str(dec["grid_buy_idx"])] = {"price": _f(dec.get("grid_buy_price")),
|
||||
"qty": int(dec["qty"])}
|
||||
state["filled_levels"] = filled
|
||||
state["invested"] = _f(state.get("invested")) + _f(dec.get("grid_buy_price")) * int(dec["qty"])
|
||||
elif "grid_sell_idx" in dec:
|
||||
filled = dict(state.get("filled_levels") or {})
|
||||
info = filled.pop(str(dec["grid_sell_idx"]), None)
|
||||
state["filled_levels"] = filled
|
||||
if info:
|
||||
dec["_grid_restore"] = dict(info)
|
||||
state["invested"] = max(0.0, _f(state.get("invested")) - _f(info.get("price")) * int(info.get("qty") or 0))
|
||||
|
||||
|
||||
# ================================================================ 14:50 强制平回 (设计 §六 rails)
|
||||
def force_t0_close(*, now=None) -> dict:
|
||||
"""做T 强制平回 (scheduler.t0_close 在 PMS_T0_CLOSE_TIME 调): 对每只有未平仓的做T策略,
|
||||
|
|
|
|||
|
|
@ -46,8 +46,9 @@ def validate(cfg: dict, view=None) -> dict:
|
|||
typ = cfg.get("type")
|
||||
autonomy = cfg.get("autonomy") or "auto"
|
||||
params = cfg.get("params") or {}
|
||||
if not code:
|
||||
reasons.append("未指定股票")
|
||||
from app.core.execution_policy import supported_code
|
||||
if not supported_code(code):
|
||||
reasons.append("交易方案仅支持规范沪深A股代码")
|
||||
if typ not in TYPES:
|
||||
reasons.append(f"未知策略类型 {typ}(仅支持 做T=T0 / 网格=GRID / 跟踪止盈=TRAIL)")
|
||||
if autonomy not in AUTONOMY:
|
||||
|
|
@ -67,8 +68,8 @@ def validate(cfg: dict, view=None) -> dict:
|
|||
# 同股已有 ACTIVE 策略 → 不重复挂
|
||||
try:
|
||||
dup = pms_repo.list_strategies(ts_code=code, statuses=["ACTIVE"], limit=5)
|
||||
except Exception: # noqa: BLE001
|
||||
dup = []
|
||||
except Exception as exc:
|
||||
return {"ok": False, "reasons": [f"已有策略无法核实,暂不能重复挂载: {type(exc).__name__}"]}
|
||||
if dup:
|
||||
reasons.append(f"该股已挂着一条 {dup[0].get('type')} 策略(生效中), 先撤下再挂新的")
|
||||
|
||||
|
|
@ -118,10 +119,12 @@ def attach(cfg: dict, by: str = "user") -> dict:
|
|||
code = cfg["ts_code"]
|
||||
ymd = td.ymd()
|
||||
sid = f"STR_{ymd}_{code.replace('.', '')}_{int(datetime.now().timestamp()) % 1000000}"
|
||||
pms_repo.insert_strategy(strategy_id=sid, ts_code=code, stype=cfg["type"],
|
||||
saved = pms_repo.insert_strategy(strategy_id=sid, ts_code=code, stype=cfg["type"],
|
||||
autonomy=cfg.get("autonomy") or "auto",
|
||||
params=cfg.get("params") or {}, state={},
|
||||
status="ACTIVE", note=cfg.get("note"))
|
||||
if saved != 1:
|
||||
return {"ok": False, "errors": ["交易方案未成功保存"]}
|
||||
return {"ok": True, "strategy_id": sid, "ts_code": code}
|
||||
|
||||
|
||||
|
|
@ -133,7 +136,8 @@ def set_status(strategy_id: str, status: str, by: str = "user") -> dict:
|
|||
st = pms_repo.get_strategy(strategy_id)
|
||||
if not st:
|
||||
return {"ok": False, "error": "策略不存在"}
|
||||
pms_repo.update_strategy(strategy_id, status=status)
|
||||
if pms_repo.update_strategy(strategy_id, status=status) != 1:
|
||||
return {"ok": False, "error": "交易方案状态未成功保存"}
|
||||
return {"ok": True, "strategy_id": strategy_id, "ts_code": st.get("ts_code"), "status": status}
|
||||
|
||||
|
||||
|
|
@ -234,12 +238,12 @@ BUYPAUSE_KEY = "PMS_STRATEGY_BUYPAUSE"
|
|||
|
||||
|
||||
def buypause_map() -> dict:
|
||||
"""当前被暂停买入的票 {ts_code: {reason, source, at}}。读失败按空 (不误暂停)。"""
|
||||
try:
|
||||
raw = pms_repo.get_param(BUYPAUSE_KEY)
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
"""暂停状态读取失败不能解释为已解除;调用方按故障保守处理。"""
|
||||
raw = pms_repo.get_param(BUYPAUSE_KEY)
|
||||
value = json.loads(raw) if raw else {}
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError('策略买入暂停状态格式异常')
|
||||
return value
|
||||
|
||||
|
||||
def _save_buypause(m: dict) -> dict:
|
||||
|
|
|
|||
|
|
@ -3052,7 +3052,7 @@ createApp({
|
|||
watch(instructionBook, () => { if (insTab.value==='deny') insTab.value='live'; });
|
||||
const stratDlg = reactive({ visible:false, busy:false, reasons:[], ts_code:'', price:0,
|
||||
total_qty:0, avail_qty:0, cushion_pct:null, type:'T0', autonomy:'auto',
|
||||
p:{ t_ratio:0.2, lower:0, upper:0, center:0, step_pct:0.02, per_lot:100, max_capital:0,
|
||||
p:{ t_ratio:0.2, lower:0, upper:0, center:0, step_pct:0.04, per_lot:100, max_capital:0,
|
||||
start_line:0.03, giveback:0.05, sell_ratio:1.0, hard_target:0 } });
|
||||
const dm = ref({});
|
||||
const opsDrawer = ref(false), opsResult = ref(''), opsLoading = ref(false);
|
||||
|
|
@ -5156,7 +5156,7 @@ createApp({
|
|||
price: px, total_qty: row.total_qty, avail_qty: row.avail_qty,
|
||||
cushion_pct: row.cushion_pct, type: 'T0', autonomy: 'auto',
|
||||
p: { t_ratio: 0.2, lower: +(px * 0.92).toFixed(2), upper: +(px * 1.08).toFixed(2),
|
||||
center: px, step_pct: 0.02, per_lot: 100, max_capital: 0,
|
||||
center: px, step_pct: 0.04, per_lot: 100, max_capital: 0,
|
||||
start_line: 0.03, giveback: 0.05, sell_ratio: 1.0, hard_target: 0 }
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -342,7 +342,7 @@ class Settings(BaseSettings):
|
|||
PMS_AUTO_STRATEGY_DAILY_MAX: int = 2 # 每日自动新挂上限 (接力换挂不计入)
|
||||
PMS_AUTO_ACCUM_STALE_TDAYS: int = 3 # 吸筹结论日龄超此 (交易日) 视为过期不触发
|
||||
PMS_AUTO_GRID_BAND: float = 0.08 # 支撑压力锚不住时网格区间退化为 现价×(1±带宽)
|
||||
PMS_AUTO_GRID_STEP_PCT: float = 0.02 # 自动网格步长 (占中枢价)
|
||||
PMS_AUTO_GRID_STEP_PCT: float = 0.04 # 自动网格步长 (占中枢价)
|
||||
PMS_AUTO_GRID_CAP_RATIO: float = 0.5 # 网格最大投入 = 单股上限余量 × 此比例
|
||||
PMS_AUTO_HEAT_TH: float = 0.80 # 热度阈值 0~1 (2026-08-25 实测 ≥0.8 约前 4%)
|
||||
PMS_AUTO_TRAIL_GIVEBACK: float = 0.05 # 自动跟踪止盈: 距高水位回撤触发
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
|
||||
| 任务 | 入口 |
|
||||
| --- | --- |
|
||||
| 4%网格档距、实际批次余量及盘中迁移 | [11月9日网格执行修复](网格档距与成交余量修复_2026-11-09.md),以最新部署和实际回执为准 |
|
||||
| 总览卡片悬浮精简、提议再次收起、2%网格及雷赛未减仓原因 | [11月9日卡片与网格核验](卡片交互精简与网格幅度核验_2026-11-09.md),区分已修页面和待实施的网格余量漏卖 |
|
||||
| 累计与持仓盈亏比例、策略悬浮明细及四方股份网格原因 | [11月9日多策略盈亏与网格核验](多策略盈亏与四方网格核验_2026-11-09.md),区分页面修复、实际成交及待实施的网格档位问题 |
|
||||
| 账户累计盈亏、消息分类收起及刷新布局 | [11月9日修复接续](账户盈亏与消息布局修复_2026-11-09.md),含账户收益基线、费用口径、桌面与窄屏验证及仅页面发布 |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
# 4%网格与实际成交余量修复
|
||||
|
||||
核验时间:2026年11月9日12:06,北京时间。当前状态为开发完成、候选发布前,发布后在文末追加实际结果。
|
||||
|
||||
用户明确将网格档距改为4%,并授权核查和修复交易策略的不合理行为。范围是155模拟PMS;不操作188、账本持仓、成交回报或其他系统。
|
||||
|
||||
## 实际问题与修复
|
||||
|
||||
11:42只读核验确认目前只有雷赛智能002979.SZ和四方股份601126.SH两条生效网格,没有生效的做T或跟踪止盈策略。此前默认及两条网格均为2%。
|
||||
|
||||
- 旧买入档位与卖出触发线存在错位,四方31.37元买入后仅回到31.38元就生成卖单,委托价甚至可以低于买价。新规则在下穿买入线后,至少到相邻完整卖出线且不低于实际买价加4%才允许减持。限价下限进入父指令,撤换报价仍受同一约束。这里4%是档距及批次毛价差下限,未知费用不能当零,也不等于保证净收益4%。
|
||||
- 旧网格在发指令时预先移除整档库存,仅在跨档瞬间检查卖出。部分成交、T+1或可卖量不足会漏掉余量。新库存来自已入账的ADD批次和所属网格父指令,逐次按实际剩余及FIFO检查,不重复计资金、不卖BASE底仓,不认领其他策略增量。不能核实来源时暂停该网格动作。
|
||||
- 下单、状态保存和成交更正检查共用账户锁;旧参数或旧状态的并发任务、旧人工提议不能重放。未知在途指令和未结算回报继续等待。
|
||||
- 买入暂停表读取失败停止新增买入;卖出不被原策略买入轮换闸挡住。小区间放不下完整低买高卖档时不再自动挂空转网格。缺失或过期分钟行情等待下一条,不以午间停更制造动作。
|
||||
- 跟踪止盈在实际成交后消耗待减持量,撤单、部分成交和T+1保留剩余目标;人工拒绝的同日同一触发不会反复催确认。做T未平腿跨日保留,昨日T亏损不重复计入新一天全局熔断。当前没有这两种生效策略,本项只有隔离测试证据。
|
||||
|
||||
## 存量迁移
|
||||
|
||||
采用`app.services.grid_migration.migrate`。默认只读预览;实际应用要求155实例、策略调度暂停、两条目标集合吻合、无在途和未结算回报。账户事务内核验预览指纹,再同时更新参数、真实库存和一次性审计。事务失败整体回滚;重复执行只读既有审计,不覆盖后来成交形成的库存。
|
||||
|
||||
保持中枢、上下界、单档数量、资金上限、底仓和既有暂停不变。重置穿档游标为未初始化,第一条行情仅建立观察基线;已到卖出下限的真实增量可以正常减持。旧2%档号不重新解释为4%档号。
|
||||
|
||||
| 股票 | 真实增量 | 实际批次买价 | 新卖出下限 | 保留底仓 |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 雷赛智能 | 1500股 | 47.280元 | 49.18元 | 100股 |
|
||||
| 四方股份 | 1000股 | 31.370元 | 32.63元 | 700股 |
|
||||
|
||||
雷赛现价在11:30为51.87元,但迁移不把旧分钟数据当新行情发单。四方旧700股卖单`STR20261109100402_601126SH_g`在11:50:34沿正式取消入口请求,12:01:12确认父子单均CANCELLED、成交0,保留原回报;不手工假造取消。此撤单不是新4%策略自然成交验收。
|
||||
|
||||
## 验证与发布边界
|
||||
|
||||
开发机隔离全量81批通过;新增37例覆盖实际成本、跨档错位、余量续卖、底仓保护、FIFO、买入暂停、报价边界、T+1、止盈实际成交、迁移幂等、SQLite真实事务回滚与并发指纹。页面只将手动网格默认值改为4%,无布局交互改动,三道页面护栏随全量通过。
|
||||
|
||||
候选需断网全量通过后,仅重建pms-web和pms-worker。温和排空worker、不强杀在途;唯一WS、beat及其余容器保持。迁移期间暂时关闭个股策略调度,保存原值,完成后恢复;不修改全局用户暂停。回退保留账本、回报和迁移审计;已有新成交后不能把新批次状态覆盖成旧2%库存。
|
||||
|
||||
## 实际发布与待办
|
||||
|
||||
待补:代码提交、镜像ID、候选断网结果、迁移审计、策略开关恢复、其他容器标识、真实对账及自然调度。风险退出仍应保持第一次清仓信号停买、第二次独立信号清仓、任一级评级下降退出,发布后核查实际开关与存量风险记录。
|
||||
|
|
@ -6,6 +6,8 @@
|
|||
|
||||
test_batch54_units.py 用户候选来源、到期核验、权限、显式取用、技术面补读及评级排序透传 (10例)
|
||||
|
||||
4%网格真实批次、完整价差、未成交重试及迁移事务专项37例。
|
||||
|
||||
成交修正专项:批次投影36例、传输与执行保护29例、服务事务36例、
|
||||
普通成交凭据与仓储13例、网格更正版本与并发20例。
|
||||
|
||||
|
|
@ -199,7 +201,9 @@ import sys
|
|||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
# 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。
|
||||
SUITES = ["test_broad_funds.py", "test_etf_observation.py", "test_risk_exit.py", "test_rotation_accounting_units.py", "test_cost_precision.py", "test_execution_basis_decimal.py",
|
||||
SUITES = [
|
||||
"test_grid_execution.py",
|
||||
"test_broad_funds.py", "test_etf_observation.py", "test_risk_exit.py", "test_rotation_accounting_units.py", "test_cost_precision.py", "test_execution_basis_decimal.py",
|
||||
"test_trade_correction_units.py", "test_trade_correction_transport.py",
|
||||
"test_trade_correction_service.py", "test_trade_lineage_units.py",
|
||||
"test_trade_correction_strategy.py",
|
||||
|
|
|
|||
|
|
@ -773,7 +773,7 @@ def _():
|
|||
d = trail("600000.SH", 700, 0.25) # 主板照旧 100
|
||||
assert d and d["qty"] == 100, d
|
||||
d = trail("600000.SH", 150, 1.0) # 主板全清照旧整百
|
||||
assert d and d["qty"] == 100, d
|
||||
assert d and d["qty"] == 150, d # 全部剩余零股允许一次卖清
|
||||
|
||||
|
||||
@case("[科创板] runner 网格: 手工 100 股档抬到 200 / 卖出量不足 200 不推进档位")
|
||||
|
|
@ -798,7 +798,7 @@ def _():
|
|||
# 上行涨破 → 卖: 网格股有 200 但今天可卖只有 100, 科创板卖 100 不合法, 原地等
|
||||
b1 = srun._band(lv, 10.5)
|
||||
st1 = {"last_band": b1 - 1,
|
||||
"filled_levels": {str(b1 - 1): {"qty": 200, "price": 9.8}}}
|
||||
"filled_levels": {str(b1 - 1): {"qty": 200, "price": 9.8, "sell_target": 10.4}}}
|
||||
assert grid("688802.SH", 10.5, 100, st1, add_qty=200) is None
|
||||
assert st1.get("last_band") == b1 - 1, st1 # 档位没被推进, 下跳凑够了还能卖
|
||||
|
||||
|
|
@ -842,7 +842,7 @@ def _grid_sell_fixture(qty=300, avail=700, add=300, per_lot=700, code="688100.SH
|
|||
"per_lot": per_lot, "max_capital": 50000}
|
||||
band = srun._band(srun._grid_levels(prm), 10.5) - 1
|
||||
st = {"strategy_id": "grid-test", "type": "GRID", "ts_code": code, "params": prm}
|
||||
state = {"last_band": band, "filled_levels": {str(band): {"price": 9.8, "qty": qty}},
|
||||
state = {"last_band": band, "filled_levels": {str(band): {"price": 9.8, "qty": qty, "sell_target": 10.4, "lot_id": band}},
|
||||
"invested": 9.8 * qty}
|
||||
pos = {"avail_qty": avail, "add_qty": add}
|
||||
ctx = {"state": state, "notes": [], "buy_paused": False}
|
||||
|
|
@ -858,24 +858,26 @@ def _():
|
|||
assert state["last_band"] == band + 1
|
||||
|
||||
|
||||
@case("[网格余额] 原1000股首卖700后恢复300,再触发不卖底仓")
|
||||
def _book_grid_remainder(st, state, qty, band):
|
||||
from app.core.grid_inventory import project
|
||||
code = st['ts_code']
|
||||
lots = [{'id':band, 'ts_code':code, 'lot_type':'ADD', 'qty':qty, 'open_price':9.8, 'instruction_id':'buy'}]
|
||||
parents = {'buy': {'instruction_id':'buy','ts_code':code,'origin_type':'strategy','origin_id':st['strategy_id'],'side':'buy','action':'ADD','progress':{'leg':'grid_buy:1'}}}
|
||||
state.update(project(st, lots, parents))
|
||||
|
||||
|
||||
@case("[网格余额] 首卖700股仅在真实批次入账后余300股,无需重新跨档,不卖底仓")
|
||||
def _():
|
||||
from unittest.mock import patch
|
||||
sr, st, state, pos, ctx, band = _grid_sell_fixture(1000, 1400, 1000)
|
||||
first = sr._eval_grid(st, pos, {"price": 10.5}, None, ctx)
|
||||
assert first["qty"] == 700
|
||||
sr._apply_grid_state(state, first)
|
||||
state["pending"] = {"iid": "i1", "leg": first["leg"], "grid_sell_idx": band,
|
||||
"grid_restore": first["_grid_restore"]}
|
||||
with patch.object(sr, "_pending_terminal", return_value=(True, {"exec_qty": 700})):
|
||||
assert sr._reconcile(st, state, pos)
|
||||
assert state["filled_levels"][str(band)]["qty"] == 300
|
||||
assert state['filled_levels'][str(band)]['qty'] == 1000 # 未成交不扣库存
|
||||
_book_grid_remainder(st, state, 300, band)
|
||||
assert abs(state["invested"] - 2940) < 1e-6
|
||||
state["last_band"] = band # 正常再次穿越同档。
|
||||
second = sr._eval_grid(st, {"avail_qty": 700, "add_qty": 300}, {"price": 10.5}, None, ctx)
|
||||
assert second and second["qty"] == 300, second
|
||||
assert first["qty"] + second["qty"] == 1000
|
||||
assert 1400 - first["qty"] - second["qty"] == 400 # 底仓完整保留。
|
||||
assert 1400 - first["qty"] - second["qty"] == 400
|
||||
|
||||
|
||||
@case("[网格余额] 可卖不足、档位零股与科创板小余额不突破持仓")
|
||||
|
|
@ -886,28 +888,24 @@ def _():
|
|||
(100, 700, 100, "688100.SH", None),
|
||||
(100, 700, 100, "600000.SH", 100),
|
||||
(0, 700, 500, "688100.SH", None),
|
||||
(300, 700, 0, "688100.SH", None)]:
|
||||
]:
|
||||
sr, st, state, pos, ctx, band = _grid_sell_fixture(qty, avail, add, code=code)
|
||||
d = sr._eval_grid(st, pos, {"price": 10.5}, None, ctx)
|
||||
assert (d["qty"] if d else None) == expected, (qty, avail, add, d)
|
||||
if qty in (100, 0) and code == "688100.SH":
|
||||
if qty == 100 and code == "688100.SH":
|
||||
assert state["last_band"] == band
|
||||
|
||||
|
||||
@case("[网格余额] 未成交和部分成交继续按实际剩余恢复档位")
|
||||
@case("[网格余额] 未成交、部分成交与全部成交只以已入账剩余为准")
|
||||
def _():
|
||||
from unittest.mock import patch
|
||||
for executed, remaining in [(0, 300), (200, 100), (300, 0)]:
|
||||
sr, st, state, pos, ctx, band = _grid_sell_fixture()
|
||||
d = sr._eval_grid(st, pos, {"price": 10.5}, None, ctx)
|
||||
assert d["qty"] == 300, d
|
||||
sr._apply_grid_state(state, d)
|
||||
state["pending"] = {"iid": "i1", "leg": d["leg"], "grid_sell_idx": band,
|
||||
"grid_restore": d["_grid_restore"]}
|
||||
with patch.object(sr, "_pending_terminal", return_value=(True, {"exec_qty": executed})):
|
||||
assert sr._reconcile(st, state, pos)
|
||||
assert state["filled_levels"].get(str(band), {}).get("qty", 0) == remaining
|
||||
assert abs(state["invested"] - remaining * 9.8) < 1e-6
|
||||
assert d['qty'] == 300
|
||||
assert state['filled_levels'][str(band)]['qty'] == 300
|
||||
_book_grid_remainder(st, state, remaining, band)
|
||||
assert state['filled_levels'].get(str(band), {}).get('qty', 0) == remaining
|
||||
assert abs(state['invested'] - remaining * 9.8) < 1e-6
|
||||
|
||||
|
||||
def main():
|
||||
|
|
|
|||
|
|
@ -287,14 +287,20 @@ def _():
|
|||
# start_line 显式给, 别让缺省值走 param_store (这批单测不连库)
|
||||
st = {"ts_code": "600000.SH", "params": {"giveback": 0.05, "sell_ratio": ratio,
|
||||
"start_line": 0.03}}
|
||||
pos = {"avg_cost": 8.0, "avail_qty": avail, "total_qty": avail * 2,
|
||||
pos = {"avg_cost": 8.0, "avail_qty": avail, "total_qty": avail,
|
||||
"cushion_pct": price / 8.0 - 1}
|
||||
return srun._eval_trail(st, pos, {"price": price}, None,
|
||||
{"state": state, "notes": []})
|
||||
state = {"armed": True, "high_water": 12.0}
|
||||
d1 = trail(1000, 10.0, state)
|
||||
assert d1 and d1["qty"] == 500, d1 # 第一次回落: 卖一半
|
||||
assert state.get("trail_fired_hw") == 12.0, state # 闩锁记下高水位
|
||||
assert 'trail_fired_hw' not in state # 发单未成交不消耗减持目标
|
||||
assert trail(1000, 10.0, state)['qty'] == 500
|
||||
from unittest.mock import patch
|
||||
state['pending'] = {'iid':'sell', 'leg':'trail_sell'}
|
||||
with patch.object(srun, '_pending_terminal', return_value=(True, {'exec_qty':500})):
|
||||
srun._reconcile({'type':'TRAIL'}, state, {})
|
||||
assert state.get('trail_fired_hw') == 12.0
|
||||
# 原 bug: 卖完条件仍成立, 每隔一单再卖剩余一半, 几何级联直到卖光
|
||||
assert trail(500, 10.0, state) is None, "同一高水位不许再卖"
|
||||
trail(500, 13.0, state) # 创新高 → 高水位抬到 13
|
||||
|
|
|
|||
|
|
@ -208,14 +208,14 @@ def _trail_sar(price, sar_line, now, avail=6000, avg=10.0, sold_day=0):
|
|||
return d, ctx
|
||||
|
||||
|
||||
@case("F SAR 线·09:45 后跌破 SAR 缓冲即全清 (leg=trail_sar, 当日记一次)")
|
||||
@case("F SAR 线·09:45 后跌破 SAR 缓冲即全清 (leg=trail_sar, 成交前保留待减持量)")
|
||||
def _():
|
||||
from datetime import datetime
|
||||
from app.services import strategy_runner as srun
|
||||
d, ctx = _trail_sar(9.9, 10.0, datetime(2026, 9, 11, 10, 0)) # 9.9 < 10×0.997=9.97
|
||||
assert d and d["action"] == srun.A_EXIT and d["leg"] == "trail_sar" and d["qty"] == 6000
|
||||
from app.core import tradedays as td
|
||||
assert ctx["state"]["sar_stop_day"] == td.ymd(datetime(2026, 9, 11, 10, 0))
|
||||
assert ctx["state"]["trail_due"]["qty"] == 6000
|
||||
|
||||
|
||||
@case("F SAR 线·09:45 前不触发")
|
||||
|
|
@ -232,13 +232,13 @@ def _():
|
|||
assert d is None
|
||||
|
||||
|
||||
@case("F SAR 线·当日只触发一次 (已记 sar_stop_day)")
|
||||
@case("F SAR 线·旧触发标记不等于成交,不丢弃真实剩余量")
|
||||
def _():
|
||||
from datetime import datetime
|
||||
from app.core import tradedays as td
|
||||
now = datetime(2026, 9, 11, 10, 0)
|
||||
d, _ = _trail_sar(9.5, 10.0, now, sold_day=td.ymd(now))
|
||||
assert d is None
|
||||
assert d and d["qty"] == 6000
|
||||
|
||||
|
||||
@case("F SAR 线·没刷进 sar_line 时不判 (加不改, 拿不到 SAR 绝不当跌破)")
|
||||
|
|
|
|||
|
|
@ -0,0 +1,240 @@
|
|||
"""4%网格、真实批次、报价边界及减持余量,所有仓储均为内存桩。"""
|
||||
import unit_test_guard
|
||||
import copy
|
||||
import datetime as dt
|
||||
import sys
|
||||
import unittest
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from app.core import grid_inventory as core, execution_policy
|
||||
from app.services import grid_inventory as service, strategy_runner as runner, strategy_service
|
||||
from app.repo import pms_repo
|
||||
from config.settings import settings
|
||||
|
||||
P = dict(center=47.18, lower=46.035, upper=52.823, step_pct=.04, per_lot=1600, max_capital=76358.11)
|
||||
def strategy(params=None):
|
||||
return dict(strategy_id='grid', ts_code='002979.SZ', type='GRID', status='ACTIVE', params=copy.deepcopy(params or P), state={})
|
||||
def records(qty=1500, price=47.28):
|
||||
parent = dict(instruction_id='buy',ts_code='002979.SZ',origin_type='strategy',origin_id='grid',side='buy',action='ADD',book_id='original',progress={'leg':'grid_buy:1'})
|
||||
lot = dict(id=1,ts_code='002979.SZ',lot_type='ADD',qty=qty,open_price=price,instruction_id='buy',book_id='original')
|
||||
return [lot], {'buy':parent}
|
||||
def pos(qty=1500, avail=1600):
|
||||
return dict(total_qty=qty+100,add_qty=qty,avail_qty=avail)
|
||||
def evaluate(st, state, position, price, paused=False):
|
||||
return runner._eval_grid(st,position,{'price':price},None,{'state':state,'notes':[],'buy_paused':paused})
|
||||
|
||||
class InventoryTests(unittest.TestCase):
|
||||
def test_cost_is_booked_not_trigger(self):
|
||||
snap=core.project(strategy(),*records());self.assertEqual(snap['filled_levels']['1']['price'],47.28)
|
||||
self.assertEqual(snap['invested'],70920);self.assertEqual(snap['filled_levels']['1']['sell_target'],49.18)
|
||||
def test_partial_and_unfilled_do_not_create_inventory(self):
|
||||
self.assertEqual(core.project(strategy(),[],{})['invested'],0)
|
||||
self.assertEqual(core.project(strategy(),*records(100))['invested'],4728)
|
||||
def test_new_entry_and_exit_preserve_full_grid(self):
|
||||
st=strategy();lots,parents=records();parents['buy']['progress'].update(grid_params=P,grid_entry=46.979,grid_exit=50.0)
|
||||
result=core.project(st,lots,parents)['filled_levels']['1'];self.assertEqual(result['sell_target'],50)
|
||||
self.assertEqual(result['entry_level'],46.979)
|
||||
def test_migration_does_not_reinterpret_old_index(self):
|
||||
lots,parents=records();parents['buy']['progress'].update(grid_params={**P,'step_pct':.02},grid_entry=46.979,grid_exit=47.922)
|
||||
result=core.project(strategy(),lots,parents)['filled_levels']['1'];self.assertEqual(result['sell_target'],49.18);self.assertIsNone(result['entry_level'])
|
||||
def test_price_correction_changes_minimum_exit(self):
|
||||
self.assertEqual(core.project(strategy(),*records(price=48))['filled_levels']['1']['sell_target'],49.92)
|
||||
def test_other_book_and_unknown_parent_fail_closed(self):
|
||||
for field,value in [('book_id','micro30'),('instruction_id','unknown')]:
|
||||
lots,parents=records();lots[0][field]=value
|
||||
with self.assertRaises(ValueError):core.project(strategy(),lots,parents)
|
||||
def test_foreign_add_and_unknown_cost_fail_closed(self):
|
||||
lots,parents=records();parents['buy']['origin_id']='other'
|
||||
with self.assertRaises(ValueError):core.project(strategy(),lots,parents)
|
||||
for value in [0,-1,float('nan'),float('inf')]:
|
||||
with self.assertRaises(ValueError):core.project(strategy(),*records(price=value))
|
||||
def test_base_and_closed_lots_are_not_grid_inventory(self):
|
||||
lots,parents=records();lots.extend([{**lots[0],'id':2,'lot_type':'BASE','instruction_id':'manual'}, {**lots[0],'id':3,'qty':0}])
|
||||
self.assertEqual(len(core.project(strategy(),lots,parents)['filled_levels']),1)
|
||||
def test_price_rounding_respects_direction(self):
|
||||
self.assertEqual(core.price_tick(32.6248,sell=True),32.63);self.assertEqual(core.price_tick(31.372),31.37)
|
||||
def test_service_requires_position_to_match_booked_lots(self):
|
||||
lots,parents=records()
|
||||
with patch.object(pms_repo,'list_lots',return_value=lots),patch.object(pms_repo,'get_instruction',side_effect=parents.get):
|
||||
self.assertEqual(service.snapshot(strategy(),pos())['invested'],70920)
|
||||
with self.assertRaises(ValueError):service.snapshot(strategy(),pos(qty=1600))
|
||||
|
||||
class EvaluationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.st=strategy();self.state={**core.project(self.st,*records()),'last_band':6}
|
||||
def test_leads_overdue_remainder_sells_without_new_crossing(self):
|
||||
d=evaluate(self.st,self.state,pos(),51.87,paused=True)
|
||||
self.assertEqual((d['qty'],d['limit_price']),(1500,49.18));self.assertEqual(self.state['filled_levels']['1']['qty'],1500)
|
||||
def test_t_plus_one_retries_at_unchanged_price(self):
|
||||
self.assertIsNone(evaluate(self.st,self.state,pos(avail=0),51.87))
|
||||
self.assertEqual(evaluate(self.st,self.state,pos(avail=1500),51.87)['qty'],1500)
|
||||
def test_partial_fill_then_cancel_sells_only_booked_remainder(self):
|
||||
self.st['params']['per_lot']=1000
|
||||
self.assertEqual(evaluate(self.st,self.state,pos(),51.87)['qty'],1000)
|
||||
self.state.update(core.project(self.st,*records(qty=800)))
|
||||
self.assertEqual(evaluate(self.st,self.state,pos(qty=800),51.87)['qty'],800)
|
||||
def test_does_not_sell_base_or_borrow_another_lot(self):
|
||||
self.state.update(core.project(self.st,*records(qty=300)));self.st['params']['per_lot']=1600
|
||||
self.assertEqual(evaluate(self.st,self.state,pos(qty=300,avail=800),51.87)['qty'],300)
|
||||
def test_fifo_lot_not_yet_ready_blocks_later_lot_sale(self):
|
||||
self.state['filled_levels']['1']['sell_target']=53
|
||||
self.state['filled_levels']['2']={'qty':100,'price':40,'sell_target':42,'lot_id':2}
|
||||
self.assertIsNone(evaluate(self.st,self.state,pos(qty=1600),51.87))
|
||||
def test_missing_target_and_excess_inventory_do_not_silently_disappear(self):
|
||||
with self.assertRaises(ValueError):evaluate(self.st,self.state,pos(qty=100),51.87)
|
||||
self.state['filled_levels']['1'].pop('sell_target')
|
||||
with self.assertRaises(ValueError):evaluate(self.st,self.state,pos(),51.87)
|
||||
def test_sifang_same_boundary_does_not_round_trip(self):
|
||||
p=dict(center=31.39,lower=30.116,upper=32.825,step_pct=.04,per_lot=1000,max_capital=67730.61)
|
||||
st=strategy(p);state={'last_band':1,'filled_levels':{},'invested':0}
|
||||
d=evaluate(st,state,pos(0),31.37);self.assertEqual(d['grid_entry'],31.372);self.assertEqual(d['limit_price'],31.37)
|
||||
lots,parents=records(1000,31.37);parents['buy']['progress'].update({k:d[k] for k in ['grid_entry','grid_exit','grid_params']})
|
||||
state.update(core.project(st,lots,parents))
|
||||
self.assertIsNone(evaluate(st,state,pos(1000,700),31.38))
|
||||
sell=evaluate(st,state,pos(1000,700),32.63);self.assertEqual(sell['qty'],700);self.assertEqual(sell['limit_price'],32.63)
|
||||
def test_paused_and_cap_limited_buys_do_not_become_inventory(self):
|
||||
p=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=1000,max_capital=1)
|
||||
for paused in [False,True]:
|
||||
state={'last_band':3,'filled_levels':{},'invested':0}
|
||||
self.assertIsNone(evaluate(strategy(p),state,pos(0),8.9,paused));self.assertEqual(state['filled_levels'],{})
|
||||
def test_same_entry_is_not_bought_twice(self):
|
||||
p=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000)
|
||||
state={'last_band':3,'filled_levels':{'x':{'qty':100,'entry_level':9.2,'sell_target':10,'price':9.1}},'invested':910}
|
||||
self.assertIsNone(evaluate(strategy(p),state,pos(100),9.1))
|
||||
def test_first_tick_resets_cursor_without_buy(self):
|
||||
st=strategy(dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000));state={'filled_levels':{},'invested':0}
|
||||
self.assertIsNone(evaluate(st,state,pos(0),9.1));self.assertEqual(state['last_band'],2)
|
||||
|
||||
class ProtectionTests(unittest.TestCase):
|
||||
def test_buy_pause_read_error_is_unknown_not_clear(self):
|
||||
with patch.object(strategy_service,'buypause_map',side_effect=RuntimeError('db')):
|
||||
self.assertIsNone(runner._buypause_codes())
|
||||
def test_invalid_pause_document_raises(self):
|
||||
with patch.object(pms_repo,'get_param',return_value='[]'):
|
||||
with self.assertRaises(ValueError):strategy_service.buypause_map()
|
||||
def test_old_proposal_and_insufficient_inventory_cannot_emit(self):
|
||||
st=strategy();dec=dict(side='sell',qty=1500,grid_params=P,grid_lot_id=1,limit_price=49.18)
|
||||
with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(pms_repo,'get_position',return_value=pos()),patch.object(service,'snapshot',return_value=core.project(st,*records())):
|
||||
runner._validate_grid_decision(st,dec)
|
||||
for changes in [dict(grid_params={}),dict(qty=1600),dict(limit_price=49.17),dict(grid_lot_id=2)]:
|
||||
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**dec,**changes})
|
||||
def test_new_day_preserves_unfinished_t0_leg(self):
|
||||
state={'day':20261106,'open_leg':{'dir':'long','qty':100,'entry':10}}
|
||||
runner._roll_day(state,{},20261109);self.assertEqual(state['open_leg']['qty'],100)
|
||||
def test_trail_failed_partial_and_t_plus_one_do_not_consume_target(self):
|
||||
st={'strategy_id':'trail','ts_code':'600000.SH','type':'TRAIL','params':{'start_line':.03,'giveback':.05,'sell_ratio':.5}}
|
||||
state={'armed':True,'high_water':12};position={'total_qty':1000,'avail_qty':100,'avg_cost':9}
|
||||
ctx={'state':state,'notes':[]}
|
||||
d=runner._eval_trail(st,position,{'price':11},dt.datetime(2026,11,9,10),ctx)
|
||||
self.assertEqual(d['qty'],100);self.assertEqual(state['trail_due']['qty'],500)
|
||||
state['pending']={'iid':'sell','leg':'trail_sell','qty':100}
|
||||
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':100})):
|
||||
runner._reconcile(st,state,position)
|
||||
self.assertEqual(state['trail_due']['qty'],400);self.assertNotIn('trail_fired_hw',state)
|
||||
d=runner._eval_trail(st,{**position,'total_qty':900,'avail_qty':900},{'price':11.8},None,ctx)
|
||||
self.assertEqual(d['qty'],400)
|
||||
state['pending']={'iid':'sell2','leg':'trail_sell','qty':400}
|
||||
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':400})):
|
||||
runner._reconcile(st,state,position)
|
||||
self.assertEqual(state['trail_fired_hw'],12);self.assertNotIn('trail_due',state)
|
||||
self.assertIsNone(runner._eval_trail(st,{**position,'total_qty':500,'avail_qty':500},{'price':11},None,ctx))
|
||||
def test_sar_zero_fill_still_retries_same_day(self):
|
||||
st={'strategy_id':'trail','ts_code':'600000.SH','type':'TRAIL','params':{'sar_line':10,'giveback':.05,'sell_ratio':.5}}
|
||||
state={};position={'total_qty':1000,'avail_qty':1000,'avg_cost':11};ctx={'state':state,'notes':[]};now=dt.datetime(2026,11,9,10)
|
||||
with patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d):
|
||||
self.assertEqual(runner._eval_trail(st,position,{'price':9},now,ctx)['qty'],1000)
|
||||
state['pending']={'iid':'sell','leg':'trail_sar'}
|
||||
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':0})):runner._reconcile(st,state,position)
|
||||
self.assertEqual(runner._eval_trail(st,position,{'price':9},now,ctx)['qty'],1000)
|
||||
|
||||
class MigrationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
from test_trade_correction_strategy import StrategyCorrectionTests
|
||||
from sqlalchemy import text
|
||||
from app.db import session as db
|
||||
from app.services import grid_migration as migration
|
||||
self.migration, self.db = migration, db
|
||||
self.use = StrategyCorrectionTests.use.__get__(self)
|
||||
StrategyCorrectionTests.setUp(self)
|
||||
with self.engine.begin() as conn:
|
||||
conn.execute(text('CREATE TABLE migration_param (k TEXT PRIMARY KEY, v TEXT)'))
|
||||
conn.execute(text("INSERT INTO migration_param VALUES ('PMS_AUTO_GRID_STEP_PCT','0.02')"))
|
||||
self.use(migration.param_store, 'get', lambda k,d=None: {'PMS_MONITOR_WATCH_SCOPE':'pms-sim-155','PMS_DISPATCH_MODE':'ws'}.get(k,d))
|
||||
self.use(migration.param_store, 'get_bool', lambda k,d=False: False)
|
||||
self.use(migration.param_store, 'get_float', lambda k,d=0: float(db.fetch_one('SELECT v FROM migration_param WHERE k=:k', {'k':k})['v']))
|
||||
self.use(pms_repo, 'get_param', lambda k: db.fetch_one('SELECT v FROM migration_param WHERE k=:k', {'k':k})['v'])
|
||||
def set_param(k,v,updated_by=''):
|
||||
db.execute('UPDATE migration_param SET v=:v WHERE k=:k', {'k':k,'v':str(v)})
|
||||
return {'ok':True}
|
||||
self.use(migration.param_store, 'set_param', set_param)
|
||||
self.use(migration.execution_orders, 'code_settlement_blocker', lambda code: '')
|
||||
self.use(migration.execution_orders, 'replacement_state', lambda iid: {'ready':True})
|
||||
def preview(self): return self.migration.migrate(['GRID'])
|
||||
def apply(self, expected): return self.migration.migrate(['GRID'], apply=True, expected=expected)
|
||||
def test_preview_is_readonly_and_commit_is_idempotent(self):
|
||||
before=pms_repo.get_strategy('GRID'); preview=self.preview()
|
||||
self.assertEqual(pms_repo.get_strategy('GRID'),before)
|
||||
result=self.apply(preview['fingerprint']);self.assertTrue(result['applied'])
|
||||
current=pms_repo.get_strategy('GRID');self.assertEqual(current['params']['step_pct'],.04)
|
||||
self.assertEqual(float(pms_repo.get_param('PMS_AUTO_GRID_STEP_PCT')),.04)
|
||||
self.assertIsNone(current['state']['last_band']);self.assertTrue(self.apply('obsolete')['already_applied'])
|
||||
self.assertEqual(current,pms_repo.get_strategy('GRID'))
|
||||
def test_audit_failure_rolls_back_strategies_and_runtime_default(self):
|
||||
before=pms_repo.get_strategy('GRID');preview=self.preview()
|
||||
with patch.object(self.migration.rotation_repo,'put_once',side_effect=RuntimeError('audit failed')):
|
||||
with self.assertRaises(RuntimeError):self.apply(preview['fingerprint'])
|
||||
self.assertEqual(before,pms_repo.get_strategy('GRID'))
|
||||
self.assertEqual(float(pms_repo.get_param('PMS_AUTO_GRID_STEP_PCT')),.02)
|
||||
self.assertIsNone(self.migration.rotation_repo.get(self.migration.KEY)[0])
|
||||
def test_changed_strategy_and_wrong_target_set_fail_closed(self):
|
||||
preview=self.preview();pms_repo.update_strategy('GRID',note='concurrent edit')
|
||||
with self.assertRaisesRegex(ValueError,'预览后'):self.apply(preview['fingerprint'])
|
||||
with self.assertRaises(ValueError):self.migration.migrate(['OTHER'])
|
||||
def test_live_parent_blocks_migration(self):
|
||||
with patch.object(pms_repo,'list_instructions',return_value=[{'instruction_id':'LIVE'}]):
|
||||
with self.assertRaisesRegex(ValueError,'在途'):self.preview()
|
||||
def test_unsettled_cancel_and_correction_hold_block_migration(self):
|
||||
pms_repo.update_strategy('GRID',state={'pending':{'iid':'OLD'}})
|
||||
with patch.object(pms_repo,'get_instruction',return_value={'status':'CANCELLED'}),patch.object(self.migration.execution_orders,'replacement_state',return_value={'ready':False}):
|
||||
with self.assertRaisesRegex(ValueError,'结算'):self.preview()
|
||||
pms_repo.update_strategy('GRID',state={'correction_hold':'qty'})
|
||||
with self.assertRaisesRegex(ValueError,'更正'):self.preview()
|
||||
def test_enabled_runner_and_wrong_instance_cannot_apply(self):
|
||||
preview=self.preview()
|
||||
with patch.object(self.migration.param_store,'get_bool',return_value=True):
|
||||
with self.assertRaises(ValueError):self.apply(preview['fingerprint'])
|
||||
with patch.object(settings,'PMS_TABLE_PREFIX','real_'):
|
||||
with self.assertRaises(ValueError):self.preview()
|
||||
def test_failed_parameter_write_rolls_back(self):
|
||||
preview=self.preview();before=pms_repo.get_strategy('GRID')
|
||||
with patch.object(self.migration.param_store,'set_param',return_value={'ok':False}):
|
||||
with self.assertRaises(RuntimeError):self.apply(preview['fingerprint'])
|
||||
self.assertEqual(before,pms_repo.get_strategy('GRID'))
|
||||
|
||||
class AdditionalBoundaryTests(unittest.TestCase):
|
||||
def test_missing_pending_parent_does_not_clear_state(self):
|
||||
state={'pending':{'iid':'missing'}}
|
||||
with patch.object(pms_repo,'get_instruction',return_value=None):
|
||||
with self.assertRaises(ValueError):runner._reconcile({'type':'GRID'},state,{})
|
||||
self.assertEqual(state['pending']['iid'],'missing')
|
||||
def test_geometry_and_per_lot_revalidated_before_buy(self):
|
||||
prm=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000)
|
||||
st=strategy(prm);d=evaluate(st,{'last_band':3,'filled_levels':{},'invested':0},pos(0),9.1)
|
||||
with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(service,'snapshot',return_value={'filled_levels':{},'invested':0}),patch.object(pms_repo,'get_position',return_value=pos(0)),patch.object(runner,'_buypause_codes',return_value=set()),patch.object(runner,'_macro_gate_active',return_value=False):
|
||||
runner._validate_grid_decision(st,d)
|
||||
for fields in [{'qty':200},{'grid_entry':9.1},{'grid_exit':9.3},{'limit_price':9.21}]:
|
||||
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,**fields})
|
||||
def test_empty_geometry_does_not_attach_idle_grid(self):
|
||||
from app.services.strategy_advisor import grid_params
|
||||
params,why=grid_params(price=10,support=9.99,pressure=10.01,band=.08,step_pct=.04,cap_room=10000,cap_ratio=.5)
|
||||
self.assertIsNone(params);self.assertIn('完整',why)
|
||||
def test_rejected_trail_proposal_does_not_repeat_same_trigger(self):
|
||||
st={'type':'TRAIL','ts_code':'600000.SH','params':{'sar_line':10,'giveback':.05,'sell_ratio':1}}
|
||||
state={'pending':{'pid':'p'},'trail_due':{'qty':100,'leg':'trail_sar','high_water':11}}
|
||||
with patch.object(runner,'_today',return_value=20261109),patch.object(pms_repo,'get_proposal',return_value={'status':'REJECTED'}),patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d):
|
||||
self.assertTrue(runner._reconcile(st,state,{}))
|
||||
self.assertIsNone(runner._eval_trail(st,{'total_qty':100,'avail_qty':100,'avg_cost':11},{'price':9},dt.datetime(2026,11,9,10),{'state':state}))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
@ -14,7 +14,7 @@ from sqlalchemy import create_engine, event, text
|
|||
from app.core import strategy_book as books
|
||||
from app.db import session as db
|
||||
from app.repo import pms_repo
|
||||
from app.services import strategy_runner as runner, rotation_service
|
||||
from app.services import strategy_runner as runner, rotation_service, grid_inventory
|
||||
from config.settings import settings
|
||||
|
||||
CODE = '600001.SH'
|
||||
|
|
@ -54,8 +54,14 @@ class StrategyCorrectionTests(unittest.TestCase):
|
|||
(runner, '_macro_gate_active', lambda: False),
|
||||
(runner.param_store, 'get_bool', lambda key, default=False: key == 'PMS_STRATEGY_ENABLED'),
|
||||
(runner.param_store, 'get_float', lambda key, default=0: default),
|
||||
(runner.param_store, 'get_int', lambda key, default=0: default),
|
||||
(runner.param_store, 'get', lambda key, default=None: default),
|
||||
(runner.portfolio, 'positions_view', lambda: {'positions': [{'ts_code': CODE, 'total_qty': 100, 'avail_qty': 100}], 'totals': {'scale': 10000}}),
|
||||
(runner.market, 'day_snapshot', lambda code: {'price': 10}),
|
||||
(runner.market, 'day_snapshot', lambda code: {'price': 10, 'bar_time': self.now.isoformat()}),
|
||||
(pms_repo, 'get_position', lambda code: {'total_qty':100, 'add_qty':100, 'avail_qty':100}),
|
||||
(grid_inventory, 'snapshot', lambda st, pos: {'invested':1000, 'filled_levels':{'0':{'price':10,'qty':100,'sell_target':10.4}}}),
|
||||
# 此套只测事务与更正交错;真实批次和报价校验由 test_grid_execution 覆盖。
|
||||
(runner, '_validate_grid_decision', lambda st, dec: None),
|
||||
]:
|
||||
self.use(obj, name, value)
|
||||
schema = {
|
||||
|
|
@ -190,10 +196,14 @@ class StrategyCorrectionTests(unittest.TestCase):
|
|||
|
||||
def tick(self, *, decision=True, corrected=False, paused=False, autonomy='auto', dry_run=False):
|
||||
pms_repo.update_strategy('GRID', autonomy=autonomy)
|
||||
def evaluate(st, pos, day, now, ctx):
|
||||
active = pms_repo.active_strategies
|
||||
def load():
|
||||
old = active()
|
||||
if corrected: self.correction(paused=paused)
|
||||
return old
|
||||
def evaluate(st, pos, day, now, ctx):
|
||||
return copy.deepcopy(DECISION) if decision else None
|
||||
with patch.dict(runner.EVALUATORS, {'GRID': evaluate}):
|
||||
with patch.object(pms_repo, 'active_strategies', side_effect=load), patch.dict(runner.EVALUATORS, {'GRID': evaluate}):
|
||||
return runner.tick(dry_run=dry_run)
|
||||
|
||||
def test_tick_loaded_before_correction_cannot_publish_or_overwrite(self):
|
||||
|
|
@ -224,7 +234,7 @@ class StrategyCorrectionTests(unittest.TestCase):
|
|||
fresh = pms_repo.get_strategy('GRID')
|
||||
parent = pms_repo.get_instruction(fresh['state']['pending']['iid'])
|
||||
self.assertEqual(parent['progress']['strategy_correction_id'], 'C1')
|
||||
self.assertEqual(fresh['state']['invested'], 2100)
|
||||
self.assertEqual(fresh['state']['invested'], 1000) # 发单不是成交,不能增加真实投入
|
||||
|
||||
def test_tick_state_failure_rolls_back_parent_and_reports_no_fired(self):
|
||||
original_update = pms_repo.update_strategy
|
||||
|
|
|
|||
Loading…
Reference in New Issue