tradingSystem/scripts/test_buy_budget.py

375 lines
20 KiB
Python

"""试探资金预算端到端边界:所有仓储、行情及账户锁均隔离。"""
import unit_test_guard
import copy
import datetime as dt
import sys
import threading
import unittest
from concurrent.futures import ThreadPoolExecutor
from contextlib import nullcontext, contextmanager
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core import buy_budget as core, strategy_book as books
from app.services import buy_budget as service, advice_service, proposal_service as ps, execution_orders
from app.repo import pms_repo, qmt_repo, execution_repo
from config.settings import settings
CODE = '600000.SH'
def hard(price=50, amount=60000, pct=.06, target=.01, tier='试探仓'):
return {'price': price, 'target_amount': amount, 'target_pct': pct,
'advice': {'tier': tier, 'target_pct': target, 'splits': (1.0,),
'mechanical': {'target_pct': .06, 'splits': (.5,.25,.25)}}}
def budget(code=CODE, price=50, amount=60000):
h = hard(price, amount)
return core.resize(h['advice'], h, code)['buy_budget']
class BudgetMath(unittest.TestCase):
def test_jpt_minimum_returns_zero_and_preserves_15695(self):
h=hard(313.9,94170)
r=core.resize(h['advice'],h,'688025.SH')
self.assertEqual((r['qty'],r['target_amount'],r['base_amount']),(0,15695,0))
self.assertEqual(r['buy_budget']['amount'],'15695.00')
self.assertEqual(r['minimum_order_amount'],62780)
self.assertIn('需62780.00元',r['note'])
def test_exact_hundred_and_one_cent_short(self):
for amount,expected in [('407.00',100),('406.99',0)]:
h=hard('4.07',amount,.01)
self.assertEqual(core.resize(h['advice'],h,CODE)['qty'],expected)
def test_same_tier_rechecks_oversized_quantity(self):
h=hard(50,10000,.01)
r=core.resize(h['advice'],h,CODE)
with self.assertRaises(ValueError):core.check_quantity(r['buy_budget'],CODE,800,50)
def test_bad_numeric_inputs_cannot_produce_quantity(self):
for key in ('price','target_amount','target_pct'):
for value in (None,0,-1,'NaN','Infinity','bad'):
h=hard();h[key]=value
with self.subTest(key=key,value=value),self.assertRaises(ValueError):core.resize(h['advice'],h,CODE)
def test_original_budget_not_rounded_down_to_executable_cost(self):
h=hard(48.55,120000)
r=core.resize(h['advice'],h,CODE)
self.assertEqual((r['qty'],r['base_amount'],r['target_amount']),(400,19420,20000))
def test_standard_batches_merge_to_sixty_forty_within_budget(self):
h=hard(100,30000,.06,target=.06,tier='标准仓')
h['advice']['splits']=(.5,.25,.25)
r=core.resize(h['advice'],h,CODE)
self.assertEqual((r['qty'],r['batch_scheme'],r['target_amount']),(100,'0.6,0.4',30000))
self.assertIn('原预算内',r['note'])
def test_star_batches_merge_to_one_without_raising_amount(self):
h=hard(150,60000,.06,target=.06,tier='标准仓')
h['advice']['splits']=(.5,.25,.25)
r=core.resize(h['advice'],h,'688001.SH')
self.assertEqual((r['qty'],r['batch_scheme'],r['target_amount']),(400,'1.0',60000))
def test_disabled_merge_preserves_explicit_batch_constraint(self):
h=hard(100,30000,.06,target=.06,tier='标准仓')
h['advice']['splits']=(.5,.25,.25);h['min_lot_merge']=False
r=core.resize(h['advice'],h,CODE)
self.assertEqual(r['qty'],0)
self.assertFalse(r['buy_budget']['min_lot_merge'])
def test_merged_scheme_also_updates_advice_text(self):
h=hard(100,30000,.06,target=.06,tier='标准仓')
h['advice']['splits']=(.5,.25,.25)
c={'action':'OPEN','ts_code':CODE,'qty':100}
with patch.object(ps.param_store,'get_int',return_value=60):
ps._apply_advice_tier(c,h,{'verdict':'PASS','confidence':90})
self.assertEqual(h['advice']['splits'],(.6,.4))
self.assertIn('60%/40%',h['advice_text'])
def test_refresh_price_scale_or_tier_cannot_raise_budget(self):
h=hard();h['buy_budget']=budget();h.update(sizing_scale=3000000,target_amount=180000)
h['advice'].update(tier='标准仓',target_pct=.06,splits=(.5,.25,.25))
r=core.resize(h['advice'],h,CODE)
self.assertEqual((r['buy_budget']['amount'],r['buy_budget']['tier'],r['batch_scheme']),('10000.00','试探仓','1.0'))
def test_unaccepted_zero_quantity_can_be_repriced_within_same_budget(self):
h=hard(150,120000)
h['buy_budget']=core.resize(h['advice'],h,'688001.SH')['buy_budget']
h['price']=90
r=core.resize(h['advice'],h,'688001.SH')
self.assertEqual((r['qty'],r['target_amount']),(200,20000))
def test_tampered_revision_and_wrong_symbol_refuse(self):
b=budget();b['amount']='50000'
with self.assertRaises(ValueError):core.validate(b,CODE)
with self.assertRaises(ValueError):core.validate(budget(),'688025.SH')
def test_force_trial_updates_text_ratio_amount_quantity(self):
h=hard(tier='标准仓',target=.06)
c={'action':'OPEN','ts_code':CODE,'qty':600}
with patch.object(ps.param_store,'get_int',return_value=60):
ps._apply_advice_tier(c,h,{'verdict':'PASS','confidence':90},force_trial=True)
self.assertEqual((c['qty'],h['target_pct'],h['target_amount'],h['batch_scheme']),(200,.01,10000,'1.0'))
self.assertIn('1.0%',h['advice_text'])
def test_resize_exception_does_not_keep_old_buy(self):
c={'action':'OPEN','ts_code':CODE,'qty':1000}
with patch.object(ps.param_store,'get_int',return_value=60),patch.object(advice_service,'resize_to_advice',side_effect=RuntimeError('failure')):
with self.assertRaises(RuntimeError):ps._apply_advice_tier(c,hard(),{'verdict':'PASS'})
def test_sell_does_not_consult_buy_budget(self):
c={'action':'EXIT','ts_code':CODE,'qty':100}
self.assertEqual(ps._apply_advice_tier(c,{},{}),({},100,False))
class ServiceBudget(unittest.TestCase):
def setUp(self):
self.parents={};self.orders=[];self.rows=[];self.ledger=[];self.pos={};self.plans={};self.commands={}
self.lock=threading.RLock()
self.mock(settings,'INFRA_STRATEGY_BOOK_SCHEMA',True)
self.mock(execution_orders,'account_guard',side_effect=lambda:self.lock)
self.mock(pms_repo,'get_position',side_effect=lambda code:copy.deepcopy(self.pos))
self.mock(pms_repo,'list_lots',side_effect=lambda *a,**kw:copy.deepcopy(self.rows))
self.mock(pms_repo,'get_instruction',side_effect=lambda iid:copy.deepcopy(self.parents.get(iid)))
self.mock(pms_repo,'list_instructions',side_effect=lambda **kw:[copy.deepcopy(p) for p in self.parents.values() if p.get('status') in kw.get('statuses',service.LIVE)])
self.mock(pms_repo,'ledger_by_ref',side_effect=lambda refs,**kw:copy.deepcopy([r for r in self.ledger if r['ref_id'] in refs]))
self.mock(pms_repo,'get_proposal',return_value=None)
self.mock(pms_repo,'get_plan',side_effect=lambda pid:copy.deepcopy(self.plans.get(pid)))
self.mock(pms_repo,'get_command',side_effect=lambda cid:copy.deepcopy(self.commands.get(cid)))
self.mock(qmt_repo,'orders_for_parent',side_effect=lambda pid:copy.deepcopy([o for o in self.orders if o['parent_id']==pid]))
self.pending=self.mock(execution_repo,'pending_trades',return_value=0)
self.mock(ps.param_store,'get_int',return_value=3)
self.mock(ps.td,'ymd',return_value=20261116)
self.mock(ps.td,'window_deadline',return_value=dt.date(2026,11,18))
self.mock(pms_repo,'insert_instruction',side_effect=self.insert)
self.token=books.CURRENT.set(books.ORIGINAL);self.addCleanup(books.CURRENT.reset,self.token)
def mock(self,obj,name,*args,**kw):
p=patch.object(obj,name,*args,**kw);value=p.start();self.addCleanup(p.stop);return value
def insert(self,**kw):
iid=kw['instruction_id']
if iid in self.parents:raise ValueError('duplicate')
self.parents[iid]=copy.deepcopy(dict(kw,book_id='original',exec_qty=0))
return 1
def root(self,*,b=None,holding=100):
p={'instruction_id':'P','ts_code':CODE,'side':'buy','action':'OPEN','origin_type':'proposal',
'book_id':'original','qty':200,'exec_qty':100,'status':'PROPOSED','progress':{'buy_budget':b or budget()}}
self.parents['P']=p
if holding:
self.pos={'total_qty':holding,'opened_date':'2026-11-05'}
self.rows=[{'id':1,'ts_code':CODE,'lot_type':'BASE','qty':holding,'open_date':'2026-11-05','instruction_id':'P','status':'OPEN'}]
return p
def filled(self,qty=100,price=50,status='CANCELLED'):
self.orders.append({'instruction_id':'P_D01','parent_id':'P','qty':200,'cum_qty':qty,
'cum_avg_price':price,'limit_price':50,'status':status})
for row in self.rows:
if row['instruction_id']=='P':row.update(open_price=price,closed_qty=max(0,qty-row['qty']))
def test_part_fill_then_price_rise_caps_remaining_money(self):
p=self.root();self.filled()
self.assertEqual(service.allowed_quantity(p,51,100)[0],0)
self.assertEqual(service.allowed_quantity(p,50,100),(100,''))
def test_filled_amount_is_not_double_counted_with_booked_quantity(self):
p=self.root();self.filled(100,49)
self.assertEqual(service.allowed_quantity(p,51,100),(100,''))
def test_live_partial_and_unconfirmed_cancel_do_not_release(self):
for status in ('PARTIAL','ACCEPTED','SENT'):
self.orders=[];p=self.root();self.filled(status=status)
self.assertEqual(service.allowed_quantity(p,1,100)[0],0)
def test_late_trade_and_missing_child_block(self):
p=self.root();self.filled();self.pending.return_value=1
self.assertEqual(service.allowed_quantity(p,1,100)[0],0)
self.pending.return_value=0;p['progress']['children']=[{'ref':'P_D99'}]
self.assertEqual(service.allowed_quantity(p,1,100)[0],0)
def test_fill_received_before_bookkeeping_blocks(self):
p=self.root();p['exec_qty']=0;self.filled()
self.assertEqual(service.allowed_quantity(p,1,100)[0],0)
def test_missing_actual_booked_fill_price_fails_closed(self):
p=self.root();self.filled(price=None)
with self.assertRaises(ValueError):service.allowed_quantity(p,1,100)
def test_qty_increase_in_parent_cannot_expand_original_plan(self):
p=self.root(holding=0);p['qty']=1000;p['exec_qty']=0
self.assertEqual(service.allowed_quantity(p,1,1000),(200,''))
def test_flat_then_new_round_does_not_inherit_old_trial(self):
self.root()['status']='CONFIRMED';self.pos={};self.rows[0].update(status='CLOSED',qty=0)
self.assertIsNone(service.before_parent(CODE))
def test_trial_label_does_not_block_independently_approved_followup(self):
self.root()['status']='EXPIRED'
for action in ('ADD','FILL','DCA'):
p={'instruction_id':'NEXT','action':action,'side':'buy','ts_code':CODE,
'origin_type':'strategy' if action=='ADD' else 'proposal','progress':{}}
self.assertIsNone(service.before_parent(CODE,action=action))
self.assertEqual(service.allowed_quantity(p,50,100),(100,''))
def test_closed_base_does_not_turn_trial_amount_into_strategy_lifetime_cap(self):
self.root()['status']='EXPIRED';self.rows[0].update(qty=0,status='CLOSED')
self.rows.append(dict(self.rows[0],id=2,qty=100,status='OPEN',lot_type='ADD',instruction_id='GRID'))
self.assertIsNone(service.before_parent(CODE,action='ADD'))
def test_unknown_origin_or_budget_blocks_instead_of_standard_default(self):
p=self.root();p['progress']={};p['status']='EXPIRED'
with self.assertRaisesRegex(ValueError,'无法核实'):service.parent_budget(p)
def test_query_failure_restricts_buy_but_sell_continues(self):
p=self.root();self.filled()
with patch.object(pms_repo,'list_lots',side_effect=RuntimeError('offline')):
with self.assertRaises(RuntimeError):service.allowed_quantity(p,50,100)
self.assertEqual(service.allowed_quantity(dict(p,side='sell'),50,100),(100,''))
def test_new_parent_keeps_budget_in_progress(self):
h=hard();h['buy_budget']=budget()
c={'ts_code':CODE,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':h}
iid=ps._make_instruction(c,50,dt.datetime(2026,11,16,10))
self.assertEqual(self.parents[iid]['progress']['buy_budget'],h['buy_budget'])
def test_jpt_oversized_auto_and_manual_create_no_parent(self):
h=hard(313.9,62780,.04);code='688025.SH'
c={'ts_code':code,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':h}
with self.assertRaises(ValueError):ps._make_instruction(c,313.9,dt.datetime(2026,11,16,10))
with patch.object(pms_repo,'accept_open_proposal') as write:
with self.assertRaises(ValueError):service.accept_open({'ts_code':code,'qty':200},h,{'progress':{}},'confirm')
write.assert_not_called()
self.assertEqual(self.parents,{})
def test_two_concurrent_proposals_allocate_only_one_budget(self):
h=hard();h['buy_budget']=budget()
def create(second):
c={'ts_code':CODE,'action':'OPEN','side':'buy','qty':200,'reason':'test','hard_numbers':copy.deepcopy(h)}
try:return ps._make_instruction(c,50,dt.datetime(2026,11,16,10,0,second))
except ValueError:return None
with ThreadPoolExecutor(max_workers=2) as pool:result=list(pool.map(create,[1,2]))
self.assertEqual(sum(bool(x) for x in result),1)
self.assertEqual(len(self.parents),1)
def test_locked_enqueue_rechecks_updated_budget_and_leaves_no_order(self):
from app.services import rotation_execution as execution
p=self.root(holding=0);p['exec_qty']=0
payload={'instruction_id':'P_D01','ts_code':CODE,'side':'buy','qty':200,'limit_price':50}
# 报价完成后,落单前看到较小的当前预算;只能在锁内读取并拒绝。
p['progress']['buy_budget']=budget(amount=30000)
account={'orders':{}};locked=[]
@contextmanager
def guard(*args):
with self.lock:
locked.append(True)
try:yield account
finally:locked.pop()
def current(iid):
self.assertTrue(locked)
return copy.deepcopy(self.parents[iid])
with patch.object(execution.store,'locked',side_effect=guard),patch.object(qmt_repo,'get_order',return_value=None), \
patch.object(execution.param_store,'get_bool',return_value=False),patch.object(execution_orders,'correction_blocker',return_value=''), \
patch.object(pms_repo,'get_instruction',side_effect=current),patch.object(execution.db,'fetch_all') as further:
with self.assertRaises(ValueError):execution.enqueue_with_reservation(payload,'P')
further.assert_not_called()
self.assertEqual(account,{'orders':{}})
self.assertEqual(self.orders,[])
def test_legacy_jpt_uses_original_trial_amount_not_actual_oversized_parent(self):
p=self.root(holding=0);p.update(ts_code='688025.SH',exec_qty=0);p['progress']={}
self.ledger=[{'ref_id':'P','action':'OPEN','verdict':'PASS','hard_numbers':hard(313.9,62780,.04)}]
b=service.parent_budget(p)
self.assertEqual((b['amount'],b['quantity_limit']),('15695.00',0))
self.assertEqual(service.allowed_quantity(p,300,200)[0],0)
def test_legacy_trial_label_with_standard_ratio_cannot_keep_standard_budget(self):
p=self.root(holding=0);p.update(ts_code='300750.SZ',exec_qty=0);p['progress']={}
self.ledger=[{'ref_id':'P','action':'OPEN','verdict':'PASS',
'hard_numbers':hard(254.83,101932,.06,target=.06)}]
b=service.parent_budget(p)
self.assertEqual((b['amount'],b['quantity_limit']),('16988.66',0))
def test_legacy_trial_without_original_mechanical_ratio_requires_review(self):
h=hard();h['advice'].pop('mechanical')
with self.assertRaisesRegex(ValueError,'原机械目标比例'):service.from_hard(h,CODE)
def test_standard_holding_keeps_original_grid_permission(self):
h=hard(target=.06,tier='标准仓');b=core.resize(h['advice'],h,CODE)['buy_budget']
self.root(b=b)
self.assertIsNone(service.before_parent(CODE,action='ADD'))
def test_pending_trial_cannot_allocate_a_second_opening_budget(self):
p=self.root(holding=0);p['exec_qty']=0
with self.assertRaisesRegex(ValueError,'重复分配建仓预算'):service.before_parent(CODE,action='OPEN')
def test_verified_user_command_has_separate_explicit_budget(self):
self.root()['status']='EXPIRED'
p=dict(self.parents['P'],instruction_id='C',origin_type='plan',origin_id='CP',exec_qty=0,progress={})
self.parents['C']=p;self.plans['CP']={'ts_code':CODE,'command_id':'CMD','amount':12000,'qty':200}
self.commands['CMD']={'issued_by':'trader','cmd_type':'OPEN_TARGET'}
self.assertEqual(service.allowed_quantity(p,60,200),(200,''))
self.assertEqual(service.allowed_quantity(p,61,200)[0],100)
self.assertEqual(self.parents['P']['progress']['buy_budget']['amount'],'10000.00')
def test_fake_command_flag_cannot_raise_original_opening_budget(self):
p=self.root(holding=0);p['exec_qty']=0;p['progress']['is_command']=True
self.assertEqual(service.allowed_quantity(p,51,200)[0],100)
def test_other_strategy_book_keeps_its_own_budget_path(self):
p=self.root();p['book_id']='micro30'
self.assertEqual(service.allowed_quantity(p,100,200),(200,''))
def test_completed_trial_does_not_get_more_after_sale_profit(self):
p=self.root();p['exec_qty']=200;self.filled(200,45,'FILLED')
self.assertEqual(service.allowed_quantity(p,1,100)[0],0)
def test_actual_lot_total_must_match_booked_fills(self):
p=self.root();self.filled();self.rows[0]['qty']=50;self.pos['total_qty']=50
with self.assertRaisesRegex(ValueError,'累计量不一致'):service.allowed_quantity(p,1,100)
def test_current_plan_budget_wins_over_prepared_quantity(self):
p=self.root(holding=0);p['exec_qty']=0
prepared={'qty':200,'limit_price':50}
smaller=budget(amount=30000);p['progress']['buy_budget']=smaller
with self.assertRaises(ValueError):service.check_order(p,prepared)
def test_t0_uses_its_own_approved_strategy_for_both_legs(self):
self.root()
p=dict(self.parents['P'],instruction_id='T',origin_type='strategy',action='T0',
progress={'stype':'T0','leg':'close'})
self.assertEqual(service.allowed_quantity(p,50,100),(100,''))
p['progress']['leg']='open'
self.assertEqual(service.allowed_quantity(p,50,100),(100,''))
class AtomicAccept(unittest.TestCase):
def test_background_refresh_cannot_enlarge_or_remove_budget(self):
from app.db import session as db
old={'ts_code':CODE,'qty':200,'hard_numbers':{'buy_budget':budget()}}
for updated in (None,budget(amount=120000)):
hard={'preparation':{'status':'ready'},'consumption_id':1}
if updated is not None:hard['buy_budget']=updated
with patch.object(db,'get_engine',side_effect=AssertionError('must reject before write')):
with self.assertRaises(ValueError):db.publish_prepared_proposal(old,{'hard_numbers':hard}, {})
def test_accept_reuses_outer_account_transaction(self):
from app.db import session as db
calls=[]
class Connection:
def execute(self,sql,params):
calls.append(str(sql));return SimpleNamespace(rowcount=1)
token=db._TRANSACTION.set(Connection())
try:
with patch.object(db,'get_engine',side_effect=AssertionError('must reuse outer transaction')),patch.object(db,'_check_cooldown'),patch.object(db,'map_tables',side_effect=lambda sql:sql):
r=db.accept_open_proposal({'action':'OPEN','ts_code':CODE,'qty':200,'proposal_id':'PR','hard_numbers_json':'{}'},
{'price':50}, {'id':'P','window':3,'progress':{}},'test')
self.assertTrue(r);self.assertEqual(len(calls),3)
finally:db._TRANSACTION.reset(token)
if __name__=='__main__':unittest.main()