tradingSystem/scripts/test_batch56_units.py

865 lines
50 KiB
Python
Raw Normal View History

"""微盘冻结后备池、持久补齐及真实在途防重。所有输入为内存数据。"""
import unit_test_guard # noqa: F401
import copy
from contextlib import contextmanager, ExitStack, nullcontext
import datetime as dt
import hashlib
import json
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core import micro_rotation as m
def snapshot(day='2026-11-03', size=100, rule=m.EXECUTION_RULE, low=True):
rows = [{'code': f'{600000+i}.SH', 'rank': i+1, 'eligible': True, 'close': 10.,
'total_mv_wan': i+1} for i in range(size)]
value = {'rule_version': rule, 'rule_parameters': m.rule_parameters(rule),
'basket_size': 50, 'data_date': '2026-11-02', 'effective_date': day,
'signal_ready': True, 'basket_ready': True,
'signal': {'date': '2026-11-02', 'ready': True, 'low': low, 'high': False, 'growth_break': False},
'members': rows[:50], 'source_hashes': {'stocks': 'fixed'}, 'errors': []}
if rule == m.EXECUTION_RULE:
value.update(candidates=rows, candidate_count=len(rows))
value['snapshot_version'] = hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(',', ':')).encode()).hexdigest()
value['frozen'] = True
return value
def state(snap=None):
snap = snap or snapshot()
return m.transition(m.initial_state(), snap, micro_qty=0, original_qty=0, budget=100000)
class MicroBuyRestrictionTests(unittest.TestCase):
def setUp(self):
from app.core import strategy_book as books
from app.repo import pms_repo
from app.services import rotation_service
self.enterContext(patch.object(rotation_service.store, 'account_guard', side_effect=nullcontext))
self.commands = []
def effective_commands(*args, **kwargs):
self.assertEqual(books.CURRENT.get(), books.ORIGINAL)
return list(self.commands)
self.enterContext(patch.object(pms_repo, 'list_effective_stock_params', side_effect=effective_commands))
def command(self, code, kind):
self.commands.append({'id': len(self.commands)+1, 'ts_code': code, 'cmd_type': kind})
def parent(self, code, side='buy'):
return {'instruction_id': code+'-'+side, 'ts_code': code, 'book_id': 'micro30',
'side': side, 'action': 'OPEN' if side == 'buy' else 'EXIT', 'qty': 300,
'exec_qty': 100, 'status': 'DISPATCHED', 'origin_type': 'rotation',
'progress': {'execution_profile': 'rotation', 'rule_version': m.EXECUTION_RULE,
'deadline': '2026-11-03'}}
def test_entry_preserves_other_members_and_authorized_sales(self):
from app.services import rotation_service
snap = snapshot()
basket = state(snap)
held, frozen, black = '000001.SZ', '600000.SH', '600001.SH'
self.command(held, 'FREEZE_STOCK')
self.command(frozen, 'FREEZE_STOCK')
self.command(black, 'BLACKLIST_ADD')
quotes = {r['code']: {'price': 10.} for r in snap['members']}
quotes[held] = {'price': 10.}
def intents():
orders, _ = m.orders(basket, snap, original=[{'ts_code': held, 'total_qty': 100}],
micro=[], quotes=quotes, cash=100000, account_mv=1000, cap_amount=110000,
buy_restrictions=rotation_service.micro_buy_restrictions())
return {(r['ts_code'], r['side']) for r in orders}
allowed = intents()
expected = {(r['code'], 'buy') for r in snap['members'] if r['code'] not in (frozen, black)}
self.assertEqual(allowed, expected | {(held, 'sell')})
self.command(frozen, 'UNFREEZE_STOCK')
self.assertEqual(intents(), allowed | {(frozen, 'buy')})
self.command(black, 'BLACKLIST_REMOVE')
self.assertEqual(intents(), allowed | {(frozen, 'buy'), (black, 'buy')})
def test_live_partial_buy_is_cancelled_without_replacing_its_remainder(self):
from app.services import rotation_service, rotation_execution as execution, executor, execution_orders
parent = self.parent('600000.SH')
self.command(parent['ts_code'], 'FREEZE_STOCK')
now = dt.datetime(2026, 11, 3, 9, 40)
with patch.object(executor, 'cancel_instruction', return_value={'ok': True}) as cancel, \
patch.object(execution_orders, 'request_replace') as reprice, \
patch.object(execution, 'send_intent') as send:
results, waits = execution.refresh_orders([parent], {parent['ts_code']: {'price': 10.}}, now,
'version', {parent['ts_code']}, rotation_service.micro_buy_restrictions())
self.assertTrue(waits)
self.assertEqual(results, [])
self.assertEqual(cancel.call_args.args, (parent['instruction_id'],))
self.assertIn('冻结', cancel.call_args.kwargs['reason'])
reprice.assert_not_called()
send.assert_not_called()
def test_user_command_cancels_only_live_micro_buys_in_that_stock(self):
from app.services import rotation_service, executor
from app.repo import pms_repo
from app.core import strategy_book as books
parent = self.parent('600000.SH')
def buys(**filters):
self.assertEqual(books.CURRENT.get(), books.MICRO)
self.assertEqual((filters['side'], filters['ts_code']), ('buy', parent['ts_code']))
self.assertIn('DISPATCHED', filters['statuses'])
return [parent]
def get_command(command_id):
self.assertEqual(books.CURRENT.get(), books.ORIGINAL)
return {'ts_code': parent['ts_code'], 'status': 'EFFECTIVE'}
with patch.object(pms_repo, 'get_command', side_effect=get_command), \
patch.object(pms_repo, 'list_instructions', side_effect=buys), \
patch.object(executor, 'cancel_instruction', return_value={'ok': True}) as cancel:
rotation_service.on_user_command('BLACKLIST_ADD', 'cmd', 'user')
cancel.assert_called_once_with(parent['instruction_id'], reason='用户单股禁买命令 cmd', arbiter='user')
def test_next_poll_retries_failed_cancel_of_legacy_parent_only_on_buy_side(self):
from app.services import rotation_service, rotation_execution as execution, executor
from app.repo import pms_repo
code = '600000.SH'
old = self.parent(code)
old['progress']['rule_version'] = m.RULE
same_stock_sell = self.parent(code, side='sell')
other_buy = self.parent('600001.SH')
self.command(code, 'FREEZE_STOCK')
def active(**filters):
return [old] if filters.get('side') == 'buy' else [old, same_stock_sell, other_buy]
with patch.object(pms_repo, 'get_command', return_value={'ts_code': code, 'status': 'EFFECTIVE'}), \
patch.object(pms_repo, 'list_instructions', side_effect=active), \
patch.object(executor, 'cancel_instruction', side_effect=[{'ok': False}, {'ok': True}]) as cancel:
with self.assertRaises(RuntimeError):
rotation_service.on_user_command('FREEZE_STOCK', 'cmd', 'user')
execution.cancel_expired(dt.datetime(2026, 11, 3, 9, 35))
self.assertEqual([call.args[0] for call in cancel.call_args_list],
[old['instruction_id'], old['instruction_id']])
self.assertEqual([call.kwargs['arbiter'] for call in cancel.call_args_list], ['user', 'system'])
def test_queued_then_frozen_then_released_at_final_send(self):
from app.services import execution_orders as eo, execution_conflicts as conflicts, rotation_service
from app.services import param_store, risk_exit
from app.repo import pms_repo, qmt_repo
from config.settings import settings
parent = self.parent('600000.SH')
order = {'instruction_id': 'child', 'parent_id': parent['instruction_id'],
'ts_code': parent['ts_code'], 'side': 'buy', 'status': 'QUEUED'}
self.enterContext(patch.object(settings, 'PMS_TABLE_PREFIX', ''))
self.enterContext(patch.object(pms_repo, 'get_param', side_effect=lambda key, **kwargs:
{'PMS_ROTATION_MODE': 'auto', 'PMS_ROTATION_CONTROL': 'run'}.get(key)))
self.enterContext(patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True))
self.enterContext(patch.object(eo, 'account_guard', side_effect=nullcontext))
self.enterContext(patch.object(eo, 'correction_blocker', return_value=None))
self.enterContext(patch.object(risk_exit, 'buy_blocker', return_value=None))
self.enterContext(patch.object(param_store, 'get_bool', return_value=False))
self.enterContext(patch.object(param_store, 'get', side_effect=lambda key, default=None: default))
self.enterContext(patch.object(rotation_service, 'configuration', return_value={'mode': 'auto', 'control': 'run'}))
self.enterContext(patch.object(rotation_service.store, 'get', return_value=({'rotation': {'phase': 'micro'}}, 1)))
self.enterContext(patch.object(pms_repo, 'get_instruction', return_value=parent))
self.enterContext(patch.object(pms_repo, 'instruction_buy_stop', return_value=False))
self.enterContext(patch.object(pms_repo, 'list_instructions', return_value=[]))
self.enterContext(patch.object(qmt_repo, 'get_order', return_value=order))
mark = self.enterContext(patch.object(qmt_repo, 'mark_send_attempt', return_value=True))
self.assertFalse(conflicts.queued_buy_blocker(order))
for stop, resume in (('FREEZE_STOCK', 'UNFREEZE_STOCK'), ('BLACKLIST_ADD', 'BLACKLIST_REMOVE')):
self.command(order['ts_code'], stop)
self.assertTrue(conflicts.queued_buy_blocker(order))
self.assertFalse(eo.prepare_send('child')['marked'])
mark.assert_not_called()
self.command(order['ts_code'], resume)
self.assertFalse(conflicts.queued_buy_blocker(order))
self.assertTrue(eo.prepare_send('child')['marked'])
mark.assert_called_once_with('child')
mark.reset_mock()
def test_new_global_halt_blocks_even_exit_sell_but_preserves_order_cancellation(self):
from app.repo import pms_repo, qmt_repo
from app.services import dispatcher, execution_orders as eo, param_store, rotation_service
from config.settings import settings
parent = self.parent('600000.SH', side='sell')
order = {'instruction_id': 'child', 'parent_id': parent['instruction_id'],
'ts_code': parent['ts_code'], 'side': 'sell', 'status': 'QUEUED'}
authoritative = {'PMS_ROTATION_MODE': 'auto', 'PMS_ROTATION_CONTROL': 'exit_disable'}
def current_param(key, *, for_update=False):
self.assertTrue(for_update)
return authoritative.get(key)
self.enterContext(patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True))
self.enterContext(patch.object(settings, 'PMS_TABLE_PREFIX', ''))
self.enterContext(patch.object(param_store, 'get_bool', return_value=False))
self.enterContext(patch.object(pms_repo, 'get_param', side_effect=current_param))
self.enterContext(patch.object(eo, 'account_guard', side_effect=nullcontext))
self.enterContext(patch.object(eo, 'correction_blocker', return_value=None))
self.enterContext(patch.object(pms_repo, 'get_instruction', return_value=parent))
self.enterContext(patch.object(qmt_repo, 'get_order', return_value=order))
self.enterContext(patch.object(rotation_service, 'configuration',
return_value={'mode': 'auto', 'control': 'exit_disable'}))
mark = self.enterContext(patch.object(qmt_repo, 'mark_send_attempt', return_value=True))
self.assertTrue(eo.prepare_send('child')['marked'])
mark.reset_mock()
authoritative['PMS_GLOBAL_EXEC_HALT'] = 'true'
result = eo.prepare_send('child')
self.assertFalse(result['marked'])
self.assertIn('暂停', result['blocked'])
mark.assert_not_called()
with patch.object(dispatcher, 'mode', return_value='ws'), \
patch.object(dispatcher, 'channel_status', return_value={'online': True}), \
patch.object(qmt_repo, 'request_cancel', return_value=1) as request:
cancelled = dispatcher.cancel(instruction_id=parent['instruction_id'])
self.assertTrue(cancelled['ok'])
self.assertTrue(cancelled['cancel_pending'])
self.assertEqual(request.call_args.kwargs['parent_id'], parent['instruction_id'])
class StockRestrictionIssueTests(unittest.TestCase):
def setUp(self):
from sqlalchemy import create_engine, event, text
from app.db import session
from app.repo import pms_repo
from app.services import param_store
from config.settings import settings
self.engine = create_engine('sqlite:///:memory:')
self.addCleanup(self.engine.dispose)
self.enterContext(patch.object(session, 'get_engine', return_value=self.engine))
self.enterContext(patch.object(session, '_check_cooldown'))
self.enterContext(patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True))
self.enterContext(patch.object(settings, 'PMS_TABLE_PREFIX', ''))
self.enterContext(patch.object(param_store, 'get_bool', return_value=False))
self.enterContext(patch.object(pms_repo, 'list_instructions', return_value=[]))
@event.listens_for(self.engine, 'begin')
def transaction_started(conn):
conn.info['account_locked'] = False
@event.listens_for(self.engine, 'before_cursor_execute', retval=True)
def sqlite_dialect(conn, cursor, statement, params, context, many):
# SQLite内存事务用写操作取得锁。保留生产的加锁次序和全部业务SQL。
if "doc_id='account-execution' FOR UPDATE" in statement:
conn.info['account_locked'] = True
statement = ("UPDATE pms_rotation_document SET revision=revision "
"WHERE doc_id='account-execution' RETURNING doc_id")
else:
statement = statement.replace(' FOR UPDATE', '')
statement = statement.replace('ON DUPLICATE KEY UPDATE doc_id=VALUES(doc_id)',
'ON CONFLICT(doc_id) DO NOTHING')
statement = statement.replace('ON DUPLICATE KEY UPDATE updated_at =',
'ON CONFLICT(book_id,ts_code) DO UPDATE SET updated_at =')
if statement.startswith('UPDATE pms_command SET status') and 'EFFECTIVE' in params:
self.assertTrue(conn.info['account_locked'])
return statement, params
with self.engine.begin() as conn:
conn.execute(text('CREATE TABLE pms_command (id INTEGER PRIMARY KEY, book_id TEXT, '
'command_id TEXT UNIQUE, cmd_class TEXT, cmd_type TEXT, ts_code TEXT, params_json TEXT, '
'status TEXT, progress_json TEXT, issued_by TEXT, issued_at TEXT, done_at TEXT, note TEXT, archived_at TEXT)'))
conn.execute(text('CREATE TABLE pms_position (book_id TEXT, ts_code TEXT, status TEXT, '
'updated_at TEXT, frozen_reason TEXT, PRIMARY KEY(book_id,ts_code))'))
conn.execute(text('CREATE TABLE pms_rotation_document (doc_id TEXT PRIMARY KEY, kind TEXT, '
'payload_json TEXT, revision INTEGER, updated_at TEXT)'))
def issue(self, kind):
from app.services import command_service
return command_service.issue(kind, {'ts_code': '600000.SH'})
def test_failed_new_effective_status_restores_prior_freeze_and_position(self):
from sqlalchemy import text
from app.repo import pms_repo
from app.services import command_service
first = self.issue('FREEZE_STOCK')
self.assertTrue(first['ok'], first)
with self.engine.begin() as conn:
conn.execute(text("CREATE TRIGGER refuse_effective BEFORE UPDATE OF status ON pms_command "
"WHEN NEW.status='EFFECTIVE' BEGIN SELECT RAISE(IGNORE); END"))
for kind in ('FREEZE_STOCK', 'UNFREEZE_STOCK'):
with self.subTest(kind=kind):
result = self.issue(kind)
self.assertFalse(result['ok'], result)
self.assertEqual(pms_repo.get_command(result['command_id'])['status'], 'CANCELLED')
self.assertEqual(pms_repo.get_command(first['command_id'])['status'], 'EFFECTIVE')
self.assertTrue(command_service.effective_stock_params()['600000.SH']['frozen'])
self.assertEqual(pms_repo.get_position('600000.SH')['frozen_reason'], 'COMMAND_HALT')
def test_releasing_one_restriction_keeps_the_other_effective(self):
from app.services import command_service, rotation_service
for kind, frozen, black in [('FREEZE_STOCK', True, False), ('BLACKLIST_ADD', True, True),
('BLACKLIST_REMOVE', True, False), ('BLACKLIST_ADD', True, True),
('UNFREEZE_STOCK', False, True), ('BLACKLIST_REMOVE', False, False)]:
with self.subTest(kind=kind):
result = self.issue(kind)
self.assertTrue(result['ok'], result)
flags = command_service.effective_stock_params()['600000.SH']
self.assertEqual((flags.get('frozen', False), flags.get('black', False)), (frozen, black))
self.assertEqual('600000.SH' in rotation_service.micro_buy_restrictions(), frozen or black)
class SnapshotTests(unittest.TestCase):
def test_v2_remains_compatible_without_candidates(self):
snap = snapshot(rule=m.RULE)
self.assertNotIn('candidates', snap)
self.assertEqual(m.snapshot_check(snap, '2026-11-03'), [])
def test_v3_contract_and_frozen_hash(self):
snap = snapshot()
self.assertEqual(m.snapshot_check(snap, '2026-11-03', expected_rule=m.EXECUTION_RULE), [])
snap['candidates'][70]['close'] = 20
self.assertIn('快照摘要不一致', m.snapshot_check(snap, '2026-11-03'))
def test_candidate_order_and_mainland_required(self):
for change in ('rank', 'code'):
snap = snapshot()
snap['candidates'][70][change] = 1 if change == 'rank' else '920001.BJ'
self.assertIn('冻结候选池数量、资格或顺序不完整', m.snapshot_check(snap, '2026-11-03'))
def test_rule_mismatch_cannot_be_silent(self):
self.assertIn('策略规则版本不一致', m.snapshot_check(snapshot(), '2026-11-03', expected_rule=m.RULE))
old = state(snapshot(rule=m.RULE))
with self.assertRaises(ValueError):
m.transition(old, snapshot(), micro_qty=100, original_qty=0, budget=100000)
def test_short_pool_is_explicit_and_valid(self):
snap = snapshot(size=51)
self.assertEqual(m.snapshot_check(snap, '2026-11-03'), [])
class TargetTests(unittest.TestCase):
def test_halted_zero_fill_uses_next_rank(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'})
self.assertNotIn('600000.SH', s['target'])
self.assertIn('600050.SH', s['target'])
self.assertEqual(len(s['target']), 50)
self.assertEqual(s['substitutions'][0]['from'], '600000.SH')
def test_partial_fill_keeps_seat(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, micro=[{'ts_code': '600000.SH', 'total_qty': 100}],
unavailable={'600000.SH': '停牌'})
self.assertIn('600000.SH', s['target'])
self.assertNotIn('600050.SH', s['target'])
def test_cancel_pending_keeps_seat(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, pending=[{'ts_code': '600000.SH'}], unavailable={'600000.SH': '停牌'})
self.assertIn('600000.SH', s['target'])
m.resolve_targets(s, snap, pending=[], unavailable={'600000.SH': '停牌'})
self.assertNotIn('600000.SH', s['target'])
def test_recovery_and_restart_do_not_switch_back_same_day(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'})
s = json.loads(json.dumps(s))
s = m.transition(s, snap, micro_qty=0, original_qty=0, budget=100000)
m.resolve_targets(s, snap, unavailable={})
self.assertNotIn('600000.SH', s['target'])
self.assertIn('600050.SH', s['target'])
def test_next_day_returns_to_new_frozen_rank(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'})
tomorrow = snapshot(day='2026-11-04')
s = m.transition(s, tomorrow, micro_qty=100, original_qty=0, budget=100000)
m.resolve_targets(s, tomorrow, unavailable={})
self.assertIn('600000.SH', s['target'])
self.assertNotIn('600050.SH', s['target'])
def test_price_lag_does_not_change_target(self):
snap = snapshot(); s = state(snap)
m.resolve_targets(s, snap, unavailable={})
self.assertEqual(s['target'], [r['code'] for r in snap['members']])
def test_pool_exhaustion_does_not_remove_good_members(self):
snap = snapshot(size=51); s = state(snap)
waits = m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌', '600001.SH': '停牌'})
self.assertEqual(len(s['target']), 49)
self.assertEqual(s['target_shortfall'], 1)
self.assertTrue(waits)
def test_incomplete_daily_member_is_still_topped_up(self):
snap = snapshot(); s = state(snap); s['phase'] = 'micro'
held = [{'ts_code': r['code'], 'total_qty': 100} for r in snap['members'][1:]]
kwargs = dict(original=[], quotes={'600000.SH': {'price': 10}}, cash=5000,
account_mv=0, cap_amount=100000)
orders, _ = m.orders(s, snap, micro=held, **kwargs)
wanted = orders[0]['qty']
held.append({'ts_code': '600000.SH', 'total_qty': 100})
s = json.loads(json.dumps(s))
orders, _ = m.orders(s, snap, micro=held, **kwargs)
self.assertEqual(orders[0]['qty'], wanted-100)
self.assertEqual(s['buy_targets']['600000.SH']['qty'], wanted)
def test_daily_target_does_not_expand_after_price_fall(self):
snap = snapshot(); s = state(snap); s['phase'] = 'micro'
s['buy_targets'] = {'600000.SH': {'qty': 300, 'snapshot_version': 'old'}}
held = [{'ts_code': r['code'], 'total_qty': 100} for r in snap['members']]
orders, _ = m.orders(s, snap, original=[], micro=held,
quotes={'600000.SH': {'price': 1}}, cash=10000, account_mv=0, cap_amount=100000)
self.assertEqual(orders[0]['qty'], 200)
def test_old_positions_do_not_create_cash(self):
snap = snapshot(); s = state(snap)
orders, _ = m.orders(s, snap, original=[{'ts_code': '000001.SZ', 'total_qty': 100}], micro=[],
quotes={'000001.SZ': {'price': 10}, **{r['code']: {'price': 10} for r in snap['members']}},
cash=0, account_mv=1000, cap_amount=100000)
self.assertTrue(orders)
self.assertTrue(all(r['side'] == 'sell' for r in orders))
def test_high_exit_overrides_unfinished_entry(self):
snap = snapshot(); s = state(snap); snap['signal']['high'] = True
s = m.transition(s, snap, micro_qty=100, original_qty=0, budget=100000)
self.assertEqual(s['phase'], 'returning_original')
before = copy.deepcopy(s)
m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'})
self.assertEqual(s, before)
class ServiceBoundaries(unittest.TestCase):
def prepare(self, snap, funds, scale, *, prepare_only=True, fail_limits=False,
missing_position=False, refresh=None, configure=None, now=None):
from app.services import rotation_service as r, rotation_execution as execution, execution_orders, command_service
stored = {'rotation': m.initial_state()}
config = {'mode': 'auto', 'control': 'run', 'rule_version': snap['rule_version'],
'candidate_pool_size': 100, 'boards': {'MAIN','CHINEXT','STAR'}, 'costs': {}}
@contextmanager
def locked(*args):
yield stored
with ExitStack() as stack:
for obj, name, value in (
(r, 'configuration', config), (r, 'documents_ready', True), (r, 'activation_errors', []),
(r.param_store, 'execution_halted', False),
(r, 'pull', snap), (r, 'reconcile_books', {'ok': True, 'diffs': []}),
(r, 'positions', [{'ts_code':'600000.SH','total_qty':100}] if missing_position else []),
(r, '_quote', {} if missing_position else {'price': 10}),
(r, '_limits', {}), (r.market, 'execution_quote', {}),
(execution_orders, 'quote_order', {'action':'WAIT','reason':'没有当日限制价'}),
(r.td, 'calendar_degraded', False), (r.td, 'is_trade_day', True),
(r.portfolio, 'cash_view', {'source': 'ws', 'cash_avail': funds}),
(r.store, 'get', (stored, 0)), (r.store, 'put_once', None),
(r, 'cancel_control_orders', None), (execution, 'cancel_expired', None),
(execution, 'suspended_rejections', {}),
(r.pms_repo, 'active_strategies', []), (command_service, 'effective_stock_params', {}),
(execution, 'pending_instructions', [])):
stack.enter_context(patch.object(obj, name, return_value=value))
stack.enter_context(patch.object(execution, 'refresh_orders',
side_effect=refresh or (lambda *a, **kw: ([], []))))
if fail_limits:
stack.enter_context(patch.object(r, '_limits', side_effect=RuntimeError('in-memory query failure')))
stack.enter_context(patch.object(r.store, 'locked', side_effect=locked))
stage = stack.enter_context(patch.object(r.store, 'stage_locked'))
stack.enter_context(patch.object(r.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True))
stack.enter_context(patch.object(r.param_store, 'get_bool', return_value=False))
stack.enter_context(patch.object(r.param_store, 'get_float', side_effect=lambda k,d=0: {
'PMS_TOTAL_SCALE': scale, 'PMS_PORTFOLIO_CAP': 1, 'PMS_CASH_RESERVE': 0}.get(k,d)))
if configure:
configure(stack, stored, config)
result = r._tick(now or dt.datetime(2026, 11, 3, 9, 31, tzinfo=r.TZ), prepare_only=prepare_only)
return stored, result, stage.call_count
def test_all_first_choices_frozen_keeps_original_exposure(self):
from app.services import command_service
snap = snapshot()
def configure(stack, stored, config):
flags = {row['code']:{'frozen':True} for row in snap['members']}
stack.enter_context(patch.object(command_service,'effective_stock_params',return_value=flags))
saved, result, writes = self.prepare(snap,100000,100000,configure=configure)
self.assertEqual(saved['rotation']['phase'],'original')
self.assertIn('禁买',result['blocked'][0])
self.assertEqual(writes,0)
def test_afternoon_tick_sells_micro_without_waiting_for_original_t0(self):
from app.db import session as db
from app.services import rotation_service as r, rotation_execution as execution, execution_orders, executor
snap = snapshot()
code = snap['members'][0]['code']
sold = []
def configure(stack, stored, config):
stored['rotation'] = state(snap)
config['control'] = 'exit_disable'
holding = {'ts_code':code,'total_qty':300,'avail_qty':200}
stack.enter_context(patch.object(r,'positions',side_effect=lambda b: [holding] if b=='micro30' else []))
old = {'instruction_id':'old','book_id':'micro30','ts_code':'600001.SH','side':'buy'}
stack.enter_context(patch.object(execution,'pending_instructions',return_value=[old]))
stack.enter_context(patch.object(executor,'cancel_instruction',return_value={'ok':False}))
stack.enter_context(patch.object(r,'_micro_unsettled',return_value=True))
stack.enter_context(patch.object(r.pms_repo,'active_strategies',return_value=[{'type':'T0','state':{'open_leg':'sell'}}]))
stack.enter_context(patch.object(r,'_limits',return_value={code:{'up_limit':11,'down_limit':9}}))
stack.enter_context(patch.object(execution_orders,'quote_order',return_value={'action':'FIRE','limit_price':10}))
stack.enter_context(patch.object(db,'savepoint',side_effect=nullcontext))
def send(intent, price, now, version):
sold.append(intent)
return {'ok':True}
stack.enter_context(patch.object(execution,'send_intent',side_effect=send))
now = dt.datetime(2026,11,3,14,12,tzinfo=r.TZ)
saved, result, _ = self.prepare(snap,100000,100000,prepare_only=False,configure=configure,now=now)
self.assertEqual(saved['rotation']['phase'],'returning_original')
self.assertTrue(any('撤销待重试' in message for message in saved['blocked']))
self.assertEqual(len(sold),1)
self.assertEqual((sold[0]['side'],sold[0]['book_id'],sold[0]['qty'],sold[0]['manual_exit_cutoff']),
('sell','micro30',200,'14:57'))
def test_static_failure_prevents_committing_entry(self):
stored, result, writes = self.prepare(snapshot(rule=m.RULE), 500, 500)
self.assertEqual(stored['rotation']['phase'], 'original')
self.assertIn('blocked', result)
self.assertEqual(writes, 0)
def test_v3_zero_budget_does_not_clear_old_strategy(self):
stored, result, writes = self.prepare(snapshot(), 0, 100000)
self.assertEqual(stored['rotation']['phase'], 'original')
self.assertEqual(writes, 0)
def test_no_today_limits_blocks_funding_sales(self):
from app.services import rotation_execution as execution
with patch.object(execution,'send_intent') as send:
stored, result, writes = self.prepare(snapshot(),100000,100000,prepare_only=False)
self.assertIn('blocked',result)
self.assertTrue(any('不卖出原策略' in reason for reason in result['blocked']))
send.assert_not_called()
def test_v3_single_expensive_member_does_not_block_other_members(self):
snap = snapshot(); snap['members'][0]['close'] = 10000
body = {k:v for k,v in snap.items() if k not in ('snapshot_version','frozen')}
snap['snapshot_version'] = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False,
separators=(',', ':')).encode()).hexdigest()
stored, result, writes = self.prepare(snap, 100000, 100000)
self.assertEqual(stored['rotation']['phase'], 'entering_micro')
self.assertNotIn('600000.SH', stored['rotation']['target'])
self.assertIn('600050.SH', stored['rotation']['target'])
self.assertEqual(writes, 1)
def test_limit_query_failure_still_refreshes_existing_orders(self):
calls=[]
def refresh(*args):
calls.append(args)
return [], []
stored,result,_=self.prepare(snapshot(),100000,100000,prepare_only=False,
fail_limits=True,refresh=refresh)
self.assertEqual(len(calls),1)
self.assertTrue(any('限制价查询失败' in reason for reason in result['blocked']))
self.assertEqual(stored['rotation'].get('skipped_candidates'),{})
def test_missing_holding_quote_cancels_during_prepare_phase(self):
calls=[]
def refresh(*args):
calls.append(args)
return [], []
_,result,writes=self.prepare(snapshot(),100000,100000,missing_position=True,refresh=refresh)
self.assertIn('blocked',result)
self.assertEqual(writes,0)
self.assertEqual(len(calls),1)
self.assertEqual(calls[0][1],{})
def test_unknown_quote_is_not_a_suspension(self):
from app.services.rotation_service import _unavailable_candidates
out = _unavailable_candidates(snapshot(), {'600000.SH': {}}, 100000,
{'MAIN', 'CHINEXT', 'STAR'}, {})
self.assertEqual(out, {})
def test_explicit_halt_affects_only_one_member(self):
from app.services.rotation_service import _unavailable_candidates
out = _unavailable_candidates(snapshot(), {'600000.SH': {'halted': True}}, 100000,
{'MAIN', 'CHINEXT', 'STAR'}, {})
self.assertEqual(set(out), {'600000.SH'})
def test_live_child_survives_terminal_parent_in_pending(self):
from app.services import rotation_execution as r
parent = {'instruction_id': 'old', 'book_id': 'micro30', 'ts_code': '600000.SH', 'status': 'CANCELLED'}
with patch.object(r.pms_repo, 'list_instructions', return_value=[]), \
patch.object(r.pms_repo, 'get_instruction', return_value=parent), \
patch.object(r.qmt_repo, 'list_orders', return_value=[{'parent_id': 'old'}]):
self.assertEqual(r.pending_instructions(), [parent])
def test_unknown_live_child_owner_blocks(self):
from app.services import rotation_execution as r
with patch.object(r.pms_repo, 'list_instructions', return_value=[]), \
patch.object(r.pms_repo, 'get_instruction', return_value=None), \
patch.object(r.qmt_repo, 'list_orders', return_value=[{'parent_id': 'unknown'}]):
with self.assertRaises(ValueError):
r.pending_instructions()
def send_existing(self, settled, cancel=False, *, now=None, cutoff=None):
from app.services import rotation_execution as r, execution_orders as e, dispatcher
side = 'sell' if cutoff else 'buy'
parent = {'instruction_id':'p', 'book_id':'micro30', 'ts_code':'600000.SH', 'side':side,
'qty':300, 'exec_qty':100, 'status':'DISPATCHED',
'progress':{'children':[{'ref':'p_D01'}], **({'cancel_requested':True} if cancel else {})}}
if cutoff:
parent['progress']['manual_exit_cutoff'] = cutoff
with patch.object(r.db, 'transaction', side_effect=nullcontext), \
patch.object(r.pms_repo, 'get_instruction', return_value=parent), \
patch.object(r.pms_repo, 'update_instruction', return_value=1), \
patch.object(e, 'code_settlement_blocker', return_value=''), \
patch.object(e, 'replacement_state', return_value=settled), \
patch.object(e, 'retry_reason', return_value=''), \
patch.object(e, 'next_child_id', return_value='p_D02'), \
patch.object(dispatcher, 'mode', return_value='ws'), \
patch.object(dispatcher, 'dispatch', return_value={'ok':True}) as send:
result = r.send_intent({'id':'p','book_id':'micro30','ts_code':'600000.SH','side':side,
'qty':300,'reason':'补齐'},10,now or dt.datetime(2026,11,3,9,40),'snapshot')
return result, send.call_args
def test_legacy_exit_can_reopen_after_system_expiry_and_honors_user_cancellation(self):
from app.services import execution_orders as e
day = '2026-11-03'
record = {'instruction_id':'legacy','book_id':'micro30','ts_code':'600000.SH','side':'sell',
'status':'CANCELLED','progress':{'execution_profile':'rotation','deadline':day}}
settled = {'active':[], 'pending_trades':0, 'booked':100, 'confirmed_filled':100, 'missing_orders':[]}
with patch.object(e.pms_repo,'list_instructions',return_value=[record]), \
patch.object(e,'replacement_state',return_value=settled):
def check(authorized_at=None):
return e.code_settlement_blocker(record['ts_code'],manual_exit_day=day,
manual_exit_requested_at=authorized_at)
record['progress']['cancel_requested'] = {'arbiter':'system','at':day+'T10:00:00'}
self.assertFalse(check())
settled['active'] = [{'status':'ACCEPTED'}]
self.assertIn('仍在途',check())
settled['active'] = []
settled['booked'] = 0
self.assertIn('入账',check())
settled['booked'] = 100
record['progress']['cancel_requested'] = {'arbiter':'user','at':day+'T13:55:00'}
self.assertIn('已被撤销',check())
self.assertIn('已被撤销',check(day+'T13:54:59+08:00'))
self.assertFalse(check(day+'T13:55:01+08:00'))
def test_manual_exit_retries_only_remaining_and_honors_its_own_session(self):
for hour, minute, cutoff, deadline in ((11,27,'11:30',(11,30)), (14,0,'14:57',(14,10)),
(14,53,'14:57',(14,57))):
with self.subTest(hour=hour, minute=minute):
now = dt.datetime(2026,11,3,hour,minute)
result, sent = self.send_existing({'ready':True,'remaining':200}, now=now, cutoff=cutoff)
self.assertEqual(sent.kwargs['side'], 'sell')
self.assertEqual(sent.kwargs['qty'], 200)
self.assertEqual(sent.kwargs['valid_until'], now.replace(hour=deadline[0],minute=deadline[1]))
ended, sent = self.send_existing({'ready':True,'remaining':200},
now=dt.datetime(2026,11,3,14,57), cutoff='14:57')
self.assertIsNone(sent)
self.assertIn('结束', ended['state'])
def test_expiry_preserves_manual_afternoon_order_across_ticks(self):
from app.services import rotation_execution as r, executor
base = {'execution_profile':'rotation', 'deadline':'2026-11-03'}
parents = [{'book_id':'micro30', 'instruction_id':key, 'progress':dict(base, **extra)}
for key, extra in [('regular',{}), ('am',{'manual_exit_cutoff':'11:30'}),
('pm',{'manual_exit_cutoff':'14:57'})]]
with patch.object(r.pms_repo, 'list_instructions', return_value=parents), \
patch.object(executor, 'cancel_instruction', return_value={'ok':True}) as cancel:
for hour, minute, expected in [(10,0,['regular']), (14,0,['regular','am']),
(14,57,['regular','am','pm'])]:
cancel.reset_mock()
r.cancel_expired(dt.datetime(2026,11,3,hour,minute))
self.assertEqual([c.args[0] for c in cancel.call_args_list], expected)
def test_v2_manual_exit_retries_but_v2_regular_still_uses_frozen_price(self):
from app.services import rotation_execution as r, execution_orders as e
common = {'book_id':'micro30','ts_code':'600000.SH','side':'sell','qty':300}
progress = {'execution_profile':'rotation','deadline':'2026-11-03','rule_version':m.RULE}
parents = [dict(common,instruction_id='manual',progress=dict(progress,manual_exit_cutoff='14:57')),
dict(common,instruction_id='regular',progress=progress)]
with patch.object(r.qmt_repo,'orders_for_parent',return_value=[]), \
patch.object(e,'quote_order',return_value={'action':'FIRE','limit_price':10}), \
patch.object(e,'replacement_state',return_value={'ready':True,'remaining':100}), \
patch.object(r.db,'savepoint',side_effect=nullcontext), \
patch.object(r,'send_intent',return_value={'ok':True}) as send:
results, waits = r.refresh_orders(parents,{},dt.datetime(2026,11,3,14,0),'snapshot',set(),{})
self.assertEqual(results,[{'ok':True}])
self.assertEqual(waits,[])
self.assertEqual(send.call_args.args[0]['id'],'manual')
self.assertEqual(send.call_args.args[0]['rule_version'],m.RULE)
def test_replacement_waits_until_cancellation_and_booking_finish(self):
result, sent = self.send_existing({'ready':False,'remaining':200})
self.assertTrue(result['pending'])
self.assertIsNone(sent)
def test_replacement_only_submits_unfilled_quantity(self):
result, sent = self.send_existing({'ready':True,'remaining':200})
self.assertEqual(sent.kwargs['qty'],200)
self.assertEqual(sent.kwargs['instruction_id'],'p_D02')
def test_user_cancelled_parent_never_reopens(self):
result, sent = self.send_existing({'ready':True,'remaining':200},cancel=True)
self.assertIsNone(sent)
def test_partial_fill_after_cancel_still_keeps_seat(self):
snap=snapshot(); s=state(snap)
m.resolve_targets(s,snap,pending=[{'ts_code':'600000.SH'}],unavailable={'600000.SH':'停牌'})
m.resolve_targets(s,snap,micro=[{'ts_code':'600000.SH','total_qty':100}],unavailable={'600000.SH':'停牌'})
self.assertIn('600000.SH',s['target'])
self.assertEqual(len(s['target']),50)
def test_missing_quote_cancels_live_child_without_substituting(self):
from app.services import rotation_execution as r, execution_orders as e, executor
parent={'instruction_id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100,
'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':'2026-11-03'}}
with patch.object(r.qmt_repo,'orders_for_parent',return_value=[{'status':'ACCEPTED'}]), \
patch.object(e,'quote_order',return_value={'action':'WAIT','reason':'行情缺失'}), \
patch.object(e,'request_replace',return_value={'pending':True}) as replace, \
patch.object(executor,'cancel_instruction') as cancel, \
patch.object(r.db,'savepoint',side_effect=nullcontext):
result,waits=r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{})
replace.assert_called_once()
cancel.assert_not_called()
self.assertEqual(result,[])
self.assertTrue(waits)
def test_missing_quote_without_live_child_only_waits(self):
from app.services import rotation_execution as r, execution_orders as e
parent={'instruction_id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100,
'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':'2026-11-03'}}
with patch.object(r.qmt_repo,'orders_for_parent',return_value=[]), \
patch.object(e,'quote_order',return_value={'action':'WAIT','reason':'行情缺失'}), \
patch.object(e,'request_replace') as replace:
r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{})
replace.assert_not_called()
class ResumeTests(unittest.TestCase):
def test_return_to_original_preserves_released_cash_and_original_t0(self):
from app.services import rotation_service as r, executor
rows = [
('old-open','original','buy',{}), ('fund','original','sell',{'execution_profile':'rotation'}),
('open','micro30','buy',{}), ('exit','micro30','sell',{}),
('close-t0','original','buy',{'leg':'close'}), ('trader-sell','original','sell',{})]
parents = [dict(instruction_id=i,book_id=b,side=s,progress=p) for i,b,s,p in rows]
parents[-2].update(origin_type='strategy', action='T0_ROUND')
with patch.object(executor,'cancel_instruction',return_value={'ok':True}) as cancel, \
patch.object(r.pms_repo,'active_strategies',return_value=[{'type':'T0','state':{'open_leg':'buy'}}]) as t0:
self.assertFalse(r._stop_leaving_orders('returning_original',parents,[{'t0_qty':100}],[]))
self.assertEqual([c.args[0] for c in cancel.call_args_list],['fund','open'])
t0.assert_not_called()
cancel.reset_mock()
self.assertTrue(r._stop_leaving_orders('entering_micro',parents,[{'t0_qty':100}],[]))
self.assertEqual([c.args[0] for c in cancel.call_args_list],['old-open'])
def test_explicit_resume_requires_settlement_and_does_not_reuse_old_signal(self):
from app.services import rotation_service as r, rotation_execution as execution
snap = snapshot()
saved = {'rotation':state(snap)}
config = {'mode':'auto','control':'run'}
@contextmanager
def locked(*args):
yield saved
def save(_key, value, _actor):
config['control'] = value
return {'ok':True}
with ExitStack() as stub:
for obj, name, kwargs in [
(r,'documents_ready',{'return_value':True}), (r.store,'account_guard',{'side_effect':nullcontext}),
(r.store,'locked',{'side_effect':locked}), (r,'configuration',{'return_value':config}),
(r.param_store,'set_param',{'side_effect':save}), (execution,'pending_instructions',{'return_value':[]})]:
stub.enter_context(patch.object(obj,name,**kwargs))
stub.enter_context(patch.object(r.settings,'INFRA_STRATEGY_BOOK_SCHEMA',True))
held = stub.enter_context(patch.object(r,'positions',return_value=[]))
unsettled = stub.enter_context(patch.object(r,'_micro_unsettled',return_value=False))
recon = stub.enter_context(patch.object(r,'reconcile_books',return_value={'ok':True}))
active = stub.enter_context(patch.object(r.pms_repo,'list_commands',return_value=[]))
command = stub.enter_context(patch.object(r.pms_repo,'get_command',return_value={'status':'EXECUTING'}))
r._set_control('exit_disable','user',exit_command='clear-all')
self.assertEqual(saved['rotation']['phase'],'returning_original')
with self.assertRaisesRegex(ValueError,'退出仍在办理'):
r._set_control('run','user')
saved['rotation'] = m.transition(saved['rotation'],snap,micro_qty=0,original_qty=0,budget=100000,control='exit_disable')
for status in ('EXECUTING','UNKNOWN'):
command.return_value = {'status':status}
with self.assertRaisesRegex(ValueError,'清仓命令'):
r._set_control('run','user')
command.return_value = {'status':'DONE'}
active.return_value = [{'command_id':'another-clear-all'}]
with self.assertRaisesRegex(ValueError,'清仓命令'):
r._set_control('run','user')
active.return_value = []
for query, active in [(held,[{'total_qty':100}]), (unsettled,True), (recon,{'ok':False})]:
old = query.return_value
query.return_value = active
with self.assertRaisesRegex(ValueError,'尚未结清'):
r._set_control('run','user')
self.assertTrue(saved['rotation']['disabled'])
self.assertEqual(config['control'],'exit_disable')
query.return_value = old
r._set_control('run','user')
self.assertFalse(saved['rotation']['disabled'])
self.assertEqual(config['control'],'run')
same_day = m.transition(saved['rotation'],snap,micro_qty=0,original_qty=0,budget=100000)
self.assertEqual(same_day['phase'],'original')
next_day = m.transition(same_day,snapshot(day='2026-11-04'),micro_qty=0,original_qty=0,budget=100000)
self.assertEqual(next_day['phase'],'entering_micro')
class ReservationTests(unittest.TestCase):
def setUp(self):
from app.repo import execution_repo
stub = patch.object(execution_repo, 'pending_corrections', return_value=0)
stub.start()
self.addCleanup(stub.stop)
def release(self, *, filled=0, fresh=True, booked=True):
from app.services import rotation_execution as r, execution_orders as e
now=dt.datetime(2026,11,3,9,40)
account={'available':10010.,'orders':{'a':1005.,'b':9005.}}
orders={'a':{'instruction_id':'a','parent_id':'pa','status':'CANCELLED',
'qty':1000,'cum_qty':filled,'limit_price':1.,'final_at':now},
'b':{'instruction_id':'b','parent_id':'pb','status':'ACCEPTED',
'qty':9000,'cum_qty':0,'limit_price':1.,'final_at':None}}
funds={'received_at':now+dt.timedelta(seconds=1 if fresh else -1)}
state={'pending_trades':0 if booked else 1,'booked':filled if booked else 0,
'confirmed_filled':filled,'missing_orders':[]}
with patch.object(r.qmt_repo,'get_order',side_effect=orders.get), \
patch.object(e,'replacement_state',return_value=state):
r.release_settled_reservations(account,funds)
r.release_settled_reservations(account,funds)
return account
def test_cancelled_one_releases_budget_while_others_live(self):
account=self.release()
self.assertEqual(account['orders'],{'a':0.,'b':9005.})
self.assertEqual(account['available']-sum(account['orders'].values()),1005.)
def test_partial_cancel_keeps_filled_principal_and_original_fee(self):
account=self.release(filled=100)
self.assertEqual(account['orders'],{'a':105.,'b':9005.})
self.assertEqual(account['original_reservations']['a'],1005.)
def test_old_funds_snapshot_cannot_release(self):
self.assertEqual(self.release(fresh=False)['orders']['a'],1005.)
def test_unbooked_trade_cannot_release(self):
self.assertEqual(self.release(filled=100,booked=False)['orders']['a'],1005.)
class SuspensionEvidenceTests(unittest.TestCase):
def evidence(self, code='SUSPENDED', filled=0, ready=True, deadline='2026-11-03'):
from app.services import rotation_execution as r, execution_orders as e
order={'instruction_id':'p_D01','parent_id':'p','ts_code':'600000.SH','status':'REJECTED',
'reject_code':code,'cum_qty':filled}
parent={'instruction_id':'p','book_id':'micro30','exec_qty':filled,
'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':deadline}}
with patch.object(r.db,'fetch_all',return_value=[order]), \
patch.object(r.pms_repo,'get_instruction',return_value=parent), \
patch.object(e,'replacement_state',return_value={'ready':ready,'confirmed_filled':filled}):
return r.suspended_rejections(dt.datetime(2026,11,3,9,40))
def test_exact_suspended_zero_fill_can_substitute(self):
result=self.evidence()
self.assertIn('600000.SH',result)
self.assertIn('p_D01',result['600000.SH'])
def test_generic_errors_and_price_errors_never_substitute(self):
for code in ('BROKER_ERROR','BAD_PARAM','UNKNOWN_CODE','LIMIT_UP','INTERNAL','INSUFFICIENT_CASH'):
self.assertEqual(self.evidence(code=code),{})
def test_partial_or_pending_never_substitutes(self):
self.assertEqual(self.evidence(filled=100),{})
self.assertEqual(self.evidence(ready=False),{})
def test_previous_day_rejection_does_not_carry_forward(self):
self.assertEqual(self.evidence(deadline='2026-11-02'),{})
if __name__ == '__main__':
unittest.main()