From 1ec6e45f5aa18c33dd7684ca59c945d315dd8a7b Mon Sep 17 00:00:00 2001 From: baobao Date: Thu, 19 Nov 2026 10:15:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8C=89=E5=8D=95=E6=97=A5=E6=8E=88=E6=9D=83?= =?UTF-8?q?=E6=8E=A5=E7=BB=AD=E5=BE=AE=E7=9B=98=E7=AF=AE=E5=AD=90=E5=BB=BA?= =?UTF-8?q?=E4=BB=93=E5=B9=B6=E5=9C=A8=E5=8F=91=E9=80=81=E5=89=8D=E5=A4=8D?= =?UTF-8?q?=E6=A0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/repo/intraday_entry_repo.py | 22 +++++ app/services/execution_conflicts.py | 8 +- app/services/execution_orders.py | 8 ++ app/services/intraday_rotation.py | 125 ++++++++++++++++++++++++++++ app/services/param_store.py | 14 ++++ app/services/rotation_execution.py | 85 +++++++++++++++---- app/services/rotation_service.py | 42 +++++++++- app/web/static/rotation.html | 2 +- scripts/run_tests.py | 1 + scripts/test_intraday_rotation.py | 120 ++++++++++++++++++++++++++ 10 files changed, 406 insertions(+), 21 deletions(-) create mode 100644 app/repo/intraday_entry_repo.py create mode 100644 app/services/intraday_rotation.py create mode 100644 scripts/test_intraday_rotation.py diff --git a/app/repo/intraday_entry_repo.py b/app/repo/intraday_entry_repo.py new file mode 100644 index 0000000..4ccdd3c --- /dev/null +++ b/app/repo/intraday_entry_repo.py @@ -0,0 +1,22 @@ +"""单日轮动执行所需的单表核验。""" +from app.core import strategy_book as books +from app.db import session as db + + +def buy_ban(code): + with books.scope(books.ORIGINAL): + rows = db.fetch_all( + "SELECT cmd_type FROM pms_command WHERE ts_code=:code AND cmd_class='param' " + "AND status='EFFECTIVE' AND cmd_type IN ('FREEZE_STOCK','UNFREEZE_STOCK'," + "'BLACKLIST_ADD','BLACKLIST_REMOVE') ORDER BY id DESC", {'code': code}) + types = [row['cmd_type'] for row in rows] + frozen = next((t for t in types if t in ('FREEZE_STOCK', 'UNFREEZE_STOCK')), '') + black = next((t for t in types if t in ('BLACKLIST_ADD', 'BLACKLIST_REMOVE')), '') + return frozen == 'FREEZE_STOCK' or black == 'BLACKLIST_ADD' + + +def release_parent(parent): + return db.execute( + "UPDATE pms_instruction SET status='PROPOSED',updated_at=:at " + "WHERE instruction_id=:iid AND origin_id=:plan AND status='WAIT_REVIEW' AND exec_qty=0", + {'at': parent['at'], 'iid': parent['id'], 'plan': 'P_'+parent['id']}) diff --git a/app/services/execution_conflicts.py b/app/services/execution_conflicts.py index 61ce988..ab45acb 100644 --- a/app/services/execution_conflicts.py +++ b/app/services/execution_conflicts.py @@ -172,8 +172,12 @@ def instruction_progress(rows): label = '等待执行' review = (row.get('progress') or {}).get('daily_review') or {} if row.get('status') == 'WAIT_REVIEW' and not active: - label = '待确认今日买入' if review.get('status') == 'confirmation' else '跨日复核中' - stage = 'review' + if (row.get('progress') or {}).get('execution_profile') == 'rotation': + label = '等待篮子执行检查' + stage = 'waiting' + else: + label = '待确认今日买入' if review.get('status') == 'confirmation' else '跨日复核中' + stage = 'review' live_prices = {str(o.get('limit_price')) for o in active if o.get('limit_price') is not None} row['execution_limit'] = next(iter(live_prices)) if len(live_prices) == 1 else None row['execution_note'] = review.get('reason') if stage == 'review' else ( diff --git a/app/services/execution_orders.py b/app/services/execution_orders.py index 3574256..80cbe76 100644 --- a/app/services/execution_orders.py +++ b/app/services/execution_orders.py @@ -109,6 +109,14 @@ def prepare_send(instruction_id): blocked = correction_blocker(parent, ts_code=order['ts_code'], side=order['side']) if blocked: return {'marked': False, 'blocked': blocked} + if ((parent or {}).get('progress') or {}).get('ticket'): + from app.services import intraday_rotation + now = policy.local_now() + if int(order.get('valid_until') or 0) <= int(now.timestamp()*1000): + return {'marked': False, 'blocked': '单笔委托已到期'} + blocked = intraday_rotation.blocker(parent, order, now) + if blocked: + return {'marked': False, 'blocked': blocked} return {'marked': qmt_repo.mark_send_attempt(instruction_id), 'blocked': ''} diff --git a/app/services/intraday_rotation.py b/app/services/intraday_rotation.py new file mode 100644 index 0000000..c684ad0 --- /dev/null +++ b/app/services/intraday_rotation.py @@ -0,0 +1,125 @@ +"""模拟盘单日盘中建仓。盘前冻结与盘中授权分别核验、分别留账。""" +import datetime as dt +import hashlib + +from app.core import micro_rotation as core, strategy_book as books +from app.core.execution_policy import local_now +from app.repo import intraday_entry_repo as repo, pms_repo, rotation_repo as store +from app.services import param_store +from config.settings import settings + + +def session_open(now): + minute = now.hour * 60 + now.minute + return 570 <= minute < 690 or 780 <= minute < 897 + + +def release_key(day): + return 'manual-entry-release:155:' + day + + +def read_release(now): + if settings.PMS_TABLE_PREFIX or not settings.INFRA_STRATEGY_BOOK_SCHEMA: + return None + day = now.date().isoformat() + release, _ = store.get(release_key(day)) + if not release or not param_store.get_bool('PMS_ROTATION_SIM_DIRECT', False): + return None + if not (dt.datetime.fromisoformat(release['released_at']) <= now < dt.datetime.fromisoformat(release['expires_at'])): + return None + if release['deadline'] != day or not release['expires_at'].startswith(day+'T'): + raise ValueError('盘中授权不属于本交易日') + with books.scope(books.MICRO): + command = pms_repo.get_command(release['command_id']) or {} + params = command.get('params') or {} + if command.get('status') != 'EXECUTING' or command.get('issued_by') != 'user' or command.get('cmd_type') != 'ROTATE_MICRO': + return None + if any(params.get(k) != release[k] for k in ('authorization','ticket','expires_at','snapshot_version','rule_version')): + raise ValueError('盘中指令与授权版本不一致') + return release + + +def basket_for(now, morning, config): + if config['mode'] != 'auto' or config['control'] != 'run' or not session_open(now): + return None + release = read_release(now) + if not release: + return None + day = now.date().isoformat() + auth, _ = store.get(release['authorization']) + ticket, _ = store.get(release['ticket']) + basket, _ = store.get('intraday-basket:155:'+day) + valid = (auth and ticket and basket and morning and morning.get('frozen') is True + and morning['snapshot_version'] == basket.get('morning_version') + and morning.get('signal_ready') and morning.get('signal') == basket.get('signal') + and not morning.get('basket_ready') and basket.get('basket_ready') + and basket.get('basis') == 'manual_intraday' and basket.get('frozen') is False + and auth.get('account') == '155模拟' and auth.get('actor') == 'user' + and auth.get('effective_date') == day and auth.get('rule_version') == config['rule_version'] + and release['rule_version'] == config['rule_version'] == core.EXECUTION_RULE + and basket.get('authorization') in (release['authorization'], (auth.get('revision') or {}).get('replaces')) + and release['expires_at'] == auth.get('expires_at') == ticket.get('expires_at') + and release['authorization'] == ticket.get('source_auth') and release['ticket'] == ticket.get('id') + and ticket.get('no_carry') is True and ticket.get('book') == books.MICRO + and release['snapshot_version'] == ticket.get('source_version') == basket.get('snapshot_version') + and basket.get('signal_ready') and not basket['signal']['high'] + and (basket['signal']['low'] or basket['signal']['growth_break'])) + if not valid or core.snapshot_check(basket, day, require_frozen=False, expected_rule=config['rule_version'], + candidate_pool_size=config['candidate_pool_size']): + raise ValueError('盘中授权、建仓票据或篮子与盘前信号不一致') + lines = {row['code']: row for row in ticket['lines']} + pool = {row['code'] for row in basket['candidates']} + if (len(lines) != len(ticket['lines']) or len(set(row['id'] for row in lines.values())) != len(lines) + or not lines.keys() <= pool or any(row['side'] != 'buy' or int(row['qty']) <= 0 for row in lines.values())): + raise ValueError('盘中父指令清单不完整') + return release, basket, lines + + +def parent_id(release, book, side, code): + identity = '|'.join([release['ticket'], book, side, code]) + return 'ROT_'+hashlib.sha256(identity.encode()).hexdigest()[:24] + + +def metadata(release): + return {key: release[key] for key in ('authorization','ticket','command_id','expires_at','deadline','snapshot_version','rule_version')} + + +def blocker(parent, order, now=None): + progress = (parent or {}).get('progress') or {} + if not progress.get('ticket'): + return '' + now = local_now(now) + release = read_release(now) + if (not release or not session_open(now) or progress.get('cancel_requested') + or any(progress.get(k) != v for k, v in metadata(release).items())): + return '盘中建仓授权已停止或不在本批交易时段' + if parent['status'] not in ('PROPOSED','DISPATCHED') or parent['ts_code'] != order['ts_code'] or parent['side'] != order['side']: + return '原指令状态或委托方向已变动' + controls = param_store.execution_controls() + if (controls['halt_all'] or (order['side'] == 'buy' and controls['halt_buy']) + or controls['control'] != 'run' or controls['mode'] != 'auto'): + return '轮动已暂停' + state, _ = store.get('state:live') + rotation = (state or {}).get('rotation') or {} + if rotation.get('phase') not in ('entering_micro','micro') or rotation.get('consumed_entry') != release['snapshot_version']: + return '当前轮次与盘中建仓授权不一致' + code = order['ts_code'] + if not core.mainland_code(code): + return '证券不在沪深策略范围' + if order['side'] == 'sell': + if parent['book_id'] != books.ORIGINAL or not release.get('funding_sales') or rotation['phase'] != 'entering_micro': + return '卖出不在本批筹资授权内' + elif order['side'] == 'buy': + if parent['book_id'] != books.MICRO or code not in rotation.get('target', []): + return '股票已不在当日执行篮子' + if repo.buy_ban(code): + return '个股已冻结或列入黑名单,暂停买入' + else: + return '未知委托方向' + with books.scope('all'): + others = pms_repo.list_instructions(ts_code=code, statuses=['PROPOSED','RULE_PASSED','JUDGE_PASSED','DISPATCHED','WAIT_REVIEW'],limit=2) + if any(row['instruction_id'] != parent['instruction_id'] for row in others): + return '同股已有其他指令,等待核对' + if int(order['qty']) <= 0 or int(order['qty']) > int(parent['qty']) - int(parent.get('exec_qty') or 0): + return '本次委托超过原指令可执行余量' + return '' diff --git a/app/services/param_store.py b/app/services/param_store.py index f15c300..7676469 100644 --- a/app/services/param_store.py +++ b/app/services/param_store.py @@ -516,6 +516,20 @@ def get(key: str, default=None): return default +def execution_controls(): + """出口在账户事务中直接核实本次执行的控制项。读取失败由调用方停止发送。""" + def current_flag(key): + raw = pms_repo.get_param(key) + if raw is None: + return bool(RUNTIME_EXTRA[key][0]) + if str(raw).strip().lower() not in ('1','true','yes','on','y','0','false','no','off','n'): + raise ValueError('执行暂停参数无法核实') + return _coerce(raw, bool) + return {'halt_all': current_flag('PMS_GLOBAL_EXEC_HALT'), 'halt_buy': current_flag('PMS_GLOBAL_BUY_HALT'), + 'control': pms_repo.get_param('PMS_ROTATION_CONTROL') or 'run', + 'mode': pms_repo.get_param('PMS_ROTATION_MODE') or 'observe'} + + def get_float(key, default=0.0): try: return float(get(key, default)) diff --git a/app/services/rotation_execution.py b/app/services/rotation_execution.py index 5ae1d42..4235ee0 100644 --- a/app/services/rotation_execution.py +++ b/app/services/rotation_execution.py @@ -75,6 +75,11 @@ def enqueue_with_reservation(payload, parent_id): if blocked: raise ValueError(blocked) book = parent['book_id'] + if (parent.get('progress') or {}).get('ticket'): + from app.services import intraday_rotation + reason = intraday_rotation.blocker(parent, payload) + if reason: + raise ValueError(reason) if side == 'buy': from app.services.buy_budget import check_order with books.scope(book): @@ -176,21 +181,48 @@ def send_intent(intent, price, now, snapshot_version): raise ValueError(blocker) existing = pms_repo.get_instruction(parent) if not existing: - command = 'ROT_CMD_'+book+'_'+now.strftime('%Y%m%d') + batch = intent.get('batch') or {} + command = (batch.get('command_id') if book == books.MICRO else None) or 'ROT_CMD_'+book+'_'+now.strftime('%Y%m%d') if not pms_repo.get_command(command): - pms_repo.insert_command(command_id=command, cmd_class='task', cmd_type='ROTATE_MICRO', + if batch and book == books.MICRO: + raise ValueError('用户轮动命令已不存在') + created = pms_repo.insert_command(command_id=command, cmd_class='task', cmd_type='ROTATE_MICRO', ts_code=None, params={'rule_version': intent.get('rule_version', core.RULE), 'snapshot_version': snapshot_version}, status='EXECUTING', issued_by='rotation', note='微盘与原策略账户轮换') + if not created: + raise RuntimeError('轮动命令未保存') + target_qty = int(intent.get('target_qty', intent['qty'])) + if target_qty < int(intent['qty']): + raise ValueError('委托超过本次建仓目标') plan = 'P_'+parent action = 'OPEN' if intent['side'] == 'buy' else 'EXIT' - pms_repo.insert_plans([{'plan_id': plan, 'command_id': command, 'ts_code': intent['ts_code'], - 'action': action, 'qty': intent['qty'], 'amount': intent['qty']*price, + plans = pms_repo.insert_plans([{'plan_id': plan, 'command_id': command, 'ts_code': intent['ts_code'], + 'action': action, 'qty': target_qty, 'amount': target_qty*price, 'deadline': now.date(), 'status': 'EXECUTING', 'reason': intent['reason']}]) - pms_repo.insert_instruction(instruction_id=parent, origin_type='plan', origin_id=plan, - ts_code=intent['ts_code'], action=action, side=intent['side'], qty=intent['qty'], + if not plans: + raise RuntimeError('轮动计划未保存') + created = pms_repo.insert_instruction(instruction_id=parent, origin_type='plan', origin_id=plan, + ts_code=intent['ts_code'], action=action, side=intent['side'], qty=target_qty, window_tdays=1, progress={'execution_profile': 'rotation', 'snapshot_version': snapshot_version, 'rule_version': intent.get('rule_version', core.RULE), - 'deadline': now.date().isoformat(), 'is_command': True, 'children': []}) + 'deadline': now.date().isoformat(), 'is_command': True, 'children': [], **batch}) + if not created: + raise RuntimeError('轮动父指令未保存') + elif existing['status'] == 'WAIT_REVIEW' and (existing.get('progress') or {}).get('ticket'): + from app.services import intraday_rotation + from app.repo import intraday_entry_repo + progress = existing['progress'] + release = intraday_rotation.read_release(now) + if not release or any(progress.get(k) != v for k, v in intraday_rotation.metadata(release).items()): + raise ValueError('等待本笔盘中建仓放行') + ticket, _ = store.get(release['ticket']) + line = next((r for r in ticket['lines'] if r['id'] == parent), None) + if (not line or intent['side'] != 'buy' or existing['book_id'] != books.MICRO + or line['code'] != existing['ts_code'] or int(line['qty']) != int(existing['qty']) + or int(existing['qty']) != int(intent['qty']) or progress.get('cancel_requested') + or existing['origin_id'] != 'P_'+parent or qmt_repo.orders_for_parent(parent) + or intraday_entry_repo.release_parent({'id': parent, 'at': now}) != 1): + raise ValueError('待执行指令的来源、数量或状态已变化') elif existing['status'] not in ('PROPOSED', 'DISPATCHED'): return {'instruction_id': parent, 'state': '已有终态记录,次日重新规划'} elif (existing.get('progress') or {}).get('cancel_requested'): @@ -205,16 +237,34 @@ def send_intent(intent, price, now, snapshot_version): if retry_reason: return {'instruction_id': parent, 'state': retry_reason, 'pending': True} child = execution_orders.next_child_id(parent) + progress = (pms_repo.get_instruction(parent) or {}).get('progress') or {} + if progress.get('ticket'): + from app.services import intraday_rotation + current = intraday_rotation.local_now() + if not intraday_rotation.session_open(current) or current.date() != now.date(): + raise ValueError('盘中建仓执行时段已结束') + checked = execution_orders.quote_order(intent['side'], intent.get('quote_basis'), current, + user_limit=(existing or {}).get('limit_price')) + if checked.get('action') != 'FIRE': + raise ValueError(checked.get('reason') or '执行报价已过期') + price = checked['limit_price'] + end = current.replace(hour=11 if current.hour < 12 else 14, minute=30 if current.hour < 12 else 57, + second=0, microsecond=0) + until = min(current+dt.timedelta(minutes=10), end, dt.datetime.fromisoformat(progress['expires_at'])) + else: + until = (now.replace(hour=10, minute=0, second=0, microsecond=0) if now.hour < 10 else + min(now+dt.timedelta(minutes=10), now.replace(hour=14, minute=57, second=0, microsecond=0))) result = dispatcher.dispatch(instruction_id=child, parent_id=parent, intent='OPEN' if intent['side'] == 'buy' else 'EXIT', ts_code=intent['ts_code'], side=intent['side'], qty=quantity, limit_price=price, - valid_until=(now.replace(hour=10, minute=0, second=0, microsecond=0) if now.hour < 10 else min(now+dt.timedelta(minutes=10), now.replace(hour=14, minute=57, second=0, microsecond=0))), note=intent['reason']) + valid_until=until, note=intent['reason']) if not result.get('ok'): raise ValueError('轮换委托未下发:'+str(result.get('error'))) progress = (pms_repo.get_instruction(parent) or {}).get('progress', {}) progress.setdefault('children', []).append({'ref': child, 'qty': quantity, 'limit': price, - 'mode': 'ws', 'ymd': int(now.strftime('%Y%m%d')), 'at': now.strftime('%H:%M:%S'), 'valid_until': '10:00'}) + 'mode': 'ws', 'ymd': int(now.strftime('%Y%m%d')), 'at': now.strftime('%H:%M:%S'), 'valid_until': until.strftime('%H:%M')}) progress['quote'] = intent.get('quote_basis') - pms_repo.update_instruction(parent, status='DISPATCHED', dispatch_ref=child, progress=progress) + if not pms_repo.update_instruction(parent, status='DISPATCHED', dispatch_ref=child, progress=progress): + raise RuntimeError('父指令状态已变化,撤回本次出口及资金保留') return {'instruction_id': parent, 'book_id': book, 'result': result} @@ -283,7 +333,8 @@ def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable): children = qmt_repo.orders_for_parent(parent['instruction_id']) live = [c for c in children if c['status'] not in TERMINAL] quote = quotes.get(code, {}) - priced = execution_orders.quote_order(side, quote, now) + priced = (execution_orders.quote_order(side, quote, now, user_limit=parent.get('limit_price')) + if progress.get('ticket') else execution_orders.quote_order(side, quote, now)) if priced.get('action') != 'FIRE': waits.append(code+str(priced.get('reason') or '执行报价不可用')) if live: @@ -317,20 +368,26 @@ def refresh_orders(parents, quotes, now, snapshot_version, target, unavailable): with db.savepoint(): results.append(send_intent(intent, priced['limit_price'], now, snapshot_version)) except Exception as exc: - waits.append(code+'重挂待重试:'+type(exc).__name__) + waits.append(code+'重挂待重试:'+str(exc)[:160]) return results, waits def cancel_expired(now): from app.services import executor with books.scope('all'): - rows = pms_repo.list_instructions(statuses=('PROPOSED', 'DISPATCHED'), limit=10000) + rows = pms_repo.list_instructions(statuses=('PROPOSED', 'DISPATCHED','WAIT_REVIEW'), limit=10000) for row in rows: p = row.get('progress') or {} if p.get('execution_profile') != 'rotation': continue deadline = str(p.get('deadline') or '') - if deadline < now.date().isoformat() or (deadline == now.date().isoformat() and now.hour >= 10): + expired = deadline < now.date().isoformat() or (deadline == now.date().isoformat() and now.hour >= 10) + if p.get('ticket') and p.get('expires_at'): + from app.core.execution_policy import local_now + expired = local_now(now) >= dt.datetime.fromisoformat(p['expires_at']) + elif row['status'] == 'WAIT_REVIEW': + continue + if expired: with books.scope(row['book_id']): result = executor.cancel_instruction(row['instruction_id'], reason='轮换当日执行窗口结束', arbiter='system') if not result.get('ok'): diff --git a/app/services/rotation_service.py b/app/services/rotation_service.py index 93c8499..2431859 100644 --- a/app/services/rotation_service.py +++ b/app/services/rotation_service.py @@ -139,6 +139,12 @@ def status(): 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']}) @@ -352,6 +358,10 @@ def _tick(now=None, *, prepare_only=False): 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')) @@ -371,7 +381,7 @@ def _tick(now=None, *, prepare_only=False): 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: + 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) @@ -400,7 +410,13 @@ def _tick(now=None, *, prepare_only=False): 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'])] - if missing and not exit_pending: + 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单先撤清,未知行情不触发递补。 @@ -409,6 +425,8 @@ def _tick(now=None, *, prepare_only=False): 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.}) @@ -459,6 +477,13 @@ def _tick(now=None, *, prepare_only=False): 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']} @@ -480,7 +505,8 @@ def _tick(now=None, *, prepare_only=False): 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 - refreshed, refresh_waits = refresh_orders(pending, execution_quotes, now, value['snapshot_version'], set(s['target']) if s['phase'] in ('entering_micro', 'micro') else set(), unavailable) + 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+['目标成员当前没有可核实执行报价,暂不卖出原策略筹资'] @@ -530,6 +556,14 @@ def _tick(now=None, *, prepare_only=False): 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')}) @@ -541,7 +575,7 @@ def _tick(now=None, *, prepare_only=False): with db.savepoint(): done.append(send_intent(intent, price, now, value['snapshot_version'])) except Exception as exc: - waits.append(c+'委托待重试:'+type(exc).__name__) + 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, diff --git a/app/web/static/rotation.html b/app/web/static/rotation.html index 9d2a88d..5bab387 100644 --- a/app/web/static/rotation.html +++ b/app/web/static/rotation.html @@ -44,7 +44,7 @@ async function copyMembers(){ function cell(row,value){const td=document.createElement('td');td.textContent=value;row.append(td);return td} function line(table,values){const tr=document.createElement('tr');values.forEach(v=>cell(tr,v));table.append(tr)} async function request(url,options){const r=await fetch(url,options);if(r.status===401)throw Error('请先返回工作台登录');if(r.status===403)throw Error('此操作需要系统管理员权限');const v=await r.json();if(!r.ok||v.ok===false)throw Error(v.error||'请求失败');return v.data||v} -async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=v.mode==='paper'?st.account:null;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':!s.frozen?'待冻结':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}} +async function load(){prepareCopy();try{const v=await request('/api/rotation'),s=v.snapshot||{},g=s.signal||{},st=v.state||{},a=v.mode==='paper'?st.account:null;el('errors').textContent=[...(v.errors||[]),...(s.errors||[]),...(!s.basket_ready?['目标名单尚未就绪,停止新增和换仓。']:[])].join('\n');el('mode').textContent=modes[v.mode]||'未知档位';el('control').textContent=controls[v.control]||'未知控制';el('phase').textContent=phases[v.phase]||'等待状态';el('reason').textContent=(st.rotation||{}).reason||'等待有效信号';el('count').textContent=(s.members||[]).length+' / '+(v.basket_size||'—');el('date').textContent=s.data_date?('数据 '+s.data_date+' · 执行 '+s.effective_date+' · '+(s.basis==='manual_intraday'?'盘中授权 '+String(s.calculated_at).slice(11,19):s.frozen?'已冻结':'未冻结')):'尚无快照';el('growth').textContent=s.signal_ready?(g.growth_break?'已触发':'未触发'):'数据未就绪';el('percentile').textContent=g.activity_percentile==null?'—':fmt(g.activity_percentile*100)+'%';el('signal').textContent=!s.signal_ready?'等待数据':!s.frozen&&s.basis!=='manual_intraday'?'待冻结':g.high?'高位退出':g.low?'极低位入场':g.growth_break?'成长瓦解入场':'保持当前阶段';el('version').textContent='规则 '+(s.rule_version||v.rule_version)+' · 快照 '+(s.snapshot_version||'暂无');el('members').replaceChildren();(s.members||[]).forEach(m=>line(el('members'),[m.rank,m.code,m.name,fmt(m.total_mv_wan/10000),fmt(m.close),fmt(m.daily_amount_yuan/10000),m.eligible?'通过':'未通过']));el('waits').hidden=!(st.blocked||[]).length;el('waits').textContent=(st.blocked||[]).join('\n');el('positions').replaceChildren();if(a){el('account').textContent='纸面可用现金 '+fmt(a.cash)+' 元 · 最近估值 '+fmt(st.nav)+' 元 · 初始化 '+a.seeded_at;Object.entries(a.books||{}).forEach(([book,rows])=>Object.entries(rows).filter(([,p])=>p.qty).forEach(([code,p])=>line(el('positions'),[book==='micro30'?'微盘轮动':'主观量化',code,p.qty,fmt(p.cost),fmt(a.realized[book]),fmt(a.fees[book])])))}else el('account').textContent='尚无纸面或自动执行账本。';el('activation').textContent=(v.activation_errors||[]).join('\n')||(v.simulation_direct?'模拟仓直接运行条件已就绪。':'自动执行的前置验收已完成。');el('automatic').disabled=!!(v.activation_errors||[]).length;renderDetails(v);prepareCopy(s)}catch(e){el('errors').textContent=e.message}} function renderDetails(v){ const st=v.state||{},isPaper=v.mode==='paper',a=isPaper?st.account:null,s=v.snapshot||{},p=st.progress||{},rule=s.rule_parameters||v.rule_parameters||{},size=v.basket_size,metrics=isPaper?(st.metrics||{}):((v.accounting||{}).metrics||{}); el('rule-summary').textContent='成长主线瓦解或低于历史'+fmt(rule.entry_percentile==null?null:rule.entry_percentile*100)+'%分位时入场,高于历史'+fmt(rule.exit_percentile==null?null:rule.exit_percentile*100)+'%分位时退出。股汇对冲指标只作用于主观量化。'; diff --git a/scripts/run_tests.py b/scripts/run_tests.py index 8a5ee2e..6714a44 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -207,6 +207,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) # 退出纪律专项:两次独立清仓信号、评级下降、事务、双策略隔离及撤单收尾。 SUITES = [ + 'test_intraday_rotation.py', # 单日轮动授权、50个席位和委托出口(7例) "test_business_evidence.py", # 历史准备覆盖与嵌套业务失败(21例) "test_signal_health.py", # 资金监测可用性与交易员提示,7例 "test_proposal_trader_view.py", # 当前分析、数据库读数保存及旧确认保护(21例) diff --git a/scripts/test_intraday_rotation.py b/scripts/test_intraday_rotation.py new file mode 100644 index 0000000..04e1f3b --- /dev/null +++ b/scripts/test_intraday_rotation.py @@ -0,0 +1,120 @@ +"""盘中名单的凭据、窗口、席位和最终出口。所有业务数据使用内存桩。""" +import unit_test_guard # noqa: F401 +import datetime as dt +from contextlib import ExitStack, nullcontext +from unittest import TestCase, main +from unittest.mock import patch +from test_batch56_units import snapshot +from app.core import micro_rotation as core +from app.services import execution_orders as eo, intraday_rotation as entry + + +buy_ban = entry.repo.buy_ban + + +class IntradayEntry(TestCase): + def setUp(self): + self.stack = ExitStack() + self.addCleanup(self.stack.close) + self.now = entry.local_now(dt.datetime(2026, 11, 19, 10, 14)) + self.day = self.now.date().isoformat() + self.basket = snapshot(self.day) + self.morning = dict(self.basket, snapshot_version='morning', basket_ready=False) + self.basket.update(frozen=False, basis='manual_intraday', authorization='auth1', morning_version='morning') + self.codes = [r['code'] for r in self.basket['members']] + self.release = dict(authorization='auth2', command_id='cmd', ticket='ticket', deadline=self.day, + snapshot_version=self.basket['snapshot_version'], rule_version=core.EXECUTION_RULE, + released_at=self.now.isoformat(), expires_at=self.now.replace(hour=15,minute=0).isoformat(), + funding_sales=True) + self.lines = [dict(code=c, id='PARENT'+c, side='buy',qty=100) for c in self.codes[:44]] + self.docs = {entry.release_key(self.day): self.release, 'intraday-basket:155:'+self.day: self.basket, + 'auth2':dict(actor='user',account='155模拟', effective_date=self.day,rule_version=core.EXECUTION_RULE, + expires_at=self.release['expires_at'],revision={'replaces':'auth1'}), + 'ticket':dict(id='ticket',source_auth='auth2',source_version=self.basket['snapshot_version'], + expires_at=self.release['expires_at'], no_carry=True,book='micro30',lines=self.lines), + 'state:live':{'rotation':{'phase':'entering_micro','consumed_entry':self.basket['snapshot_version'], + 'target':self.codes}}} + self.cfg = dict(mode='auto',control='run',rule_version=core.EXECUTION_RULE,candidate_pool_size=100) + self.mock(entry.settings,'PMS_TABLE_PREFIX','') + self.mock(entry.settings,'INFRA_STRATEGY_BOOK_SCHEMA',True) + self.mock(entry.store,'get',side_effect=lambda k:(self.docs.get(k),1)) + self.mock(entry.param_store,'get_bool',return_value=True) + self.mock(entry.param_store,'execution_controls',return_value=dict(halt_all=False,halt_buy=False,control='run',mode='auto')) + self.cmd=dict(params=dict(self.release), status='EXECUTING', issued_by='user',cmd_type='ROTATE_MICRO') + self.mock(entry.pms_repo,'get_command',return_value=self.cmd) + self.parent=dict(instruction_id='p',status='DISPATCHED',book_id='micro30',side='buy',ts_code=self.codes[0], + qty=100,exec_qty=0,progress=entry.metadata(self.release)) + self.order=dict(instruction_id='child',parent_id='p',ts_code=self.codes[0],side='buy',qty=100, + valid_until=int((self.now+dt.timedelta(minutes=1)).timestamp()*1000)) + self.other = self.mock(entry.pms_repo,'list_instructions',return_value=[self.parent]) + self.ban = self.mock(entry.repo,'buy_ban',return_value=False) + + def mock(self, obj, key, *args, **kwargs): + return self.stack.enter_context(patch.object(obj,key,*args,**kwargs)) + + def test_fifty_targets_preserve_original_ids(self): + release, basket, lines = entry.basket_for(self.now,self.morning,self.cfg) + rotation = core.transition(core.initial_state(),basket,micro_qty=0,original_qty=0,budget=500000) + pending = [dict(ts_code=c) for c in lines] + core.resolve_targets(rotation,basket,pending=pending) + self.assertEqual(len(rotation['target']),50) + intents,_ = core.orders(rotation,basket,original=[],micro=[],pending=pending,cash=500000,account_mv=0, + cap_amount=500000,quotes={c:{'price':10} for c in self.codes[44:]}) + self.assertEqual({i['ts_code'] for i in intents},set(self.codes[44:])) + self.assertFalse(basket['frozen']) + self.assertTrue(self.morning['frozen']) + self.assertEqual([lines[c]['id'] for c in self.codes[:44]],[r['id'] for r in self.lines]) + + def test_no_release_or_wrong_instance(self): + self.mock(entry.settings,'PMS_TABLE_PREFIX','real_') + self.assertIsNone(entry.basket_for(self.now,self.morning,self.cfg)) + self.mock(entry.settings,'PMS_TABLE_PREFIX','') + del self.docs[entry.release_key(self.day)] + self.assertIsNone(entry.basket_for(self.now,self.morning,self.cfg)) + + def test_revised_or_corrupt_snapshot(self): + self.basket['members'][0]['close'] = 1 + with self.assertRaises(ValueError): + entry.basket_for(self.now,self.morning,self.cfg) + + def test_trading_sessions_and_expiry(self): + for h,m,allowed in [(9,29,False),(10,0,True),(11,30,False),(13,0,True),(14,57,False),(15,0,False)]: + self.assertEqual(entry.session_open(self.now.replace(hour=h,minute=m)),allowed) + self.assertIsNone(entry.read_release(self.now.replace(hour=15))) + + def test_wire_freeze_then_sell(self): + self.mock(eo,'account_guard',side_effect=nullcontext) + self.mock(eo.qmt_repo,'get_order',return_value=self.order) + self.mock(eo.pms_repo,'get_instruction',return_value=self.parent) + self.mock(eo,'correction_blocker',return_value='') + self.mock(eo.policy,'local_now',return_value=self.now) + mark=self.mock(eo.qmt_repo,'mark_send_attempt',return_value=True) + self.ban.return_value=True + self.assertFalse(eo.prepare_send('child')['marked']) + mark.assert_not_called() + self.order['side']='sell' + self.parent.update(book_id='original',side='sell') + self.assertTrue(eo.prepare_send('child')['marked']) + self.cmd['status']='CANCELLED' + self.assertFalse(eo.prepare_send('child')['marked']) + self.assertEqual(mark.call_count,1) + + def test_duplicate_or_partial(self): + self.other.return_value=[self.parent,dict(instruction_id='other')] + self.assertIn('其他指令',entry.blocker(self.parent,self.order,self.now)) + self.other.return_value=[self.parent] + self.parent['exec_qty']=60 + self.assertIn('余量',entry.blocker(self.parent,self.order,self.now)) + self.order['qty']=40 + self.assertFalse(entry.blocker(self.parent,self.order,self.now)) + + def test_ban_removal_does_not_remove_other_ban(self): + rows=self.mock(entry.repo.db,'fetch_all',return_value=[{'cmd_type':t} for t in + ('UNFREEZE_STOCK','BLACKLIST_ADD','FREEZE_STOCK')]) + self.assertTrue(buy_ban(self.codes[0])) + rows.return_value.insert(0,{'cmd_type':'BLACKLIST_REMOVE'}) + self.assertFalse(buy_ban(self.codes[0])) + + +if __name__ == '__main__': + main()