476 lines
28 KiB
Python
476 lines
28 KiB
Python
"""策略成交更正版本:真实 SQLite CAS、旧运行快照与提议交错,禁止联网。"""
|
||
import unit_test_guard # noqa: F401
|
||
import copy
|
||
import datetime as dt
|
||
import json
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
import unittest
|
||
from pathlib import Path
|
||
from unittest.mock import patch
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
from sqlalchemy import create_engine, event, text
|
||
from app.core import strategy_book as books
|
||
from app.db import session as db
|
||
from app.repo import pms_repo, qmt_repo
|
||
from app.services import strategy_runner as runner, rotation_service, grid_inventory
|
||
from app.services import execution_orders, strategy_advisor, strategy_service
|
||
from config.settings import settings
|
||
|
||
CODE = '600001.SH'
|
||
DECISION = {'side': 'buy', 'action': 'ADD', 'qty': 100, 'leg': 'grid_buy:1',
|
||
'reason': '测试档位', 'grid_buy_idx': 1, 'grid_buy_price': 10.0}
|
||
|
||
|
||
class StrategyCorrectionTests(unittest.TestCase):
|
||
def setUp(self):
|
||
self.now = dt.datetime(2026, 11, 5, 10)
|
||
owner = self
|
||
class Clock(dt.datetime):
|
||
@classmethod
|
||
def now(cls, tz=None):
|
||
return owner.now
|
||
self.use(runner, 'datetime', Clock)
|
||
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
|
||
self.engine = create_engine('sqlite:///'+self.tmp.name+'/strategy.sqlite')
|
||
self.addCleanup(self.engine.dispose)
|
||
self.statements = []
|
||
@event.listens_for(self.engine, 'before_cursor_execute', retval=True)
|
||
def dialect(conn, cursor, sql, params, context, many):
|
||
db.assert_single_table(sql)
|
||
self.statements.append(sql)
|
||
sql = sql.replace(' FOR UPDATE', '')
|
||
if 'ON DUPLICATE KEY UPDATE' in sql:
|
||
self.assertIn('pms_rotation_document', sql)
|
||
sql = sql.split('ON DUPLICATE KEY UPDATE')[0]+'ON CONFLICT DO NOTHING'
|
||
return sql, params
|
||
for obj, name, value in [
|
||
(db, 'get_engine', lambda *args: self.engine),
|
||
(db, '_check_cooldown', lambda *args: None),
|
||
(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True),
|
||
(rotation_service, 'original_buy_blocker', lambda: ''),
|
||
(runner, '_today', lambda: 20261105),
|
||
(runner, '_buypause_codes', lambda: set()),
|
||
(runner, '_macro_gate_active', lambda: False),
|
||
(runner.param_store, 'get_bool', lambda key, default=False: key == 'PMS_STRATEGY_ENABLED'),
|
||
(runner.param_store, 'get_float', lambda key, default=0: default),
|
||
(runner.param_store, 'get_int', lambda key, default=0: default),
|
||
(runner.param_store, 'get', lambda key, default=None: default),
|
||
(runner.portfolio, 'positions_view', lambda: {'positions': [{'ts_code': CODE, 'total_qty': 100, 'avail_qty': 100}], 'totals': {'scale': 10000}, 'params': {'scale': 10000, 'stock_cap': .2}}),
|
||
(runner.market, 'day_snapshot', lambda code: {'price': 10, 'bar_time': self.now.isoformat()}),
|
||
(pms_repo, 'get_position', lambda code: {'total_qty':100, 'add_qty':100, 'avail_qty':100}),
|
||
(grid_inventory, 'snapshot', lambda st, pos: {'invested':1000, 'filled_levels':{'0':{'price':10,'qty':100,'sell_target':10.4}}}),
|
||
# 此套只测事务与更正交错;真实批次和报价校验由 test_grid_execution 覆盖。
|
||
(runner, '_validate_grid_decision', lambda st, dec: None),
|
||
]:
|
||
self.use(obj, name, value)
|
||
schema = {
|
||
'pms_strategy': 'id INTEGER PRIMARY KEY,book_id TEXT,strategy_id TEXT UNIQUE,ts_code TEXT,type TEXT,status TEXT,autonomy TEXT,state_json TEXT,params_json TEXT,note TEXT,archived_at TEXT,created_at TEXT,updated_at TEXT',
|
||
'pms_instruction': 'id INTEGER PRIMARY KEY,book_id TEXT,instruction_id TEXT UNIQUE,origin_type TEXT,origin_id TEXT,ts_code TEXT,action TEXT,side TEXT,qty INTEGER,limit_price REAL,window_tdays INTEGER,status TEXT,exec_qty INTEGER,exec_avg_price REAL,progress_json TEXT,archived_at TEXT,created_at TEXT,updated_at TEXT',
|
||
'pms_proposal': 'id INTEGER PRIMARY KEY,book_id TEXT,proposal_id TEXT UNIQUE,ts_code TEXT,action TEXT,qty INTEGER,hard_numbers_json TEXT,judge_verdict TEXT,judge_reason TEXT,status TEXT,expire_at TEXT,created_at TEXT,archived_at TEXT',
|
||
'pms_rotation_document': 'doc_id TEXT PRIMARY KEY,kind TEXT,payload_json TEXT,revision INTEGER,updated_at TEXT',
|
||
}
|
||
with self.engine.begin() as conn:
|
||
for table, cols in schema.items(): conn.execute(text('CREATE TABLE '+table+'('+cols+')'))
|
||
pms_repo.insert_strategy(strategy_id='GRID', ts_code=CODE, stype='GRID', state={'invested': 1000, 'filled_levels': {'0': {'price': 10, 'qty': 100}}})
|
||
self.original = pms_repo.get_strategy('GRID')
|
||
|
||
def use(self, obj, name, value):
|
||
p = patch.object(obj, name, value); p.start(); self.addCleanup(p.stop)
|
||
|
||
def count(self, table):
|
||
with self.engine.connect() as conn:
|
||
return conn.execute(text('SELECT COUNT(*) FROM '+table)).scalar_one()
|
||
|
||
def correction(self, cid='C1', paused=False):
|
||
old = pms_repo.get_strategy('GRID')['state']
|
||
new = copy.deepcopy(old)
|
||
new.update(invested=1100, trade_correction={'correction_id': cid})
|
||
if paused: new['correction_hold'] = '数量更正后等待核对'
|
||
pms_repo.update_strategy('GRID', state=new, status='PAUSED' if paused else 'ACTIVE',
|
||
correction_expected=(old.get('trade_correction') or {}).get('correction_id'))
|
||
return new
|
||
|
||
def test_legacy_state_and_json_null_epoch_update(self):
|
||
self.assertEqual(pms_repo.update_strategy('GRID', state={'pending': None}), 1)
|
||
self.assertEqual(pms_repo.update_strategy('GRID', state={'trade_correction': {'correction_id': None}}), 1)
|
||
self.assertEqual(pms_repo.update_strategy('GRID', state={'invested': 2}), 1)
|
||
|
||
def test_original_snapshot_cannot_overwrite_new_state_or_paused_status(self):
|
||
new = self.correction(paused=True)
|
||
with self.assertRaisesRegex(RuntimeError, '更正版本'):
|
||
pms_repo.update_strategy('GRID', state=self.original['state'], status='ACTIVE', note='旧任务')
|
||
fresh = pms_repo.get_strategy('GRID')
|
||
self.assertEqual(fresh['state'], new)
|
||
self.assertEqual(fresh['status'], 'PAUSED')
|
||
self.assertIsNone(fresh['note'])
|
||
|
||
def test_chain_compare_and_set_requires_previous_id(self):
|
||
self.correction('C1')
|
||
self.correction('C2')
|
||
with self.assertRaises(RuntimeError):
|
||
pms_repo.update_strategy('GRID', state={'trade_correction': {'correction_id': 'C3'}}, correction_expected='C1')
|
||
self.assertEqual(runner._correction_id(pms_repo.get_strategy('GRID')), 'C2')
|
||
|
||
def test_json_state_cannot_bypass_cas(self):
|
||
self.correction()
|
||
with self.assertRaises(RuntimeError): pms_repo.update_strategy('GRID', state_json='{}')
|
||
self.assertEqual(pms_repo.update_strategy('GRID', state_json=json.dumps({'trade_correction': {'correction_id': 'C1'}, 'pending': None})), 1)
|
||
|
||
def test_missing_strategy_state_write_fails_but_ordinary_status_keeps_zero(self):
|
||
self.assertEqual(pms_repo.update_strategy('missing', status='PAUSED'), 0)
|
||
with self.assertRaises(RuntimeError): pms_repo.update_strategy('missing', state={})
|
||
|
||
def test_version_keyword_is_not_a_column_and_requires_state(self):
|
||
with self.assertRaises(ValueError): pms_repo.update_strategy('GRID', status='PAUSED', correction_expected=None)
|
||
self.correction()
|
||
self.assertFalse(any('SET correction_expected' in sql for sql in self.statements))
|
||
|
||
def test_cross_book_cannot_touch_other_strategy(self):
|
||
with books.scope('micro30'):
|
||
with self.assertRaises(RuntimeError): pms_repo.update_strategy('GRID', state={})
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['state'], self.original['state'])
|
||
|
||
def test_stale_snapshot_rejected_for_instruction_and_proposal(self):
|
||
self.correction()
|
||
for emit in (runner._emit_instruction, runner._emit_proposal):
|
||
with self.assertRaisesRegex(RuntimeError, '更正版本'): emit(self.original, DECISION)
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertEqual(self.count('pms_proposal'), 0)
|
||
|
||
def test_paused_hold_and_archived_strategy_do_not_emit(self):
|
||
for fields in ({'status': 'PAUSED'}, {'state': {'correction_hold': '等待核对'}}):
|
||
old = pms_repo.get_strategy('GRID')
|
||
pms_repo.update_strategy('GRID', **fields)
|
||
with self.assertRaises(RuntimeError): runner._emit_instruction(old, DECISION)
|
||
pms_repo.update_strategy('GRID', status='ACTIVE', state={})
|
||
with self.engine.begin() as conn:
|
||
conn.execute(text("UPDATE pms_strategy SET archived_at='2026-11-05'"))
|
||
with self.assertRaises(RuntimeError): runner._emit_proposal(self.original, DECISION)
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertEqual(self.count('pms_proposal'), 0)
|
||
|
||
def test_new_instruction_and_proposal_record_exact_epoch_under_lock(self):
|
||
self.correction()
|
||
fresh = pms_repo.get_strategy('GRID')
|
||
insert = pms_repo.insert_instruction
|
||
def guarded(**kwargs):
|
||
self.assertIsNotNone(db._TRANSACTION.get())
|
||
return insert(**kwargs)
|
||
with patch.object(pms_repo, 'insert_instruction', side_effect=guarded):
|
||
iid = runner._emit_instruction(fresh, DECISION)
|
||
pid = runner._emit_proposal(fresh, DECISION)
|
||
self.assertEqual(pms_repo.get_instruction(iid)['progress']['strategy_correction_id'], 'C1')
|
||
self.assertEqual(pms_repo.get_proposal(pid)['hard_numbers']['strategy_correction_id'], 'C1')
|
||
self.assertTrue(any("doc_id='account-execution' FOR UPDATE" in sql for sql in self.statements))
|
||
|
||
def test_pre_correction_proposal_cannot_be_accepted_after_correction(self):
|
||
pid = runner._emit_proposal(self.original, DECISION)
|
||
spec = pms_repo.get_proposal(pid)['hard_numbers']
|
||
self.correction()
|
||
result = runner.emit_from_spec(spec)
|
||
self.assertFalse(result['ok'], result)
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertNotIn('pending', pms_repo.get_strategy('GRID')['state'])
|
||
|
||
def test_current_proposal_accepts_and_keeps_epoch_in_pending_state(self):
|
||
self.correction()
|
||
spec = dict(DECISION, strategy_id='GRID', strategy_correction_id='C1')
|
||
result = runner.emit_from_spec(spec)
|
||
self.assertTrue(result['ok'], result)
|
||
fresh = pms_repo.get_strategy('GRID')
|
||
self.assertEqual(fresh['state']['pending']['iid'], result['instruction_id'])
|
||
self.assertEqual(runner._correction_id(fresh), 'C1')
|
||
|
||
def test_legacy_proposal_before_any_correction_still_accepts(self):
|
||
result = runner.emit_from_spec(dict(DECISION, strategy_id='GRID'))
|
||
self.assertTrue(result['ok'], result)
|
||
self.assertIsNone(pms_repo.get_instruction(result['instruction_id'])['progress']['strategy_correction_id'])
|
||
|
||
def test_accept_state_write_failure_rolls_back_new_parent(self):
|
||
with patch.object(pms_repo, 'update_strategy', side_effect=RuntimeError('模拟状态冲突')):
|
||
with self.assertLogs('pms.strategy', level='ERROR'):
|
||
result = runner.emit_from_spec(dict(DECISION, strategy_id='GRID'))
|
||
self.assertFalse(result['ok'], result)
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
|
||
def tick(self, *, decision=True, corrected=False, paused=False, autonomy='auto', dry_run=False):
|
||
pms_repo.update_strategy('GRID', autonomy=autonomy)
|
||
active = pms_repo.active_strategies
|
||
def load():
|
||
old = active()
|
||
if corrected: self.correction(paused=paused)
|
||
return old
|
||
def evaluate(st, pos, day, now, ctx):
|
||
return copy.deepcopy(DECISION) if decision else None
|
||
with patch.object(pms_repo, 'active_strategies', side_effect=load), patch.dict(runner.EVALUATORS, {'GRID': evaluate}):
|
||
return runner.tick(dry_run=dry_run)
|
||
|
||
def test_tick_loaded_before_correction_cannot_publish_or_overwrite(self):
|
||
for autonomy in ('auto', 'confirm'):
|
||
with self.assertLogs('pms.strategy', level='ERROR'):
|
||
out = self.tick(corrected=True, paused=autonomy=='confirm', autonomy=autonomy)
|
||
self.assertFalse(out['ok'], out)
|
||
self.assertEqual(out['fired'], [])
|
||
self.assertEqual(out['queued'], [])
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertEqual(self.count('pms_proposal'), 0)
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['state']['invested'], 1100)
|
||
# 下一子例从新的、无更正标记的独立策略状态开始。
|
||
with self.engine.begin() as conn:
|
||
conn.execute(text("UPDATE pms_strategy SET state_json=:body,status='ACTIVE'"), {'body':json.dumps(self.original['state'])})
|
||
|
||
def test_idle_tick_old_state_cannot_erase_correction(self):
|
||
with self.assertLogs('pms.strategy', level='ERROR'):
|
||
out = self.tick(decision=False, corrected=True)
|
||
self.assertFalse(out['ok'], out)
|
||
self.assertEqual(runner._correction_id(pms_repo.get_strategy('GRID')), 'C1')
|
||
|
||
def test_tick_success_persists_pending_and_parent_together(self):
|
||
self.correction()
|
||
out = self.tick()
|
||
self.assertTrue(out['ok'], out)
|
||
self.assertEqual(len(out['fired']), 1)
|
||
fresh = pms_repo.get_strategy('GRID')
|
||
parent = pms_repo.get_instruction(fresh['state']['pending']['iid'])
|
||
self.assertEqual(parent['progress']['strategy_correction_id'], 'C1')
|
||
self.assertEqual(fresh['state']['invested'], 1000) # 发单不是成交,不能增加真实投入
|
||
|
||
def test_tick_state_failure_rolls_back_parent_and_reports_no_fired(self):
|
||
original_update = pms_repo.update_strategy
|
||
def fail_state(sid, **fields):
|
||
if 'state' in fields: raise RuntimeError('模拟版本冲突')
|
||
return original_update(sid, **fields)
|
||
with patch.object(pms_repo, 'update_strategy', side_effect=fail_state):
|
||
with self.assertLogs('pms.strategy', level='ERROR'): out = self.tick()
|
||
self.assertFalse(out['ok'], out)
|
||
self.assertEqual(out['fired'], [])
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['state'], self.original['state'])
|
||
|
||
def test_dry_run_keeps_strategy_and_does_not_lock_or_insert(self):
|
||
self.statements.clear()
|
||
out = self.tick(dry_run=True)
|
||
self.assertTrue(out['ok'], out)
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['state'], self.original['state'])
|
||
self.assertFalse(any('account-execution' in sql for sql in self.statements))
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
|
||
def attach_trail(self):
|
||
return strategy_service.attach({'ts_code': CODE, 'type': 'TRAIL', 'params': {'giveback': .05}})
|
||
|
||
def test_resume_cannot_take_over_another_active_strategy(self):
|
||
self.assertTrue(strategy_service.set_status('GRID', 'PAUSED')['ok'])
|
||
trail = self.attach_trail()
|
||
self.assertTrue(trail['ok'], trail)
|
||
self.assertFalse(strategy_service.set_status('GRID', 'ACTIVE')['ok'])
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['status'], 'PAUSED')
|
||
self.assertTrue(strategy_service.set_status(trail['strategy_id'], 'CANCELLED')['ok'])
|
||
self.assertFalse(strategy_service.set_status(trail['strategy_id'], 'ACTIVE')['ok'])
|
||
with patch.object(pms_repo, 'get_position', return_value=None):
|
||
self.assertFalse(strategy_service.set_status('GRID', 'ACTIVE')['ok'])
|
||
self.assertTrue(strategy_service.set_status('GRID', 'ACTIVE')['ok'])
|
||
self.assertEqual([s['strategy_id'] for s in pms_repo.active_strategies()], ['GRID'])
|
||
|
||
def test_snapshot_is_read_outside_lock_and_actual_availability_is_rechecked_inside(self):
|
||
self.assertTrue(strategy_service.set_status('GRID', 'PAUSED')['ok'])
|
||
def quote_snapshot():
|
||
self.assertIsNone(db._TRANSACTION.get())
|
||
return {'positions': [{'ts_code': CODE, 'total_qty': 100, 'avail_qty': 100,
|
||
'price_ok': True, 'price': 10}],
|
||
'params': {'scale': 10000, 'stock_cap': .2}}
|
||
def changed_position(code):
|
||
self.assertIsNotNone(db._TRANSACTION.get())
|
||
return {'total_qty': 180, 'avail_qty': 0}
|
||
with (patch.object(runner.portfolio, 'positions_view', side_effect=quote_snapshot),
|
||
patch.object(pms_repo, 'get_position', side_effect=changed_position)):
|
||
self.assertFalse(self.attach_trail()['ok'])
|
||
grid = {'ts_code': CODE, 'type': 'GRID', 'params': {'lower': 9, 'center': 10,
|
||
'upper': 11, 'step': .5, 'max_capital': 500}}
|
||
result = strategy_service.attach(grid)
|
||
self.assertIn('超过', result['errors'][0], result)
|
||
with patch.object(runner.portfolio, 'positions_view', side_effect=RuntimeError('行情不可用')):
|
||
self.assertFalse(self.attach_trail()['ok'])
|
||
self.assertFalse(pms_repo.active_strategies())
|
||
|
||
def test_legacy_account_without_position_cannot_attach_or_resume_but_can_cancel(self):
|
||
self.use(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False)
|
||
with self.engine.begin() as connection:
|
||
connection.execute(text('CREATE TABLE pms_position (ts_code TEXT PRIMARY KEY,total_qty INTEGER)'))
|
||
connection.execute(text("INSERT INTO pms_strategy(strategy_id,ts_code,type,status) "
|
||
"VALUES ('legacy',:code,'GRID','PAUSED')"), {'code': CODE})
|
||
with (patch.object(runner.portfolio, 'positions_view', return_value={'positions': []}),
|
||
patch.object(pms_repo, 'get_position', return_value=None)):
|
||
self.assertFalse(self.attach_trail()['ok'])
|
||
self.assertFalse(strategy_service.set_status('legacy', 'ACTIVE')['ok'])
|
||
self.assertTrue(strategy_service.set_status('legacy', 'CANCELLED')['ok'])
|
||
self.assertTrue(any('FROM pms_position WHERE ts_code' in sql and 'FOR UPDATE' in sql
|
||
for sql in self.statements))
|
||
|
||
def test_concurrent_attach_and_resume_leave_one_owner(self):
|
||
# SQLite 没有行锁,用写事务模拟同一账户锁的排它性;读写走真实 repo。
|
||
@event.listens_for(self.engine, 'begin')
|
||
def begin_immediate(connection):
|
||
connection.exec_driver_sql('BEGIN IMMEDIATE')
|
||
self.assertTrue(strategy_service.set_status('GRID', 'PAUSED')['ok'])
|
||
barrier = threading.Barrier(2)
|
||
def compete(action):
|
||
barrier.wait(timeout=5)
|
||
return action()
|
||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||
results = list(pool.map(compete, [self.attach_trail, lambda: strategy_service.set_status('GRID', 'ACTIVE')]))
|
||
self.assertEqual(sum(result['ok'] for result in results), 1, results)
|
||
self.assertEqual(len(pms_repo.active_strategies()), 1)
|
||
self.assertTrue(any("doc_id='account-execution' FOR UPDATE" in sql for sql in self.statements))
|
||
|
||
def test_existing_duplicate_owners_stop_tick_and_manual_acceptance(self):
|
||
pms_repo.insert_strategy(strategy_id='TRAIL', ts_code=CODE, stype='TRAIL')
|
||
out = runner.tick(now=self.now)
|
||
self.assertFalse(out['ok'])
|
||
self.assertEqual(out['fired'] + out['queued'], [])
|
||
with self.assertLogs('pms.strategy', level='ERROR'):
|
||
result = runner.emit_from_spec(dict(DECISION, strategy_id='GRID'))
|
||
self.assertFalse(result['ok'])
|
||
self.assertEqual(self.count('pms_instruction'), 0)
|
||
self.assertTrue(strategy_service.set_status('TRAIL', 'PAUSED')['ok'])
|
||
|
||
def test_stale_missing_or_future_price_cannot_move_trailing_high_or_trigger(self):
|
||
strategy_service.set_status('GRID', 'PAUSED')
|
||
strategy_id = self.attach_trail()['strategy_id']
|
||
pms_repo.update_strategy(strategy_id, state={'high_water': 12, 'armed': True})
|
||
for bars in ([], [{'close': 20, 'time': self.now - dt.timedelta(days=1)}],
|
||
[{'close': 8, 'time': self.now - dt.timedelta(seconds=91)}],
|
||
[{'close': 20, 'time': self.now + dt.timedelta(seconds=1)}],
|
||
[{'close': 'nan', 'time': self.now}]):
|
||
with self.subTest(bars=bars), patch.object(runner.market, '_bars', return_value=bars):
|
||
out = runner.tick(now=self.now)
|
||
self.assertTrue(out['ok'], out)
|
||
self.assertFalse(out['fired'])
|
||
self.assertEqual(pms_repo.get_strategy(strategy_id)['state']['high_water'], 12)
|
||
self.assertNotIn('trail_due', pms_repo.get_strategy(strategy_id)['state'])
|
||
with patch.object(runner.market, '_bars', return_value=[{'close': 10, 'time': self.now}]):
|
||
out = runner.tick(now=self.now)
|
||
self.assertEqual([row['qty'] for row in out['fired']], [100], out)
|
||
|
||
def test_late_receipt_is_settled_once_then_only_remainder_fires_on_fresh_quote(self):
|
||
strategy_service.set_status('GRID', 'PAUSED')
|
||
strategy_id = self.attach_trail()['strategy_id']
|
||
due = {'qty': 200, 'leg': 'trail_sell', 'partial': False, 'high_water': 12, 'reason': '回撤'}
|
||
pms_repo.update_strategy(strategy_id, state={'pending': {'iid':'prior', 'leg':'trail_sell'},
|
||
'trail_due': due, 'high_water': 12, 'armed': True})
|
||
pms_repo.insert_instruction(instruction_id='prior', origin_type='strategy', origin_id=strategy_id,
|
||
ts_code=CODE, action='EXIT', side='sell', qty=200, status='CANCELLED')
|
||
pms_repo.update_instruction('prior', exec_qty=100)
|
||
self.use(runner.param_store, 'get', lambda key, default=None: 'ws' if key == 'PMS_DISPATCH_MODE' else default)
|
||
with (patch.object(runner.market, '_bars', return_value=[]),
|
||
patch.object(execution_orders, 'replacement_state', return_value={'ready': False})):
|
||
self.assertFalse(runner.tick(now=self.now)['fired'])
|
||
self.assertEqual(pms_repo.get_strategy(strategy_id)['state']['trail_due']['qty'], 200)
|
||
self.assertEqual(pms_repo.get_strategy(strategy_id)['state']['pending']['iid'], 'prior')
|
||
with (patch.object(runner.market, '_bars', return_value=[]),
|
||
patch.object(execution_orders, 'replacement_state', return_value={'ready': True})):
|
||
for _ in range(2):
|
||
self.assertFalse(runner.tick(now=self.now)['fired'])
|
||
after = pms_repo.get_strategy(strategy_id)['state']
|
||
self.assertEqual(after['trail_due']['qty'], 100)
|
||
self.assertIsNone(after['pending'])
|
||
with patch.object(runner.market, '_bars', return_value=[{'time': self.now, 'close': 10}]):
|
||
out = runner.tick(now=self.now)
|
||
self.assertEqual([row['qty'] for row in out['fired']], [100], out)
|
||
|
||
def test_grid_waits_on_missing_unrecognized_or_unsettled_parent_and_proposal(self):
|
||
def waiting(pending):
|
||
return strategy_advisor._has_pending({'strategy_id': 'GRID', 'ts_code': CODE, 'state': {'pending': pending}})
|
||
self.assertFalse(waiting(None))
|
||
self.assertTrue(waiting({}))
|
||
with patch.object(pms_repo, 'list_instructions', return_value=[{'status': 'DISPATCHED'}]):
|
||
self.assertTrue(waiting(None))
|
||
with patch.object(pms_repo, 'list_instructions', side_effect=RuntimeError('不能核实同股在途指令')):
|
||
self.assertTrue(waiting(None))
|
||
self.assertTrue(waiting({'iid': 'absent'}))
|
||
self.assertTrue(waiting({'pid': 'absent'}))
|
||
for status in ('JUDGE_PASSED', 'UNKNOWN'):
|
||
with patch.object(pms_repo, 'get_instruction', return_value={'status': status}):
|
||
self.assertTrue(waiting({'iid': 'prior'}))
|
||
with patch.object(pms_repo, 'get_instruction', side_effect=RuntimeError('读失败')):
|
||
self.assertTrue(waiting({'iid': 'prior'}))
|
||
for status in ('WAIT_USER', 'ACCEPTED', 'unknown'):
|
||
with patch.object(pms_repo, 'get_proposal', return_value={'status': status}):
|
||
self.assertTrue(waiting({'pid': 'prior'}))
|
||
with patch.object(pms_repo, 'get_proposal', return_value={'status':'DECLINED'}):
|
||
self.assertFalse(waiting({'pid': 'prior'}))
|
||
self.use(runner.param_store, 'get', lambda key, default=None: 'ws' if key == 'PMS_DISPATCH_MODE' else default)
|
||
with patch.object(qmt_repo, 'list_orders', return_value=[{'status':'PARTIAL'}]):
|
||
self.assertTrue(waiting(None))
|
||
with (patch.object(qmt_repo, 'list_orders', return_value=[]),
|
||
patch.object(pms_repo, 'get_instruction', return_value={'status': 'CONFIRMED'})):
|
||
for ready in (False, True):
|
||
with patch.object(execution_orders, 'replacement_state', return_value={'ready': ready}):
|
||
self.assertEqual(waiting({'iid':'prior'}), not ready)
|
||
|
||
def test_handoff_requires_current_breakout_and_seeds_the_new_trail_from_its_quote(self):
|
||
prm = {'handoff_enabled': True, 'rules': [strategy_advisor.R_HANDOFF],
|
||
'heat_th': .7, 'trail_giveback': .05, 'trail_sell_ratio': .5}
|
||
pms_repo.update_strategy('GRID', note='自动挂载: 网格', params_json='{"upper":11}')
|
||
st = pms_repo.get_strategy('GRID')
|
||
pos = {'ts_code': CODE, 'price': 13, 'price_ok': True, 'avg_cost': 9.8, 'cushion_pct': .3}
|
||
self.use(runner.param_store, 'get', lambda key, default=None: 'ws' if key == 'PMS_DISPATCH_MODE' else default)
|
||
def read_history(code):
|
||
self.assertIsNone(db._TRANSACTION.get())
|
||
return ''
|
||
def tend(bars):
|
||
out = {'skipped': [], 'errors': [], 'handoffs': []}
|
||
with (patch.object(runner.market, '_bars', return_value=bars),
|
||
patch.object(qmt_repo, 'list_orders', return_value=[]),
|
||
patch.object(execution_orders, 'code_settlement_blocker', side_effect=read_history),
|
||
patch.object(runner.portfolio, 'positions_view', side_effect=AssertionError('接力须复用持仓快照')),
|
||
patch.object(pms_repo, 'insert_ledger', return_value=1)):
|
||
strategy_advisor._tend_existing(st, pos, {}, False, .9, prm, {}, set(), 20261105,
|
||
False, out, strategy_service, now=self.now)
|
||
return out
|
||
for bars in ([], [{'time': self.now - dt.timedelta(days=1), 'close': 13}],
|
||
[{'time': self.now, 'close': 10.5}]):
|
||
self.assertFalse(tend(bars)['handoffs'])
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['status'], 'ACTIVE')
|
||
out = tend([{'time': self.now, 'close': 11.5}])
|
||
self.assertEqual(len(out['handoffs']), 1, out)
|
||
self.assertEqual(pms_repo.get_strategy('GRID')['status'], 'CANCELLED')
|
||
active = pms_repo.active_strategies()
|
||
self.assertEqual(len(active), 1)
|
||
self.assertEqual(active[0]['state']['high_water'], 11.5)
|
||
|
||
def test_failed_handoff_ledger_rolls_back_both_strategies_and_high_water(self):
|
||
out = {'errors': [], 'skipped': [], 'handoffs': []}
|
||
history = []
|
||
def fail_pass(**row):
|
||
history.append(row['verdict'])
|
||
return int(row['verdict'] == 'REJECT')
|
||
with patch.object(pms_repo, 'insert_ledger', side_effect=fail_pass):
|
||
strategy_advisor._do_handoff(self.original, {'ts_code': CODE}, .9,
|
||
{'trail_giveback': .05, 'trail_sell_ratio': .5}, '站上上界', out,
|
||
strategy_service, high_water=12)
|
||
self.assertTrue(out['errors'], out)
|
||
self.assertFalse(out['handoffs'])
|
||
self.assertEqual(history, ['PASS', 'REJECT'])
|
||
self.assertEqual(self.count('pms_strategy'), 1)
|
||
active = pms_repo.get_strategy('GRID')
|
||
self.assertEqual(active['status'], 'ACTIVE')
|
||
self.assertEqual(active['state'], self.original['state'])
|
||
self.assertEqual(active['note'], self.original['note'])
|
||
|
||
def test_soft_archived_parent_does_not_archive_current_strategy(self):
|
||
iid = runner._emit_instruction(self.original, DECISION)
|
||
with self.engine.begin() as conn:
|
||
conn.execute(text("UPDATE pms_instruction SET status='CONFIRMED',archived_at='2026-11-05' WHERE instruction_id=:iid"), {'iid': iid})
|
||
self.correction()
|
||
self.now += dt.timedelta(minutes=1)
|
||
result = runner.emit_from_spec(dict(DECISION, strategy_id='GRID', strategy_correction_id='C1', leg='grid_sell:1', side='sell', action='TRIM'))
|
||
self.assertTrue(result['ok'], result)
|
||
self.assertEqual(self.count('pms_instruction'), 2)
|
||
|
||
|
||
if __name__ == '__main__': unittest.main()
|