轮换决定先落账并等待下游撤单完成
This commit is contained in:
parent
14b79019ad
commit
316d31d694
|
|
@ -50,7 +50,7 @@ def snapshot_check(value, execution_date, *, require_frozen=True):
|
||||||
return errors
|
return errors
|
||||||
|
|
||||||
|
|
||||||
def transition(state, snapshot, *, micro_qty, original_qty, budget, control='run'):
|
def transition(state, snapshot, *, micro_qty, original_qty, budget, control='run', micro_pending=False):
|
||||||
s = copy.deepcopy(state)
|
s = copy.deepcopy(state)
|
||||||
if s['phase'] not in PHASES:
|
if s['phase'] not in PHASES:
|
||||||
raise ValueError('未知轮换阶段')
|
raise ValueError('未知轮换阶段')
|
||||||
|
|
@ -64,7 +64,7 @@ def transition(state, snapshot, *, micro_qty, original_qty, budget, control='run
|
||||||
s['phase'], s['reason'] = 'returning_original', '用户退出并停用'
|
s['phase'], s['reason'] = 'returning_original', '用户退出并停用'
|
||||||
if ready and signal.get('high') and s['phase'] in ('entering_micro', 'micro'):
|
if ready and signal.get('high') and s['phase'] in ('entering_micro', 'micro'):
|
||||||
s.update(phase='returning_original', exit_date=snapshot['effective_date'], reason='微盘活跃度高位')
|
s.update(phase='returning_original', exit_date=snapshot['effective_date'], reason='微盘活跃度高位')
|
||||||
if s['phase'] == 'returning_original' and micro_qty == 0:
|
if s['phase'] == 'returning_original' and micro_qty == 0 and not micro_pending:
|
||||||
s.update(phase='original', target=[], entry_budget=0., entry_quantities={},
|
s.update(phase='original', target=[], entry_budget=0., entry_quantities={},
|
||||||
closed_date=(snapshot or {}).get('effective_date') or s.get('exit_date'))
|
closed_date=(snapshot or {}).get('effective_date') or s.get('exit_date'))
|
||||||
return s # 清完当天不立即重开下一轮。
|
return s # 清完当天不立即重开下一轮。
|
||||||
|
|
|
||||||
|
|
@ -202,16 +202,39 @@ def _limits(day):
|
||||||
return {r['ts_code']: r for r in rows}
|
return {r['ts_code']: r for r in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def _micro_unsettled(pending):
|
||||||
|
"""本地撤销不等于下游终态;未入账成交也不能视为退出已完成。"""
|
||||||
|
if any(r['book_id'] == books.MICRO for r in pending) or qmt_repo.inbox_pending_count():
|
||||||
|
return True
|
||||||
|
rows = qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=10001)
|
||||||
|
if len(rows) > 10000:
|
||||||
|
raise ValueError('在途委托超出轮换核验上限')
|
||||||
|
with books.scope('all'):
|
||||||
|
for row in rows:
|
||||||
|
parent = pms_repo.get_instruction(row['parent_id'])
|
||||||
|
if not parent:
|
||||||
|
raise ValueError('在途委托策略归属尚未核实')
|
||||||
|
if parent['book_id'] == books.MICRO:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def tick(now=None):
|
def tick(now=None):
|
||||||
"""交易态与所有账户委托使用相同的锁顺序:账户锁,然后轮换状态锁。"""
|
"""先独立提交轮换决定,再执行;两段均先锁账户,再锁轮换状态。"""
|
||||||
config = configuration()
|
config = configuration()
|
||||||
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
if settings.INFRA_STRATEGY_BOOK_SCHEMA and config['mode'] == 'auto':
|
||||||
|
# 撤单、限制价查询或下发失败不能回滚已经确认的入场/退出任务。
|
||||||
|
# 两段之间释放账户锁;执行段重新读取用户控制、资金和实际持仓。
|
||||||
|
with store.account_guard():
|
||||||
|
prepared = _tick(now, prepare_only=True)
|
||||||
|
if not prepared.get('prepared'):
|
||||||
|
return prepared
|
||||||
with store.account_guard():
|
with store.account_guard():
|
||||||
return _tick(now)
|
return _tick(now)
|
||||||
return _tick(now)
|
return _tick(now)
|
||||||
|
|
||||||
|
|
||||||
def _tick(now=None):
|
def _tick(now=None, *, prepare_only=False):
|
||||||
now = now or dt.datetime.now(TZ)
|
now = now or dt.datetime.now(TZ)
|
||||||
if now.tzinfo is None:
|
if now.tzinfo is None:
|
||||||
now = now.replace(tzinfo=TZ)
|
now = now.replace(tzinfo=TZ)
|
||||||
|
|
@ -244,6 +267,7 @@ def _tick(now=None):
|
||||||
store.put_once('observed:'+day, 'observed_day', {'date': day, 'rule_version': core.RULE, 'snapshot_version': value['snapshot_version']})
|
store.put_once('observed:'+day, 'observed_day', {'date': day, 'rule_version': core.RULE, 'snapshot_version': value['snapshot_version']})
|
||||||
if config['mode'] == 'observe':
|
if config['mode'] == 'observe':
|
||||||
return {'mode': 'observe', 'snapshot': value, 'blocked': errors}
|
return {'mode': 'observe', 'snapshot': value, 'blocked': errors}
|
||||||
|
exit_pending = exit_pending or bool(value and value.get('signal_ready') and value.get('signal', {}).get('high') and saved.get('rotation', {}).get('phase') in ('entering_micro', 'micro'))
|
||||||
if config['mode'] == 'auto':
|
if config['mode'] == 'auto':
|
||||||
blocked = activation_errors()
|
blocked = activation_errors()
|
||||||
# 初次启用必须完成全部验收;已确认的退出不因监控/观察证据故障卡住。
|
# 初次启用必须完成全部验收;已确认的退出不因监控/观察证据故障卡住。
|
||||||
|
|
@ -255,7 +279,6 @@ def _tick(now=None):
|
||||||
# 仅作为已确认退出的执行上下文,不写成新快照、不生成任何入场。
|
# 仅作为已确认退出的执行上下文,不写成新快照、不生成任何入场。
|
||||||
value = {'members': [], 'signal_ready': False, 'basket_ready': False,
|
value = {'members': [], 'signal_ready': False, 'basket_ready': False,
|
||||||
'effective_date': day, 'snapshot_version': saved.get('rotation', {}).get('last_snapshot'), 'signal': {}}
|
'effective_date': day, 'snapshot_version': saved.get('rotation', {}).get('last_snapshot'), 'signal': {}}
|
||||||
exit_pending = exit_pending or (value.get('signal_ready') and value.get('signal', {}).get('high') and saved.get('rotation', {}).get('phase') in ('entering_micro', 'micro'))
|
|
||||||
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
if param_store.get_bool('PMS_GLOBAL_EXEC_HALT', False):
|
||||||
config['control'] = 'pause_all'
|
config['control'] = 'pause_all'
|
||||||
elif param_store.get_bool('PMS_GLOBAL_BUY_HALT', False) and config['control'] == 'run':
|
elif param_store.get_bool('PMS_GLOBAL_BUY_HALT', False) and config['control'] == 'run':
|
||||||
|
|
@ -302,11 +325,14 @@ def _tick(now=None):
|
||||||
reserve = scale*param_store.get_float('PMS_CASH_RESERVE', 0.)
|
reserve = scale*param_store.get_float('PMS_CASH_RESERVE', 0.)
|
||||||
budget = max(0., min(cap, cash+account_mv-reserve))
|
budget = max(0., min(cap, cash+account_mv-reserve))
|
||||||
s = core.transition(state['rotation'], value, micro_qty=sum(r['total_qty'] for r in micro),
|
s = core.transition(state['rotation'], value, micro_qty=sum(r['total_qty'] for r in micro),
|
||||||
original_qty=sum(r['total_qty'] for r in original), budget=budget, control=config['control'])
|
original_qty=sum(r['total_qty'] for r in original), budget=budget, control=config['control'],
|
||||||
|
micro_pending=config['mode'] == 'auto' and exit_pending and _micro_unsettled(pending))
|
||||||
state['rotation'] = s
|
state['rotation'] = s
|
||||||
if s['phase'] == 'returning_original' and not s.get('exit_date'):
|
if s['phase'] == 'returning_original' and not s.get('exit_date'):
|
||||||
s['exit_date'] = day
|
s['exit_date'] = day
|
||||||
store.stage_locked(key, state)
|
store.stage_locked(key, state)
|
||||||
|
if prepare_only:
|
||||||
|
return {'prepared': True, 'mode': config['mode'], 'phase': s['phase']}
|
||||||
if config['mode'] == 'auto' and s['phase'] in ('entering_micro', 'returning_original'):
|
if config['mode'] == 'auto' and s['phase'] in ('entering_micro', 'returning_original'):
|
||||||
from app.services import executor
|
from app.services import executor
|
||||||
for old in pending:
|
for old in pending:
|
||||||
|
|
|
||||||
|
|
@ -140,8 +140,64 @@ class Acceptance(unittest.TestCase):
|
||||||
self.assertEqual(stored['rotation']['exit_date'], '2024-01-02')
|
self.assertEqual(stored['rotation']['exit_date'], '2024-01-02')
|
||||||
self.assertEqual(qmt_repo.list_orders(), [])
|
self.assertEqual(qmt_repo.list_orders(), [])
|
||||||
self.snap = None # 下一跳模拟重启后监控失联,退出事实仍须存在。
|
self.snap = None # 下一跳模拟重启后监控失联,退出事实仍须存在。
|
||||||
|
try:
|
||||||
|
service.tick(self.now+dt.timedelta(minutes=1))
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
self.assertEqual(store.get('state:live')[0]['rotation']['phase'], 'returning_original')
|
||||||
|
|
||||||
|
def test_entry_is_saved_before_cancel_failure(self):
|
||||||
|
parent('original-buy', book='original', code='600101.SH')
|
||||||
|
self.mock(service, 'reconcile_books', return_value={'ok': True, 'diffs': []})
|
||||||
|
from app.services import executor
|
||||||
|
self.mock(executor, 'cancel_instruction', return_value={'ok': False})
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
service.tick(self.now)
|
||||||
|
stored, _ = store.get('state:live')
|
||||||
|
self.assertEqual(stored['rotation']['phase'], 'entering_micro')
|
||||||
|
self.assertEqual(stored['rotation']['consumed_entry'], self.snap['snapshot_version'])
|
||||||
|
self.assertIsNotNone(service.original_buy_blocker())
|
||||||
|
self.assertEqual(qmt_repo.list_orders(), [])
|
||||||
|
|
||||||
|
def test_zero_positions_wait_for_downstream_cancel(self):
|
||||||
|
store.put_once('state:live', 'state', {'rotation': {**core.initial_state(), 'phase': 'entering_micro', 'cycle': 1}})
|
||||||
|
parent('old-buy')
|
||||||
|
qmt_repo.enqueue_order(**{**payload('old-buy'), 'parent_id': 'old-buy'})
|
||||||
|
self.snap = snapshot('2024-01-02', high=True)
|
||||||
|
self.mock(service, 'reconcile_books', return_value={'ok': True, 'diffs': []})
|
||||||
|
from app.services import dispatcher
|
||||||
|
self.mock(dispatcher, 'mode', return_value='ws')
|
||||||
|
self.mock(dispatcher, 'channel_status', return_value={'online': True})
|
||||||
|
service.tick(self.now)
|
||||||
|
self.assertEqual(store.get('state:live')[0]['rotation']['phase'], 'returning_original')
|
||||||
|
with books.scope('micro30'):
|
||||||
|
self.assertEqual(pms_repo.get_instruction('old-buy')['status'], 'CANCELLED')
|
||||||
|
child = qmt_repo.get_order('old-buy_D01')
|
||||||
|
self.assertEqual(child['cancel_state'], 'REQUESTED')
|
||||||
|
self.assertNotIn(child['status'], qmt_repo.FINAL)
|
||||||
|
self.snap = None
|
||||||
service.tick(self.now+dt.timedelta(minutes=1))
|
service.tick(self.now+dt.timedelta(minutes=1))
|
||||||
self.assertEqual(store.get('state:live')[0]['rotation']['phase'], 'returning_original')
|
self.assertEqual(store.get('state:live')[0]['rotation']['phase'], 'returning_original')
|
||||||
|
db.execute("UPDATE pms_qmt_order SET status='CANCELLED' WHERE instruction_id='old-buy_D01'")
|
||||||
|
service.tick(self.now+dt.timedelta(minutes=2))
|
||||||
|
self.assertEqual(store.get('state:live')[0]['rotation']['phase'], 'original')
|
||||||
|
self.assertEqual(len(qmt_repo.list_orders()), 1)
|
||||||
|
|
||||||
|
def test_exit_survives_missing_validation_and_limit_service(self):
|
||||||
|
store.put_once('state:live', 'state', {'rotation': {**core.initial_state(), 'phase': 'micro', 'cycle': 1}})
|
||||||
|
with books.scope('micro30'):
|
||||||
|
pms_repo.ensure_position('600100.SH')
|
||||||
|
pms_repo.bump_position_qty('600100.SH', total_delta=100, avail_delta=100)
|
||||||
|
self.snap = snapshot('2024-01-02', high=True)
|
||||||
|
self.mock(service, 'activation_errors', return_value=['验收记录暂不可用'])
|
||||||
|
self.mock(service, 'reconcile_books', return_value={'ok': True, 'diffs': []})
|
||||||
|
self.mock(service, '_limits', side_effect=RuntimeError('fixture limits unavailable'))
|
||||||
|
with self.assertRaises(RuntimeError):
|
||||||
|
service.tick(self.now)
|
||||||
|
stored, _ = store.get('state:live')
|
||||||
|
self.assertEqual(stored['rotation']['phase'], 'returning_original')
|
||||||
|
self.assertEqual(stored['rotation']['reason'], '微盘活跃度高位')
|
||||||
|
self.assertEqual(qmt_repo.list_orders(), [])
|
||||||
|
|
||||||
def test_user_conflict_keeps_pause_when_cancel_fails(self):
|
def test_user_conflict_keeps_pause_when_cancel_fails(self):
|
||||||
store.put_once('state:live', 'state', {'rotation': {**core.initial_state(), 'phase': 'micro'}})
|
store.put_once('state:live', 'state', {'rotation': {**core.initial_state(), 'phase': 'micro'}})
|
||||||
|
|
|
||||||
|
|
@ -80,6 +80,12 @@ class RotationTests(unittest.TestCase):
|
||||||
s = m.initial_state();s['phase'] = 'entering_micro'
|
s = m.initial_state();s['phase'] = 'entering_micro'
|
||||||
r = m.transition(s, snapshot(high=True), micro_qty=100, original_qty=100, budget=100)
|
r = m.transition(s, snapshot(high=True), micro_qty=100, original_qty=100, budget=100)
|
||||||
self.assertEqual(r['phase'], 'returning_original')
|
self.assertEqual(r['phase'], 'returning_original')
|
||||||
|
r = m.transition(s, snapshot(high=True), micro_qty=0, original_qty=100, budget=100, micro_pending=True)
|
||||||
|
self.assertEqual(r['phase'], 'returning_original')
|
||||||
|
r = m.transition(r, None, micro_qty=0, original_qty=100, budget=100, micro_pending=True)
|
||||||
|
self.assertEqual(r['phase'], 'returning_original')
|
||||||
|
r = m.transition(r, None, micro_qty=0, original_qty=100, budget=100)
|
||||||
|
self.assertEqual(r['phase'], 'original')
|
||||||
|
|
||||||
def test_missing_signal_does_not_exit(self):
|
def test_missing_signal_does_not_exit(self):
|
||||||
s = m.initial_state();s['phase'] = 'micro'
|
s = m.initial_state();s['phase'] = 'micro'
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue