tradingSystem/scripts/rehearse_micro30.py

91 lines
6.9 KiB
Python
Raw Normal View History

"""只允许专用隔离数据库的迁移与真实SQL事务演练。不得对业务库运行。"""
import datetime as dt,json,os,sys
from pathlib import Path
from urllib.parse import urlsplit
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from sqlalchemy import text
from config.settings import settings
from app.db import session as db
from app.core import strategy_book as books,rotation_account as capital
from app.repo import pms_repo,qmt_repo,rotation_repo as store
from app.services import rotation_execution as execution
from init_db import parse_statements
from migrate_strategy_books import migrate
def main():
u=urlsplit(settings.PROXY_DB_URL)
assert u.hostname=='micro30-rehearsal-db' and u.path=='/micro30_rehearsal' and not settings.PMS_TABLE_PREFIX,'仅允许专用隔离库'
assert not settings.INFRA_STRATEGY_BOOK_SCHEMA,'演练应从旧表开始'
with db.get_engine().begin() as c:
assert not c.execute(text('SHOW TABLES')).all(),'隔离库必须为空'
for kind,table,sql in parse_statements((Path(__file__).resolve().parents[1]/'ddl_pms_v1.sql').read_text()):
assert kind!='?';c.execute(text(sql))
pms_repo.ensure_position('600000.SH');pms_repo.bump_position_qty('600000.SH',total_delta=100,avail_delta=100)
pms_repo.insert_lot(ts_code='600000.SH',lot_type='BASE',qty=100,open_price=20,open_date=dt.date(2024,1,2))
pms_repo.insert_cash_flow(ymd=20240102,kind='FEE',amount=-5,trade_no='legacy',estimated=False)
proof=migrate(True);assert all(r['applied'] for r in proof)
assert all(r['original_columns_sha256'] for r in proof)
migrate(True) # 重跑不得改历史字段或重复索引。
settings.INFRA_STRATEGY_BOOK_SCHEMA=True
with books.scope('micro30'):
pms_repo.ensure_position('600000.SH');pms_repo.bump_position_qty('600000.SH',total_delta=200,avail_delta=0)
assert pms_repo.get_position('600000.SH')['total_qty']==100
with books.scope('micro30'):assert pms_repo.get_position('600000.SH')['total_qty']==200
with books.scope('all'):assert len(pms_repo.list_positions())==2
# 清除纯隔离样例的微盘虚拟数量,后续使用真实委托与成交路径。
with books.scope('micro30'):pms_repo.update_position('600000.SH',total_qty=0)
store.put_once('state:live','state',{'rotation':{'phase':'micro'}})
cash=capital.seed(100000,{'original':2000,'micro30':0});store.put_once('capital:live','capital',cash)
params={'PMS_ROTATION_MODE':'auto','PMS_ROTATION_CONTROL':'run','PMS_TOTAL_SCALE':200000.,'PMS_PORTFOLIO_CAP':.7,'PMS_CASH_RESERVE':0.,'PMS_MICRO30_COMMISSION_RATE':.0002}
now=dt.datetime.now()
funds={'seq':100,'age_sec':0,'received_at':now,'payload':{'data':{'available_cash':100000,'frozen_cash':0,'market_value':2000,'total_asset':102000}}}
with patch('app.services.param_store.get',side_effect=lambda k,d=None:params.get(k,d)),patch('app.services.param_store.get_float',side_effect=lambda k,d=0:float(params.get(k,d))),patch('app.services.param_store.get_bool',side_effect=lambda k,d=False:bool(params.get(k,d))),patch('app.services.market.day_snapshot',return_value={'price':20,'bar_time':now.isoformat()}),patch('app.services.market.get_price',return_value=20),patch('app.repo.qmt_repo.latest_snapshot',return_value=funds):
for i in range(30):
pid='B'+str(i);code=str(600100+i)+'.SH'
with books.scope('micro30'):pms_repo.insert_instruction(instruction_id=pid,origin_type='plan',origin_id=None,ts_code=code,action='OPEN',side='buy',qty=100)
payload={'instruction_id':pid+'_D01','ts_code':code,'side':'buy','qty':100,'limit_price':10,'valid_until':int((now+dt.timedelta(hours=1)).timestamp()*1000),'intent':'OPEN'}
execution.enqueue_with_reservation(payload,pid)
execution.enqueue_with_reservation(payload,pid)
assert db.fetch_one('SELECT COUNT(*) AS n FROM pms_qmt_order')['n']==30
reserve,_=store.get('account-execution');assert len(reserve['orders'])==30
assert 30000<sum(reserve['orders'].values())<30200
# 大单资金不足不得进入出口。
with books.scope('micro30'):pms_repo.insert_instruction(instruction_id='HUGE',origin_type='plan',origin_id=None,ts_code='600199.SH',action='OPEN',side='buy',qty=10000)
try:execution.enqueue_with_reservation({**payload,'instruction_id':'HUGE_D01','ts_code':'600199.SH','qty':10000},'HUGE')
except ValueError:pass
else:raise AssertionError('超买未被拦截')
assert qmt_repo.get_order('HUGE_D01') is None
# 成交标记失败时,持仓、批次、现金和指令必须一起回滚。
qmt_repo.inbox_put(seq=1,msg_id='trade1',msg_type='trade',payload={'trade_no':'T1'},msg_ts=int(now.timestamp()*1000),processed=0)
act={'kind':'BUY','ts_code':'600100.SH','qty':100,'price':10.,'lot_type':'BASE','instruction_id':'B0','order_id':'T1'}
fees=[{'amount':-5.,'ts_code':act['ts_code'],'estimated':False,'trade_no':'T1','instruction_id':'B0','note':'演练费用'}]
with patch('app.repo.qmt_repo.inbox_mark',side_effect=RuntimeError('模拟落账尾部故障')):
try:execution.book_trade(act,fees,1)
except RuntimeError:pass
else:raise AssertionError('应发生尾部故障')
with books.scope('micro30'):
assert pms_repo.get_position('600100.SH') is None
assert pms_repo.get_instruction('B0')['exec_qty']==0
assert execution.book_trade(act,fees,1)
assert not execution.book_trade(act,fees,1)
with books.scope('micro30'):
assert pms_repo.get_position('600100.SH')['total_qty']==100
assert pms_repo.get_instruction('B0')['exec_qty']==100
assert len(pms_repo.list_lots('600100.SH'))==1
assert pms_repo.get_position('600100.SH') is None
# 子事务故障保留阶段,但不留下半条委托。
with store.locked('savepoint-test','state',{'phase':'returning_original'}) as state:
try:
with db.savepoint():
state['irrelevant']='local-memory-only'
db.execute("INSERT INTO pms_rotation_document (doc_id,kind,payload_json,revision,updated_at) VALUES ('must-rollback','test','{}',0,NOW())")
raise ValueError('演练回滚')
except ValueError:pass
assert store.get('must-rollback')[0] is None
assert store.get('savepoint-test')[0]['phase']=='returning_original'
result={'migration_tables':proof,'checks':['迁移字段哈希一致','重复迁移','同名股票分账','30股批量委托','重复委托幂等','超买拦截','成交尾部故障原子回滚','重复成交幂等','子事务回滚保留退出阶段'],'status':'PASS','environment':'155专用内部网络MariaDB,合成数据,无QMT与业务库连接'}
print(json.dumps(result,ensure_ascii=False,default=str))
if __name__=='__main__':main()