tradingSystem/scripts/test_batch45_units.py

143 lines
6.1 KiB
Python
Raw Normal View History

"""父指令数量上限。入口隔离配置并禁止联网,不以回放及时完成为前提。"""
import unit_test_guard
import os
import sys
import unittest
from datetime import datetime
from unittest.mock import patch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test_wiring import install_fakes
from app.repo import qmt_repo
from app.services import executor, exec_advisor
CODE = '002865.SZ'
NOW = datetime(2026, 10, 23, 9, 35)
class ParentQuantityTest(unittest.TestCase):
def setUp(self):
self.fake = install_fakes(prices={CODE: 35}, positions=[{
'ts_code': CODE, 'total_qty': 1300, 'avail_qty': 1300,
'base_qty': 1300, 'avg_cost': 32.82,
}], params={'PMS_DISPATCH_MODE': 'ws'})
self.fake.qmt.set_channel()
self.fake.insert_instruction(instruction_id='P', origin_type='strategy',
origin_id='STR', ts_code=CODE, action='TRIM', side='sell', qty=600,
status='DISPATCHED', progress={'deadline': '2026-10-23',
'is_command': False, 'children': []})
self.parent = self.fake.instructions['P']
# 使用仓储的真实入口形状。返回副本,避免内存共享掩盖两个任务的快照延迟。
self.orders = self.fake.qmt.orders
p = patch.object(qmt_repo, 'orders_for_parent',
side_effect=lambda pid: [dict(o) for o in self.orders.values()
if o['parent_id'] == pid])
p.start()
self.addCleanup(p.stop)
def child(self, status, done, *, qty=600, day=20261023, remember=True):
iid = 'P_D01'
self.fake.qmt.enqueue_order(instruction_id=iid, parent_id='P', ts_code=CODE,
side=self.parent['side'], qty=qty, limit_price=35, valid_until=1)
self.orders[iid].update(status=status, cum_qty=done)
if remember:
self.parent['progress']['children'].append(
{'ref': iid, 'ymd': day, 'qty': qty, 'mode': 'ws'})
def tick(self):
with patch.object(executor.td, 'ymd', return_value=20261023), \
patch.object(executor.td, 'trade_days_left', return_value=1), \
patch.object(exec_advisor, 'decide', return_value={
'action': 'FIRE', 'qty_hint': 600, 'limit_price': 35,
'reason': '测试触发'}), \
patch.object(executor.rule_gate, 'check', return_value={
'passed': True, 'failed': [], 'hard_numbers': {}}):
return executor.run_tick(now=NOW)
def test_filled_child_before_replay_does_not_sell_again(self):
self.child('FILLED', 600)
result = self.tick()
self.assertEqual(result['fired'], [])
self.assertEqual(len(self.orders), 1)
self.assertEqual(self.parent['exec_qty'], 0, '数量检查不能代替成交入账')
def test_actual_trailing_path_does_not_repeat_after_terminal_fill(self):
self.parent['progress'].update(origin='strategy', stype='TRAIL')
self.child('FILLED', 600)
with patch.object(executor.td, 'ymd', return_value=20261023), \
patch.object(executor.td, 'trade_days_left', return_value=1):
result = executor.run_tick(now=NOW)
self.assertEqual(result['errors'], [])
self.assertEqual(result['fired'], [])
self.assertEqual(len(self.orders), 1)
def test_partial_then_cancelled_only_releases_unfilled_tail(self):
self.child('CANCELLED', 400)
result = self.tick()
self.assertEqual([r['qty'] for r in result['fired']], [200])
def test_partial_live_keeps_whole_parent_reserved(self):
self.child('PARTIAL', 200)
self.parent['exec_qty'] = 200
self.assertEqual(self.tick()['fired'], [])
def test_previous_day_live_child_still_reserves_quantity(self):
self.child('ACCEPTED', 0, day=20261022)
self.assertEqual(self.tick()['fired'], [])
def test_previous_day_filled_child_waits_for_replay(self):
self.child('FILLED', 600, day=20261022)
self.assertEqual(self.tick()['fired'], [])
def test_zero_fill_expired_releases_quantity(self):
self.child('EXPIRED', 0)
self.assertEqual([r['qty'] for r in self.tick()['fired']], [600])
def test_replay_ahead_of_order_update_remains_conservative(self):
self.child('PARTIAL', 100, qty=400)
self.parent['exec_qty'] = 300
self.assertEqual(self.tick()['fired'], [])
def test_orphaned_progress_cannot_hide_filled_outlet(self):
self.child('FILLED', 600, remember=False)
self.assertEqual(self.tick()['fired'], [])
def test_outlet_read_failure_cannot_dispatch(self):
with patch.object(qmt_repo, 'orders_for_parent', side_effect=RuntimeError('不可读')):
result = self.tick()
self.assertEqual(result['fired'], [])
self.assertTrue(result['errors'])
def test_buy_obeys_same_parent_cap(self):
self.parent.update(side='buy', action='OPEN')
self.child('FILLED', 600)
self.assertEqual(self.tick()['fired'], [])
def test_filled_without_cumulative_quantity_cannot_release(self):
self.child('FILLED', 0)
self.assertEqual(self.tick()['fired'], [])
def test_missing_child_is_reserved_instead_of_ignored(self):
self.parent['progress']['children'] = [
{'ref': 'P_D01', 'qty': 600, 'ymd': 20261022, 'mode': 'ws'}]
self.assertEqual(self.tick()['fired'], [])
def test_overfill_never_creates_compensating_trade(self):
self.child('FILLED', 1200, qty=1200)
self.assertEqual(self.tick()['fired'], [])
self.assertEqual(len(self.orders), 1)
def test_terminal_partial_does_not_double_subtract_booked_fill(self):
self.child('CANCELLED', 400)
self.parent['exec_qty'] = 400
self.assertEqual([r['qty'] for r in self.tick()['fired']], [200])
def test_shadow_does_not_require_qmt_outlet(self):
self.fake.params['PMS_DISPATCH_MODE'] = 'shadow'
with patch.object(qmt_repo, 'orders_for_parent', side_effect=AssertionError('不应查出口')):
self.assertEqual([r['qty'] for r in self.tick()['fired']], [600])
if __name__ == '__main__':
unittest.main()