727 lines
42 KiB
Python
727 lines
42 KiB
Python
"""宏观微盘策略编排。观察与纸面状态独立;只有验收完成才能接现有委托通道。"""
|
||
import datetime as dt
|
||
import hashlib
|
||
import json
|
||
import logging
|
||
import math
|
||
from zoneinfo import ZoneInfo
|
||
import requests
|
||
from config.settings import settings
|
||
from app.core import micro_rotation as core, strategy_book as books, tradedays as td
|
||
from app.repo import pms_repo, qmt_repo, rotation_repo as store
|
||
from app.services import param_store, portfolio, market
|
||
|
||
TZ = ZoneInfo('Asia/Shanghai')
|
||
logger = logging.getLogger('pms.rotation')
|
||
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
||
TERMINAL = qmt_repo.FINAL
|
||
|
||
|
||
def documents_ready():
|
||
return settings.INFRA_ROTATION_DOCUMENT_SCHEMA or settings.INFRA_STRATEGY_BOOK_SCHEMA
|
||
|
||
|
||
def configuration():
|
||
return {'mode': str(param_store.get('PMS_ROTATION_MODE', 'observe')),
|
||
'rule_version': str(param_store.get('PMS_ROTATION_RULE_VERSION', core.RULE)),
|
||
'candidate_pool_size': param_store.get_int('PMS_ROTATION_CANDIDATE_POOL_SIZE', 100),
|
||
'control': str(param_store.get('PMS_ROTATION_CONTROL', 'run')),
|
||
'url': str(param_store.get('PMS_ROTATION_MONITOR_URL', '')).rstrip('/'),
|
||
'boards': set(str(param_store.get('PMS_MICRO30_ALLOWED_BOARDS', '')).split(','))-{''},
|
||
'costs': {'rate': param_store.get_float('PMS_MICRO30_COMMISSION_RATE', .0002),
|
||
'minimum': param_store.get_float('PMS_MICRO30_MIN_COMMISSION', 5.),
|
||
'sell_tax': param_store.get_float('PMS_MICRO30_SELL_TAX', .0005),
|
||
'transfer_rate': param_store.get_float('PMS_MICRO30_TRANSFER_RATE', .00001)}}
|
||
|
||
|
||
def pull(execution_date=None):
|
||
config = configuration()
|
||
if config['rule_version'] not in core.SUPPORTED_RULES:
|
||
raise ValueError('运行规则与已部署代码不一致')
|
||
day = execution_date or dt.datetime.now(TZ).date().isoformat()
|
||
if not config['url']:
|
||
return None
|
||
response = requests.get(config['url']+'/v1/snapshot', params={'effective_date': day}, timeout=(3, 15))
|
||
response.raise_for_status()
|
||
if len(response.content) > 1024*1024:
|
||
raise ValueError('监控快照超过大小限制')
|
||
value = response.json()
|
||
errors = core.snapshot_check(value, day, require_frozen=False, expected_rule=config['rule_version'], candidate_pool_size=config.get('candidate_pool_size', 100))
|
||
if errors:
|
||
raise ValueError(';'.join(errors))
|
||
return value
|
||
|
||
|
||
def activation_errors():
|
||
if settings.PMS_TABLE_PREFIX:
|
||
return ['本次策略只开放155模拟实例']
|
||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||
return ['策略账本迁移尚未启用']
|
||
if configuration()['rule_version'] not in core.SUPPORTED_RULES:
|
||
return ['运行规则与已部署版本不一致']
|
||
if param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False):
|
||
# 用户授权155模拟仓直接运行。该授权不伪造历史验收或交易日记录。
|
||
errors = []
|
||
capital, _ = store.get('capital:live')
|
||
if not capital or not capital.get('cash') or not capital.get('source_funds_seq'):
|
||
errors.append('分策略现金尚未按实际账户初始化')
|
||
if param_store.get('PMS_DISPATCH_MODE', 'shadow') != 'ws' or not param_store.get_bool('PMS_QMT_WS_ENABLED', False):
|
||
errors.append('自动执行需要启用唯一QMT直连通道')
|
||
config = configuration()
|
||
if not {'MAIN', 'STAR', 'CHINEXT'} <= config['boards']:
|
||
errors.append('沪深及创业板、科创板权限尚未确认')
|
||
if any(not math.isfinite(v) or v < 0 for v in config['costs'].values()):
|
||
errors.append('交易费用参数无效')
|
||
return errors
|
||
evidence, _ = store.get('validation:'+configuration()['rule_version'])
|
||
evidence = evidence or {}
|
||
required = ('backtest', 'capacity', 'fees', 'board_permissions', 'migration', 'regression', 'browser', 'fill_attribution', 'fund_reservation')
|
||
labels = dict(backtest='回测', capacity='成交容量', fees='交易费用', board_permissions='板块权限',
|
||
migration='策略账本迁移', regression='回归测试', browser='页面检查', fill_attribution='成交归属', fund_reservation='资金占用')
|
||
errors = [labels[k]+'尚未验收' for k in required if not evidence.get(k)]
|
||
observed = store.recent('observed_day', 1000)
|
||
paper = store.recent('paper_day', 1000)
|
||
dates = sorted({r['value']['date'] for r in observed if r['value'].get('rule_version') == configuration()['rule_version']})
|
||
paper_dates = sorted({r['value']['date'] for r in paper if r['value'].get('rule_version') == configuration()['rule_version'] and r['value'].get('healthy')})
|
||
if len(dates) < 3:
|
||
errors.append('有效观察不足3个交易日')
|
||
if len(paper_dates) < 10 or (len(dates) >= 3 and any(d <= dates[2] for d in paper_dates[:10])):
|
||
errors.append('观察完成后的健康纸面运行不足10个交易日')
|
||
return errors
|
||
|
||
|
||
def signal_history(end, limit=60):
|
||
"""只读展示历史,来自监控同一公式;不参与轮换决策。"""
|
||
day = dt.date.fromisoformat(end)
|
||
if day > dt.datetime.now(TZ).date():
|
||
raise ValueError('趋势日期不能晚于今天')
|
||
config = configuration()
|
||
if config['rule_version'] not in core.SUPPORTED_RULES:
|
||
raise ValueError('运行规则与趋势代码不一致')
|
||
url = config['url']
|
||
if not url:
|
||
raise ValueError('监控地址未配置')
|
||
n = max(1, min(120, int(limit)))
|
||
response = requests.get(url+'/v1/history', params={'end': end, 'limit': n}, timeout=(3, 8))
|
||
response.raise_for_status()
|
||
if len(response.content) > 512*1024:
|
||
raise ValueError('趋势数据超过大小限制')
|
||
value = response.json()
|
||
rows = value.get('records')
|
||
if value.get('rule_version') != config['rule_version'] or value.get('rule_parameters') != core.rule_parameters(config['rule_version'], config.get('candidate_pool_size', 100)) or not isinstance(rows, list) or len(rows) > n:
|
||
raise ValueError('趋势规则或格式不符')
|
||
previous = ''
|
||
for row in rows:
|
||
date = row.get('date', '')
|
||
dt.date.fromisoformat(date)
|
||
if date <= previous or date > end:
|
||
raise ValueError('趋势日期重复、乱序或超出范围')
|
||
previous = date
|
||
values = [row.get(k) for k in ('activity', 'activity_percentile', 'low_threshold', 'high_threshold')]
|
||
values += list((row.get('group_percentiles') or {}).values())
|
||
if any(v is not None and (isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v)) for v in values):
|
||
raise ValueError('趋势数值无效')
|
||
return value
|
||
|
||
|
||
def status():
|
||
config = configuration()
|
||
out = {'mode': config['mode'], 'control': config['control'], 'rule_version': config['rule_version'],
|
||
'rule_parameters': core.rule_parameters(config['rule_version'], config.get('candidate_pool_size', 100)) if config['rule_version'] in core.SUPPORTED_RULES else {},
|
||
'simulation_direct': not settings.PMS_TABLE_PREFIX and param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False),
|
||
'basket_size': core.SIZE, 'schema_ready': settings.INFRA_STRATEGY_BOOK_SCHEMA, 'documents_ready': documents_ready(),
|
||
'phase': 'original', 'snapshot': None, 'errors': [], 'activation_errors': []}
|
||
try:
|
||
out['snapshot'] = pull()
|
||
except Exception as exc:
|
||
out['errors'].append('监控暂不可用:'+type(exc).__name__)
|
||
if documents_ready():
|
||
value, _ = store.get('state:'+('paper' if config['mode'] == 'paper' else 'live'))
|
||
if value:
|
||
out.update(state=value, phase=value.get('rotation', {}).get('phase', 'original'))
|
||
morning = out['snapshot'] or {}
|
||
if config['mode'] == 'auto' and value.get('intraday_date') == morning.get('effective_date') and value.get('intraday_date'):
|
||
basket, _ = store.get('intraday-basket:155:'+value['intraday_date'])
|
||
if (basket and basket.get('morning_version') == morning.get('snapshot_version')
|
||
and basket.get('snapshot_version') == value['rotation'].get('consumed_entry')):
|
||
out.update(morning_snapshot=morning, snapshot=basket)
|
||
out['activation_errors'] = activation_errors()
|
||
out['recent'] = store.recent('execution', 30)
|
||
out['observed_days'] = len({r['value']['date'] for r in store.recent('observed_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version']})
|
||
out['paper_days'] = len({r['value']['date'] for r in store.recent('paper_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version'] and r['value'].get('healthy')})
|
||
out['daily'] = store.recent('paper_day' if config['mode'] == 'paper' else 'live_day', 500)
|
||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] != 'paper':
|
||
try:
|
||
from app.services.rotation_accounting import view
|
||
out['accounting'] = view()
|
||
if out['accounting'].get('reason'):
|
||
out['errors'].append(out['accounting']['reason'])
|
||
except Exception as exc:
|
||
logger.warning('策略资金读取失败:%s', type(exc).__name__)
|
||
out['errors'].append('策略资金暂不可用,请稍后刷新;持仓数量仍单独核对。')
|
||
# 数量对账不依赖估值,单只股票没有分钟行情不能遮蔽账户持仓核验。
|
||
try:
|
||
out['reconciliation'] = reconcile_books()
|
||
except Exception as exc:
|
||
out['reconciliation'] = {'ok': False, 'diffs': [], 'fixes': [],
|
||
'errors': ['持仓数量对账暂不可用'], 'severity': 'ERROR'}
|
||
logger.warning('策略持仓数量对账失败:%s', type(exc).__name__)
|
||
out['errors'].append('持仓数量暂未核实,请稍后刷新。')
|
||
else:
|
||
out['activation_errors'] = ['策略账本迁移尚未启用']
|
||
out['stock_budget'] = param_store.get_float('PMS_TOTAL_SCALE', 0)*param_store.get_float('PMS_PORTFOLIO_CAP', 0)
|
||
out['costs'] = config['costs']
|
||
out['boards'] = sorted(config['boards'])
|
||
return out
|
||
|
||
|
||
def control(*, mode=None, action=None, actor='user'):
|
||
if mode not in (None, 'observe', 'paper', 'auto') or action not in (None, 'run', 'pause_new', 'pause_all', 'exit_disable'):
|
||
raise ValueError('轮换档位或控制动作非法')
|
||
if mode in ('paper', 'auto') and not documents_ready():
|
||
raise ValueError('观察与纸面记录表尚未建立')
|
||
if mode == 'paper' and not (not settings.PMS_TABLE_PREFIX and param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False)):
|
||
days = {r['value']['date'] for r in store.recent('observed_day', 1000) if r['value'].get('rule_version') == configuration()['rule_version']}
|
||
if len(days) < 3:
|
||
raise ValueError('有效观察不足3个交易日,暂不进入纸面运行')
|
||
if mode == 'auto':
|
||
errors = activation_errors()
|
||
if errors:
|
||
raise ValueError(';'.join(errors))
|
||
if mode:
|
||
current, _ = store.get('state:live') if settings.INFRA_STRATEGY_BOOK_SCHEMA else (None, 0)
|
||
if current and current.get('rotation', {}).get('phase') != 'original' and mode != 'auto':
|
||
raise ValueError('实有微盘持仓或轮换在途,请先使用暂停或退出操作,不直接切换账本模式')
|
||
result = param_store.set_param('PMS_ROTATION_MODE', mode, actor)
|
||
if not result.get('ok'):
|
||
raise RuntimeError('档位保存失败')
|
||
if action:
|
||
result = param_store.set_param('PMS_ROTATION_CONTROL', action, actor)
|
||
if not result.get('ok'):
|
||
raise RuntimeError('控制保存失败')
|
||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and configuration()['mode'] == 'auto':
|
||
cancel_control_orders(action)
|
||
return status()
|
||
|
||
|
||
def cancel_control_orders(action):
|
||
"""先保存暂停,再撤已发出的轮换委托;失败保留暂停并由调度重试。"""
|
||
if action not in ('pause_all', 'pause_new', 'exit_disable'):
|
||
return
|
||
from app.services import executor
|
||
with books.scope('all'):
|
||
rows = pms_repo.list_instructions(statuses=LIVE, limit=10000)
|
||
failed = []
|
||
for row in rows:
|
||
if (row.get('progress') or {}).get('execution_profile') != 'rotation':
|
||
continue
|
||
if action != 'pause_all' and row['side'] != 'buy':
|
||
continue
|
||
with books.scope(row['book_id']):
|
||
result = executor.cancel_instruction(row['instruction_id'], reason='用户轮换控制:'+action, arbiter='user')
|
||
if not result.get('ok'):
|
||
failed.append(row['instruction_id'])
|
||
if failed:
|
||
raise RuntimeError('已停止新增指令,部分既有委托尚未完成撤销')
|
||
|
||
|
||
def positions(book):
|
||
with books.scope(book):
|
||
return pms_repo.list_positions(only_open=True)
|
||
|
||
|
||
def _paper_seed():
|
||
funds = portfolio.cash_view()
|
||
if funds['source'] != 'ws' or funds.get('cash_avail') is None:
|
||
raise ValueError('纸面账户初始化需要有效QMT资金快照')
|
||
account = {'cash': funds['cash_avail'], 'books': {'original': {}, 'micro30': {}},
|
||
'realized': {'original': 0., 'micro30': 0.}, 'fees': {'original': 0., 'micro30': 0.},
|
||
'fills': {}, 'seeded_at': dt.datetime.now(TZ).isoformat(), 'seed_asset': funds.get('total_asset')}
|
||
with books.scope('original'):
|
||
for p in pms_repo.list_positions(only_open=True):
|
||
lots = [{'date': str(r['open_date'])[:10], 'qty': int(r['qty'])} for r in pms_repo.list_lots(p['ts_code'])]
|
||
if sum(r['qty'] for r in lots) != p['total_qty']:
|
||
raise ValueError('原策略批次数量与主档不一致')
|
||
account['books']['original'][p['ts_code']] = {'qty': p['total_qty'],
|
||
'cost': float(p.get('avg_cost') or 0)*p['total_qty'], 'lots': lots,
|
||
'base_qty': p['base_qty'], 'cushion_pct': float(p.get('cushion_pct') or 0)}
|
||
return account
|
||
|
||
|
||
def _paper_positions(account, book, day):
|
||
return [{'ts_code': code, 'total_qty': p['qty'], 'avail_qty': sum(r['qty'] for r in p['lots'] if r['date'] < day),
|
||
'base_qty': p.get('base_qty', p['qty']), 'cushion_pct': p.get('cushion_pct'), 'neg_cushion_days': p.get('neg_cushion_days', 0)}
|
||
for code, p in account['books'][book].items() if p['qty']]
|
||
|
||
|
||
def _quote(code, now):
|
||
quote = market.day_snapshot(code)
|
||
raw = quote.get('bar_time')
|
||
if not raw:
|
||
return {}
|
||
try:
|
||
stamp = dt.datetime.fromisoformat(str(raw).replace('Z', '+00:00'))
|
||
if stamp.tzinfo is None:
|
||
stamp = stamp.replace(tzinfo=TZ)
|
||
if not 0 <= (now-stamp).total_seconds() <= 180:
|
||
return {}
|
||
except ValueError:
|
||
return {}
|
||
return quote
|
||
|
||
|
||
def _limits(day):
|
||
if param_store.get_bool('PMS_LIMIT_CACHE_ENABLED', False):
|
||
from app.services import price_limits
|
||
return price_limits.get_limits(day)
|
||
from app.db import session as db
|
||
rows = db.fetch_all('SELECT ts_code,up_limit,down_limit FROM gp_stk_limit WHERE trade_date=:day '
|
||
"AND (ts_code LIKE '60____.SH' OR ts_code LIKE '68____.SH' OR ts_code LIKE '00____.SZ' OR ts_code LIKE '30____.SZ')", {'day': day})
|
||
return {r['ts_code']: r for r in rows}
|
||
|
||
|
||
def _unavailable_candidates(snapshot, quotes, budget, boards, costs):
|
||
"""仅明确停牌或静态交易资格问题递补;行情缺失和价格落后都不是停牌。"""
|
||
unavailable = {}
|
||
for member in snapshot.get('candidates', snapshot.get('members', [])):
|
||
code = member['code']
|
||
quote = quotes.get(code, {})
|
||
if quote.get('halted') is True:
|
||
unavailable[code] = '行情来源明确标记停牌'
|
||
elif core.board(code) not in boards:
|
||
unavailable[code] = '账户没有该板块权限'
|
||
elif budget > 0 and not core.buy_qty(code, float(member.get('close') or 0), budget/core.SIZE, costs):
|
||
unavailable[code] = '单股预算不足最低交易单位及费用'
|
||
return unavailable
|
||
|
||
|
||
def _micro_unsettled(pending):
|
||
"""本地撤销不等于下游终态;未入账成交也不能视为退出已完成。"""
|
||
if any(r['book_id'] == books.MICRO for r in pending) or qmt_repo.inbox_pending_count():
|
||
return True
|
||
rows = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
|
||
if len(rows) > 10000:
|
||
raise ValueError('在途委托超出轮换核验上限')
|
||
with books.scope('all'):
|
||
for row in rows:
|
||
parent = pms_repo.get_instruction(row['parent_id'])
|
||
if not parent:
|
||
raise ValueError('在途委托策略归属尚未核实')
|
||
if parent['book_id'] == books.MICRO:
|
||
return True
|
||
return False
|
||
|
||
|
||
def tick(now=None):
|
||
"""先独立提交轮换决定,再执行;两段均先锁账户,再锁轮换状态。"""
|
||
config = configuration()
|
||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
||
# 撤单、限制价查询或下发失败不能回滚已经确认的入场/退出任务。
|
||
# 两段之间释放账户锁;执行段重新读取用户控制、资金和实际持仓。
|
||
with store.account_guard():
|
||
prepared = _tick(now, prepare_only=True)
|
||
if not prepared.get('prepared'):
|
||
return prepared
|
||
with store.account_guard():
|
||
return _tick(now)
|
||
return _tick(now)
|
||
|
||
|
||
def _tick(now=None, *, prepare_only=False):
|
||
now = now or dt.datetime.now(TZ)
|
||
if now.tzinfo is None:
|
||
now = now.replace(tzinfo=TZ)
|
||
config = configuration()
|
||
day = now.date().isoformat()
|
||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
||
cancel_control_orders(config['control'])
|
||
if config['mode'] == 'auto' and settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||
from app.services.rotation_execution import cancel_expired
|
||
cancel_expired(now)
|
||
if td.calendar_degraded(day) or not td.is_trade_day(day):
|
||
return {'skipped': '交易日历不可用或非交易日'}
|
||
key = 'state:'+('paper' if config['mode'] == 'paper' else 'live')
|
||
saved, _ = store.get(key) if documents_ready() else (None, 0)
|
||
saved = saved or {}
|
||
exit_pending = saved.get('rotation', {}).get('phase') == 'returning_original' or config['control'] == 'exit_disable'
|
||
value, errors = None, []
|
||
try:
|
||
value = pull(day)
|
||
errors = core.snapshot_check(value, day, expected_rule=config['rule_version'], candidate_pool_size=config.get('candidate_pool_size', 100))
|
||
except Exception as exc:
|
||
errors = ['监控暂不可用:'+type(exc).__name__]
|
||
if errors:
|
||
value = None
|
||
if not documents_ready():
|
||
return {'snapshot': value, 'mode': 'observe', 'blocked': errors+['观察记录表尚未启用']}
|
||
if value:
|
||
store.put_once('snapshot:'+day+':'+value['snapshot_version'], 'snapshot', value)
|
||
if value['signal_ready'] and value['basket_ready']:
|
||
store.put_once('observed:'+day, 'observed_day', {'date': day, 'rule_version': config['rule_version'], 'snapshot_version': value['snapshot_version']})
|
||
from app.services import intraday_rotation
|
||
batch = intraday_rotation.basket_for(now, value, config) if value and not value.get('basket_ready') else None
|
||
if batch:
|
||
release, value, staged = batch
|
||
if config['mode'] == 'observe':
|
||
return {'mode': 'observe', 'snapshot': value, 'blocked': errors}
|
||
exit_pending = exit_pending or bool(value and value.get('signal_ready') and value.get('signal', {}).get('high') and saved.get('rotation', {}).get('phase') in ('entering_micro', 'micro'))
|
||
if config['mode'] == 'auto':
|
||
blocked = activation_errors()
|
||
# 初次启用必须完成全部验收;已确认的退出不因监控/观察证据故障卡住。
|
||
if blocked and not (exit_pending and settings.INFRA_STRATEGY_BOOK_SCHEMA):
|
||
return {'blocked': blocked}
|
||
if not value and not exit_pending:
|
||
return {'blocked': errors}
|
||
if value is None:
|
||
# 仅作为已确认退出的执行上下文,不写成新快照、不生成任何入场。
|
||
value = {'members': [], 'signal_ready': False, 'basket_ready': False,
|
||
'effective_date': day, 'snapshot_version': saved.get('rotation', {}).get('last_snapshot'), 'signal': {}}
|
||
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
||
config['control'] = 'pause_all'
|
||
elif param_store.get_bool('PMS_GLOBAL_BUY_HALT', False) and config['control'] == 'run':
|
||
config['control'] = 'pause_new'
|
||
manual_exit = config['control'] == 'exit_disable' and (570 <= now.hour*60+now.minute < 690 or 780 <= now.hour*60+now.minute < 895)
|
||
if not 570 <= now.hour*60+now.minute < 600 and not manual_exit and not batch:
|
||
if config['mode'] == 'auto':
|
||
from app.services.rotation_execution import cancel_expired
|
||
cancel_expired(now)
|
||
return {'skipped': '执行窗口之外'}
|
||
key = 'state:'+('paper' if config['mode'] == 'paper' else 'live')
|
||
with store.locked(key, 'state', {'rotation': core.initial_state()}) as state:
|
||
if config['mode'] == 'paper':
|
||
if 'account' not in state:
|
||
state['account'] = _paper_seed()
|
||
account = state['account']
|
||
original = _paper_positions(account, 'original', day)
|
||
micro = _paper_positions(account, 'micro30', day)
|
||
cash = account['cash']
|
||
pending = []
|
||
else:
|
||
recon = reconcile_books()
|
||
if recon['diffs'] or not recon['ok']:
|
||
return {'blocked': ['策略账本与QMT尚未对齐']}
|
||
original, micro = positions('original'), positions('micro30')
|
||
funds = portfolio.cash_view()
|
||
if funds['source'] != 'ws':
|
||
raise ValueError('真实资金快照不可用')
|
||
cash = funds['cash_avail']
|
||
from app.services.rotation_execution import pending_instructions
|
||
pending = pending_instructions()
|
||
codes = {r['ts_code'] for r in original+micro}|{r['code'] for r in value.get('candidates', value['members'])}
|
||
quotes = {c: _quote(c, now) for c in codes}
|
||
missing = [r['ts_code'] for r in original+micro if not quotes.get(r['ts_code'])]
|
||
physical_mv = None
|
||
if batch:
|
||
age = funds.get('age_sec')
|
||
physical_mv = funds.get('account_market_value')
|
||
if age is None or not 0 <= age <= 60 or physical_mv is None or not math.isfinite(float(physical_mv)) or physical_mv < 0:
|
||
return {'blocked': ['当日授权等待有效的账户资金和持仓市值快照']}
|
||
if missing and not exit_pending and physical_mv is None:
|
||
if config['mode'] == 'auto' and config['rule_version'] == core.EXECUTION_RULE:
|
||
from app.services.rotation_execution import refresh_orders
|
||
# 估值不完整时不增加风险,已发v3单先撤清,未知行情不触发递补。
|
||
refresh_orders(pending, {}, now, value['snapshot_version'],
|
||
set(state.get('rotation', {}).get('target') or []), {})
|
||
state['blocked'] = ['持仓行情不完整,无法核算全账户仓位']+missing
|
||
return {'blocked': state['blocked']}
|
||
account_mv = sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in original+micro)
|
||
if physical_mv is not None:
|
||
account_mv = max(account_mv, float(physical_mv))
|
||
if config['mode'] == 'paper' and 'capital' not in account and not missing:
|
||
from app.core import rotation_account as capital
|
||
account['capital'] = capital.seed(cash, {'original': account_mv, 'micro30': 0.})
|
||
scale = param_store.get_float('PMS_TOTAL_SCALE', 0.)
|
||
cap = scale*param_store.get_float('PMS_PORTFOLIO_CAP', 0.)
|
||
reserve = scale*param_store.get_float('PMS_CASH_RESERVE', 0.)
|
||
budget = max(0., min(cap, cash+account_mv-reserve))
|
||
boards = config['boards'] if config['mode'] == 'auto' else {'MAIN', 'STAR', 'CHINEXT'}
|
||
execution_quotes = {}
|
||
buy_prices = {}
|
||
quote_errors = []
|
||
limits = None
|
||
if config['rule_version'] == core.EXECUTION_RULE and not prepare_only:
|
||
from app.services import execution_orders
|
||
try:
|
||
limits = _limits(day)
|
||
except Exception as exc:
|
||
limits = {}
|
||
quote_errors.append('当日限制价查询失败:'+type(exc).__name__)
|
||
for c in codes:
|
||
try:
|
||
execution_quotes[c] = market.execution_quote(c, now=now, limits=limits.get(c, {}))
|
||
except Exception as exc:
|
||
# 查询失败是未知,不能把故障改写成该股不可交易的资格结论。
|
||
execution_quotes[c] = {}
|
||
quote_errors.append(c+'执行行情查询失败:'+type(exc).__name__)
|
||
for c, execution_quote in execution_quotes.items():
|
||
priced = execution_orders.quote_order('buy', execution_quote, now)
|
||
if priced.get('action') == 'FIRE':
|
||
buy_prices[c] = {**quotes.get(c, {}), 'price': priced['limit_price']}
|
||
unavailable = _unavailable_candidates(value, execution_quotes, budget, boards, config['costs'])
|
||
if config['mode'] == 'auto' and config['rule_version'] == core.EXECUTION_RULE and not prepare_only:
|
||
from app.services.rotation_execution import suspended_rejections
|
||
unavailable.update(suspended_rejections(now))
|
||
fresh_entry = state['rotation']['phase'] == 'original' and config['control'] == 'run' and value.get('signal_ready') and value.get('basket_ready') and not value['signal'].get('high') and (value['signal'].get('low') or value['signal'].get('growth_break'))
|
||
if fresh_entry:
|
||
# 先排除确定性整体不可执行,不能先清旧仓再发现根本没有建仓预算。
|
||
static_issues = core.preflight(value['members'], budget, boards, config['costs'])
|
||
if config['rule_version'] == core.EXECUTION_RULE:
|
||
static_issues = ['没有可执行的初始建仓候选或预算'] if budget <= 0 or not any(m['code'] not in unavailable for m in value['candidates']) else []
|
||
if static_issues:
|
||
state['blocked'] = static_issues
|
||
return {'blocked': static_issues}
|
||
s = core.transition(state['rotation'], value, micro_qty=sum(r['total_qty'] for r in micro),
|
||
original_qty=sum(r['total_qty'] for r in original), budget=budget, control=config['control'],
|
||
micro_pending=config['mode'] == 'auto' and exit_pending and _micro_unsettled(pending))
|
||
state['rotation'] = s
|
||
target_waits = core.resolve_targets(s, value, micro=micro, pending=pending, unavailable=unavailable)
|
||
if s['phase'] == 'returning_original' and not s.get('exit_date'):
|
||
s['exit_date'] = day
|
||
if batch:
|
||
if s['phase'] not in ('entering_micro', 'micro') or s.get('consumed_entry') != release['snapshot_version']:
|
||
return {'blocked': ['盘中名单与当前实有轮次不一致']}
|
||
state['intraday_date'] = day
|
||
for code, row in staged.items():
|
||
if code in s['target']:
|
||
s['entry_quantities'].setdefault(code, int(row['qty']))
|
||
store.stage_locked(key, state)
|
||
if prepare_only:
|
||
return {'prepared': True, 'mode': config['mode'], 'phase': s['phase']}
|
||
if config['mode'] == 'auto' and s['phase'] in ('entering_micro', 'returning_original'):
|
||
from app.services import executor
|
||
for old in pending:
|
||
if old['side'] == 'buy' and not (old['book_id'] == 'original' and closing_t0(old)) and (s['phase'] == 'returning_original' or old['book_id'] == 'original'):
|
||
with books.scope(old['book_id']):
|
||
result = executor.cancel_instruction(old['instruction_id'], reason='策略轮换停止新增投入', arbiter='system')
|
||
if not result.get('ok'):
|
||
raise RuntimeError('原买入撤单尚未确认,暂停轮换')
|
||
with books.scope('original'):
|
||
t0_open = any((r.get('state') or {}).get('open_leg') for r in pms_repo.active_strategies() if r.get('type') == 'T0')
|
||
if t0_open or any(p.get('t0_qty', 0) for p in original):
|
||
state['blocked'] = ['原策略尚有做T批次,等待完成后继续轮换']
|
||
return {'blocked': state['blocked']}
|
||
from app.services import command_service
|
||
black = command_service.blacklist()
|
||
refreshed, refresh_waits = [], []
|
||
if config['mode'] == 'auto' and s.get('rule_version') == core.EXECUTION_RULE and config['control'] == 'run':
|
||
from app.services.rotation_execution import refresh_orders
|
||
refreshable = [p for p in pending if (p.get('progress') or {}).get('ticket') == release['ticket']] if batch else pending
|
||
refreshed, refresh_waits = refresh_orders(refreshable, execution_quotes, now, value['snapshot_version'], set(s['target']) if s['phase'] in ('entering_micro', 'micro') else set(), unavailable)
|
||
if s['phase'] == 'entering_micro' and s.get('rule_version') == core.EXECUTION_RULE and not any(c in buy_prices and c not in unavailable for c in s['target']):
|
||
# 先完成已有单的撤销确认,避免全部停牌时卡住递补;不新卖原仓筹资。
|
||
state['blocked'] = quote_errors+target_waits+refresh_waits+['目标成员当前没有可核实执行报价,暂不卖出原策略筹资']
|
||
return {'blocked': state['blocked'], 'phase': s['phase'], 'results': refreshed}
|
||
planning_quotes = {**quotes, **buy_prices}
|
||
intents, waits = core.orders(s, value, original=original, micro=micro, quotes=planning_quotes,
|
||
cash=cash, account_mv=account_mv, cap_amount=cap, reserve_cash=reserve,
|
||
pending=pending, control=config['control'], blacklisted=black, costs=config['costs'])
|
||
# 纸面档明确采用全沪深权限假设,不把它当实际账户权限判收。
|
||
issues = core.preflight(value['members'], budget, boards, config['costs']) if value['basket_ready'] else ['名单未就绪']
|
||
if issues and s.get('rule_version') != core.EXECUTION_RULE:
|
||
intents = [r for r in intents if r['side'] == 'sell']
|
||
waits.extend(issues)
|
||
if s.get('rule_version') == core.EXECUTION_RULE:
|
||
intents = [r for r in intents if r['side'] == 'sell' or r['ts_code'] not in unavailable]
|
||
waits.extend(quote_errors+target_waits+refresh_waits)
|
||
if limits is None:
|
||
limits = _limits(day)
|
||
done = list(refreshed)
|
||
for i, intent in enumerate(intents):
|
||
c, side = intent['ts_code'], intent['side']
|
||
quote = quotes.get(c, {})
|
||
price = quote.get('price')
|
||
lim = limits.get(c)
|
||
if s.get('rule_version') == core.EXECUTION_RULE:
|
||
from app.services import execution_orders
|
||
priced = execution_orders.quote_order(side, execution_quotes.get(c, {}), now)
|
||
if priced.get('action') != 'FIRE':
|
||
waits.append(c+str(priced.get('reason') or '执行报价不可用'))
|
||
continue
|
||
price = priced['limit_price']
|
||
intent['quote_basis'] = {**execution_quotes.get(c, {}), **priced}
|
||
intent['rule_version'] = core.EXECUTION_RULE
|
||
if not price or not lim or not lim.get('up_limit') or not lim.get('down_limit'):
|
||
waits.append(c+'行情或限制价不完整')
|
||
continue
|
||
if s.get('rule_version') != core.EXECUTION_RULE and ((side == 'buy' and price >= float(lim['up_limit'])) or (side == 'sell' and price <= float(lim['down_limit']))):
|
||
waits.append(c+'涨跌停阻止成交')
|
||
continue
|
||
rows = original if intent['book_id'] == 'original' else micro
|
||
pos = next((r for r in rows if r['ts_code'] == c), {})
|
||
if side == 'sell':
|
||
intent['qty'] = min(intent['qty'], int(pos.get('avail_qty') or 0))
|
||
if not intent['qty']:
|
||
continue
|
||
# 报价是可变执行信息,不进入父任务幂等键。
|
||
identity = {k: v for k, v in intent.items() if k != 'quote_basis'}
|
||
token = hashlib.sha256(json.dumps([day, s['cycle'], identity, len(state.get('account', {}).get('fills', {}))], sort_keys=True).encode()).hexdigest()[:24]
|
||
intent['id'] = 'ROT_'+token
|
||
if batch:
|
||
if side == 'sell' and (not release.get('funding_sales') or intent['book_id'] != books.ORIGINAL):
|
||
continue
|
||
intent['batch'] = intraday_rotation.metadata(release)
|
||
if side == 'buy':
|
||
intent['target_qty'] = s.get('entry_quantities', {}).get(c, intent['qty']) - int(pos.get('total_qty') or 0)
|
||
intent['id'] = (staged[c]['id'] if side == 'buy' and c in staged else
|
||
intraday_rotation.parent_id(release, intent['book_id'], side, c))
|
||
if config['mode'] == 'paper':
|
||
core.apply_paper_fill(account, intent, price, day, config['costs'],
|
||
prices={c: q['price'] for c, q in quotes.items() if q.get('price')})
|
||
done.append(intent)
|
||
else:
|
||
from app.services.rotation_execution import send_intent
|
||
from app.db import session as db
|
||
try:
|
||
with db.savepoint():
|
||
done.append(send_intent(intent, price, now, value['snapshot_version']))
|
||
except Exception as exc:
|
||
waits.append(c+'委托待重试:'+str(exc)[:160] if batch else c+'委托待重试:'+type(exc).__name__)
|
||
if s['phase'] == 'entering_micro' and len(s['target']) == core.SIZE and not original and all(any(p['ts_code'] == c and p['total_qty'] >= s.get('entry_quantities', {}).get(c, 0) for p in micro) for c in s['target']) and not pending:
|
||
s['phase'] = 'micro'
|
||
state.update(last_tick=now.isoformat(), blocked=waits+errors, last_intents=intents, last_results=done,
|
||
signal_healthy=bool(value.get('signal_ready') and value.get('basket_ready')),
|
||
progress={'original_market_value': sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in original),
|
||
'micro_market_value': sum(r['total_qty']*quotes.get(r['ts_code'], {}).get('price', 0) for r in micro),
|
||
'available_cash': cash, 'allowed_stock_budget': budget, 'original_count': len(original), 'micro_count': len(micro)})
|
||
if config['mode'] == 'paper':
|
||
state['board_permission_assumption'] = '纸面使用沪深全部板块,不是实际权限核实'
|
||
state['nav'] = account['cash']+sum(p['qty']*quotes.get(c, {}).get('price', 0.) for b in account['books'].values() for c, p in b.items())
|
||
if done:
|
||
event = {'at': now.isoformat(), 'mode': config['mode'], 'phase': s['phase'], 'results': done, 'snapshot_version': value['snapshot_version']}
|
||
store.put_once('execution:'+hashlib.sha256(json.dumps(event, sort_keys=True, default=str).encode()).hexdigest(), 'execution', event)
|
||
return {'mode': config['mode'], 'phase': s['phase'], 'results': done, 'blocked': waits+errors}
|
||
|
||
|
||
def original_buy_blocker():
|
||
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
||
return None
|
||
value, _ = store.get('state:live')
|
||
phase = (value or {}).get('rotation', {}).get('phase', 'original')
|
||
return '账户正在转入或运行微盘策略,原策略停止新增投入' if phase in ('entering_micro', 'micro') else None
|
||
|
||
|
||
|
||
def closing_t0(parent):
|
||
p = parent or {}
|
||
return p.get('origin_type') == 'strategy' and p.get('action') == 'T0_ROUND' and (p.get('progress') or {}).get('leg') == 'close'
|
||
|
||
|
||
def strategy_buy_blocker(book, parent=None):
|
||
config = configuration()
|
||
if book == books.ORIGINAL:
|
||
if closing_t0(parent):
|
||
return None
|
||
return original_buy_blocker()
|
||
if config['mode'] != 'auto' or config['control'] != 'run':
|
||
return '微盘未在自动运行档或用户已停止新增'
|
||
value, _ = store.get('state:live')
|
||
if (value or {}).get('rotation', {}).get('phase') not in ('entering_micro', 'micro'):
|
||
return '微盘阶段不允许新增买入'
|
||
return None
|
||
|
||
|
||
def reconcile_books():
|
||
from app.services.ledger_service import positions_source
|
||
from app.core.recon import diff_positions
|
||
source = positions_source()
|
||
totals = {}
|
||
with books.scope('all'):
|
||
rows = pms_repo.list_positions()
|
||
for row in rows:
|
||
code = row['ts_code']
|
||
totals[code] = totals.get(code, 0)+int(row['total_qty'])
|
||
if source['source'] != 'ws':
|
||
return {'ok': False, 'diffs': [], 'fixes': [], 'errors': ['没有有效账户持仓事实源'], 'severity': 'ERROR'}
|
||
differences = diff_positions([{'ts_code': c, 'total_qty': q} for c, q in totals.items()], source['rows'])
|
||
return {'ok': not differences, 'diffs': differences, 'fixes': [], 'errors': [],
|
||
'severity': 'ERROR' if differences else 'OK', 'source': source['source'],
|
||
'note': '策略数量之和核对账户;不猜测差异归属,不自动把差异并入任何策略'}
|
||
|
||
|
||
def on_user_command(cmd_type, command_id, issued_by):
|
||
if issued_by in ('rotation', 'macro') or str(issued_by).startswith('macro'):
|
||
return
|
||
if cmd_type in ('LIQUIDATE_ALL', 'HALT_ALL', 'HALT_BUY'):
|
||
action = {'LIQUIDATE_ALL': 'exit_disable', 'HALT_ALL': 'pause_all', 'HALT_BUY': 'pause_new'}[cmd_type]
|
||
result = param_store.set_param('PMS_ROTATION_CONTROL', action, issued_by)
|
||
if not result.get('ok'):
|
||
raise RuntimeError('全账户命令未同步到轮换控制')
|
||
from app.services import executor
|
||
with books.scope('micro30'):
|
||
for ins in pms_repo.list_instructions(statuses=LIVE, limit=10000):
|
||
if cmd_type == 'HALT_ALL' or ins['side'] == 'buy':
|
||
result = executor.cancel_instruction(ins['instruction_id'], reason='用户全账户命令'+command_id, arbiter='user')
|
||
if not result.get('ok'):
|
||
raise RuntimeError('用户命令已停新增,既有委托撤销尚未确认')
|
||
elif cmd_type in ('OPEN_TARGET', 'INCREASE_EXPOSURE', 'REDUCE_EXPOSURE', 'EXIT_STOCK', 'REDUCE_STOCK'):
|
||
state, _ = store.get('state:live')
|
||
if state and state['rotation']['phase'] != 'original':
|
||
result = param_store.set_param('PMS_ROTATION_CONTROL', 'pause_all', issued_by)
|
||
if not result.get('ok'):
|
||
raise RuntimeError('用户命令冲突暂停未保存')
|
||
cancel_control_orders('pause_all')
|
||
store.put_once('conflict:'+command_id, 'command_conflict', {'command_id': command_id, 'reason': '用户命令优先,轮换已暂停'})
|
||
|
||
|
||
def settle_day(now=None):
|
||
now = now or dt.datetime.now(TZ)
|
||
day = now.date().isoformat()
|
||
if not documents_ready() or now.hour*60+now.minute < 15*60+20 or td.calendar_degraded(day) or not td.is_trade_day(day):
|
||
return {'skipped': '未到有效交易日结算时间或观察表未启用'}
|
||
config = configuration()
|
||
if config['mode'] == 'auto':
|
||
from app.services.rotation_accounting import view
|
||
result = view()
|
||
healthy = result['ready'] and result['cash_difference'] is not None and abs(result['cash_difference']) <= .02 and reconcile_books()['ok']
|
||
record = {'date': day, 'rule_version': config['rule_version'], 'healthy': healthy, **result}
|
||
store.put_once('live_day:'+day, 'live_day', record)
|
||
return record
|
||
if config['mode'] != 'paper':
|
||
return {'skipped': '非纸面模式'}
|
||
with store.locked('state:paper', 'state', {'rotation': core.initial_state()}) as state:
|
||
account = state.get('account')
|
||
if not account:
|
||
return {'skipped': '纸面账户尚未初始化'}
|
||
from app.core import rotation_account as capital
|
||
values = {b: 0. for b in ('original','micro30')}
|
||
missing = []
|
||
for book, rows in account['books'].items():
|
||
for code, p in rows.items():
|
||
if not p['qty']:
|
||
continue
|
||
q = market.day_snapshot(code)
|
||
stamp = str(q.get('bar_time') or '')
|
||
try:
|
||
at = dt.datetime.fromisoformat(stamp)
|
||
valid = at.date().isoformat() == day and at.hour*60+at.minute >= 890
|
||
except ValueError:
|
||
valid = False
|
||
if not valid or not q.get('price'):
|
||
missing.append(code)
|
||
continue
|
||
values[book] += p['qty']*q['price']
|
||
healthy = bool(not missing and state.get('signal_healthy') and str(state.get('last_tick','')).startswith(day) and config['control'] != 'pause_all')
|
||
metrics = capital.metrics(account['capital'], values) if account.get('capital') and not missing else None
|
||
record = {'date': day, 'rule_version': config['rule_version'], 'healthy': healthy, 'missing_prices': missing,
|
||
'metrics': metrics, 'fees': account['fees'], 'snapshot_version': state['rotation'].get('last_snapshot')}
|
||
if metrics:
|
||
state['metrics'] = metrics
|
||
state['nav'] = metrics['account']['equity']
|
||
store.put_once('paper_day:'+day, 'paper_day', record)
|
||
return record
|
||
|
||
|
||
def reset_micro_available(now=None):
|
||
now = now or dt.datetime.now(TZ)
|
||
if now.hour*60+now.minute >= 565:
|
||
return {'skipped': '可卖数量只在盘前更新'}
|
||
with books.scope('micro30'), store.locked('micro_available:'+now.date().isoformat(), 'daily_reset', {'done': False}) as marker:
|
||
if marker['done']:
|
||
return {'skipped': '当日已完成'}
|
||
for p in pms_repo.list_positions(only_open=True):
|
||
lots = pms_repo.list_lots(p['ts_code'])
|
||
available = sum(int(r['qty']) for r in lots if str(r['open_date'])[:10] < now.date().isoformat())
|
||
pms_repo.update_position(p['ts_code'], avail_qty=min(available, p['total_qty']))
|
||
marker['done'] = True
|
||
return {'done': True}
|