tradingSystem/app/core/grid_inventory.py

96 lines
4.9 KiB
Python
Raw Normal View History

"""网格只认已入账的剩余批次;几何档位与实际成交价各司其职。"""
from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR
from datetime import datetime
from app.core.cushion import sell_allocation
from app.core.execution_policy import supported_code
def price_tick(value, *, sell=False):
value = Decimal(str(value))
if not value.is_finite() or value <= 0:
raise ValueError('网格价格必须为有限正数')
return float(value.quantize(Decimal('.01'), rounding=ROUND_CEILING if sell else ROUND_FLOOR))
def project(strategy, lots, parents):
"""输入同证券、同账本剩余批次及父指令,输出本网格真实库存。无网络与写入。"""
sid, code = strategy['strategy_id'], strategy['ts_code']
if not supported_code(code):
raise ValueError('网格仅支持沪深A股')
params = strategy.get('params') or {}
pct = Decimal(str(params.get('step_pct') or 0))
step = Decimal(str(params.get('step') or 0))
if not pct.is_finite() or not step.is_finite() or (pct <= 0 and step <= 0):
raise ValueError('网格档距无法核实')
# 与真实成交及成交修正共用核销顺序:增量按开仓日新→旧,同日按批次编号。
# 做T批次的核销优先级更高,未平时不能将网格卖单误记入做T。
open_lots = [lot for lot in lots if int(lot.get('qty') or 0) > 0]
if any(lot.get('lot_type') == 'T0' for lot in open_lots):
raise ValueError('同股仍有未平做T批次,网格等待核对')
candidates, by_id = [], {}
for lot in open_lots:
if lot.get('lot_type') != 'ADD':
continue
lid = int(lot['id'])
if lid in by_id:
raise ValueError('网格批次重复')
day = datetime.strptime(str(lot.get('open_date'))[:10].replace('-', ''), '%Y%m%d')
candidates.append({'lot_id':lid, 'lot_type':'ADD', 'qty':int(lot['qty']), 'open_date':int(day.strftime('%Y%m%d'))})
by_id[lid] = lot
candidates.sort(key=lambda row:(row['open_date'], row['lot_id']))
ordered = sell_allocation(candidates, sum(row['qty'] for row in candidates))
filled, invested = {}, Decimal(0)
for allocation in ordered:
lot = by_id[allocation['lot_id']]
qty = int(lot.get('qty') or 0)
if qty <= 0 or lot.get('lot_type') != 'ADD':
continue
parent = parents.get(lot.get('instruction_id'))
if (lot.get('ts_code') != code or not parent or parent.get('ts_code') != code
or parent.get('origin_type') != 'strategy' or parent.get('origin_id') != sid
or parent.get('side') != 'buy' or parent.get('action') != 'ADD'):
raise ValueError('同股存在无法归属本网格的增量批次,停止网格动作等待核对')
if lot.get('book_id', 'original') != 'original' or parent.get('book_id', 'original') != 'original':
raise ValueError('网格批次账本归属不一致')
progress = parent.get('progress') or {}
if not str(progress.get('leg', '')).startswith('grid_buy:'):
raise ValueError('网格批次缺少买入来源')
cost = Decimal(str(lot['open_price']))
if not cost.is_finite() or cost <= 0:
raise ValueError('网格实际成交成本不可核实')
target = cost + step if step > 0 else cost * (1 + pct)
# 旧档距的目标不继承;存量采用本次已批准档距和实际买价。
entry = progress.get('grid_entry')
if progress.get('grid_params') == params and entry is not None:
target = max(target, Decimal(str(progress['grid_exit'])))
key = str(lot['id'])
if key in filled:
raise ValueError('网格批次重复')
filled[key] = {'qty': qty, 'price': float(cost), 'sell_target': price_tick(target, sell=True),
'entry_level': entry if progress.get('grid_params') == params else None,
'buy_instruction_id': parent['instruction_id'], 'lot_id': lot['id']}
invested += qty * cost
return {'filled_levels': filled, 'invested': float(invested), 'inventory_source': 'booked_lots'}
def sell_slice(filled, qty, *, price=None):
"""按账本顺序取连续的可卖批次;任一批未到价便停止,不跨过它核销后面的批次。"""
remaining = int(qty)
slices, floor = [], 0.
for key, row in filled.items():
available = int(row.get('qty') or 0)
if available <= 0:
continue
target = float(row.get('sell_target') or 0)
price_tick(target, sell=True) # 同时拒绝未知、无穷或NaN边界。
if price is not None and price < target:
break
take = min(remaining, available)
if take > 0:
slices.append({'lot_id':row.get('lot_id'), 'qty':take})
floor = max(floor, target)
remaining -= take
if remaining <= 0:
break
return {'qty':int(qty)-remaining, 'lots':slices, 'limit_price':floor}