"""日内先卖后买的做 T 规则,不包含趋势补仓或整仓止盈。""" import logging as log import math from libs.grid_take_profit import GridState from sdk import OP_BUY, OP_SELL, PositionItem from libs.order import PlaceOrderRequest from libs.runtime import Runtime def manage_positions( run: Runtime, ticks, positions: list[PositionItem], available: float, today: str, force_buy_back: bool = False, ) -> float: """遍历本地底仓记录;全部卖出后即使持仓快照为空,也必须处理买回。""" by_code = {position.stock_code: position for position in positions} for code, state in list(state_store.items.items()): try: if code in run.account_cfg.excluded_codes: continue if run.orders.busy(code, "BUY") or run.orders.busy(code, "SELL"): continue tick = ticks.get(code) price = tick.last_price if tick else 0.0 if not math.isfinite(price) or price <= 0: continue position = by_code.get(code) actual_qty = position.volume if position else 0 expected_qty = state.base_qty - state.sell_qty + state.buy_qty # 快照延迟或手动增减仓不能当作新的做 T 信号,先核对数量差异。 if actual_qty != expected_qty: log.warning( "[ZT 持仓] %s 数量不符,记录=%d,实际=%d,暂停交易", code, expected_qty, actual_qty, ) continue if state.phase == SOLD: available = _try_buy_back( run, state, price, available, force_buy_back ) elif state.phase == READY and position and not force_buy_back: if price <= run.account_cfg.zt_max_price: _try_sell(run, state, position, price, today) except Exception: log.exception("[ZT 持仓] %s 处理异常,继续后续证券", code) return available def _try_sell( run: Runtime, state, position: PositionItem, price: float, today: str, ) -> None: """基于独立保存的底仓成本,用跨轮最高盈利网格判断做 T 卖出。""" if state.base_cost <= 0: return pnl_rate = (price - state.base_cost) / state.base_cost * 100 key = f"{run.account_cfg.account_id}:{state.code}:{today}" observation = run.profit_tracker.observe(key, pnl_rate) if observation.state != GridState.RETREAT: return volume = min( position.can_use_volume, int(state.base_qty * run.account_cfg.zt_sell_ratio) ) volume = volume // 100 * 100 if volume <= 0: return order_id = run.orders.new_order_id("t-sell") request = PlaceOrderRequest( OP_SELL, state.code, volume, order_id, "zt", kind="sell" ) if run.orders.place(run.client, request): log.info("[ZT 卖出] %s %d 股,等待成交后确定买回数量和价格", state.code, volume) def _try_buy_back( run: Runtime, state, price: float, available: float, force: bool, ) -> float: """按实际卖出均价下跌后反弹买回;尾盘不再受下跌幅度、反弹及价格上限限制。""" target = state.sell_price * (1 - run.account_cfg.zt_buy_fall_pct / 100) if not force and (price > target or price > run.account_cfg.zt_max_price): return available volume = state.sell_qty - state.buy_qty amount = price * volume * 1.01 if volume <= 0 or amount > available: log.warning("[ZT 买回] %s 买回资金不足或数量无效,保留未完成轮次", state.code) return available if not force and not run.add_watch.triggered("ZT 买回", state.code, price): return available order_id = run.orders.new_order_id("t-buy") request = PlaceOrderRequest(OP_BUY, state.code, volume, order_id, "zt", kind="buy") # 本轮预留资金;状态簿只在取得实际成交后入账。 available -= amount if run.orders.place(run.client, request): run.add_watch.forget(state.code) log.info( "[ZT 买回] %s %d 股,%s", state.code, volume, "尾盘强制买回" if force else "下跌后反弹", ) return available