2026-11-05 12:23:33 +08:00
|
|
|
|
"""退出纪律:虚构事件、真实SQLite事务与双策略隔离,禁止联网。"""
|
|
|
|
|
|
import unit_test_guard # noqa: F401
|
|
|
|
|
|
import copy
|
|
|
|
|
|
import datetime as dt
|
|
|
|
|
|
import json
|
|
|
|
|
|
import sys
|
|
|
|
|
|
import tempfile
|
|
|
|
|
|
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 risk_exit as core, signal_rules, strategy_book as books
|
|
|
|
|
|
from app.db import session as db
|
|
|
|
|
|
from app.repo import pms_repo, qmt_repo, rotation_repo as store
|
|
|
|
|
|
from app.services import risk_exit as service, param_store, strategy_service, logic_state_service
|
|
|
|
|
|
from app.services import executor, execution_orders, execution_conflicts, signal_service
|
|
|
|
|
|
from config.settings import settings
|
|
|
|
|
|
|
|
|
|
|
|
CODE = '600001.SH'
|
|
|
|
|
|
NOW = dt.datetime(2026, 11, 5, 10, tzinfo=core.TZ)
|
|
|
|
|
|
START = NOW-dt.timedelta(hours=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def signal(n=1, *, at=None, source='intraday', reason='独立研判确认退出'):
|
|
|
|
|
|
return {'ts_code': CODE, 'action': 'SELL', 'confidence': .95, 'reason': reason,
|
|
|
|
|
|
'source': source, 'producer_id': 'bionic_brain_intraday_v2.0',
|
|
|
|
|
|
'msg_id': str(n), 'signal_id': 'S'+str(n),
|
|
|
|
|
|
'event_time': (at or NOW).isoformat(), 'is_fallback': False}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def review(grade='好', ref='a', days=2):
|
|
|
|
|
|
return {'overall': grade, 'review_ref': ref*64,
|
|
|
|
|
|
'report_ran_at': (NOW-dt.timedelta(days=days)).isoformat(),
|
|
|
|
|
|
'qual': 'ok', 'brain_status': 'ok'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CoreTests(unittest.TestCase):
|
|
|
|
|
|
def parse(self, value):
|
|
|
|
|
|
return core.signal_event(value, now=NOW, since=START)
|
|
|
|
|
|
|
|
|
|
|
|
def test_valid_and_invalid_event_boundaries(self):
|
|
|
|
|
|
self.assertIsNotNone(self.parse(signal())[0])
|
|
|
|
|
|
changes = [dict(ts_code='920001.BJ'), dict(confidence=.6), dict(confidence=float('nan')),
|
|
|
|
|
|
dict(action='BUY'), dict(source='unknown'), dict(producer_id='smoketest'),
|
|
|
|
|
|
dict(event_time=None), dict(msg_id=None), dict(reason=''), dict(is_fallback=True),
|
|
|
|
|
|
dict(is_fallback='true'), dict(event_time=(NOW+dt.timedelta(seconds=1)).isoformat()),
|
|
|
|
|
|
dict(event_time=(NOW-dt.timedelta(minutes=6)).isoformat()),
|
|
|
|
|
|
dict(expires_at=(NOW-dt.timedelta(seconds=1)).isoformat()), dict(expires_at='bad')]
|
|
|
|
|
|
for changeset in changes:
|
|
|
|
|
|
with self.subTest(changeset=changeset):
|
|
|
|
|
|
self.assertIsNone(self.parse({**signal(), **changeset})[0])
|
|
|
|
|
|
|
|
|
|
|
|
def test_cutover_does_not_replay_old_signals(self):
|
|
|
|
|
|
self.assertIsNone(core.signal_event(signal(),now=NOW,since=NOW+dt.timedelta(seconds=1))[0])
|
|
|
|
|
|
self.assertIsNone(core.signal_event(signal(),now=NOW,since='')[0])
|
|
|
|
|
|
|
|
|
|
|
|
def test_replay_and_cross_stream_copy_do_not_count_twice(self):
|
|
|
|
|
|
a=self.parse(signal())[0]
|
|
|
|
|
|
self.assertTrue(core.duplicate([a],a))
|
|
|
|
|
|
copy_event=self.parse({**signal(2,source='risk_sell'), 'event_time':(NOW-dt.timedelta(seconds=1)).isoformat()})[0]
|
|
|
|
|
|
self.assertTrue(core.duplicate([a],copy_event))
|
|
|
|
|
|
copy_event=self.parse(signal(3,source='risk_sell',reason='同一研判的另一份文字'))[0]
|
|
|
|
|
|
self.assertTrue(core.duplicate([a],copy_event))
|
|
|
|
|
|
modified=self.parse({**signal(3), 'signal_id':'S1','reason':'重新包装的同一信号'})[0]
|
|
|
|
|
|
self.assertTrue(core.duplicate([a],modified))
|
|
|
|
|
|
self.assertFalse(core.duplicate([a],self.parse(signal(4))[0]))
|
|
|
|
|
|
|
|
|
|
|
|
def test_parser_preserves_upstream_identity_and_expiry(self):
|
|
|
|
|
|
t=int(NOW.timestamp()*1000)
|
|
|
|
|
|
a=signal_rules.parse_intraday({'ts_code':CODE,'action':'SELL','confidence':'.95',
|
|
|
|
|
|
'signal_id':'id','trigger_time':str(t),'producer_id':'bionic_brain_intraday_v2.0',
|
|
|
|
|
|
'signal_validity':json.dumps({'expires_at':t+300000}),'audit_reason':'退出'},msg_id='1')
|
|
|
|
|
|
self.assertEqual(a['event_time'],str(t));self.assertEqual(a['expires_at'],t+300000)
|
|
|
|
|
|
self.assertIsNotNone(self.parse(a)[0])
|
|
|
|
|
|
b=signal_rules.parse_risk_sell({'data':json.dumps({'ts_code':CODE,'action':'SELL',
|
|
|
|
|
|
'confidence':95,'timestamp':t,'is_fallback':False,'llm_reason':'退出'})},msg_id='2')
|
|
|
|
|
|
self.assertIsNotNone(self.parse(b)[0])
|
|
|
|
|
|
|
|
|
|
|
|
def test_every_overall_downgrade_counts(self):
|
|
|
|
|
|
for before,after in [('好','中'),('中','差'),('好','差')]:
|
|
|
|
|
|
with self.subTest(before=before,after=after):
|
|
|
|
|
|
a=core.review_snapshot(review(before),now=NOW)
|
|
|
|
|
|
b=core.review_snapshot(review(after,'b',1),now=NOW)
|
|
|
|
|
|
self.assertEqual(core.review_change(a,b),'downgrade')
|
|
|
|
|
|
|
|
|
|
|
|
def test_missing_stale_incomplete_and_future_review_are_not_downgrades(self):
|
|
|
|
|
|
for value in [None,{},review('未知'),{**review(),'qual':'off'},
|
|
|
|
|
|
{**review(),'brain_status':'timeout'},review(days=121),review(days=-1),
|
|
|
|
|
|
{**review(),'review_ref':''}]:
|
|
|
|
|
|
self.assertIsNone(core.review_snapshot(value,now=NOW))
|
|
|
|
|
|
|
|
|
|
|
|
def test_review_order_and_immutable_identity(self):
|
|
|
|
|
|
a=core.review_snapshot(review(),now=NOW)
|
|
|
|
|
|
self.assertEqual(core.review_change(a,a),'same')
|
|
|
|
|
|
self.assertEqual(core.review_change(None,a),'baseline')
|
|
|
|
|
|
self.assertEqual(core.review_change(a,None),'missing')
|
|
|
|
|
|
self.assertEqual(core.review_change(a,core.review_snapshot(review('差','b',3),now=NOW)),'old')
|
|
|
|
|
|
with self.assertRaises(ValueError):core.review_change(a,{**a,'grade':'中'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ServiceTests(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
|
|
|
|
|
self.engine=create_engine('sqlite:///'+self.tmp.name+'/risk.sqlite');self.addCleanup(self.engine.dispose)
|
|
|
|
|
|
@event.listens_for(self.engine,'before_cursor_execute',retval=True)
|
|
|
|
|
|
def dialect(conn,cursor,sql,params,context,many):
|
|
|
|
|
|
db.assert_single_table(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
|
|
|
|
|
|
self.params={'PMS_RISK_EXIT_ENABLED':True,'PMS_RISK_EXIT_START_AT':START.isoformat()}
|
|
|
|
|
|
self.use(db,'get_engine',lambda *args:self.engine)
|
|
|
|
|
|
self.use(db,'_check_cooldown',lambda *args:None)
|
|
|
|
|
|
self.use(settings,'INFRA_STRATEGY_BOOK_SCHEMA',True)
|
|
|
|
|
|
for name in ('get','get_bool','get_int','get_float'):
|
|
|
|
|
|
self.use(param_store,name,lambda key,default=None:self.params.get(key,default))
|
|
|
|
|
|
self.use(logic_state_service,'entry_view',lambda code:{'company_review':review()})
|
|
|
|
|
|
self.reviews={CODE:{'company_review':review()}}
|
|
|
|
|
|
self.use(logic_state_service,'state_map',lambda:self.reviews)
|
|
|
|
|
|
self.use(execution_orders,'correction_blocker',lambda *a,**k:'')
|
|
|
|
|
|
self.pending,self.orphans=0,0
|
|
|
|
|
|
self.use(qmt_repo,'inbox_pending_count',lambda:self.pending)
|
|
|
|
|
|
self.use(qmt_repo,'inbox_orphan_count',lambda:self.orphans)
|
|
|
|
|
|
self.use(strategy_service,'buypause_map',lambda:(store.get('test-pause')[0] or {}))
|
|
|
|
|
|
def pause(code,reason='',source='signal'):
|
|
|
|
|
|
with store.locked('test-pause','test',{}) as m:
|
|
|
|
|
|
e=m.setdefault(code,{'sources':{}})
|
|
|
|
|
|
e['sources'][source]={'reason':reason,'at':NOW.isoformat()}
|
|
|
|
|
|
return []
|
|
|
|
|
|
def clear(code,only_source=None):
|
|
|
|
|
|
with store.locked('test-pause','test',{}) as m:m.pop(code,None)
|
|
|
|
|
|
return {'ok':True,'cleared':True}
|
|
|
|
|
|
self.use(strategy_service,'pause_buy',pause)
|
|
|
|
|
|
self.use(strategy_service,'clear_buypause',clear)
|
|
|
|
|
|
self.cancel_pending=False
|
|
|
|
|
|
def cancel(iid,reason='',arbiter='user',**kwargs):
|
|
|
|
|
|
self.assertEqual(arbiter,'system')
|
|
|
|
|
|
if not self.cancel_pending:pms_repo.update_instruction(iid,status='CANCELLED')
|
|
|
|
|
|
return {'ok':True,'pending':self.cancel_pending}
|
|
|
|
|
|
self.use(executor,'cancel_instruction',cancel)
|
|
|
|
|
|
schema={
|
2026-11-16 11:41:27 +08:00
|
|
|
|
'pms_command':'id INTEGER PRIMARY KEY,book_id TEXT,command_id TEXT,cmd_class TEXT,cmd_type TEXT,ts_code TEXT,params_json TEXT,status TEXT,progress_json TEXT,issued_by TEXT,issued_at TEXT,archived_at TEXT',
|
2026-11-18 18:03:41 +08:00
|
|
|
|
'pms_runtime_param':'param_key TEXT PRIMARY KEY,param_value TEXT',
|
2026-11-05 12:23:33 +08:00
|
|
|
|
'pms_position':'id INTEGER PRIMARY KEY,book_id TEXT,ts_code TEXT,total_qty INTEGER,avail_qty INTEGER,opened_date TEXT,status TEXT',
|
|
|
|
|
|
'pms_lot':'id INTEGER PRIMARY KEY,book_id TEXT,ts_code TEXT,instruction_id TEXT,qty INTEGER,status TEXT,open_date 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 DEFAULT 0,exec_avg_price REAL,progress_json TEXT,created_at TEXT,updated_at TEXT,archived_at TEXT',
|
|
|
|
|
|
'pms_action_ledger':'id INTEGER PRIMARY KEY,book_id TEXT,ts_code TEXT,decided_at TEXT,action TEXT,arbiter TEXT,verdict TEXT,price_at REAL,hard_numbers_json TEXT,failed_checks_json TEXT,reason TEXT,ref_id TEXT,outcome_scored INTEGER',
|
|
|
|
|
|
'pms_proposal':'id INTEGER PRIMARY KEY,book_id TEXT,proposal_id TEXT,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,decided_at TEXT,archived_at TEXT',
|
|
|
|
|
|
'pms_strategy':'id INTEGER PRIMARY KEY,book_id TEXT,strategy_id TEXT,ts_code TEXT,type TEXT,status TEXT,params_json TEXT,state_json TEXT,autonomy TEXT,note TEXT,created_at TEXT,updated_at TEXT,archived_at TEXT',
|
|
|
|
|
|
'pms_rotation_document':'doc_id TEXT PRIMARY KEY,kind TEXT,payload_json TEXT,revision INTEGER,updated_at TEXT',
|
|
|
|
|
|
'pms_plan':'id INTEGER PRIMARY KEY,book_id TEXT,plan_id TEXT,ts_code TEXT,action TEXT,status TEXT,priority INTEGER,created_at TEXT,updated_at TEXT',
|
|
|
|
|
|
'pms_qmt_order':'id INTEGER PRIMARY KEY,instruction_id TEXT,parent_id TEXT,ts_code TEXT,side TEXT,status TEXT',
|
|
|
|
|
|
}
|
|
|
|
|
|
with self.engine.begin() as conn:
|
|
|
|
|
|
for table,cols in schema.items():conn.execute(text('CREATE TABLE '+table+' ('+cols+')'))
|
|
|
|
|
|
self.insert('pms_position',dict(book_id='original',ts_code=CODE,total_qty=1600,avail_qty=1600,opened_date='2026-11-03',status='HOLDING'))
|
|
|
|
|
|
self.insert('pms_lot',dict(id=1,book_id='original',ts_code=CODE,instruction_id='BASE',qty=1600,status='OPEN',open_date='2026-11-03'))
|
|
|
|
|
|
|
|
|
|
|
|
def use(self,obj,name,value):
|
|
|
|
|
|
p=patch.object(obj,name,value);p.start();self.addCleanup(p.stop)
|
|
|
|
|
|
|
|
|
|
|
|
def insert(self,table,value):
|
|
|
|
|
|
with self.engine.begin() as conn:
|
|
|
|
|
|
conn.execute(text('INSERT INTO '+table+' ('+','.join(value)+') VALUES ('+','.join(':'+k for k in value)+')'),value)
|
|
|
|
|
|
|
|
|
|
|
|
def change(self,sql):
|
|
|
|
|
|
with self.engine.begin() as conn:conn.execute(text(sql))
|
|
|
|
|
|
|
|
|
|
|
|
def state(self):return store.get(service._key(CODE))[0] or {}
|
|
|
|
|
|
def instructions(self):return pms_repo.list_instructions(ts_code=CODE,include_archived=True)
|
|
|
|
|
|
def fire(self,n=1,**kwargs):return service.on_signal(signal(n,**kwargs),now=NOW)
|
|
|
|
|
|
|
|
|
|
|
|
def test_first_stops_buys_second_creates_one_full_exit(self):
|
|
|
|
|
|
self.assertEqual(self.fire()['count'],1)
|
|
|
|
|
|
self.assertTrue(execution_conflicts.buy_blocker(CODE));self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.assertEqual(self.fire(2)['count'],2)
|
|
|
|
|
|
orders=self.instructions();self.assertEqual(len(orders),1)
|
|
|
|
|
|
self.assertEqual((orders[0]['action'],orders[0]['qty']),('EXIT',1600))
|
|
|
|
|
|
self.assertTrue(orders[0]['progress']['urgent'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_duplicate_after_restart_does_not_count(self):
|
|
|
|
|
|
self.fire();self.fire()
|
|
|
|
|
|
self.assertEqual(self.state()['count'],1);self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.fire(2);self.fire(2);service.scan(now=NOW)
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_same_report_and_upgrade_no_exit_downgrade_exits(self):
|
|
|
|
|
|
self.assertEqual(service.observe_review(CODE,review(),now=NOW),'same')
|
|
|
|
|
|
service.drive(CODE,now=NOW);self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.assertEqual(service.observe_review(CODE,review('中','b',1),now=NOW),'downgrade')
|
|
|
|
|
|
service.drive(CODE,now=NOW)
|
|
|
|
|
|
self.assertEqual(self.instructions()[0]['qty'],1600)
|
|
|
|
|
|
self.assertEqual(self.state()['review_exit']['before']['grade'],'好')
|
|
|
|
|
|
|
|
|
|
|
|
def test_missing_entry_review_starts_baseline_without_fabricated_decline(self):
|
|
|
|
|
|
self.use(logic_state_service,'entry_view',lambda code:{})
|
|
|
|
|
|
self.assertEqual(service.observe_review(CODE,review('中'),now=NOW),'baseline')
|
|
|
|
|
|
service.drive(CODE,now=NOW);self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_incomplete_review_keeps_last_valid_baseline(self):
|
|
|
|
|
|
service.observe_review(CODE,review(),now=NOW)
|
|
|
|
|
|
service.observe_review(CODE,{**review('差','b',1),'brain_status':'timeout'},now=NOW)
|
|
|
|
|
|
self.assertEqual(self.state()['review']['grade'],'好');self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_stale_or_changed_same_version_does_not_exit(self):
|
|
|
|
|
|
service.observe_review(CODE,review(),now=NOW)
|
|
|
|
|
|
self.assertEqual(service.observe_review(CODE,review('差','b',3),now=NOW),'old')
|
|
|
|
|
|
with self.assertRaises(ValueError):service.observe_review(CODE,review('差'),now=NOW)
|
|
|
|
|
|
self.assertEqual(self.state()['review']['grade'],'好');self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_global_pause_records_intent_without_actions(self):
|
|
|
|
|
|
self.params['PMS_GLOBAL_EXEC_HALT']=True
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'EXIT_PENDING');self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.params['PMS_GLOBAL_EXEC_HALT']=False
|
|
|
|
|
|
service.scan(now=NOW);self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_dry_run_writes_nothing(self):
|
|
|
|
|
|
result=service.on_signal(signal(),now=NOW,dry_run=True)
|
|
|
|
|
|
self.assertTrue(result['dry_run']);self.assertEqual(self.state(),{});self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_feature_off_keeps_legacy_path(self):
|
|
|
|
|
|
self.params['PMS_RISK_EXIT_ENABLED']=False
|
|
|
|
|
|
self.assertIsNone(self.fire());self.assertIsNone(service.buy_blocker(CODE))
|
|
|
|
|
|
|
|
|
|
|
|
def test_micro_book_untouched(self):
|
|
|
|
|
|
self.insert('pms_position',dict(book_id='micro30',ts_code=CODE,total_qty=900,avail_qty=900,opened_date='2026-11-03'))
|
|
|
|
|
|
self.insert('pms_lot',dict(id=2,book_id='micro30',ts_code=CODE,instruction_id='MICRO',qty=900,status='OPEN'))
|
|
|
|
|
|
with books.scope('micro30'):
|
|
|
|
|
|
self.assertIsNone(self.fire());self.assertIsNone(service.buy_blocker(CODE))
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
self.assertEqual(self.instructions()[0]['qty'],1600)
|
|
|
|
|
|
with books.scope('micro30'):
|
|
|
|
|
|
self.assertEqual(self.instructions(),[]);self.assertEqual(pms_repo.get_position(CODE)['total_qty'],900)
|
|
|
|
|
|
|
|
|
|
|
|
def test_t1_retains_full_exit_quantity_until_available(self):
|
|
|
|
|
|
self.change('UPDATE pms_position SET avail_qty=0')
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
self.assertEqual(self.instructions()[0]['qty'],1600)
|
|
|
|
|
|
service.scan(now=NOW);self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_exit_insert_failure_does_not_consume_second_signal_twice(self):
|
|
|
|
|
|
self.fire()
|
|
|
|
|
|
with patch.object(pms_repo,'insert_instruction',return_value=0):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):self.fire(2)
|
|
|
|
|
|
self.assertEqual(self.state()['count'],2);self.assertEqual(self.state()['phase'],'EXIT_PENDING')
|
|
|
|
|
|
self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.fire(2);self.assertEqual(len(self.instructions()),1);self.assertEqual(self.state()['count'],2)
|
|
|
|
|
|
|
|
|
|
|
|
def test_audit_failure_rolls_back_signal_count(self):
|
|
|
|
|
|
with patch.object(pms_repo,'insert_ledger',return_value=0):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):self.fire()
|
|
|
|
|
|
self.assertEqual(self.state(),{})
|
|
|
|
|
|
self.fire();self.assertEqual(self.state()['count'],1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_first_cancels_buy_but_preserves_sell(self):
|
|
|
|
|
|
pms_repo.insert_instruction(instruction_id='BUY',origin_type='proposal',origin_id=None,ts_code=CODE,action='ADD',side='buy',qty=100,status='PROPOSED')
|
|
|
|
|
|
pms_repo.insert_instruction(instruction_id='SELL',origin_type='plan',origin_id=None,ts_code=CODE,action='TRIM',side='sell',qty=100,status='PROPOSED')
|
|
|
|
|
|
self.fire()
|
|
|
|
|
|
self.assertEqual(pms_repo.get_instruction('BUY')['status'],'CANCELLED')
|
|
|
|
|
|
self.assertEqual(pms_repo.get_instruction('SELL')['status'],'PROPOSED')
|
|
|
|
|
|
self.assertIsNotNone(pms_repo.instruction_buy_stop('BUY'))
|
|
|
|
|
|
|
|
|
|
|
|
def test_existing_sell_finishes_before_full_exit(self):
|
|
|
|
|
|
pms_repo.insert_instruction(instruction_id='SELL',origin_type='plan',origin_id=None,ts_code=CODE,action='TRIM',side='sell',qty=100,status='PROPOSED')
|
|
|
|
|
|
self.fire();self.fire(2);self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
pms_repo.update_instruction('SELL',status='CONFIRMED')
|
|
|
|
|
|
self.change('UPDATE pms_position SET total_qty=1500,avail_qty=1500')
|
|
|
|
|
|
self.change('UPDATE pms_lot SET qty=1500')
|
|
|
|
|
|
service.drive(CODE,now=NOW)
|
|
|
|
|
|
self.assertEqual(self.instructions()[0]['qty'],1500)
|
|
|
|
|
|
|
|
|
|
|
|
def test_pending_order_even_with_terminal_parent_prevents_double_sell(self):
|
|
|
|
|
|
pms_repo.insert_instruction(instruction_id='OLD',origin_type='strategy',origin_id=None,ts_code=CODE,action='TRIM',side='sell',qty=100,status='CANCELLED')
|
|
|
|
|
|
self.insert('pms_qmt_order',dict(instruction_id='CHILD',parent_id='OLD',ts_code=CODE,side='sell',status='ACCEPTED'))
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_pending_ledger_and_correction_hold_wait(self):
|
|
|
|
|
|
self.fire();self.pending=1;self.fire(2)
|
|
|
|
|
|
self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.pending=0
|
|
|
|
|
|
with patch.object(execution_orders,'correction_blocker',return_value='修正待核实'):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):service.drive(CODE,now=NOW)
|
|
|
|
|
|
self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
service.drive(CODE,now=NOW);self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancelled_exit_is_not_reopened(self):
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
pms_repo.update_instruction(self.instructions()[0]['instruction_id'],status='CANCELLED')
|
|
|
|
|
|
service.drive(CODE,now=NOW)
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'MANUAL');self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
service.resume_buy(CODE)
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'WATCH')
|
|
|
|
|
|
self.assertIsNone(service.buy_blocker(CODE))
|
|
|
|
|
|
|
|
|
|
|
|
def test_late_buy_after_flat_is_still_closed_out(self):
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
iid=self.instructions()[0]['instruction_id'];pms_repo.update_instruction(iid,status='CONFIRMED',exec_qty=1600)
|
|
|
|
|
|
self.change('UPDATE pms_position SET total_qty=0,avail_qty=0');self.change("UPDATE pms_lot SET qty=0,status='CLOSED'")
|
|
|
|
|
|
service.scan(now=NOW);self.assertEqual(self.state()['phase'],'CLOSED')
|
|
|
|
|
|
self.insert('pms_lot',dict(id=2,book_id='original',ts_code=CODE,instruction_id='BASE',qty=100,status='OPEN'))
|
|
|
|
|
|
self.change('UPDATE pms_position SET total_qty=100,avail_qty=0')
|
|
|
|
|
|
service.scan(now=NOW)
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),2);self.assertEqual(self.instructions()[0]['qty'],100)
|
|
|
|
|
|
|
|
|
|
|
|
def test_new_holding_round_does_not_inherit_old_signal(self):
|
|
|
|
|
|
self.fire();old=self.state()['round_id']
|
|
|
|
|
|
self.change("UPDATE pms_lot SET qty=0,status='CLOSED'")
|
|
|
|
|
|
self.insert('pms_lot',dict(id=2,book_id='original',ts_code=CODE,instruction_id='NEW',qty=1600,status='OPEN'))
|
|
|
|
|
|
service.observe_review(CODE,review(),now=NOW)
|
|
|
|
|
|
self.assertNotEqual(self.state()['round_id'],old);self.assertEqual(self.state()['count'],0)
|
|
|
|
|
|
self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_human_resume_resets_count_but_cannot_undo_started_exit(self):
|
|
|
|
|
|
self.fire();service.resume_buy(CODE)
|
|
|
|
|
|
self.assertIsNone(service.buy_blocker(CODE));self.assertEqual(self.state()['count'],0)
|
|
|
|
|
|
self.fire();self.assertEqual(self.state()['count'],0) # 已处理的旧信号不得重算。
|
|
|
|
|
|
self.change("DELETE FROM pms_rotation_document WHERE doc_id LIKE 'risk-exit:%'")
|
|
|
|
|
|
self.fire();self.fire(2)
|
|
|
|
|
|
with self.assertRaises(ValueError):service.resume_buy(CODE)
|
|
|
|
|
|
|
|
|
|
|
|
def test_legacy_pause_only_seeds_one_real_signal(self):
|
|
|
|
|
|
reason='风控 SELL 置信度 95% ≥ 85%, 清仓 1600 股 —— 旧真实研判'
|
|
|
|
|
|
strategy_service.pause_buy(CODE,reason=reason,source='intraday')
|
|
|
|
|
|
pms_repo.insert_proposal(proposal_id='LEGACY',ts_code=CODE,action='EXIT',qty=1600,
|
|
|
|
|
|
hard_numbers={'on_strategy':True,'confidence':.95,'signal_source':'intraday','reason':'策略暂停。 —— '+reason},
|
|
|
|
|
|
expire_at=NOW+dt.timedelta(days=1),judge_verdict='STRATEGY_RISK')
|
|
|
|
|
|
self.change("UPDATE pms_proposal SET created_at='2026-11-05 10:00:00'")
|
|
|
|
|
|
service.observe_review(CODE,review(),now=NOW)
|
|
|
|
|
|
self.assertEqual(self.state()['count'],1);self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
self.fire(2)
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
self.assertEqual(pms_repo.get_proposal('LEGACY')['status'],'EXPIRED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_signal_handler_bypasses_legacy_daily_dedup_and_pending_proposal(self):
|
|
|
|
|
|
view={'positions':[{'ts_code':CODE,'total_qty':1600,'avail_qty':1600}]}
|
|
|
|
|
|
prm={'sell_conf_min':.6,'auto_exit_conf':.85,'trim_ratio':.3333}
|
|
|
|
|
|
seen={signal_rules.dedup_key(signal(),20261105):None}
|
|
|
|
|
|
class Clock(dt.datetime):
|
|
|
|
|
|
@classmethod
|
|
|
|
|
|
def now(cls,tz=None):return NOW
|
|
|
|
|
|
with patch.object(service,'datetime',Clock):
|
|
|
|
|
|
out={'ignored':0}
|
|
|
|
|
|
signal_service._handle(signal(),view,prm,seen,20261105,False,out,{CODE})
|
|
|
|
|
|
signal_service._handle(signal(2),view,prm,seen,20261105,False,out,{CODE})
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_independent_review_refresh_and_timeout_keep_baseline(self):
|
|
|
|
|
|
from app.services import plan_feed
|
|
|
|
|
|
with patch.object(plan_feed,'fetch_logic_states',return_value={CODE:{'company_review':review('中','b',1)}}) as fetch:
|
|
|
|
|
|
out=service.refresh_reviews(now=NOW)
|
|
|
|
|
|
self.assertTrue(out['ok']);self.assertEqual(out['reviews'][CODE],'downgrade')
|
|
|
|
|
|
fetch.assert_called_once_with([CODE],timeout=3)
|
|
|
|
|
|
self.assertEqual(self.instructions(),[]) # 刷新只记意图,委托留给执行任务。
|
|
|
|
|
|
service.refresh_reviews(now=NOW+dt.timedelta(seconds=60))
|
|
|
|
|
|
self.assertEqual(fetch.call_count,1)
|
|
|
|
|
|
with patch.object(plan_feed,'fetch_logic_states',side_effect=TimeoutError):
|
|
|
|
|
|
out=service.refresh_reviews(now=NOW+dt.timedelta(minutes=6))
|
|
|
|
|
|
self.assertFalse(out['ok']);self.assertEqual(self.state()['review']['grade'],'中')
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'EXIT_PENDING')
|
|
|
|
|
|
service.scan(now=NOW)
|
|
|
|
|
|
self.assertEqual(len(self.instructions()),1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_refresh_missing_rows_and_disabled_do_not_manufacture_downgrade(self):
|
|
|
|
|
|
from app.services import plan_feed
|
|
|
|
|
|
with patch.object(plan_feed,'fetch_logic_states',return_value={}) as fetch:
|
|
|
|
|
|
out=service.refresh_reviews(now=NOW)
|
|
|
|
|
|
self.assertEqual(out['reviews'][CODE],'missing')
|
|
|
|
|
|
self.assertEqual(self.state()['review']['grade'],'好')
|
|
|
|
|
|
self.params['PMS_RISK_EXIT_ENABLED']=False
|
|
|
|
|
|
service.refresh_reviews(now=NOW+dt.timedelta(minutes=6))
|
|
|
|
|
|
self.assertEqual(fetch.call_count,1)
|
|
|
|
|
|
self.assertEqual(self.instructions(),[])
|
|
|
|
|
|
|
|
|
|
|
|
def test_failed_unfreeze_command_cannot_clear_risk_pause(self):
|
|
|
|
|
|
from app.services import command_service
|
|
|
|
|
|
self.fire()
|
|
|
|
|
|
with patch.object(command_service,'active_commands',return_value=[]), \
|
|
|
|
|
|
patch.object(pms_repo,'next_command_seq',return_value=1), \
|
|
|
|
|
|
patch.object(pms_repo,'insert_command',return_value=1), \
|
|
|
|
|
|
patch.object(pms_repo,'update_command',return_value=1), \
|
|
|
|
|
|
patch.object(command_service,'_apply_param',return_value={'ok':False}):
|
|
|
|
|
|
result=command_service.issue('UNFREEZE_STOCK',{'ts_code':CODE})
|
|
|
|
|
|
self.assertFalse(result['ok'])
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'STOP_BUY')
|
|
|
|
|
|
self.assertIn('risk_exit',strategy_service.buypause_map()[CODE]['sources'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_new_buy_command_does_not_silently_reset_stop(self):
|
|
|
|
|
|
from app.services import command_service
|
|
|
|
|
|
self.fire()
|
|
|
|
|
|
with patch.object(command_service,'active_commands',return_value=[]), \
|
|
|
|
|
|
patch.object(pms_repo,'next_command_seq',return_value=1), \
|
|
|
|
|
|
patch.object(pms_repo,'insert_command',return_value=1), \
|
|
|
|
|
|
patch.object(pms_repo,'get_command',return_value={}), \
|
|
|
|
|
|
patch.object(command_service,'plan_command',return_value={'ok':False}):
|
|
|
|
|
|
command_service.issue('OPEN_TARGET',{'ts_code':CODE,'target_ratio':.05})
|
|
|
|
|
|
self.assertEqual(self.state()['phase'],'STOP_BUY')
|
|
|
|
|
|
|
|
|
|
|
|
def test_refresh_runs_independently_of_reprice_switch(self):
|
|
|
|
|
|
from app import scheduler
|
|
|
|
|
|
self.params['PMS_EXEC_REPRICE_ENABLED']=False
|
|
|
|
|
|
fn=scheduler.execution_basis_refresh.run
|
|
|
|
|
|
while hasattr(fn,'__wrapped__'):fn=fn.__wrapped__
|
|
|
|
|
|
with patch.object(service,'refresh_reviews',return_value={'ok':True,'reviews':{CODE:'same'}}) as fresh:
|
|
|
|
|
|
result=fn()
|
|
|
|
|
|
fresh.assert_called_once()
|
|
|
|
|
|
self.assertEqual(result['risk_reviews']['reviews'],{CODE:'same'})
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-11 12:04:55 +08:00
|
|
|
|
class DisplayTests(unittest.TestCase):
|
2026-11-16 12:21:33 +08:00
|
|
|
|
def setUp(self):
|
|
|
|
|
|
from app.services import timing_state, timing_fusion
|
|
|
|
|
|
self.latest = self.enterContext(patch.object(timing_state, 'latest', return_value=None))
|
|
|
|
|
|
self.enterContext(patch.object(timing_fusion, 'enabled', return_value=True))
|
|
|
|
|
|
|
2026-11-11 12:04:55 +08:00
|
|
|
|
def test_first_stop_without_strategy_is_visible(self):
|
|
|
|
|
|
rows=[{'ts_code':CODE,'total_qty':100}]
|
2026-11-16 11:41:27 +08:00
|
|
|
|
with patch.object(service,'supported',return_value=True), patch.object(service,'enabled',return_value=True), patch.object(store,'get',return_value=({'phase':'STOP_BUY','reason':'第一次信号'},1)):
|
2026-11-11 12:04:55 +08:00
|
|
|
|
service.decorate_positions(rows)
|
|
|
|
|
|
self.assertEqual(rows[0]['exit_status_text'],'只卖不买')
|
|
|
|
|
|
|
|
|
|
|
|
def test_exit_stages_are_not_mislabelled_as_add(self):
|
|
|
|
|
|
for phase,text in [('EXIT_PENDING','等待清仓'),('EXITING','清仓中'),('MANUAL','退出待处理')]:
|
|
|
|
|
|
rows=[{'ts_code':CODE,'total_qty':100}]
|
2026-11-16 11:41:27 +08:00
|
|
|
|
with patch.object(service,'supported',return_value=True), patch.object(service,'enabled',return_value=True), patch.object(store,'get',return_value=({'phase':phase},1)):
|
2026-11-11 12:04:55 +08:00
|
|
|
|
service.decorate_positions(rows)
|
|
|
|
|
|
self.assertEqual(rows[0]['exit_status_text'],text)
|
|
|
|
|
|
|
|
|
|
|
|
def test_failure_is_visible_without_changing_trade_state(self):
|
|
|
|
|
|
rows=[{'ts_code':CODE,'total_qty':100}]
|
2026-11-16 11:41:27 +08:00
|
|
|
|
with patch.object(service,'supported',return_value=True), patch.object(service,'enabled',return_value=True), patch.object(store,'get',side_effect=ValueError('unavailable')):
|
2026-11-11 12:04:55 +08:00
|
|
|
|
service.decorate_positions(rows)
|
|
|
|
|
|
self.assertEqual(rows[0]['exit_status_text'],'退出状态待核实')
|
|
|
|
|
|
|
|
|
|
|
|
def test_disabled_and_empty_positions_do_not_read_state(self):
|
2026-11-16 11:41:27 +08:00
|
|
|
|
with patch.object(service,'supported',return_value=False), patch.object(store,'get') as get:
|
2026-11-11 12:04:55 +08:00
|
|
|
|
service.decorate_positions([{'ts_code':CODE,'total_qty':100}]);get.assert_not_called()
|
2026-11-16 11:41:27 +08:00
|
|
|
|
with patch.object(service,'supported',return_value=True), patch.object(service,'enabled',return_value=True), patch.object(store,'get') as get:
|
2026-11-11 12:04:55 +08:00
|
|
|
|
service.decorate_positions([{'ts_code':CODE,'total_qty':0}]);get.assert_not_called()
|
|
|
|
|
|
|
2026-11-16 12:21:33 +08:00
|
|
|
|
def test_timing_read_failure_preserves_stop_and_original_reason(self):
|
|
|
|
|
|
self.latest.side_effect = ValueError('unavailable')
|
|
|
|
|
|
rows = [{'ts_code': CODE, 'total_qty': 100}]
|
|
|
|
|
|
state = {'phase': 'STOP_BUY', 'reason': '首次停买原文'}
|
|
|
|
|
|
with patch.object(service, 'supported', return_value=True), patch.object(service, 'enabled', return_value=True), patch.object(store, 'get', return_value=(state, 1)):
|
|
|
|
|
|
service.decorate_positions(rows, now=NOW)
|
|
|
|
|
|
self.assertEqual(rows[0]['exit_status_text'], '只卖不买')
|
|
|
|
|
|
self.assertEqual(rows[0]['exit_status_reason'], '首次停买原文')
|
|
|
|
|
|
self.assertIn('读取失败', rows[0]['exit_detail']['current'])
|
|
|
|
|
|
self.assertEqual(state, {'phase': 'STOP_BUY', 'reason': '首次停买原文'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ExitPresentationTests(unittest.TestCase):
|
|
|
|
|
|
def event(self, action='SELL', at=NOW, n=1):
|
|
|
|
|
|
from app.core import timing_fusion_contract as contract
|
|
|
|
|
|
sign = {'SELL': -1, 'BUY': 1, 'WAIT': 0}[action]
|
|
|
|
|
|
groups = {name: {'weight': 1/3, 'direction': sign, 'state': 'VALID', 'evidence': [
|
|
|
|
|
|
{'group': name, 'ts_code': CODE, 'at': at.isoformat(),
|
|
|
|
|
|
'expires_at': (at+dt.timedelta(minutes=30)).isoformat(), 'identity': core.digest([name, n])}]}
|
|
|
|
|
|
for name in contract.GROUPS}
|
|
|
|
|
|
return {'source': 'timing_fusion', 'version': contract.VERSION, 'ts_code': CODE,
|
|
|
|
|
|
'key': core.digest([action, n]), 'action': action, 'score': sign,
|
|
|
|
|
|
'at': at.isoformat(), 'verified_at': at.isoformat(),
|
|
|
|
|
|
'expires_at': (at+dt.timedelta(seconds=100)).isoformat(), 'groups': groups}
|
|
|
|
|
|
|
|
|
|
|
|
def render(self, current=None, state=None, now=NOW):
|
|
|
|
|
|
from app.core.exit_presentation import view
|
|
|
|
|
|
return view(state or {'phase': 'STOP_BUY', 'events': [self.event()]}, current,
|
|
|
|
|
|
fusion_enabled=True, now=now)
|
|
|
|
|
|
|
|
|
|
|
|
def test_expired_cannot_displace_valid_current_or_become_neutral(self):
|
|
|
|
|
|
self.assertIn('没有有效', self.render(self.event(), now=NOW+dt.timedelta(minutes=2))['current'])
|
|
|
|
|
|
fresh = self.event('BUY', NOW+dt.timedelta(minutes=2), 2)
|
|
|
|
|
|
self.assertIn('当前择时看多', self.render(fresh, now=NOW+dt.timedelta(minutes=2))['current'])
|
|
|
|
|
|
self.assertIn('仍待', self.render(fresh, now=NOW+dt.timedelta(minutes=2))['current'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_unknown_is_not_neutral(self):
|
|
|
|
|
|
e = self.event('WAIT')
|
|
|
|
|
|
for g in e['groups'].values():
|
|
|
|
|
|
g.update(state='UNKNOWN', evidence=[])
|
|
|
|
|
|
self.assertEqual(self.render(e)['current'].count('暂不可用'), 3)
|
|
|
|
|
|
self.assertNotIn('中性', self.render(e)['current'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_wait_shows_neutral_conflict_and_partial_coverage(self):
|
|
|
|
|
|
e = self.event('WAIT')
|
|
|
|
|
|
self.assertEqual(self.render(e)['current'].count('中性'), 3)
|
|
|
|
|
|
e['groups']['qrs']['direction'] = -1
|
|
|
|
|
|
e['groups']['main_fund']['direction'] = 1
|
|
|
|
|
|
e['groups']['v3f'].update(state='UNKNOWN', evidence=[])
|
|
|
|
|
|
detail = self.render(e)['current']
|
|
|
|
|
|
self.assertIn('量化择时看空', detail)
|
|
|
|
|
|
self.assertIn('主力资金看多', detail)
|
|
|
|
|
|
self.assertIn('资金异动暂不可用', detail)
|
|
|
|
|
|
self.assertIn('尚未形成', detail)
|
|
|
|
|
|
|
|
|
|
|
|
def test_duplicate_and_one_new_group_cannot_be_displayed_as_confirmation(self):
|
|
|
|
|
|
old = self.event()
|
|
|
|
|
|
self.assertIn('不足以构成第二次', self.render(old)['current'])
|
|
|
|
|
|
later = NOW+dt.timedelta(seconds=30)
|
|
|
|
|
|
fresh = self.event(at=later, n=2)
|
|
|
|
|
|
fresh['groups']['qrs'] = old['groups']['qrs']
|
|
|
|
|
|
fresh['groups']['v3f'] = old['groups']['v3f']
|
|
|
|
|
|
self.assertIn('不足以构成第二次', self.render(fresh, now=later)['current'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_two_new_groups_wait_for_existing_state_machine_not_fake_exit(self):
|
|
|
|
|
|
later = NOW+dt.timedelta(seconds=30)
|
|
|
|
|
|
detail = self.render(self.event(at=later, n=2), now=later)
|
|
|
|
|
|
self.assertEqual(detail['status'], '只卖不买')
|
|
|
|
|
|
self.assertIn('等待退出纪律处理', detail['current'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_original_audit_unchanged_and_legacy_first_supported(self):
|
|
|
|
|
|
state = {'phase': 'STOP_BUY', 'events': [{'source': 'intraday', 'at': NOW.isoformat(), 'reason': '原始依据'}]}
|
|
|
|
|
|
before = copy.deepcopy(state)
|
|
|
|
|
|
detail = self.render(self.event(), state)
|
|
|
|
|
|
self.assertEqual(detail['first_reason'], '原始依据')
|
|
|
|
|
|
self.assertEqual(detail['first_at'], '2026-11-05 10:00:00')
|
|
|
|
|
|
self.assertEqual(state, before)
|
|
|
|
|
|
|
|
|
|
|
|
def test_exit_and_manual_stop_do_not_wait_for_second_signal(self):
|
|
|
|
|
|
for phase in ('EXIT_PENDING', 'EXITING', 'MANUAL', 'CLOSED'):
|
|
|
|
|
|
detail = self.render(state={'phase': phase, 'user_stop': {'price': 10}, 'reason': '人工止损触价'})
|
|
|
|
|
|
self.assertNotIn('current', detail)
|
|
|
|
|
|
self.assertNotIn('第二次', detail['next'])
|
|
|
|
|
|
self.assertEqual(detail['reason'], '人工止损触价')
|
|
|
|
|
|
|
2026-11-11 12:04:55 +08:00
|
|
|
|
|
2026-11-05 12:23:33 +08:00
|
|
|
|
if __name__=='__main__':unittest.main()
|