tradingSystem/app/services/buy_budget.py

167 lines
8.1 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.

"""试探预算贯穿提议、父指令和真实委托;不另外冻结或重复扣账户现金。"""
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
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 before_parent(code, *, action='OPEN', exclude=None):
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']
budget = parent_budget(parent)
# 原建仓预算仅约束该父指令;后续策略沿各自审批、额度和退出纪律。
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)