tradingSystem/app/services/timing_fusion.py

64 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""周期采纳Bionic合成方向,原始证据随状态和账本留存。"""
from datetime import datetime
from config.settings import settings
from app.core import timing_fusion_contract as contract, risk_exit as rules, strategy_book as books
from app.repo import rotation_repo, pms_repo
from app.services import param_store
def enabled():
return (settings.INFRA_STRATEGY_BOOK_SCHEMA and not settings.PMS_TABLE_PREFIX
and param_store.get_bool('PMS_TIMING_FUSION_ENABLED', False))
def request_fields():
return {'timing_fusion_scope': 'pms-sim-155'} if enabled() else {}
def refresh(*, now=None, dry_run=False):
if not enabled():
return {'enabled': False}
import requests
from app.services import exec_advisor, timing_state, risk_exit
now = now or datetime.now()
response = requests.get(exec_advisor.base_url()+'/api/intraday/timing_fusion', timeout=(2,5))
response.raise_for_status()
data = response.json()
if data.get('version') != contract.VERSION or data.get('enabled') is not True:
raise ValueError('合成择时来源未就绪')
states = data.get('states')
if not isinstance(states, list) or len(states)>6000:
raise ValueError('合成择时响应超过完整读取边界')
out = {'enabled': True, 'accepted': 0, 'invalid': 0, 'source_errors': data.get('errors', []), 'actions': []}
for state in states:
event = contract.valid(state, now, since=param_store.get('PMS_TIMING_FUSION_START_AT', ''))
if not event:
out['invalid'] += 1
continue
code = event['ts_code']
if dry_run:
out['accepted'] += 1
continue
with rotation_repo.account_guard(), rotation_repo.locked(timing_state.key(code), timing_state.KIND, {}) as current:
if current and rules.stamp(current.get('verified_at') or current.get('at')) > rules.stamp(event['verified_at']):
continue
changed = current.get('key') != event['key']
current.clear()
current.update(event)
if changed:
with books.scope(books.ORIGINAL):
if pms_repo.insert_ledger(ts_code=code, action='SIGNAL', arbiter='system', verdict='NOTE',
price_at=0, hard_numbers={'timing_direction':event}, reason=event['reason'],
ref_id=event['key'][:64]) != 1:
raise RuntimeError('合成择时依据未成功入账')
out['accepted'] += 1
if event['action'] == 'BUY':
result = risk_exit.recover_on_buy(code, event, now=now)
elif event['action'] == 'SELL':
result = risk_exit.on_signal(event, now=now)
else:
continue
out['actions'].append({'ts_code':code, 'action':event['action'], 'result':result})
return out