跳转至

grid_trading_manager

网格交易管理器模块

提供网格交易的核心功能: - GridSession: 网格会话数据模型 - PriceTracker: 价格追踪状态机 - GridTradingManager: 网格交易管理器

GridSession dataclass

GridSession(id: Optional[int] = None, stock_code: str = '', status: str = 'active', enabled: bool = True, center_price: float = 0.0, current_center_price: float = 0.0, price_interval: float = 0.05, position_ratio: float = 0.25, callback_ratio: float = 0.005, trade_mode: str = 'amount', fixed_volume: int = 0, max_investment: float = 0.0, current_investment: float = 0.0, max_deviation: float = 0.15, target_profit: float = 0.1, stop_loss: float = -0.1, end_time: Optional[datetime] = None, trade_count: int = 0, buy_count: int = 0, sell_count: int = 0, total_buy_amount: float = 0.0, total_sell_amount: float = 0.0, total_buy_volume: int = 0, total_sell_volume: int = 0, start_time: Optional[datetime] = None, stop_time: Optional[datetime] = None, stop_reason: Optional[str] = None)

网格交易会话

get_profit_ratio

get_profit_ratio() -> float

计算网格盈亏率(基于max_investment)

公式: (total_sell_amount - total_buy_amount) / max_investment

设计原则: 1. 只计算网格交易本身的现金流差额,完全隔离市场波动 2. 分母使用max_investment,避免除零错误,且含义清晰(投入回报率) 3. 无交易时返回0.0,避免误触发止盈止损

get_profit_ratio_by_market_value

get_profit_ratio_by_market_value(position_volume: float, current_price: float) -> float

以持仓市值为分母计算网格盈亏率(供 _check_exit_conditions 使用)

公式: (total_sell_amount - total_buy_amount) / (position_volume * current_price)

与 get_profit_ratio() 的区别: get_profit_ratio() 分母 = max_investment(固定) 本方法 分母 = 持仓市值(动态)

max_investment 通常远小于持仓市值,导致单次买入的净现金流出占比就

超过 stop_loss 阈值(生产 Bug 2026-04-01:-19.04% ≤ -10% 即触发)。 改用持仓市值后,止损衡量的是"网格净流出相对于整体持仓的风险占比", 单次买入不再误触发,多次买入叠加价格下跌时仍会正确触发(DESIGN-4保留)。

降级条件: position_volume ≤ 0 或 current_price ≤ 0 → 降级为 get_profit_ratio() 测试参考: test/test_grid_profit_ratio_fix.py

get_true_pnl_ratio

get_true_pnl_ratio(current_price: float, position_volume: float = 0) -> float

True P&L ratio -- industry best practice (realized + unrealized)

Formula

open_grid_volume = total_buy_volume - total_sell_volume true_pnl = (total_sell - total_buy) + open_grid_volume * current_price ratio = true_pnl / max_investment

At purchase moment: true_pnl = 0 (cash out = position value) After price drop: true_pnl < 0 (reflects actual loss) After round-trip: true_pnl = realized profit (open_vol = 0)

Fallback

If no volume tracking data (old sessions), uses get_profit_ratio_by_market_value() or get_profit_ratio()

get_grid_profit

get_grid_profit() -> float

获取网格累计利润(绝对金额)

返回:

类型 描述
float

网格累计利润 = total_sell_amount - total_buy_amount

get_deviation_ratio

get_deviation_ratio() -> float

计算当前偏离度

get_grid_levels

get_grid_levels() -> dict

生成当前网格档位

PriceTracker dataclass

PriceTracker(session_id: int, last_price: float = 0.0, peak_price: float = 0.0, valley_price: float = 0.0, direction: Optional[str] = None, crossed_level: Optional[float] = None, waiting_callback: bool = False)

价格追踪器,用于检测回调

update_price

update_price(new_price: float)

更新价格并追踪峰谷值

check_callback

check_callback(callback_ratio: float) -> Optional[str]

检查是否触发回调,返回信号类型

reset

reset(price: float)

重置追踪器

GridTradingManager

GridTradingManager(db_manager, position_manager, trading_executor)

网格交易管理器

get_pnl_snapshot

get_pnl_snapshot(session, current_price: float = None, position_snapshot=None, ledger_summary: dict = None) -> dict

返回统一的网格 PnL 快照。

用户可见利润、退出判断和日志都应使用这个方法,避免同一会话出现 "退出按 True PnL,展示按现金流" 的口径不一致。

reconcile_pending_grid_orders_if_due

reconcile_pending_grid_orders_if_due(force: bool = False, reason: str = '运行期对账')

运行期 pending 委托对账;QMT 成交/委托推送漏掉时兜底落账。

start_grid_session

start_grid_session(stock_code: str, user_config: dict) -> GridSession

启动网格交易会话(三阶段设计,避免AB-BA死锁)

阶段1(锁外):获取持仓数据并验证前置条件 阶段2(锁内):停止旧session、创建数据库记录、创建内存对象 阶段3(锁外):触发数据版本更新、打印成功日志

stop_grid_session

stop_grid_session(session_id: int, reason: str) -> dict

停止网格交易会话(公共接口,会获取锁)

实盘成交确认模式下采用撤单闭环: 1. 若存在提交中/待成交委托,先把会话置为 stopping,并对待成交委托发撤单请求。 2. 等委托终态回调或锁外下单完成后,再真正清理内存会话。 3. 无未完成委托时保持旧行为,立即停止。

set_session_enabled

set_session_enabled(session_id: int, enabled: bool) -> dict

设置单个网格会话是否允许自动产生新单。

check_grid_signals

check_grid_signals(stock_code: str, current_price: float) -> Optional[dict]

检查网格交易信号(在持仓监控线程中调用)

参数:

名称 类型 描述 默认
stock_code str

股票代码

必需
current_price float

当前价格

必需

返回:

类型 描述
Optional[dict]

网格交易信号字典或None

handle_deal_callback

handle_deal_callback(trade) -> bool

实盘成交回调确认网格委托;只有真实成交后才更新网格统计和交易表

部分成交阶段只累积填充量并更新 grid_orders 状态,不写 grid_trades/trade_records、不重建网格。 全部成交后一次性落账:写一条聚合 grid_trades + 一条 trade_records + 重建一次网格。 避免 QMT 拆单(如 1300 股拆成 12 笔部分成交)导致重复落账和统计失真。

handle_order_callback

handle_order_callback(order) -> bool

处理网格委托状态回报,撤单/废单/拒单时清理 pending 委托

execute_grid_trade

execute_grid_trade(signal: dict) -> bool

执行网格交易

参数:

名称 类型 描述 默认
signal dict

网格交易信号

必需

返回:

类型 描述
bool

执行是否成功

get_session_stats

get_session_stats(session_id: int) -> dict

获取会话统计信息

get_trade_history

get_trade_history(session_id: int, limit=50, offset=0) -> list

获取交易历史