"""只允许专用隔离数据库的迁移与真实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