"""网格只认已入账的剩余批次;几何档位与实际成交价各司其职。""" from decimal import Decimal, ROUND_CEILING, ROUND_FLOOR 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'] 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('网格档距无法核实') filled, invested = {}, Decimal(0) for lot in lots: 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'}