"""期末合成结算替换末快照;强制记账不证明当天可交易。""" from decimal import Decimal as D import json def run(active_exit=False,force=True,terminal_blocked=False): cash,quantity,fees=D(1000),0,D(0);fills=[];snapshots=[] closes=[D(10),D(11),D(12)] cash-=401;quantity=40;fees+=1;fills.append([0,'buy',40,'10','1','signal']) def close(i,mark,reason): nonlocal cash,quantity,fees if not quantity:return price=mark*(1-D('.01'));q=quantity cash+=q*price-1;quantity=0;fees+=1 fills.append([i,'sell',q,str(price),'1',reason]) for i,mark in enumerate(closes): if active_exit and i==1:close(i,mark,'signal') snapshots.append({'i':i,'cash':str(cash),'quantity':quantity, 'mark':str(mark),'unrealized':str(quantity*(mark-10)), 'equity':str(cash+quantity*mark)}) before=dict(snapshots[-1]) if force: close(2,closes[-1],'end_of_backtest') snapshots[-1]={'i':2,'cash':str(cash),'quantity':quantity,'mark':str(closes[-1]), 'unrealized':'0','equity':str(cash)} count=len(fills);cash_before,fees_before=cash,fees if force:close(2,closes[-1],'end_of_backtest') assert (len(fills),cash,fees)==(count,cash_before,fees_before) return {'before_terminal':before,'snapshots':snapshots,'fills':fills,'ending_cash':str(cash), 'quantity':quantity,'fees':str(fees),'terminal_execution_verified':False, 'terminal_market_blocked':terminal_blocked, 'accounting_policy':'synthetic terminal settlement may bypass ordinary eligibility'} result=run() assert result['fills']==[[0,'buy',40,'10','1','signal'],[2,'sell',40,'11.88','1','end_of_backtest']] assert result['before_terminal']=={'i':2,'cash':'599','quantity':40,'mark':'12','unrealized':'80','equity':'1079'} assert len(result['snapshots'])==3 and result['snapshots'][:2]==[ {'i':0,'cash':'599','quantity':40,'mark':'10','unrealized':'0','equity':'999'}, {'i':1,'cash':'599','quantity':40,'mark':'11','unrealized':'40','equity':'1039'}] assert D(result['ending_cash'])==D(result['snapshots'][-1]['equity'])==D('1073.20') assert result['snapshots'][-1]['unrealized']=='0' and result['quantity']==0 and result['fees']=='2' assert D(1079)-D(result['ending_cash'])==40*(D(12)-D('11.88'))+1==D('5.80') assert D(result['ending_cash'])-1000==40*(D('11.88')-10)-2==D('73.20') marked=run(force=False) assert marked['quantity']==40 and marked['snapshots'][-1]['equity']=='1079' and marked['fees']=='1' active=run(active_exit=True) assert active['fills']==[[0,'buy',40,'10','1','signal'],[1,'sell',40,'10.89','1','signal']] assert D(active['ending_cash'])==D('1033.60') and active['fees']=='2' and active['quantity']==0 assert not any(f[-1]=='end_of_backtest' for f in active['fills']) blocked=run(terminal_blocked=True) assert blocked['ending_cash']==result['ending_cash'] and blocked['terminal_market_blocked'] assert not blocked['terminal_execution_verified'] print(json.dumps({'terminal_settlement':result,'marked_only_reference':marked, 'strategy_exit_control':active,'blocked_terminal_control':blocked, 'scope':'synthetic settlement accounting, not an executable halt or T+1 bypass'}))