tradingSystem/app/services/execution_basis.py

133 lines
7.6 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.

"""独立刷新执行依据;在途监控不做HTTP,也不因配额已占用而跳过。"""
import time
from datetime import timedelta
from app.core import execution_policy as policy, strategy_book as books
from app.repo import pms_repo, execution_repo
from app.services import param_store, execution_orders
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED')
def uses_basis(parent):
progress = parent.get('progress') or {}
# STOP 表达看空或离场,不能反向禁止已经获准的减仓和退出。
return (parent.get('side') == 'buy'
and progress.get('execution_profile') != 'rotation'
and not (progress.get('origin') == 'strategy' and progress.get('stype') in ('GRID', 'TRAIL')))
def cache_reason(progress, now=None):
cache = (progress or {}).get('execution_basis_cache') or {}
return policy.basis_reason(cache.get('basis'), now,
max_source_days=max(0, param_store.get_int('PMS_EXEC_BASIS_SOURCE_MAX_DAYS', 7)))
def refresh(now=None):
"""短请求有整轮预算。失败留痕,但不会把旧依据时间重新延长。"""
from app.services import exec_advisor, market
current = policy.local_now(now)
out = {'enabled': execution_orders.enabled(), 'refreshed': [], 'errors': [], 'skipped': []}
if not out['enabled']:
return out
deadline = time.monotonic()+max(1, param_store.get_int('PMS_EXEC_BASIS_REFRESH_BUDGET_SEC', 20))
with books.scope('all'):
parents = pms_repo.list_instructions(statuses=list(LIVE), limit=10000)
parents.sort(key=lambda p: ((p.get('progress') or {}).get('execution_basis_cache') or {}).get('fetched_at', ''))
for parent in parents:
if not policy.supported_code(parent.get('ts_code')) or not uses_basis(parent) or (parent.get('progress') or {}).get('cancel_requested'):
continue
cache = dict((parent.get('progress') or {}).get('execution_basis_cache') or {})
due = policy.timestamp(cache.get('refresh_after'))
if due and current < due:
continue
left = deadline-time.monotonic()
if left < 1:
out['skipped'].append('本轮执行依据刷新预算用尽')
break
fresh = dict(cache)
try:
if not exec_advisor.available():
raise ValueError('执行依据来源未配置')
with books.scope(parent.get('book_id') or books.ORIGINAL):
position = pms_repo.get_position(parent['ts_code']) or {}
day = market.day_snapshot(parent['ts_code'])
payload = {'direction': 'PMS_EXEC', 'ts_code': parent['ts_code'],
'side': parent['side'], 'action': parent.get('action'),
'qty_left': max(0, int(parent['qty'])-int(parent.get('exec_qty') or 0)),
'now': current.strftime('%H:%M'), 'day': day,
'refs': {k: position.get(k+'_ref') for k in ('support', 'pressure', 'stop')},
'position': {k: position.get(k) for k in ('total_qty', 'avail_qty', 'avg_cost')},
'is_last_day': False, 'tdays_left': None}
response = exec_advisor._post(exec_advisor.base_url()+param_store.get('PMS_EXEC_PATH', '/api/intraday/pms_exec'),
payload, max(1, min(param_store.get_int('PMS_EXEC_TIMEOUT_SEC', 8), int(left))))
if not isinstance(response, dict):
raise ValueError('执行依据响应格式无效')
basis = response.get('execution_basis')
# 明确未知或停止立即覆盖旧事实。只有传输失败可保留尚在有效期内的旧依据。
fresh = {'basis': basis if isinstance(basis, dict) else {},
'observed': response.get('observed') or {}, 'error': ''}
reason = policy.basis_reason(fresh['basis'], current,
max_source_days=max(0, param_store.get_int('PMS_EXEC_BASIS_SOURCE_MAX_DAYS', 7)))
if reason:
fresh['error'] = reason
except Exception as exc:
fresh['error'] = str(exc)[:300]
out['errors'].append({'instruction_id': parent['instruction_id'], 'error': fresh['error']})
fresh['fetched_at'] = current.isoformat()
fresh['refresh_after'] = (current+timedelta(seconds=max(1,
param_store.get_int('PMS_EXEC_BASIS_REFRESH_SEC', 60)))).isoformat()
with books.scope(parent.get('book_id') or books.ORIGINAL):
execution_repo.save_basis(parent['instruction_id'], fresh)
out['refreshed'].append(parent['instruction_id'])
return out
def monitor(now=None, cancel_only=False):
from app.services import executor, market
current = policy.local_now(now)
out = {'cancelled': [], 'replacing': [], 'errors': []}
with books.scope('all'):
parents = pms_repo.list_instructions(statuses=list(LIVE)+['CANCELLED', 'EXPIRED'], limit=10000)
for parent in parents:
if not policy.supported_code(parent.get('ts_code')):
continue
try:
with books.scope(parent.get('book_id') or books.ORIGINAL):
progress = parent.get('progress') or {}
if progress.get('cancel_requested') or parent.get('status') in ('CANCELLED', 'EXPIRED'):
result = executor.cancel_instruction(parent['instruction_id'],
reason=(progress.get('cancel_requested') or {}).get('reason', '继续确认撤单'), arbiter='system')
if not result.get('ok'):
raise ValueError(result.get('error') or result.get('message'))
out['cancelled'].append(result)
continue
if cancel_only:
continue
if not execution_orders.enabled() or progress.get('execution_profile') == 'rotation':
continue
state = execution_orders.replacement_state(parent['instruction_id'])
if not state['active']:
continue
reason = cache_reason(progress, current) if uses_basis(parent) else ''
if reason:
result = execution_orders.request_replace(parent['instruction_id'], reason, current)
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': reason, 'pending': result['pending']})
continue
try:
quote = market.execution_quote(parent['ts_code'], now=current)
desired = execution_orders.quote_order(parent['side'], quote, current,
user_limit=progress.get('user_limit_price', parent.get('limit_price')),
anchor_price=progress.get('execution_anchor_price'))
except Exception as exc:
desired = {'action': 'WAIT', 'reason': '行情读取失败,等待恢复:'+str(exc)[:200]}
if desired.get('action') != 'FIRE':
result = execution_orders.request_replace(parent['instruction_id'], desired['reason'], current)
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': desired['reason'], 'pending': result['pending']})
continue
if execution_orders.should_replace(parent, desired, current):
result = execution_orders.request_replace(parent['instruction_id'], desired['reason'], current)
out['replacing'].append({'instruction_id': parent['instruction_id'], 'reason': desired['reason'], 'pending': result['pending']})
except Exception as exc:
out['errors'].append({'instruction_id': parent['instruction_id'], 'error': str(exc)[:300]})
return out