133 lines
5.5 KiB
Python
133 lines
5.5 KiB
Python
"""独立采集进程的限制价目标清单。只读资料,不授权交易或写入业务状态。
|
||
|
||
监控读取复用 rotation_service.pull,HTTP 连接和读取超时分别为 3、15 秒。
|
||
本函数不得在下单事务或账户锁内调用。未冻结快照只用于预取限制价,
|
||
实际轮换仍须执行原有的冻结、信号、资金和权限校验。
|
||
"""
|
||
import datetime as dt
|
||
import re
|
||
|
||
from app.core import micro_rotation, strategy_book as books
|
||
from app.repo import pms_repo, qmt_repo, rotation_repo
|
||
from app.services import rotation_service
|
||
|
||
|
||
SOURCE_CAP = 5000
|
||
# 仓储 recent 自身最多返回 1000 行,不能按 5000 行误判为读取完整。
|
||
SNAPSHOT_CAP = 1000
|
||
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
||
|
||
|
||
def collect_targets(day):
|
||
"""返回证券、逐来源错误和来源名;一个来源失败不丢弃其他已知证券。"""
|
||
day = day.isoformat() if isinstance(day, dt.date) and not isinstance(day, dt.datetime) else day
|
||
try:
|
||
if not isinstance(day, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
|
||
raise ValueError('date')
|
||
dt.date.fromisoformat(day)
|
||
except (TypeError, ValueError):
|
||
return {'codes': [], 'errors': ['目标交易日格式无效'], 'sources': {}}
|
||
|
||
sources, errors = {}, []
|
||
|
||
def error(reason):
|
||
if reason not in errors:
|
||
errors.append(reason)
|
||
|
||
def add(code, name):
|
||
code = code.strip().upper() if isinstance(code, str) else ''
|
||
if micro_rotation.mainland_code(code):
|
||
sources.setdefault(code, set()).add(name)
|
||
|
||
def read(name, loader, cap=SOURCE_CAP):
|
||
try:
|
||
rows = loader()
|
||
except Exception:
|
||
error(name+'读取失败')
|
||
return []
|
||
if not isinstance(rows, list):
|
||
error(name+'记录格式异常')
|
||
return []
|
||
if len(rows) >= cap:
|
||
error(name+'达到读取上限,结果可能不完整')
|
||
return rows[:cap]
|
||
|
||
with books.scope('all'):
|
||
loaders = (
|
||
('策略持仓', lambda: pms_repo.list_positions(only_open=True)),
|
||
('待执行指令', lambda: pms_repo.list_instructions(statuses=LIVE, limit=SOURCE_CAP)),
|
||
('QMT在途委托', lambda: qmt_repo.list_orders(statuses=qmt_repo.LIVE, limit=SOURCE_CAP)),
|
||
('执行计划', lambda: pms_repo.list_plans(statuses=('PENDING', 'GATED', 'EXECUTING'), limit=SOURCE_CAP)),
|
||
('交易建议', lambda: pms_repo.list_proposals(statuses=('WAIT_USER', 'ACCEPTED'), limit=SOURCE_CAP)),
|
||
)
|
||
for name, loader in loaders:
|
||
for row in read(name, loader):
|
||
if not isinstance(row, dict) or 'ts_code' not in row:
|
||
error(name+'记录格式异常')
|
||
continue
|
||
add(row['ts_code'], name)
|
||
|
||
try:
|
||
state, _ = rotation_repo.get('state:live')
|
||
rotation = (state or {}).get('rotation') or {}
|
||
targets = rotation.get('target') or []
|
||
if not isinstance(targets, list):
|
||
raise ValueError('target')
|
||
if len(targets) >= SOURCE_CAP:
|
||
error('微盘执行目标达到读取上限,结果可能不完整')
|
||
for code in targets[:SOURCE_CAP]:
|
||
add(code, '微盘执行目标')
|
||
except Exception:
|
||
error('微盘执行目标读取失败')
|
||
|
||
try:
|
||
config = rotation_service.configuration()
|
||
rule = config['rule_version']
|
||
pool_size = config.get('candidate_pool_size', 100)
|
||
micro_rotation.rule_parameters(rule, pool_size)
|
||
except Exception:
|
||
error('微盘运行规则读取失败')
|
||
config = None
|
||
|
||
def snapshot_codes(value, name):
|
||
if not isinstance(value, dict):
|
||
error(name+'记录格式异常')
|
||
return
|
||
# effective_date 是既有快照的执行日字段;历史日期和历史规则不参与本次采集。
|
||
if value.get('effective_date') != day or value.get('rule_version') != rule:
|
||
return
|
||
try:
|
||
issues = micro_rotation.snapshot_check(value, day, require_frozen=False,
|
||
expected_rule=rule, candidate_pool_size=pool_size)
|
||
except Exception:
|
||
issues = ['invalid']
|
||
if issues:
|
||
error(name+'校验未通过')
|
||
return
|
||
if not value.get('basket_ready'):
|
||
error(name+'名单尚未就绪')
|
||
return
|
||
members = value['candidates'] if rule == micro_rotation.EXECUTION_RULE else value['members']
|
||
for member in members:
|
||
add(member['code'], name)
|
||
|
||
if config is not None:
|
||
for row in read('近期微盘快照', lambda: rotation_repo.recent('snapshot', limit=SNAPSHOT_CAP), SNAPSHOT_CAP):
|
||
snapshot_codes(row.get('value') if isinstance(row, dict) else None, '微盘保存快照')
|
||
if not config.get('url'):
|
||
error('微盘监控地址未配置')
|
||
else:
|
||
try:
|
||
value = rotation_service.pull(day)
|
||
except Exception:
|
||
error('微盘监控快照读取失败')
|
||
else:
|
||
if not isinstance(value, dict) or value.get('effective_date') != day or value.get('rule_version') != rule:
|
||
error('微盘监控快照日期或规则不符')
|
||
else:
|
||
snapshot_codes(value, '微盘监控快照')
|
||
|
||
codes = sorted(sources)
|
||
return {'codes': codes, 'errors': errors,
|
||
'sources': {code: sorted(sources[code]) for code in codes}}
|