tradingSystem/app/services/grid_migration.py

96 lines
5.1 KiB
Python
Raw Normal View History

"""已授权网格档距迁移:先预览,暂停策略调度后原子更新,不改成交与持仓。"""
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