237 lines
11 KiB
Python
237 lines
11 KiB
Python
|
|
"""试探预算贯穿提议、父指令和真实委托;不另外冻结或重复扣账户现金。"""
|
|||
|
|
from copy import deepcopy
|
|||
|
|
from decimal import Decimal
|
|||
|
|
from app.core import buy_budget as core, strategy_book as books
|
|||
|
|
from app.repo import pms_repo, qmt_repo
|
|||
|
|
from config.settings import settings
|
|||
|
|
|
|||
|
|
LIVE = ('PROPOSED', 'RULE_PASSED', 'JUDGE_PASSED', 'DISPATCHED', 'WAIT_REVIEW')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def from_hard(hard, code):
|
|||
|
|
if hard.get('buy_budget') is not None:
|
|||
|
|
return deepcopy(core.validate(hard['buy_budget'], code))
|
|||
|
|
advice = hard.get('advice')
|
|||
|
|
if advice is None and hard.get('sizing_scale') is not None:
|
|||
|
|
advice = {'tier': '标准仓', 'target_pct': hard.get('target_pct'),
|
|||
|
|
'splits': tuple(str(hard.get('batch_scheme') or '1.0').split(','))}
|
|||
|
|
if isinstance(advice, dict):
|
|||
|
|
return core.resize(advice, hard, code)['buy_budget']
|
|||
|
|
return None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def candidate(hard, code, qty, price=None):
|
|||
|
|
budget = from_hard(hard, code)
|
|||
|
|
if budget is not None:
|
|||
|
|
core.check_quantity(budget, code, qty, price if price is not None else hard.get('price'))
|
|||
|
|
elif settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
|||
|
|
raise ValueError('缺少可追溯的建仓预算,暂不建仓')
|
|||
|
|
return budget
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _source_hard(parent):
|
|||
|
|
prog = parent.get('progress') or {}
|
|||
|
|
refs = [parent['instruction_id']]
|
|||
|
|
if parent.get('origin_type') == 'proposal' and parent.get('origin_id'):
|
|||
|
|
refs.append(parent['origin_id'])
|
|||
|
|
if prog.get('from_proposal'):
|
|||
|
|
refs.append(prog['from_proposal'])
|
|||
|
|
rows = pms_repo.ledger_by_ref(refs, limit=1001)
|
|||
|
|
if len(rows) >= 1001:
|
|||
|
|
raise ValueError('原建仓审计超过核验范围,暂停新增买入')
|
|||
|
|
values = [r.get('hard_numbers') or {} for r in rows
|
|||
|
|
if r.get('verdict') == 'PASS' and r.get('action') == 'OPEN']
|
|||
|
|
values = [v for v in values if v.get('advice') or v.get('buy_budget')]
|
|||
|
|
if not values:
|
|||
|
|
# 老提议的保存内容只能用于已明确关联的父指令,不能拿当天新建议补旧预算。
|
|||
|
|
for ref in dict.fromkeys(refs[1:]):
|
|||
|
|
p = pms_repo.get_proposal(ref)
|
|||
|
|
if p and p.get('status') == 'ACCEPTED' and p.get('ts_code') == parent['ts_code']:
|
|||
|
|
h = p.get('hard_numbers') or {}
|
|||
|
|
if h.get('advice') or h.get('buy_budget'):
|
|||
|
|
values.append(h)
|
|||
|
|
if not values:
|
|||
|
|
return None
|
|||
|
|
# 同一来源有试探证据时采用较小预算,重评不能把旧试探变成标准仓。
|
|||
|
|
trials = [h for h in values if (h.get('advice') or h.get('buy_budget') or {}).get('tier') == '试探仓']
|
|||
|
|
if trials:
|
|||
|
|
return min(trials, key=lambda h: core.number(from_hard(h, parent['ts_code'])['amount'], '原建仓预算'))
|
|||
|
|
return values[0]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def explicit_command(parent):
|
|||
|
|
"""命令身份来自真实命令和方案;网格、做T的is_command不构成扩大预算授权。"""
|
|||
|
|
if parent.get('origin_type') != 'plan' or not parent.get('origin_id'):
|
|||
|
|
return False
|
|||
|
|
plan = pms_repo.get_plan(parent['origin_id'])
|
|||
|
|
if not plan or plan.get('ts_code') != parent['ts_code']:
|
|||
|
|
return False
|
|||
|
|
command = pms_repo.get_command(plan.get('command_id'))
|
|||
|
|
issuer = str((command or {}).get('issued_by') or '')
|
|||
|
|
return bool(command and issuer and issuer not in ('rotation', 'system', 'auto')
|
|||
|
|
and not issuer.startswith('macro')
|
|||
|
|
and command.get('cmd_type') in ('OPEN_TARGET', 'INCREASE_EXPOSURE'))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def parent_budget(parent):
|
|||
|
|
if parent.get('side') != 'buy' or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL:
|
|||
|
|
return None
|
|||
|
|
prog = parent.get('progress') or {}
|
|||
|
|
if prog.get('buy_budget') is not None:
|
|||
|
|
return deepcopy(core.validate(prog['buy_budget'], parent['ts_code']))
|
|||
|
|
if explicit_command(parent):
|
|||
|
|
plan = pms_repo.get_plan(parent['origin_id'])
|
|||
|
|
amount = core.number(plan.get('amount'), '命令计划预算')
|
|||
|
|
value = {'version': core.VERSION, 'ts_code': parent['ts_code'], 'amount': str(amount),
|
|||
|
|
'scale': str(amount), 'target_pct': '1', 'quantity_limit': int(plan['qty']),
|
|||
|
|
'tier': '用户命令', 'command_id': plan['command_id'], 'plan_id': parent['origin_id'],
|
|||
|
|
'basis': '命令批准的买入成交金额,不含另记的交易费用'}
|
|||
|
|
value['revision'] = core.identity(value)
|
|||
|
|
return core.validate(value, parent['ts_code'])
|
|||
|
|
if not settings.INFRA_STRATEGY_BOOK_SCHEMA:
|
|||
|
|
return None
|
|||
|
|
if parent.get('action') == 'OPEN' and parent.get('origin_type') != 'strategy':
|
|||
|
|
hard = _source_hard(parent)
|
|||
|
|
if hard is None:
|
|||
|
|
raise ValueError('旧建仓指令的原预算无法核实,停止续买,等待重新明确计划')
|
|||
|
|
return from_hard(hard, parent['ts_code'])
|
|||
|
|
return None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _holding_blocker(code, *, parent_id=None):
|
|||
|
|
"""当前轮次只要仍有试探仓,不经明确新命令扩大;底仓卖光也不解除。"""
|
|||
|
|
if not settings.INFRA_STRATEGY_BOOK_SCHEMA or books.CURRENT.get() != books.ORIGINAL:
|
|||
|
|
return ''
|
|||
|
|
pending = pms_repo.list_instructions(ts_code=code, side='buy', statuses=LIVE, limit=1001)
|
|||
|
|
if len(pending) >= 1001:
|
|||
|
|
return '买入安排超过完整核验范围,暂停自动加仓'
|
|||
|
|
for other in pending:
|
|||
|
|
if other['instruction_id'] == parent_id or other.get('action') != 'OPEN':
|
|||
|
|
continue
|
|||
|
|
limit = parent_budget(other)
|
|||
|
|
if limit and limit.get('tier') == '试探仓':
|
|||
|
|
return '该股已有试探建仓安排,不能从其他路径重复增加投入'
|
|||
|
|
position = pms_repo.get_position(code) or {}
|
|||
|
|
if int(position.get('total_qty') or 0) <= 0:
|
|||
|
|
return ''
|
|||
|
|
opened = str(position.get('opened_date') or '')[:10]
|
|||
|
|
if not opened:
|
|||
|
|
return '本轮持仓的建仓预算尚未核实,暂停自动加仓'
|
|||
|
|
lots = pms_repo.list_lots(code, status='', limit=2001)
|
|||
|
|
if len(lots) >= 2001:
|
|||
|
|
return '持仓批次超过完整核验范围,暂停自动加仓'
|
|||
|
|
active = [r for r in lots if r.get('status') == 'OPEN' and int(r.get('qty') or 0) > 0]
|
|||
|
|
if sum(int(r['qty']) for r in active) != int(position['total_qty']):
|
|||
|
|
return '持仓与批次数量待核对,暂停自动加仓'
|
|||
|
|
roots = {}
|
|||
|
|
for lot in lots:
|
|||
|
|
if str(lot.get('open_date') or '')[:10] < opened or lot.get('lot_type') != 'BASE':
|
|||
|
|
continue
|
|||
|
|
pid = lot.get('instruction_id')
|
|||
|
|
if not pid:
|
|||
|
|
return '本轮底仓来源无法核实,暂停自动加仓'
|
|||
|
|
parent = pms_repo.get_instruction(pid)
|
|||
|
|
if not parent or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL or parent.get('ts_code') != code:
|
|||
|
|
return '本轮底仓归属无法核实,暂停自动加仓'
|
|||
|
|
roots[pid] = parent
|
|||
|
|
if not roots:
|
|||
|
|
return '本轮建仓依据尚未核实,暂停自动加仓'
|
|||
|
|
for pid, parent in roots.items():
|
|||
|
|
if explicit_command(parent):
|
|||
|
|
continue
|
|||
|
|
budget = parent_budget(parent)
|
|||
|
|
if budget is None:
|
|||
|
|
return '本轮原建仓预算尚未核实,暂停自动加仓'
|
|||
|
|
if budget.get('tier') == '试探仓' and pid != parent_id:
|
|||
|
|
return '本轮为试探仓,暂停网格及其他自动加仓;扩大投入须明确新的买入命令'
|
|||
|
|
return ''
|
|||
|
|
|
|||
|
|
|
|||
|
|
def holding_blocker(code, *, parent_id=None):
|
|||
|
|
# 缺预算只暂停新增;不得因为查询失败而挡住同一轮的正常网格卖出。
|
|||
|
|
try:
|
|||
|
|
return _holding_blocker(code, parent_id=parent_id)
|
|||
|
|
except ValueError as exc:
|
|||
|
|
return str(exc)
|
|||
|
|
except Exception:
|
|||
|
|
import logging
|
|||
|
|
logging.getLogger('pms.buy_budget').exception('核对持仓建仓预算失败 %s', code)
|
|||
|
|
return '本轮建仓预算暂不可核实,暂停自动加仓;已有卖出安排继续'
|
|||
|
|
|
|||
|
|
|
|||
|
|
def before_parent(code, *, action='OPEN', exclude=None):
|
|||
|
|
blocked = holding_blocker(code)
|
|||
|
|
if blocked:
|
|||
|
|
raise ValueError(blocked)
|
|||
|
|
if settings.INFRA_STRATEGY_BOOK_SCHEMA and action == 'OPEN':
|
|||
|
|
parents = pms_repo.list_instructions(ts_code=code, side='buy', statuses=LIVE, limit=1001)
|
|||
|
|
if len(parents) >= 1001 or any(p['instruction_id'] != exclude for p in parents):
|
|||
|
|
raise ValueError('该股已有买入安排,不能重复分配建仓预算')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def allowed_quantity(parent, price, requested):
|
|||
|
|
"""按已确认成交与原预算限制本次报价;调用方在落单锁内再次执行。"""
|
|||
|
|
if parent.get('side') != 'buy' or parent.get('book_id', books.ORIGINAL) != books.ORIGINAL:
|
|||
|
|
return int(requested), ''
|
|||
|
|
from app.services import execution_orders
|
|||
|
|
code = parent['ts_code']
|
|||
|
|
prog = parent.get('progress') or {}
|
|||
|
|
budget = parent_budget(parent)
|
|||
|
|
# 平回做T只恢复先前卖出的库存;新增腿仍受持仓预算约束。
|
|||
|
|
closing = prog.get('stype') == 'T0' and prog.get('leg') == 'close'
|
|||
|
|
if not explicit_command(parent) and not closing:
|
|||
|
|
blocked = holding_blocker(code, parent_id=parent['instruction_id'])
|
|||
|
|
if blocked:
|
|||
|
|
return 0, blocked
|
|||
|
|
if budget is None:
|
|||
|
|
return int(requested), ''
|
|||
|
|
state = execution_orders.replacement_state(parent['instruction_id'])
|
|||
|
|
if not state['ready']:
|
|||
|
|
return 0, '原委托或成交尚未结清,不能释放建仓预算'
|
|||
|
|
spent = Decimal(0)
|
|||
|
|
if state['confirmed_filled']:
|
|||
|
|
# 逐笔批次保留实际成交价,包含已卖出的份额;不以当前市值或四舍五入的均价释放额度。
|
|||
|
|
lots = pms_repo.list_lots(code, status='', limit=2001)
|
|||
|
|
if len(lots) >= 2001:
|
|||
|
|
raise ValueError('实际成交批次超过完整核验范围,停止续买')
|
|||
|
|
filled = 0
|
|||
|
|
for lot in lots:
|
|||
|
|
if lot.get('instruction_id') != parent['instruction_id']:
|
|||
|
|
continue
|
|||
|
|
remaining_qty = core.number(lot.get('qty'), '批次剩余数量', zero=True)
|
|||
|
|
closed_qty = core.number(lot.get('closed_qty', 0), '批次已卖数量', zero=True)
|
|||
|
|
done = remaining_qty + closed_qty
|
|||
|
|
if done != int(done):
|
|||
|
|
raise ValueError('批次数量不可核实,停止续买')
|
|||
|
|
if done:
|
|||
|
|
spent += done * core.number(lot.get('open_price'), '实际成交价格')
|
|||
|
|
filled += int(done)
|
|||
|
|
if filled != state['confirmed_filled']:
|
|||
|
|
raise ValueError('实际成交批次与委托累计量不一致,停止释放预算')
|
|||
|
|
remaining = max(Decimal(0), core.number(budget['amount'], '原建仓预算') - spent)
|
|||
|
|
count = min(int(requested), state['remaining'], core.quantity(remaining, price, code),
|
|||
|
|
max(0, int(budget['quantity_limit']) - state['confirmed_filled']))
|
|||
|
|
from app.core.sizer import lot_of
|
|||
|
|
count = count // 100 * 100
|
|||
|
|
if count < lot_of(code):
|
|||
|
|
return 0, '原建仓预算的剩余额度不足最低买入量,停止续买'
|
|||
|
|
return count, ''
|
|||
|
|
|
|||
|
|
|
|||
|
|
def check_order(parent, payload):
|
|||
|
|
count, reason = allowed_quantity(parent, payload['limit_price'], payload['qty'])
|
|||
|
|
if count != int(payload['qty']):
|
|||
|
|
raise ValueError(reason or '本次报价超过原建仓预算,需减少数量后重新检查')
|
|||
|
|
|
|||
|
|
|
|||
|
|
def accept_open(old, hard, instruction, reason):
|
|||
|
|
from app.services import execution_orders
|
|||
|
|
with execution_orders.account_guard():
|
|||
|
|
budget = candidate(hard, old['ts_code'], old['qty'])
|
|||
|
|
before_parent(old['ts_code'])
|
|||
|
|
if budget is not None:
|
|||
|
|
hard = dict(hard, buy_budget=budget)
|
|||
|
|
instruction = deepcopy(instruction)
|
|||
|
|
instruction['progress']['buy_budget'] = budget
|
|||
|
|
return pms_repo.accept_open_proposal(old, hard, instruction, reason)
|