2026-10-30 10:47:52 +08:00
|
|
|
|
"""当日限价有效期、撤单与成交交错,以及传输状态的真实SQL回归。"""
|
|
|
|
|
|
import unit_test_guard
|
|
|
|
|
|
import asyncio
|
|
|
|
|
|
import copy
|
|
|
|
|
|
import os
|
|
|
|
|
|
import sys
|
|
|
|
|
|
import tempfile
|
|
|
|
|
|
import unittest
|
|
|
|
|
|
from contextlib import nullcontext
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
|
|
from sqlalchemy import create_engine, text
|
|
|
|
|
|
from app.db import session
|
2026-11-05 09:26:15 +08:00
|
|
|
|
from app.repo import qmt_repo, pms_repo, execution_repo
|
2026-10-30 10:47:52 +08:00
|
|
|
|
from app.services import executor, dispatcher
|
|
|
|
|
|
from app.ws.runner import WsRunner
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChannelTest(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
self.loop = asyncio.new_event_loop(); asyncio.set_event_loop(self.loop)
|
|
|
|
|
|
self.addCleanup(self.loop.close)
|
|
|
|
|
|
self.runner = WsRunner()
|
|
|
|
|
|
self.row = {'instruction_id': 'P_D01', 'parent_id': 'P', 'qty': 400, 'cum_qty': 0,
|
|
|
|
|
|
'status': 'ACCEPTED', 'cancel_state': 'SENT', 'ts_code': '688100.SH'}
|
|
|
|
|
|
self.use(qmt_repo, 'get_order', side_effect=lambda _: copy.deepcopy(self.row))
|
|
|
|
|
|
self.use(qmt_repo, 'update_order', side_effect=self.update)
|
2026-11-05 09:26:15 +08:00
|
|
|
|
self.use(execution_repo, 'pending_corrections', return_value=0)
|
|
|
|
|
|
self.use(pms_repo, 'get_instruction', return_value={'instruction_id': 'P', 'progress': {}})
|
2026-10-30 10:47:52 +08:00
|
|
|
|
|
|
|
|
|
|
def use(self, obj, name, **kw):
|
|
|
|
|
|
p = patch.object(obj, name, **kw); m = p.start(); self.addCleanup(p.stop); return m
|
|
|
|
|
|
|
|
|
|
|
|
def update(self, _, **fields): self.row.update(fields); return 1
|
|
|
|
|
|
def reject(self, code='ALREADY_FINAL'):
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._apply_side_effects('reject',
|
|
|
|
|
|
{'instruction_id': 'P_D01', 'code': code, 'reason': 'cancel denied'}, {}))
|
|
|
|
|
|
def state(self, status, done):
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._on_order_update('P_D01',
|
|
|
|
|
|
{'status': status, 'cum_qty': done, 'final': status in qmt_repo.FINAL, 'leaves_qty': 0}))
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancel_reject_keeps_order_and_reservation(self):
|
|
|
|
|
|
self.row.update(status='PARTIAL', cum_qty=100)
|
|
|
|
|
|
self.reject('INTERNAL')
|
|
|
|
|
|
self.assertEqual((self.row['status'], self.row['cum_qty']), ('PARTIAL', 100))
|
|
|
|
|
|
self.assertNotIn('final_at', self.row)
|
|
|
|
|
|
with patch.object(dispatcher, 'mode', return_value='ws'), patch.object(qmt_repo, 'orders_for_parent', return_value=[self.row]):
|
|
|
|
|
|
self.assertEqual(executor._parent_available({'instruction_id': 'P', 'qty': 400, 'exec_qty': 0}, []), 0)
|
|
|
|
|
|
|
|
|
|
|
|
def test_already_final_before_final_update_keeps_pending(self):
|
|
|
|
|
|
self.row['cancel_state'] = 'NONE'
|
|
|
|
|
|
self.reject(); self.assertEqual(self.row['status'], 'ACCEPTED')
|
|
|
|
|
|
self.state('FILLED', 400); self.assertEqual(self.row['status'], 'FILLED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_reject_cannot_overwrite_filled(self):
|
|
|
|
|
|
self.row.update(status='FILLED', cum_qty=400)
|
|
|
|
|
|
self.reject(); self.assertEqual((self.row['status'], self.row['cum_qty']), ('FILLED', 400))
|
|
|
|
|
|
|
|
|
|
|
|
def test_genuine_place_rejection_still_finishes(self):
|
|
|
|
|
|
self.row.update(status='SENT', cancel_state='NONE')
|
|
|
|
|
|
self.reject('INVALID_PRICE'); self.assertEqual(self.row['status'], 'REJECTED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_partial_cancel_preserves_fill_releases_only_remainder(self):
|
|
|
|
|
|
self.row['cum_qty'] = 100
|
|
|
|
|
|
self.state('CANCELLED', 100)
|
|
|
|
|
|
with patch.object(dispatcher, 'mode', return_value='ws'), patch.object(qmt_repo, 'orders_for_parent', return_value=[self.row]):
|
|
|
|
|
|
self.assertEqual(executor._parent_available({'instruction_id': 'P', 'qty': 400, 'exec_qty': 0}, []), 300)
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancel_cannot_zero_previously_reported_fills(self):
|
|
|
|
|
|
self.row.update(status='PARTIAL', cum_qty=100)
|
|
|
|
|
|
self.state('CANCELLED', 0)
|
|
|
|
|
|
self.assertEqual((self.row['status'], self.row['cum_qty']), ('PARTIAL', 100))
|
|
|
|
|
|
self.assertEqual(self.runner._stat['order_update_conflicts'], 1)
|
|
|
|
|
|
|
|
|
|
|
|
def test_missing_or_invalid_cumulative_quantity_keeps_pending(self):
|
|
|
|
|
|
for quantity in (None, -1, 500):
|
|
|
|
|
|
self.state('CANCELLED', quantity)
|
|
|
|
|
|
self.assertEqual(self.row['status'], 'ACCEPTED')
|
|
|
|
|
|
self.state('FILLED', 0); self.assertEqual(self.row['status'], 'ACCEPTED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_late_cancel_does_not_override_full_fill(self):
|
|
|
|
|
|
self.state('FILLED', 400); self.state('CANCELLED', 400)
|
|
|
|
|
|
self.assertEqual(self.row['status'], 'FILLED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_restarted_queued_order_is_cancelled_at_qmt(self):
|
|
|
|
|
|
self.row.update(status='QUEUED', sent_at=datetime.now(), cancel_state='REQUESTED', cancel_id='C')
|
|
|
|
|
|
with patch.object(qmt_repo, 'next_cancel_requests', return_value=[self.row]), \
|
|
|
|
|
|
patch.object(qmt_repo, 'mark_cancel_sent'), patch.object(qmt_repo, 'abort_order') as abort, \
|
|
|
|
|
|
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._drain_cancels('unused'))
|
|
|
|
|
|
abort.assert_not_called(); send.assert_awaited_once()
|
|
|
|
|
|
self.assertEqual(send.call_args.args[0], 'cancel_order')
|
|
|
|
|
|
|
|
|
|
|
|
def test_unsent_queue_can_be_aborted_locally(self):
|
|
|
|
|
|
self.row.update(status='QUEUED', sent_at=None, cancel_state='REQUESTED')
|
|
|
|
|
|
with patch.object(qmt_repo, 'next_cancel_requests', return_value=[self.row]), \
|
|
|
|
|
|
patch.object(qmt_repo, 'mark_cancel_sent'), patch.object(qmt_repo, 'abort_order') as abort, \
|
|
|
|
|
|
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._drain_cancels('unused'))
|
|
|
|
|
|
abort.assert_called_once(); send.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_expired_uncertain_send_needs_downstream_cancel(self):
|
|
|
|
|
|
self.row.update(status='QUEUED', sent_at=datetime.now(), cancel_state='NONE')
|
|
|
|
|
|
with patch.object(qmt_repo, 'request_order_cancel', return_value=1) as cancel, patch.object(qmt_repo, 'abort_order') as abort:
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._stop_outbox_order('P_D01', 'expired'))
|
|
|
|
|
|
cancel.assert_called_once(); abort.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancel_between_claim_and_send_prevents_transport(self):
|
|
|
|
|
|
from app.services import execution_conflicts
|
|
|
|
|
|
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
|
|
|
|
|
|
valid_until=9999999999999)
|
|
|
|
|
|
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \
|
|
|
|
|
|
patch.object(qmt_repo, 'claim_order', return_value=True), \
|
|
|
|
|
|
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
|
|
|
|
|
|
patch.object(qmt_repo, 'mark_send_attempt', return_value=False), \
|
|
|
|
|
|
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._drain_outbox('unused'))
|
|
|
|
|
|
send.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_send_error_after_attempt_keeps_uncertain_order_retryable(self):
|
|
|
|
|
|
from app.services import execution_conflicts
|
|
|
|
|
|
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
|
|
|
|
|
|
valid_until=9999999999999)
|
|
|
|
|
|
def attempted(_): self.row['sent_at'] = datetime.now(); return True
|
|
|
|
|
|
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \
|
|
|
|
|
|
patch.object(qmt_repo, 'claim_order', return_value=True), \
|
|
|
|
|
|
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
|
|
|
|
|
|
patch.object(qmt_repo, 'mark_send_attempt', side_effect=attempted), \
|
|
|
|
|
|
patch.object(qmt_repo, 'requeue_order') as requeue, \
|
|
|
|
|
|
patch.object(self.runner, '_send', new_callable=AsyncMock, side_effect=RuntimeError('uncertain send')):
|
|
|
|
|
|
with self.assertRaises(RuntimeError):
|
|
|
|
|
|
self.loop.run_until_complete(self.runner._drain_outbox('unused'))
|
|
|
|
|
|
self.assertTrue(self.row['sent_at'])
|
|
|
|
|
|
self.assertFalse(requeue.call_args.args[-1])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class DeadlineTest(unittest.TestCase):
|
|
|
|
|
|
def test_qmt_day_order_always_ends_at_close(self):
|
|
|
|
|
|
with patch.object(executor.param_store, 'get_bool', return_value=True):
|
|
|
|
|
|
for hour, minute in [(9, 31), (11, 25), (14, 58)]:
|
|
|
|
|
|
self.assertEqual(executor.order_deadline(datetime(2026, 10, 30, hour, minute),
|
|
|
|
|
|
{'qmt_price_monitor': True}, ttl_min=10), 900)
|
|
|
|
|
|
|
|
|
|
|
|
def test_old_mode_keeps_ten_minute_lifetime(self):
|
|
|
|
|
|
now = datetime(2026, 10, 30, 10, 22)
|
|
|
|
|
|
with patch.object(executor.param_store, 'get_bool', return_value=False):
|
|
|
|
|
|
self.assertEqual(executor.order_deadline(now, {'qmt_price_monitor': True}, ttl_min=10), 632)
|
|
|
|
|
|
with patch.object(executor.param_store, 'get_bool', return_value=True):
|
|
|
|
|
|
self.assertEqual(executor.order_deadline(now, {}, ttl_min=10), 632)
|
|
|
|
|
|
|
|
|
|
|
|
def test_repeated_cancel_request_reports_pending(self):
|
|
|
|
|
|
with patch.object(dispatcher, 'mode', return_value='ws'), \
|
|
|
|
|
|
patch.object(qmt_repo, 'request_cancel', return_value=0), \
|
|
|
|
|
|
patch.object(qmt_repo, 'orders_for_parent', return_value=[{'status': 'PARTIAL', 'cancel_state': 'SENT'}]):
|
|
|
|
|
|
result = dispatcher.cancel(instruction_id='P')
|
2026-10-30 10:49:30 +08:00
|
|
|
|
self.assertTrue(result['ok']); self.assertTrue(result['cancel_pending'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancel_intent_survives_status_read_failure(self):
|
|
|
|
|
|
with patch.object(dispatcher, 'mode', return_value='ws'), \
|
|
|
|
|
|
patch.object(qmt_repo, 'request_cancel', return_value=0), \
|
|
|
|
|
|
patch.object(qmt_repo, 'orders_for_parent', side_effect=RuntimeError('temporarily unavailable')):
|
|
|
|
|
|
result = dispatcher.cancel(instruction_id='P')
|
2026-10-30 10:47:52 +08:00
|
|
|
|
self.assertTrue(result['ok']); self.assertTrue(result['cancel_pending'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SqlTest(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
|
|
|
|
|
|
self.engine = create_engine('sqlite:///' + self.tmp.name + '/orders.sqlite'); self.addCleanup(self.engine.dispose)
|
|
|
|
|
|
for obj, name, kwargs in [(session, 'get_engine', {'return_value': self.engine}), (session, '_check_cooldown', {})]:
|
|
|
|
|
|
p = patch.object(obj, name, **kwargs); p.start(); self.addCleanup(p.stop)
|
|
|
|
|
|
with self.engine.begin() as c:
|
|
|
|
|
|
c.execute(text('CREATE TABLE pms_qmt_order(instruction_id TEXT PRIMARY KEY,status TEXT,sent_at TEXT,updated_at TEXT,send_attempts INTEGER,cancel_state TEXT,reject_code TEXT,reject_reason TEXT,final_at TEXT)'))
|
|
|
|
|
|
c.execute(text("INSERT INTO pms_qmt_order(instruction_id,status,send_attempts,cancel_state) VALUES('I','SENDING',0,'NONE')"))
|
|
|
|
|
|
def row(self): return session.fetch_one("SELECT * FROM pms_qmt_order WHERE instruction_id='I'")
|
|
|
|
|
|
|
|
|
|
|
|
def test_send_marker_persists_before_transport(self):
|
|
|
|
|
|
self.assertTrue(qmt_repo.mark_send_attempt('I')); self.assertTrue(self.row()['sent_at'])
|
|
|
|
|
|
self.assertEqual(qmt_repo.abort_order('I', 'cancel'), 0)
|
|
|
|
|
|
self.assertEqual(self.row()['status'], 'SENDING')
|
|
|
|
|
|
|
|
|
|
|
|
def test_cancel_wins_before_transport(self):
|
|
|
|
|
|
qmt_repo.update_order('I', cancel_state='REQUESTED')
|
|
|
|
|
|
self.assertFalse(qmt_repo.mark_send_attempt('I'))
|
|
|
|
|
|
self.assertEqual(qmt_repo.abort_order('I', 'cancel'), 1)
|
|
|
|
|
|
self.assertEqual(self.row()['status'], 'ABORTED')
|
|
|
|
|
|
|
|
|
|
|
|
def test_fast_ack_or_fill_never_regresses_to_sent(self):
|
|
|
|
|
|
for status in ('ACCEPTED', 'PARTIAL', 'FILLED', 'CANCELLED'):
|
|
|
|
|
|
qmt_repo.update_order('I', status=status)
|
|
|
|
|
|
qmt_repo.mark_sent('I'); self.assertEqual(self.row()['status'], status)
|
|
|
|
|
|
qmt_repo.requeue_order('I', 'error'); self.assertEqual(self.row()['status'], status)
|
|
|
|
|
|
|
|
|
|
|
|
def test_restart_retains_send_uncertainty(self):
|
|
|
|
|
|
qmt_repo.mark_send_attempt('I'); qmt_repo.reset_stuck_sending()
|
|
|
|
|
|
self.assertEqual(self.row()['status'], 'QUEUED'); self.assertTrue(self.row()['sent_at'])
|
|
|
|
|
|
self.assertEqual(qmt_repo.abort_order('I', 'expired'), 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ZBookTest(unittest.TestCase):
|
|
|
|
|
|
def test_late_trade_after_parent_cancel_books_once_in_own_strategy(self):
|
|
|
|
|
|
from test_wiring import install_fakes
|
2026-11-05 09:26:15 +08:00
|
|
|
|
from app.services import rotation_execution as re, rotation_accounting as ra, trade_lineage
|
2026-10-30 10:47:52 +08:00
|
|
|
|
from app.repo import rotation_repo
|
|
|
|
|
|
fake = install_fakes(prices={'688100.SH': 23.3})
|
|
|
|
|
|
fake.insert_instruction(instruction_id='P', origin_type='proposal', origin_id='X',
|
|
|
|
|
|
ts_code='688100.SH', action='OPEN', side='buy', qty=400, status='CANCELLED')
|
|
|
|
|
|
fake.instructions['P']['book_id'] = 'original'
|
|
|
|
|
|
fake.qmt.put_trade(seq=1, instruction_id='P_D01', ts_code='688100.SH', side='buy', qty=100, price=23.3)
|
|
|
|
|
|
act = {'instruction_id': 'P', 'kind': 'BUY', 'ts_code': '688100.SH', 'qty': 100, 'price': 23.3, 'lot_type': 'BASE', 'order_id': 'T1'}
|
|
|
|
|
|
with patch.object(re.db, 'transaction', side_effect=nullcontext), \
|
2026-11-05 09:26:15 +08:00
|
|
|
|
patch.object(trade_lineage, 'record'), \
|
2026-10-30 10:47:52 +08:00
|
|
|
|
patch.object(rotation_repo, 'account_guard', side_effect=nullcontext), \
|
|
|
|
|
|
patch.object(re.db, 'fetch_one', side_effect=lambda *a, **kw: {'processed': fake.qmt.inbox[1]['processed']}), \
|
|
|
|
|
|
patch.object(pms_repo, 'get_instruction', side_effect=lambda iid: copy.deepcopy(fake.instructions.get(iid))), \
|
|
|
|
|
|
patch.object(ra, 'record_fill') as cash:
|
|
|
|
|
|
self.assertTrue(re.book_trade(act, [], 1))
|
|
|
|
|
|
self.assertFalse(re.book_trade(act, [], 1))
|
|
|
|
|
|
self.assertEqual(fake.positions['688100.SH']['total_qty'], 100)
|
|
|
|
|
|
self.assertEqual(fake.instructions['P']['exec_qty'], 100)
|
|
|
|
|
|
self.assertEqual(fake.instructions['P']['status'], 'CANCELLED')
|
|
|
|
|
|
cash.assert_called_once_with('original', 'buy', 2330., 0, '1')
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 18:03:41 +08:00
|
|
|
|
class DailyQuantityTests(unittest.TestCase):
|
|
|
|
|
|
def setUp(self):
|
|
|
|
|
|
from app.services import command_service, market, param_store, portfolio
|
|
|
|
|
|
self.now = datetime(2026, 11, 18, 10, 10)
|
|
|
|
|
|
self.code = '600000.SH'
|
|
|
|
|
|
self.parent = {'instruction_id': 'reduction', 'ts_code': self.code, 'action': 'TRIM',
|
|
|
|
|
|
'side': 'sell', 'qty': 3000, 'exec_qty': 0, 'status': 'DISPATCHED', 'origin_type': 'plan',
|
|
|
|
|
|
'progress': {'deadline': '2026-11-20', 'is_command': True, 'children': []}}
|
|
|
|
|
|
self.orders = []
|
|
|
|
|
|
self.position = {'ts_code': self.code, 'total_qty': 5000, 'avail_qty': 5000}
|
|
|
|
|
|
self.use(pms_repo, 'list_instructions', return_value=[self.parent])
|
|
|
|
|
|
self.use(pms_repo, 'get_instruction', return_value=self.parent)
|
|
|
|
|
|
self.use(qmt_repo, 'orders_for_parent', side_effect=lambda _: copy.deepcopy(self.orders))
|
|
|
|
|
|
self.use(qmt_repo, 'get_order', side_effect=lambda iid: next(
|
|
|
|
|
|
(r for r in self.orders if r['instruction_id'] == iid), None))
|
|
|
|
|
|
self.use(execution_repo, 'pending_corrections', return_value=0)
|
|
|
|
|
|
self.use(execution_repo, 'pending_trades', return_value=[])
|
|
|
|
|
|
self.use(dispatcher, 'mode', return_value='ws')
|
|
|
|
|
|
self.use(param_store, 'get_bool', side_effect=lambda k, d=False: k == 'PMS_EXEC_REPRICE_ENABLED' or d)
|
|
|
|
|
|
self.use(param_store, 'get_int', side_effect=lambda k, d=0: d)
|
|
|
|
|
|
self.use(param_store, 'get_float', side_effect=lambda k, d=0.: d)
|
|
|
|
|
|
self.use(param_store, 'get', side_effect=lambda k, d=None: d)
|
|
|
|
|
|
self.use(command_service, 'effective_stock_params', return_value={})
|
|
|
|
|
|
self.use(portfolio, 'positions_view', return_value={'positions': [self.position],
|
|
|
|
|
|
'params': {'exec_halt': False, 'buy_halt': False}, 'sector_ready': True})
|
|
|
|
|
|
self.use(market, 'day_snapshot', return_value={'price': 10, 'low': 9, 'high': 11})
|
|
|
|
|
|
self.use(market, 'execution_quote', return_value={'source': '测试', 'kind': 'level1',
|
|
|
|
|
|
'last': 10, 'bid': 9.99, 'ask': 10, 'as_of': self.now.isoformat()+'+08:00',
|
|
|
|
|
|
'limit_down': 9, 'limit_up': 11})
|
|
|
|
|
|
|
|
|
|
|
|
def use(self, obj, name, **kwargs):
|
|
|
|
|
|
hook = patch.object(obj, name, **kwargs)
|
|
|
|
|
|
self.addCleanup(hook.stop)
|
|
|
|
|
|
return hook.start()
|
|
|
|
|
|
|
|
|
|
|
|
def child(self, qty, filled, *, day=None, status='CANCELLED', progress=True):
|
|
|
|
|
|
ref = f"reduction_D{len(self.orders)+1:02d}"
|
|
|
|
|
|
day = day or self.now
|
|
|
|
|
|
self.orders.append({'instruction_id': ref, 'parent_id': 'reduction', 'qty': qty,
|
|
|
|
|
|
'cum_qty': filled, 'status': status, 'created_at': day})
|
|
|
|
|
|
self.parent['exec_qty'] += filled
|
|
|
|
|
|
if progress:
|
|
|
|
|
|
self.parent['progress']['children'].append({'ref': ref, 'qty': qty,
|
|
|
|
|
|
'ymd': int(day.strftime('%Y%m%d'))})
|
|
|
|
|
|
|
|
|
|
|
|
def quantity(self):
|
|
|
|
|
|
result = executor.run_tick(now=self.now, dry_run=True)
|
|
|
|
|
|
self.assertEqual(result['errors'], [])
|
|
|
|
|
|
self.assertEqual(result['rejected'], [])
|
|
|
|
|
|
return sum(item['qty'] for item in result['fired'])
|
|
|
|
|
|
|
|
|
|
|
|
def test_outdated_execution_read_cannot_overwrite_a_new_review_claim(self):
|
|
|
|
|
|
from app.services import daily_buy_review
|
|
|
|
|
|
self.parent.update(action='OPEN', side='buy', status='PROPOSED')
|
|
|
|
|
|
self.use(pms_repo, 'get_instruction', side_effect=lambda _: copy.deepcopy(self.parent))
|
|
|
|
|
|
self.use(pms_repo, 'instruction_buy_stop', return_value=None)
|
|
|
|
|
|
update = self.use(pms_repo, 'update_instruction')
|
|
|
|
|
|
|
|
|
|
|
|
def gate(_, *, now):
|
|
|
|
|
|
self.parent.update(status='WAIT_REVIEW')
|
|
|
|
|
|
self.parent['progress']['daily_review'] = {'ymd': 20261118, 'status': 'pending', 'attempts': 1}
|
|
|
|
|
|
return '旧买入安排需完成当日复核'
|
|
|
|
|
|
self.use(daily_buy_review, 'blocker', side_effect=gate)
|
|
|
|
|
|
result = executor.run_tick(now=self.now)
|
|
|
|
|
|
self.assertEqual(result['errors'], [])
|
|
|
|
|
|
self.assertTrue(result['waited'])
|
|
|
|
|
|
update.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_partial_fill_does_not_shrink_opening_allotment(self):
|
|
|
|
|
|
self.assertEqual(self.quantity(), 1000)
|
|
|
|
|
|
self.child(1000, 700)
|
|
|
|
|
|
self.assertEqual(self.quantity(), 300)
|
|
|
|
|
|
self.assertEqual(self.quantity(), 300)
|
|
|
|
|
|
self.child(300, 300, status='FILLED', progress=False)
|
|
|
|
|
|
self.assertEqual(self.quantity(), 0)
|
|
|
|
|
|
|
|
|
|
|
|
def test_yesterday_and_missing_progress_are_counted_on_their_own_day(self):
|
|
|
|
|
|
self.child(600, 600, day=datetime(2026, 11, 17), status='FILLED')
|
|
|
|
|
|
self.child(800, 300, progress=False)
|
|
|
|
|
|
self.assertEqual(self.quantity(), 500)
|
|
|
|
|
|
self.orders[-1]['status'] = 'PARTIAL'
|
|
|
|
|
|
self.assertEqual(self.quantity(), 0)
|
|
|
|
|
|
self.assertEqual(executor.dispatch_allowance(self.parent, self.now, 3), 0)
|
|
|
|
|
|
self.orders[-1]['status'] = 'CANCELLED'
|
|
|
|
|
|
self.parent['exec_qty'] = 600
|
|
|
|
|
|
self.assertEqual(self.quantity(), 0)
|
|
|
|
|
|
self.parent['exec_qty'] = 900
|
|
|
|
|
|
self.assertEqual(self.quantity(), 500)
|
|
|
|
|
|
|
|
|
|
|
|
def test_partial_lot_and_full_odd_lot_exit(self):
|
|
|
|
|
|
self.child(1000, 725)
|
|
|
|
|
|
self.assertEqual(self.quantity(), 200)
|
|
|
|
|
|
self.parent.update(action='EXIT', qty=1000)
|
|
|
|
|
|
self.position.update(total_qty=275, avail_qty=275)
|
|
|
|
|
|
self.parent['progress']['urgent'] = True
|
|
|
|
|
|
self.assertEqual(self.quantity(), 100)
|
|
|
|
|
|
self.parent['progress']['deadline'] = '2026-11-18'
|
|
|
|
|
|
self.assertEqual(self.quantity(), 275)
|
|
|
|
|
|
self.parent['progress']['urgent'] = False
|
|
|
|
|
|
self.assertEqual(self.quantity(), 275)
|
|
|
|
|
|
|
|
|
|
|
|
def test_fill_between_quote_and_dispatch_waits_then_the_next_tick_uses_balance(self):
|
|
|
|
|
|
from app.services import execution_orders
|
|
|
|
|
|
clock = self.use(dispatcher, 'datetime', wraps=datetime)
|
|
|
|
|
|
clock.now.return_value = self.now
|
|
|
|
|
|
self.use(pms_repo, 'account_decision_guard', side_effect=nullcontext)
|
|
|
|
|
|
outlet = self.use(dispatcher, '_ws', return_value={'ok': True})
|
|
|
|
|
|
|
|
|
|
|
|
def other_tick_settles(_):
|
|
|
|
|
|
self.child(1000, 700, progress=False)
|
|
|
|
|
|
return 'reduction_D02'
|
|
|
|
|
|
self.use(execution_orders, 'next_child_id', side_effect=other_tick_settles)
|
|
|
|
|
|
result = executor.run_tick(now=self.now)
|
|
|
|
|
|
self.assertEqual(result['errors'], [])
|
|
|
|
|
|
self.assertEqual(result['fired'], [])
|
|
|
|
|
|
self.assertIn('300股', result['waited'][0]['reason'])
|
|
|
|
|
|
outlet.assert_not_called()
|
|
|
|
|
|
self.assertEqual(self.quantity(), 300)
|
|
|
|
|
|
|
|
|
|
|
|
def test_rotation_and_urgent_parents_keep_their_execution_rules(self):
|
|
|
|
|
|
from app.services import execution_orders
|
|
|
|
|
|
self.use(execution_orders, 'enabled', return_value=False)
|
|
|
|
|
|
self.use(execution_orders, 'account_guard', side_effect=nullcontext)
|
|
|
|
|
|
ordinary_guard = self.use(pms_repo, 'account_decision_guard')
|
|
|
|
|
|
self.use(dispatcher, '_ws', return_value={'ok': True})
|
|
|
|
|
|
clock = self.use(dispatcher, 'datetime', wraps=datetime)
|
|
|
|
|
|
clock.now.return_value = self.now
|
|
|
|
|
|
for field, value in [('execution_profile', 'rotation'), ('urgent', True)]:
|
|
|
|
|
|
self.parent['progress'][field] = value
|
|
|
|
|
|
result = dispatcher.dispatch(instruction_id='reduction_D01', parent_id='reduction',
|
|
|
|
|
|
ts_code=self.code, side='sell', qty=3000, limit_price=10, valid_until=self.now)
|
|
|
|
|
|
self.assertTrue(result['ok'], result)
|
|
|
|
|
|
del self.parent['progress'][field]
|
|
|
|
|
|
ordinary_guard.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
def test_dispatch_rechecks_day_usage_after_quote_and_retains_idempotent_retry(self):
|
|
|
|
|
|
self.child(1000, 700, progress=False)
|
|
|
|
|
|
clock = self.use(dispatcher, 'datetime', wraps=datetime)
|
|
|
|
|
|
clock.now.return_value = self.now
|
|
|
|
|
|
guard = self.use(pms_repo, 'account_decision_guard', side_effect=nullcontext)
|
|
|
|
|
|
outlet = self.use(dispatcher, '_ws', return_value={'ok': True})
|
|
|
|
|
|
from app.services import execution_orders
|
|
|
|
|
|
self.use(execution_orders, 'enabled', return_value=False)
|
|
|
|
|
|
def send(qty, iid='reduction_D02'):
|
|
|
|
|
|
return dispatcher.dispatch(instruction_id=iid, parent_id='reduction', ts_code=self.code,
|
|
|
|
|
|
side='sell', qty=qty, limit_price=10, valid_until=self.now.replace(minute=20))
|
|
|
|
|
|
stale = send(1000)
|
|
|
|
|
|
self.assertFalse(stale['ok'])
|
|
|
|
|
|
self.assertTrue(stale['deferred'])
|
|
|
|
|
|
self.assertIn('300股', stale['error'])
|
|
|
|
|
|
outlet.assert_not_called()
|
|
|
|
|
|
self.assertTrue(send(300)['ok'])
|
|
|
|
|
|
self.assertTrue(send(1000, 'reduction_D01')['ok'])
|
|
|
|
|
|
self.assertEqual(guard.call_count, 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-30 10:47:52 +08:00
|
|
|
|
if __name__ == '__main__': unittest.main()
|