2026-11-09 12:08:56 +08:00
|
|
|
|
"""4%网格、真实批次、报价边界及减持余量,所有仓储均为内存桩。"""
|
|
|
|
|
|
import unit_test_guard
|
|
|
|
|
|
import copy
|
|
|
|
|
|
import datetime as dt
|
|
|
|
|
|
import sys
|
|
|
|
|
|
import unittest
|
|
|
|
|
|
from contextlib import nullcontext
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
from unittest.mock import patch
|
|
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
|
|
from app.core import grid_inventory as core, execution_policy
|
|
|
|
|
|
from app.services import grid_inventory as service, strategy_runner as runner, strategy_service
|
|
|
|
|
|
from app.repo import pms_repo
|
|
|
|
|
|
from config.settings import settings
|
|
|
|
|
|
|
|
|
|
|
|
P = dict(center=47.18, lower=46.035, upper=52.823, step_pct=.04, per_lot=1600, max_capital=76358.11)
|
|
|
|
|
|
def strategy(params=None):
|
|
|
|
|
|
return dict(strategy_id='grid', ts_code='002979.SZ', type='GRID', status='ACTIVE', params=copy.deepcopy(params or P), state={})
|
|
|
|
|
|
def records(qty=1500, price=47.28):
|
|
|
|
|
|
parent = dict(instruction_id='buy',ts_code='002979.SZ',origin_type='strategy',origin_id='grid',side='buy',action='ADD',book_id='original',progress={'leg':'grid_buy:1'})
|
2026-11-09 12:40:37 +08:00
|
|
|
|
lot = dict(id=1,ts_code='002979.SZ',lot_type='ADD',qty=qty,open_price=price,open_date='2026-11-04',instruction_id='buy',book_id='original')
|
2026-11-09 12:08:56 +08:00
|
|
|
|
return [lot], {'buy':parent}
|
|
|
|
|
|
def pos(qty=1500, avail=1600):
|
|
|
|
|
|
return dict(total_qty=qty+100,add_qty=qty,avail_qty=avail)
|
|
|
|
|
|
def evaluate(st, state, position, price, paused=False):
|
|
|
|
|
|
return runner._eval_grid(st,position,{'price':price},None,{'state':state,'notes':[],'buy_paused':paused})
|
|
|
|
|
|
|
|
|
|
|
|
class InventoryTests(unittest.TestCase):
|
|
|
|
|
|
def test_cost_is_booked_not_trigger(self):
|
|
|
|
|
|
snap=core.project(strategy(),*records());self.assertEqual(snap['filled_levels']['1']['price'],47.28)
|
|
|
|
|
|
self.assertEqual(snap['invested'],70920);self.assertEqual(snap['filled_levels']['1']['sell_target'],49.18)
|
|
|
|
|
|
def test_partial_and_unfilled_do_not_create_inventory(self):
|
|
|
|
|
|
self.assertEqual(core.project(strategy(),[],{})['invested'],0)
|
|
|
|
|
|
self.assertEqual(core.project(strategy(),*records(100))['invested'],4728)
|
|
|
|
|
|
def test_new_entry_and_exit_preserve_full_grid(self):
|
|
|
|
|
|
st=strategy();lots,parents=records();parents['buy']['progress'].update(grid_params=P,grid_entry=46.979,grid_exit=50.0)
|
|
|
|
|
|
result=core.project(st,lots,parents)['filled_levels']['1'];self.assertEqual(result['sell_target'],50)
|
|
|
|
|
|
self.assertEqual(result['entry_level'],46.979)
|
|
|
|
|
|
def test_migration_does_not_reinterpret_old_index(self):
|
|
|
|
|
|
lots,parents=records();parents['buy']['progress'].update(grid_params={**P,'step_pct':.02},grid_entry=46.979,grid_exit=47.922)
|
|
|
|
|
|
result=core.project(strategy(),lots,parents)['filled_levels']['1'];self.assertEqual(result['sell_target'],49.18);self.assertIsNone(result['entry_level'])
|
|
|
|
|
|
def test_price_correction_changes_minimum_exit(self):
|
|
|
|
|
|
self.assertEqual(core.project(strategy(),*records(price=48))['filled_levels']['1']['sell_target'],49.92)
|
|
|
|
|
|
def test_other_book_and_unknown_parent_fail_closed(self):
|
|
|
|
|
|
for field,value in [('book_id','micro30'),('instruction_id','unknown')]:
|
|
|
|
|
|
lots,parents=records();lots[0][field]=value
|
|
|
|
|
|
with self.assertRaises(ValueError):core.project(strategy(),lots,parents)
|
|
|
|
|
|
def test_foreign_add_and_unknown_cost_fail_closed(self):
|
|
|
|
|
|
lots,parents=records();parents['buy']['origin_id']='other'
|
|
|
|
|
|
with self.assertRaises(ValueError):core.project(strategy(),lots,parents)
|
|
|
|
|
|
for value in [0,-1,float('nan'),float('inf')]:
|
|
|
|
|
|
with self.assertRaises(ValueError):core.project(strategy(),*records(price=value))
|
|
|
|
|
|
def test_base_and_closed_lots_are_not_grid_inventory(self):
|
|
|
|
|
|
lots,parents=records();lots.extend([{**lots[0],'id':2,'lot_type':'BASE','instruction_id':'manual'}, {**lots[0],'id':3,'qty':0}])
|
|
|
|
|
|
self.assertEqual(len(core.project(strategy(),lots,parents)['filled_levels']),1)
|
|
|
|
|
|
def test_price_rounding_respects_direction(self):
|
|
|
|
|
|
self.assertEqual(core.price_tick(32.6248,sell=True),32.63);self.assertEqual(core.price_tick(31.372),31.37)
|
|
|
|
|
|
def test_service_requires_position_to_match_booked_lots(self):
|
|
|
|
|
|
lots,parents=records()
|
|
|
|
|
|
with patch.object(pms_repo,'list_lots',return_value=lots),patch.object(pms_repo,'get_instruction',side_effect=parents.get):
|
|
|
|
|
|
self.assertEqual(service.snapshot(strategy(),pos())['invested'],70920)
|
|
|
|
|
|
with self.assertRaises(ValueError):service.snapshot(strategy(),pos(qty=1600))
|
|
|
|
|
|
|
|
|
|
|
|
class EvaluationTests(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
self.st=strategy();self.state={**core.project(self.st,*records()),'last_band':6}
|
|
|
|
|
|
def test_leads_overdue_remainder_sells_without_new_crossing(self):
|
|
|
|
|
|
d=evaluate(self.st,self.state,pos(),51.87,paused=True)
|
|
|
|
|
|
self.assertEqual((d['qty'],d['limit_price']),(1500,49.18));self.assertEqual(self.state['filled_levels']['1']['qty'],1500)
|
|
|
|
|
|
def test_t_plus_one_retries_at_unchanged_price(self):
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st,self.state,pos(avail=0),51.87))
|
|
|
|
|
|
self.assertEqual(evaluate(self.st,self.state,pos(avail=1500),51.87)['qty'],1500)
|
|
|
|
|
|
def test_partial_fill_then_cancel_sells_only_booked_remainder(self):
|
|
|
|
|
|
self.st['params']['per_lot']=1000
|
|
|
|
|
|
self.assertEqual(evaluate(self.st,self.state,pos(),51.87)['qty'],1000)
|
|
|
|
|
|
self.state.update(core.project(self.st,*records(qty=800)))
|
|
|
|
|
|
self.assertEqual(evaluate(self.st,self.state,pos(qty=800),51.87)['qty'],800)
|
|
|
|
|
|
def test_does_not_sell_base_or_borrow_another_lot(self):
|
|
|
|
|
|
self.state.update(core.project(self.st,*records(qty=300)));self.st['params']['per_lot']=1600
|
|
|
|
|
|
self.assertEqual(evaluate(self.st,self.state,pos(qty=300,avail=800),51.87)['qty'],300)
|
2026-11-09 12:40:37 +08:00
|
|
|
|
def test_next_accounting_lot_not_yet_ready_blocks_later_lot_sale(self):
|
2026-11-09 12:08:56 +08:00
|
|
|
|
self.state['filled_levels']['1']['sell_target']=53
|
|
|
|
|
|
self.state['filled_levels']['2']={'qty':100,'price':40,'sell_target':42,'lot_id':2}
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st,self.state,pos(qty=1600),51.87))
|
|
|
|
|
|
def test_missing_target_and_excess_inventory_do_not_silently_disappear(self):
|
|
|
|
|
|
with self.assertRaises(ValueError):evaluate(self.st,self.state,pos(qty=100),51.87)
|
|
|
|
|
|
self.state['filled_levels']['1'].pop('sell_target')
|
|
|
|
|
|
with self.assertRaises(ValueError):evaluate(self.st,self.state,pos(),51.87)
|
|
|
|
|
|
def test_sifang_same_boundary_does_not_round_trip(self):
|
|
|
|
|
|
p=dict(center=31.39,lower=30.116,upper=32.825,step_pct=.04,per_lot=1000,max_capital=67730.61)
|
|
|
|
|
|
st=strategy(p);state={'last_band':1,'filled_levels':{},'invested':0}
|
|
|
|
|
|
d=evaluate(st,state,pos(0),31.37);self.assertEqual(d['grid_entry'],31.372);self.assertEqual(d['limit_price'],31.37)
|
|
|
|
|
|
lots,parents=records(1000,31.37);parents['buy']['progress'].update({k:d[k] for k in ['grid_entry','grid_exit','grid_params']})
|
|
|
|
|
|
state.update(core.project(st,lots,parents))
|
|
|
|
|
|
self.assertIsNone(evaluate(st,state,pos(1000,700),31.38))
|
|
|
|
|
|
sell=evaluate(st,state,pos(1000,700),32.63);self.assertEqual(sell['qty'],700);self.assertEqual(sell['limit_price'],32.63)
|
|
|
|
|
|
def test_paused_and_cap_limited_buys_do_not_become_inventory(self):
|
|
|
|
|
|
p=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=1000,max_capital=1)
|
|
|
|
|
|
for paused in [False,True]:
|
|
|
|
|
|
state={'last_band':3,'filled_levels':{},'invested':0}
|
|
|
|
|
|
self.assertIsNone(evaluate(strategy(p),state,pos(0),8.9,paused));self.assertEqual(state['filled_levels'],{})
|
|
|
|
|
|
def test_same_entry_is_not_bought_twice(self):
|
|
|
|
|
|
p=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000)
|
|
|
|
|
|
state={'last_band':3,'filled_levels':{'x':{'qty':100,'entry_level':9.2,'sell_target':10,'price':9.1}},'invested':910}
|
|
|
|
|
|
self.assertIsNone(evaluate(strategy(p),state,pos(100),9.1))
|
|
|
|
|
|
def test_first_tick_resets_cursor_without_buy(self):
|
|
|
|
|
|
st=strategy(dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000));state={'filled_levels':{},'invested':0}
|
|
|
|
|
|
self.assertIsNone(evaluate(st,state,pos(0),9.1));self.assertEqual(state['last_band'],2)
|
|
|
|
|
|
|
2026-11-16 09:37:01 +08:00
|
|
|
|
|
|
|
|
|
|
class InventoryOpportunityTests(unittest.TestCase):
|
|
|
|
|
|
"""11月9日至10日四方实际价位重放,只有内存批次,不发真实委托。"""
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
self.params = dict(center=31.39, lower=30.116, upper=32.825,
|
|
|
|
|
|
step_pct=.04, per_lot=1000, max_capital=67730.61)
|
|
|
|
|
|
self.st = strategy(self.params)
|
|
|
|
|
|
self.st['ts_code'] = '601126.SH'
|
|
|
|
|
|
self.lots, self.parents = records(1000, 31.37)
|
|
|
|
|
|
self.lots[0].update(ts_code='601126.SH', open_date='2026-11-09')
|
|
|
|
|
|
self.parents['buy']['ts_code'] = '601126.SH'
|
|
|
|
|
|
|
|
|
|
|
|
def state(self):
|
|
|
|
|
|
return {**core.project(self.st, self.lots, self.parents), 'last_band': 1}
|
|
|
|
|
|
|
|
|
|
|
|
def test_sifang_legacy_inventory_cannot_buy_same_line_after_migration(self):
|
|
|
|
|
|
state = self.state()
|
|
|
|
|
|
before = copy.deepcopy(state['filled_levels'])
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st, state, pos(1000, 700), 31.37))
|
|
|
|
|
|
self.assertEqual(state['filled_levels'], before)
|
|
|
|
|
|
self.assertEqual(state['invested'], 31370)
|
|
|
|
|
|
|
|
|
|
|
|
def test_parameter_revision_preserves_original_observation(self):
|
|
|
|
|
|
self.parents['buy']['progress'].update(
|
|
|
|
|
|
grid_params={**self.params, 'step_pct': .02},
|
|
|
|
|
|
grid_entry=31.372, grid_exit=31.999)
|
|
|
|
|
|
row = self.state()['filled_levels']['1']
|
|
|
|
|
|
self.assertIsNone(row['entry_level'])
|
|
|
|
|
|
self.assertEqual(row['original_entry_level'], 31.372)
|
|
|
|
|
|
self.assertTrue(core.buy_blocker({'1': row}, self.params, 31.372))
|
|
|
|
|
|
|
|
|
|
|
|
def test_percent_boundary_is_rounded_down_not_up(self):
|
|
|
|
|
|
filled = self.state()['filled_levels']
|
|
|
|
|
|
self.assertTrue(core.buy_blocker(filled, self.params, 30.12))
|
|
|
|
|
|
self.assertEqual(core.buy_blocker(filled, self.params, 30.11), '')
|
|
|
|
|
|
|
|
|
|
|
|
def test_lower_existing_lot_controls_the_next_opportunity(self):
|
|
|
|
|
|
filled = self.state()['filled_levels']
|
|
|
|
|
|
filled['2'] = {'qty': 100, 'price': 30}
|
|
|
|
|
|
self.assertTrue(core.buy_blocker(filled, self.params, 29))
|
|
|
|
|
|
self.assertEqual(core.buy_blocker(filled, self.params, 28.8), '')
|
|
|
|
|
|
|
|
|
|
|
|
def test_absolute_spacing_overrides_percent_spacing(self):
|
|
|
|
|
|
filled = self.state()['filled_levels']
|
|
|
|
|
|
params = {**self.params, 'step': 1}
|
|
|
|
|
|
self.assertTrue(core.buy_blocker(filled, params, 30.38))
|
|
|
|
|
|
self.assertEqual(core.buy_blocker(filled, params, 30.37), '')
|
|
|
|
|
|
|
|
|
|
|
|
def test_partial_sale_does_not_release_remaining_inventory(self):
|
|
|
|
|
|
self.lots[0]['qty'] = 100
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st, self.state(), pos(100), 31.37))
|
|
|
|
|
|
|
|
|
|
|
|
def test_fully_booked_sale_allows_same_price_after_new_crossing(self):
|
|
|
|
|
|
self.lots[0]['qty'] = 0
|
|
|
|
|
|
state = self.state()
|
|
|
|
|
|
decision = evaluate(self.st, state, pos(0), 31.37)
|
|
|
|
|
|
self.assertEqual((decision['side'], decision['qty'], decision['limit_price']),
|
|
|
|
|
|
('buy', 1000, 31.37))
|
|
|
|
|
|
|
|
|
|
|
|
def test_changed_center_and_quantity_do_not_release_inventory(self):
|
|
|
|
|
|
for changes in ({'center': 31.4}, {'per_lot': 500}, {'step_pct': .02}):
|
|
|
|
|
|
params = {**self.params, **changes}
|
|
|
|
|
|
self.assertTrue(core.buy_blocker(self.state()['filled_levels'], params, 31.37))
|
|
|
|
|
|
|
|
|
|
|
|
def test_restart_and_roll_day_preserve_inventory_limit(self):
|
|
|
|
|
|
state = self.state()
|
|
|
|
|
|
state.pop('last_band')
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st, state, pos(1000), 31.40))
|
|
|
|
|
|
runner._roll_day(state, pos(1000), 20261110)
|
|
|
|
|
|
self.assertIsNone(evaluate(self.st, state, pos(1000), 31.37))
|
|
|
|
|
|
|
|
|
|
|
|
def test_invalid_cost_and_spacing_cannot_allow_new_risk(self):
|
|
|
|
|
|
for cost in (0, -1, float('nan'), float('inf')):
|
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
|
|
core.buy_blocker({'1': {'qty': 100, 'price': cost}}, self.params, 30)
|
|
|
|
|
|
for pct in (0, -1, 1, float('nan'), float('inf')):
|
|
|
|
|
|
with self.assertRaises(ValueError):
|
|
|
|
|
|
core.buy_blocker(self.state()['filled_levels'], {**self.params, 'step_pct': pct}, 30)
|
|
|
|
|
|
|
|
|
|
|
|
def test_old_prepared_buy_rechecked_against_newly_booked_inventory(self):
|
|
|
|
|
|
empty = {'last_band': 1, 'filled_levels': {}, 'invested': 0}
|
|
|
|
|
|
decision = evaluate(self.st, empty, pos(0), 31.37)
|
|
|
|
|
|
with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False), \
|
|
|
|
|
|
patch.object(runner, '_current_strategy', return_value=nullcontext(self.st)), \
|
|
|
|
|
|
patch.object(pms_repo, 'list_instructions', return_value=[]), \
|
|
|
|
|
|
patch.object(pms_repo, 'get_position', return_value=pos(1000)), \
|
|
|
|
|
|
patch.object(service, 'snapshot', return_value=self.state()), \
|
|
|
|
|
|
patch.object(runner, '_buypause_codes', return_value=set()), \
|
|
|
|
|
|
patch.object(runner, '_macro_gate_active', return_value=False), \
|
|
|
|
|
|
patch.object(pms_repo, 'insert_instruction') as insert:
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError, '已有未卖出的网格仓'):
|
|
|
|
|
|
runner._emit_instruction(self.st, decision)
|
|
|
|
|
|
insert.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_existing_profit_sale_keeps_original_target_and_quantity(self):
|
|
|
|
|
|
decision = evaluate(self.st, self.state(), pos(1000, 1000), 32.63)
|
|
|
|
|
|
self.assertEqual((decision['side'], decision['qty'], decision['limit_price']),
|
|
|
|
|
|
('sell', 1000, 32.63))
|
|
|
|
|
|
|
2026-11-09 12:08:56 +08:00
|
|
|
|
class ProtectionTests(unittest.TestCase):
|
|
|
|
|
|
def test_buy_pause_read_error_is_unknown_not_clear(self):
|
|
|
|
|
|
with patch.object(strategy_service,'buypause_map',side_effect=RuntimeError('db')):
|
|
|
|
|
|
self.assertIsNone(runner._buypause_codes())
|
|
|
|
|
|
def test_invalid_pause_document_raises(self):
|
|
|
|
|
|
with patch.object(pms_repo,'get_param',return_value='[]'):
|
|
|
|
|
|
with self.assertRaises(ValueError):strategy_service.buypause_map()
|
|
|
|
|
|
def test_old_proposal_and_insufficient_inventory_cannot_emit(self):
|
|
|
|
|
|
st=strategy();dec=dict(side='sell',qty=1500,grid_params=P,grid_lot_id=1,limit_price=49.18)
|
|
|
|
|
|
with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(pms_repo,'get_position',return_value=pos()),patch.object(service,'snapshot',return_value=core.project(st,*records())):
|
|
|
|
|
|
runner._validate_grid_decision(st,dec)
|
|
|
|
|
|
for changes in [dict(grid_params={}),dict(qty=1600),dict(limit_price=49.17),dict(grid_lot_id=2)]:
|
|
|
|
|
|
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**dec,**changes})
|
|
|
|
|
|
def test_new_day_preserves_unfinished_t0_leg(self):
|
|
|
|
|
|
state={'day':20261106,'open_leg':{'dir':'long','qty':100,'entry':10}}
|
|
|
|
|
|
runner._roll_day(state,{},20261109);self.assertEqual(state['open_leg']['qty'],100)
|
|
|
|
|
|
def test_trail_failed_partial_and_t_plus_one_do_not_consume_target(self):
|
|
|
|
|
|
st={'strategy_id':'trail','ts_code':'600000.SH','type':'TRAIL','params':{'start_line':.03,'giveback':.05,'sell_ratio':.5}}
|
|
|
|
|
|
state={'armed':True,'high_water':12};position={'total_qty':1000,'avail_qty':100,'avg_cost':9}
|
|
|
|
|
|
ctx={'state':state,'notes':[]}
|
|
|
|
|
|
d=runner._eval_trail(st,position,{'price':11},dt.datetime(2026,11,9,10),ctx)
|
|
|
|
|
|
self.assertEqual(d['qty'],100);self.assertEqual(state['trail_due']['qty'],500)
|
|
|
|
|
|
state['pending']={'iid':'sell','leg':'trail_sell','qty':100}
|
|
|
|
|
|
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':100})):
|
|
|
|
|
|
runner._reconcile(st,state,position)
|
|
|
|
|
|
self.assertEqual(state['trail_due']['qty'],400);self.assertNotIn('trail_fired_hw',state)
|
|
|
|
|
|
d=runner._eval_trail(st,{**position,'total_qty':900,'avail_qty':900},{'price':11.8},None,ctx)
|
|
|
|
|
|
self.assertEqual(d['qty'],400)
|
|
|
|
|
|
state['pending']={'iid':'sell2','leg':'trail_sell','qty':400}
|
|
|
|
|
|
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':400})):
|
|
|
|
|
|
runner._reconcile(st,state,position)
|
|
|
|
|
|
self.assertEqual(state['trail_fired_hw'],12);self.assertNotIn('trail_due',state)
|
|
|
|
|
|
self.assertIsNone(runner._eval_trail(st,{**position,'total_qty':500,'avail_qty':500},{'price':11},None,ctx))
|
|
|
|
|
|
def test_sar_zero_fill_still_retries_same_day(self):
|
|
|
|
|
|
st={'strategy_id':'trail','ts_code':'600000.SH','type':'TRAIL','params':{'sar_line':10,'giveback':.05,'sell_ratio':.5}}
|
|
|
|
|
|
state={};position={'total_qty':1000,'avail_qty':1000,'avg_cost':11};ctx={'state':state,'notes':[]};now=dt.datetime(2026,11,9,10)
|
|
|
|
|
|
with patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d):
|
|
|
|
|
|
self.assertEqual(runner._eval_trail(st,position,{'price':9},now,ctx)['qty'],1000)
|
|
|
|
|
|
state['pending']={'iid':'sell','leg':'trail_sar'}
|
|
|
|
|
|
with patch.object(runner,'_pending_terminal',return_value=(True,{'exec_qty':0})):runner._reconcile(st,state,position)
|
|
|
|
|
|
self.assertEqual(runner._eval_trail(st,position,{'price':9},now,ctx)['qty'],1000)
|
|
|
|
|
|
|
|
|
|
|
|
class MigrationTests(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
from test_trade_correction_strategy import StrategyCorrectionTests
|
|
|
|
|
|
from sqlalchemy import text
|
|
|
|
|
|
from app.db import session as db
|
|
|
|
|
|
from app.services import grid_migration as migration
|
|
|
|
|
|
self.migration, self.db = migration, db
|
|
|
|
|
|
self.use = StrategyCorrectionTests.use.__get__(self)
|
|
|
|
|
|
StrategyCorrectionTests.setUp(self)
|
|
|
|
|
|
with self.engine.begin() as conn:
|
|
|
|
|
|
conn.execute(text('CREATE TABLE migration_param (k TEXT PRIMARY KEY, v TEXT)'))
|
|
|
|
|
|
conn.execute(text("INSERT INTO migration_param VALUES ('PMS_AUTO_GRID_STEP_PCT','0.02')"))
|
|
|
|
|
|
self.use(migration.param_store, 'get', lambda k,d=None: {'PMS_MONITOR_WATCH_SCOPE':'pms-sim-155','PMS_DISPATCH_MODE':'ws'}.get(k,d))
|
|
|
|
|
|
self.use(migration.param_store, 'get_bool', lambda k,d=False: False)
|
|
|
|
|
|
self.use(migration.param_store, 'get_float', lambda k,d=0: float(db.fetch_one('SELECT v FROM migration_param WHERE k=:k', {'k':k})['v']))
|
|
|
|
|
|
self.use(pms_repo, 'get_param', lambda k: db.fetch_one('SELECT v FROM migration_param WHERE k=:k', {'k':k})['v'])
|
|
|
|
|
|
def set_param(k,v,updated_by=''):
|
|
|
|
|
|
db.execute('UPDATE migration_param SET v=:v WHERE k=:k', {'k':k,'v':str(v)})
|
|
|
|
|
|
return {'ok':True}
|
|
|
|
|
|
self.use(migration.param_store, 'set_param', set_param)
|
|
|
|
|
|
self.use(migration.execution_orders, 'code_settlement_blocker', lambda code: '')
|
|
|
|
|
|
self.use(migration.execution_orders, 'replacement_state', lambda iid: {'ready':True})
|
|
|
|
|
|
def preview(self): return self.migration.migrate(['GRID'])
|
|
|
|
|
|
def apply(self, expected): return self.migration.migrate(['GRID'], apply=True, expected=expected)
|
|
|
|
|
|
def test_preview_is_readonly_and_commit_is_idempotent(self):
|
|
|
|
|
|
before=pms_repo.get_strategy('GRID'); preview=self.preview()
|
|
|
|
|
|
self.assertEqual(pms_repo.get_strategy('GRID'),before)
|
|
|
|
|
|
result=self.apply(preview['fingerprint']);self.assertTrue(result['applied'])
|
|
|
|
|
|
current=pms_repo.get_strategy('GRID');self.assertEqual(current['params']['step_pct'],.04)
|
|
|
|
|
|
self.assertEqual(float(pms_repo.get_param('PMS_AUTO_GRID_STEP_PCT')),.04)
|
|
|
|
|
|
self.assertIsNone(current['state']['last_band']);self.assertTrue(self.apply('obsolete')['already_applied'])
|
|
|
|
|
|
self.assertEqual(current,pms_repo.get_strategy('GRID'))
|
|
|
|
|
|
def test_audit_failure_rolls_back_strategies_and_runtime_default(self):
|
|
|
|
|
|
before=pms_repo.get_strategy('GRID');preview=self.preview()
|
|
|
|
|
|
with patch.object(self.migration.rotation_repo,'put_once',side_effect=RuntimeError('audit failed')):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):self.apply(preview['fingerprint'])
|
|
|
|
|
|
self.assertEqual(before,pms_repo.get_strategy('GRID'))
|
|
|
|
|
|
self.assertEqual(float(pms_repo.get_param('PMS_AUTO_GRID_STEP_PCT')),.02)
|
|
|
|
|
|
self.assertIsNone(self.migration.rotation_repo.get(self.migration.KEY)[0])
|
|
|
|
|
|
def test_changed_strategy_and_wrong_target_set_fail_closed(self):
|
|
|
|
|
|
preview=self.preview();pms_repo.update_strategy('GRID',note='concurrent edit')
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError,'预览后'):self.apply(preview['fingerprint'])
|
|
|
|
|
|
with self.assertRaises(ValueError):self.migration.migrate(['OTHER'])
|
|
|
|
|
|
def test_live_parent_blocks_migration(self):
|
|
|
|
|
|
with patch.object(pms_repo,'list_instructions',return_value=[{'instruction_id':'LIVE'}]):
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError,'在途'):self.preview()
|
|
|
|
|
|
def test_unsettled_cancel_and_correction_hold_block_migration(self):
|
|
|
|
|
|
pms_repo.update_strategy('GRID',state={'pending':{'iid':'OLD'}})
|
|
|
|
|
|
with patch.object(pms_repo,'get_instruction',return_value={'status':'CANCELLED'}),patch.object(self.migration.execution_orders,'replacement_state',return_value={'ready':False}):
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError,'结算'):self.preview()
|
|
|
|
|
|
pms_repo.update_strategy('GRID',state={'correction_hold':'qty'})
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError,'更正'):self.preview()
|
|
|
|
|
|
def test_enabled_runner_and_wrong_instance_cannot_apply(self):
|
|
|
|
|
|
preview=self.preview()
|
|
|
|
|
|
with patch.object(self.migration.param_store,'get_bool',return_value=True):
|
|
|
|
|
|
with self.assertRaises(ValueError):self.apply(preview['fingerprint'])
|
|
|
|
|
|
with patch.object(settings,'PMS_TABLE_PREFIX','real_'):
|
|
|
|
|
|
with self.assertRaises(ValueError):self.preview()
|
|
|
|
|
|
def test_failed_parameter_write_rolls_back(self):
|
|
|
|
|
|
preview=self.preview();before=pms_repo.get_strategy('GRID')
|
|
|
|
|
|
with patch.object(self.migration.param_store,'set_param',return_value={'ok':False}):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):self.apply(preview['fingerprint'])
|
|
|
|
|
|
self.assertEqual(before,pms_repo.get_strategy('GRID'))
|
|
|
|
|
|
|
|
|
|
|
|
class AdditionalBoundaryTests(unittest.TestCase):
|
|
|
|
|
|
def test_missing_pending_parent_does_not_clear_state(self):
|
|
|
|
|
|
state={'pending':{'iid':'missing'}}
|
|
|
|
|
|
with patch.object(pms_repo,'get_instruction',return_value=None):
|
|
|
|
|
|
with self.assertRaises(ValueError):runner._reconcile({'type':'GRID'},state,{})
|
|
|
|
|
|
self.assertEqual(state['pending']['iid'],'missing')
|
|
|
|
|
|
def test_geometry_and_per_lot_revalidated_before_buy(self):
|
|
|
|
|
|
prm=dict(center=10,lower=8,upper=12,step_pct=.04,per_lot=100,max_capital=10000)
|
|
|
|
|
|
st=strategy(prm);d=evaluate(st,{'last_band':3,'filled_levels':{},'invested':0},pos(0),9.1)
|
|
|
|
|
|
with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(service,'snapshot',return_value={'filled_levels':{},'invested':0}),patch.object(pms_repo,'get_position',return_value=pos(0)),patch.object(runner,'_buypause_codes',return_value=set()),patch.object(runner,'_macro_gate_active',return_value=False):
|
|
|
|
|
|
runner._validate_grid_decision(st,d)
|
|
|
|
|
|
for fields in [{'qty':200},{'grid_entry':9.1},{'grid_exit':9.3},{'limit_price':9.21}]:
|
|
|
|
|
|
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,**fields})
|
|
|
|
|
|
def test_empty_geometry_does_not_attach_idle_grid(self):
|
|
|
|
|
|
from app.services.strategy_advisor import grid_params
|
|
|
|
|
|
params,why=grid_params(price=10,support=9.99,pressure=10.01,band=.08,step_pct=.04,cap_room=10000,cap_ratio=.5)
|
|
|
|
|
|
self.assertIsNone(params);self.assertIn('完整',why)
|
|
|
|
|
|
def test_rejected_trail_proposal_does_not_repeat_same_trigger(self):
|
|
|
|
|
|
st={'type':'TRAIL','ts_code':'600000.SH','params':{'sar_line':10,'giveback':.05,'sell_ratio':1}}
|
|
|
|
|
|
state={'pending':{'pid':'p'},'trail_due':{'qty':100,'leg':'trail_sar','high_water':11}}
|
|
|
|
|
|
with patch.object(runner,'_today',return_value=20261109),patch.object(pms_repo,'get_proposal',return_value={'status':'REJECTED'}),patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d):
|
|
|
|
|
|
self.assertTrue(runner._reconcile(st,state,{}))
|
|
|
|
|
|
self.assertIsNone(runner._eval_trail(st,{'total_qty':100,'avail_qty':100,'avg_cost':11},{'price':9},dt.datetime(2026,11,9,10),{'state':state}))
|
|
|
|
|
|
|
2026-11-09 12:40:37 +08:00
|
|
|
|
|
|
|
|
|
|
class AccountingOrderReviewTests(unittest.TestCase):
|
|
|
|
|
|
def fixture(self, code='002979.SZ', quantities=(100,100), prices=(10,12)):
|
|
|
|
|
|
st=strategy(dict(center=11,lower=8,upper=14,step_pct=.04,per_lot=1000,max_capital=100000));st['ts_code']=code
|
|
|
|
|
|
lots, parents=records(quantities[0],prices[0]);lots[0]['ts_code']=code;parents['buy']['ts_code']=code
|
|
|
|
|
|
lots.append({**lots[0],'id':2,'qty':quantities[1],'open_price':prices[1],'open_date':'2026-11-06'})
|
|
|
|
|
|
return st,lots,parents
|
|
|
|
|
|
def test_ledger_and_grid_use_identical_newest_day_first_order(self):
|
|
|
|
|
|
st,lots,parents=self.fixture();snap=core.project(st,list(reversed(lots)),parents)
|
|
|
|
|
|
self.assertEqual(list(snap['filled_levels']),['2','1'])
|
|
|
|
|
|
from app.core.cushion import sell_allocation
|
|
|
|
|
|
actual=sell_allocation([{'lot_id':l['id'],'lot_type':'ADD','qty':l['qty'],'open_date':int(l['open_date'].replace('-',''))} for l in lots],200)
|
|
|
|
|
|
self.assertEqual(core.sell_slice(snap['filled_levels'],200)['lots'],actual)
|
|
|
|
|
|
def test_newer_expensive_lot_cannot_be_sold_using_old_cheaper_cost(self):
|
|
|
|
|
|
st,lots,parents=self.fixture();snap=core.project(st,lots,parents)
|
|
|
|
|
|
self.assertIsNone(evaluate(st,snap,pos(200,300),11.5))
|
|
|
|
|
|
def test_same_day_uses_id_order_even_if_input_reversed(self):
|
|
|
|
|
|
st,lots,parents=self.fixture();lots[0]['open_date']=lots[1]['open_date']
|
|
|
|
|
|
snap=core.project(st,list(reversed(lots)),parents)
|
|
|
|
|
|
self.assertEqual(list(snap['filled_levels']),['1','2'])
|
|
|
|
|
|
def test_split_star_fills_combine_to_legal_quantity_and_keep_base(self):
|
|
|
|
|
|
st,lots,parents=self.fixture('688100.SH');snap=core.project(st,lots,parents)
|
|
|
|
|
|
d=evaluate(st,snap,pos(200,300),13)
|
|
|
|
|
|
self.assertEqual(d['qty'],200);self.assertEqual(d['grid_lots'],[{'lot_id':2,'qty':100},{'lot_id':1,'qty':100}])
|
|
|
|
|
|
self.assertEqual(d['limit_price'],12.48)
|
|
|
|
|
|
with patch.object(pms_repo,'list_instructions',return_value=[]),patch.object(pms_repo,'get_position',return_value=pos(200,300)),patch.object(service,'snapshot',return_value=snap):
|
|
|
|
|
|
runner._validate_grid_decision(st,d)
|
|
|
|
|
|
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,'limit_price':10.4})
|
|
|
|
|
|
with self.assertRaises(ValueError):runner._validate_grid_decision(st,{**d,'grid_lots':list(reversed(d['grid_lots']))})
|
|
|
|
|
|
def test_unready_second_piece_is_not_borrowed_to_reach_minimum(self):
|
|
|
|
|
|
st,lots,parents=self.fixture('688100.SH',prices=(12,10));snap=core.project(st,lots,parents)
|
|
|
|
|
|
self.assertIsNone(evaluate(st,snap,pos(200,300),11))
|
|
|
|
|
|
def test_one_hundred_star_add_does_not_borrow_base(self):
|
|
|
|
|
|
st,lots,parents=self.fixture('688100.SH',quantities=(0,100));snap=core.project(st,lots,parents)
|
|
|
|
|
|
self.assertIsNone(evaluate(st,snap,pos(100,300),13))
|
|
|
|
|
|
def test_small_fills_form_one_lot_without_rounding_each_piece_away(self):
|
|
|
|
|
|
st,lots,parents=self.fixture(quantities=(75,25));snap=core.project(st,lots,parents)
|
|
|
|
|
|
d=evaluate(st,snap,pos(100,200),13)
|
|
|
|
|
|
self.assertEqual(d['qty'],100);self.assertEqual([r['qty'] for r in d['grid_lots']],[25,75])
|
|
|
|
|
|
def test_partial_sale_keeps_actual_remaining_lots(self):
|
|
|
|
|
|
st,lots,parents=self.fixture(quantities=(150,150));snap=core.project(st,lots,parents)
|
|
|
|
|
|
st['params']['per_lot']=200
|
|
|
|
|
|
d=evaluate(st,snap,pos(300,400),13);self.assertEqual(d['grid_lots'],[{'lot_id':2,'qty':150},{'lot_id':1,'qty':50}])
|
|
|
|
|
|
lots[1]['qty']=0;lots[0]['qty']=100;snap=core.project(st,lots,parents)
|
|
|
|
|
|
remaining=evaluate(st,snap,pos(100,200),13);self.assertEqual(remaining['qty'],100);self.assertEqual(remaining['grid_lot_id'],1)
|
|
|
|
|
|
def test_open_t0_and_missing_dates_fail_closed(self):
|
|
|
|
|
|
st,lots,parents=self.fixture();lots.append({**lots[0],'id':3,'lot_type':'T0'})
|
|
|
|
|
|
with self.assertRaisesRegex(ValueError,'做T'):core.project(st,lots,parents)
|
|
|
|
|
|
lots.pop();lots[0].pop('open_date')
|
|
|
|
|
|
with self.assertRaises(ValueError):core.project(st,lots,parents)
|
|
|
|
|
|
def test_actual_sell_accounting_closes_the_same_pieces(self):
|
|
|
|
|
|
from app.services import ledger_service
|
|
|
|
|
|
st,lots,parents=self.fixture(quantities=(150,150));snap=core.project(st,lots,parents)
|
|
|
|
|
|
st['params']['per_lot']=200;d=evaluate(st,snap,pos(300,400),13);closed=[]
|
|
|
|
|
|
with patch.object(pms_repo,'ensure_position'),patch.object(pms_repo,'list_lots',return_value=lots),patch.object(pms_repo,'close_lot_qty',side_effect=lambda lid,**kw:closed.append({'lot_id':lid,'qty':kw['qty']})),patch.object(pms_repo,'bump_position_qty'):
|
|
|
|
|
|
ledger_service._apply_action({'kind':'SELL','ts_code':st['ts_code'],'qty':d['qty'],'price':d['limit_price']})
|
|
|
|
|
|
self.assertEqual(closed,d['grid_lots'])
|
|
|
|
|
|
|
|
|
|
|
|
class ExitBoundaryReviewTests(unittest.TestCase):
|
|
|
|
|
|
def test_all_three_execution_modes_preserve_grid_price_boundary(self):
|
|
|
|
|
|
from app.services import exec_advisor, market
|
|
|
|
|
|
now=dt.datetime(2026,11,9,10);quote={'kind':'minute','source':'recorded-test','as_of':'2026-11-09T10:00:00+08:00','last':10,'limit_down':9,'limit_up':11}
|
|
|
|
|
|
for mode in ['legacy','monitor','reprice']:
|
|
|
|
|
|
flags={'PMS_EXEC_REPRICE_ENABLED':mode=='reprice','PMS_EXEC_QMT_PRICE_MONITOR':mode=='monitor','PMS_EXEC_ALLOW_MINUTE_QUOTE':True}
|
|
|
|
|
|
with patch.object(exec_advisor.param_store,'get_bool',side_effect=lambda k,d=False:flags.get(k,d)),patch.object(exec_advisor.param_store,'get_float',side_effect=lambda k,d=0:d),patch.object(exec_advisor.param_store,'get_int',side_effect=lambda k,d=0:d),patch.object(market,'execution_quote',return_value=quote):
|
|
|
|
|
|
for side,limit in [('buy',9.99),('sell',10.01)]:
|
|
|
|
|
|
result=exec_advisor.decide(side=side,action='ADD' if side=='buy' else 'TRIM',ts_code='600000.SH',now=now,day={'price':10},params={},is_last_day=True,is_command=False,quota=100,prog={'origin':'strategy','stype':'GRID'},instruction_limit=limit)
|
|
|
|
|
|
self.assertEqual(result['action'],'FIRE',(mode,result))
|
|
|
|
|
|
self.assertTrue(result['limit_price']<=limit if side=='buy' else result['limit_price']>=limit,(mode,side,result))
|
|
|
|
|
|
def test_sar_upgrades_partial_profit_target_to_whole_remaining_position(self):
|
|
|
|
|
|
for hard in [False,True]:
|
|
|
|
|
|
st={'type':'TRAIL','ts_code':'600000.SH','params':{'sar_line':0 if hard else 10,'hard_target':.2 if hard else 0,'giveback':.05,'sell_ratio':.5}}
|
|
|
|
|
|
state={'high_water':12,'trail_due':{'qty':200,'partial':True,'leg':'trail_sell','high_water':12,'reason':'old'}}
|
|
|
|
|
|
with patch.object(runner.param_store,'get_bool',return_value=True),patch.object(runner.param_store,'get_float',side_effect=lambda k,d:d):
|
|
|
|
|
|
d=runner._eval_trail(st,{'total_qty':800,'avail_qty':700,'avg_cost':10},{'price':13 if hard else 9},dt.datetime(2026,11,9,10),{'state':state})
|
|
|
|
|
|
self.assertEqual(d['action'],'EXIT');self.assertEqual(d['qty'],700)
|
|
|
|
|
|
self.assertEqual(state['trail_due']['qty'],800);self.assertFalse(state['trail_due']['partial'])
|
|
|
|
|
|
def test_parent_and_proposal_keep_exact_piece_list(self):
|
|
|
|
|
|
st=strategy();d={'side':'sell','action':'TRIM','qty':200,'leg':'grid_sell:2','grid_lots':[{'lot_id':2,'qty':100},{'lot_id':1,'qty':100}],'grid_lot_id':2,'grid_params':P,'limit_price':49.18}
|
|
|
|
|
|
with patch.object(runner,'_current_strategy',return_value=nullcontext(st)),patch.object(runner,'_validate_grid_decision'),patch.object(pms_repo,'insert_instruction',return_value=1) as ins,patch.object(pms_repo,'insert_proposal',return_value=1) as prop:
|
|
|
|
|
|
runner._emit_instruction(st,d);runner._emit_proposal(st,d)
|
|
|
|
|
|
self.assertEqual(ins.call_args.kwargs['progress']['grid_lots'],d['grid_lots'])
|
|
|
|
|
|
self.assertEqual(prop.call_args.kwargs['hard_numbers']['grid_lots'],d['grid_lots'])
|
|
|
|
|
|
|
2026-11-09 12:08:56 +08:00
|
|
|
|
if __name__=='__main__':unittest.main()
|