跳转至

stop_profit — 止盈止损后台监控

stop_profit.py — 动态止盈止损后台监控(xtquant_manager 模块)

直接复用 position_manager.py 中已验证的止盈止损算法: - calculate_stop_loss_price() — 动态止盈位计算 - _get_profit_level_info() — 匹配止盈档位 - check_trading_signals() — 信号检测逻辑

设计原则: 1. 仅依赖 xtquant_manager.account (XtQuantAccount) 进行持仓查询与下单 2. 状态(最高价/止盈标记等)存储在内存 dict 中,停止即丢失 (与 main.py 模式不同——那里有 SQLite 持久化。网关模式不持久化, 因为持仓状态应从 QMT 查询,重启后 current_price/cost_price 作为 initial 值即可) 3. 信号去重:同一股票同类型信号 60 秒内不重复触发 4. 线程安全:每次检测循环加锁,避免与 HTTP handler 竞争

StopProfitConfig dataclass

StopProfitConfig(enabled: bool = True, stop_loss_ratio: float = -0.075, initial_take_profit_ratio: float = 0.06, initial_take_profit_pullback_ratio: float = 0.005, initial_take_profit_sell_ratio: float = 0.6, dynamic_take_profit: List[Tuple[float, float]] = (lambda: [(0.05, 0.96), (0.1, 0.93), (0.15, 0.9), (0.2, 0.87), (0.3, 0.85)])(), monitor_interval: float = 3.0, signal_dedup_seconds: float = 60.0, price_staleness_seconds: float = 120.0)

止盈止损配置——字段名与 config.py 保持一致,方便对照。

StopProfitMonitor

StopProfitMonitor(manager: Any, cfg: Optional[StopProfitConfig] = None)

后台线程,循环检测所有账号的持仓信号并执行卖出。

Usage

monitor = StopProfitMonitor(manager, config) monitor.start() ... monitor.stop()

参数:

名称 类型 描述 默认
manager Any

XtQuantManager 单例(避免循环导入,使用 Any 类型)

必需
manager Any

XtQuantManager 单例

必需
cfg Optional[StopProfitConfig]

止盈止损配置,None 则使用默认值

None

get_states

get_states() -> Dict[str, Dict[str, dict]]

返回所有持仓状态的快照(供 API 查询)。

manual_sell

manual_sell(acc_id: str, stock_code: str, volume: int, price: float, strategy: str = 'manual') -> int

手动卖出,成功返回 order_id,失败返回 -1。

PositionState dataclass

PositionState(stock_code: str, highest_price: float = 0.0, profit_triggered: bool = False, profit_breakout_triggered: bool = False, breakout_highest_price: float = 0.0, last_price: float = 0.0, last_price_time: float = 0.0)