From c926586f8dc814cdbc3246327fac115b77e7b797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=96=87=E8=96=87=E5=AE=89?= Date: Sat, 28 Feb 2026 19:09:54 +0800 Subject: [PATCH] feat(position_manager): Implement trailing stop-loss logic for profit protection Enhanced the stop-loss mechanism to include a trailing stop-loss feature that activates when a position is significantly profitable. This update calculates a protective stop-loss price based on current profits, ensuring better risk management. Improved logging for tracking profit levels and stop-loss adjustments during monitoring. --- trading_system/position_manager.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/trading_system/position_manager.py b/trading_system/position_manager.py index e984d38..089d529 100644 --- a/trading_system/position_manager.py +++ b/trading_system/position_manager.py @@ -3990,6 +3990,32 @@ class PositionManager: else: stop_loss_price = None take_profit_price = None + # 若当前已明显盈利,不用交易所初始止损,直接算锁利止损(避免重启后把 226.97 这类初始止损再挂回去) + entry_price_f = float(entry_price) + current_price_f = float(current_price or entry_price_f) + margin = (entry_price_f * quantity) / leverage if leverage else (entry_price_f * quantity) + if side == 'BUY': + pnl_amount = (current_price_f - entry_price_f) * quantity + else: + pnl_amount = (entry_price_f - current_price_f) * quantity + pnl_percent_margin = (pnl_amount / margin * 100) if margin > 0 else 0 + trailing_activation = config.TRADING_CONFIG.get('TRAILING_STOP_ACTIVATION', 0.10) + if trailing_activation and trailing_activation <= 1: + trailing_activation = trailing_activation * 100 + if pnl_percent_margin >= (trailing_activation or 10): + protect_amount = max(margin * float(config.TRADING_CONFIG.get('TRAILING_STOP_PROTECT', 0.02) or 0.02), self._min_protect_amount_for_fees(margin, leverage)) + if side == 'BUY': + stop_loss_price = entry_price_f + (pnl_amount - protect_amount) / quantity + stop_loss_price = max(stop_loss_price, self._breakeven_stop_price(entry_price_f, 'BUY')) + else: + stop_loss_price = entry_price_f - protect_amount / quantity + stop_loss_price = max(stop_loss_price, self._breakeven_stop_price(entry_price_f, 'SELL')) + logger.info(f"[账号{self.account_id}] {symbol} 接入监控时已盈利{pnl_percent_margin:.1f}%,使用锁利止损 {stop_loss_price:.4f} 替代交易所原止损") + if take_profit_price is None: + tp_pct = config.TRADING_CONFIG.get('TAKE_PROFIT_PERCENT', 0.15) or 0.15 + if tp_pct > 1: + tp_pct = tp_pct / 100.0 + take_profit_price = self.risk_manager.get_take_profit_price(entry_price, side, quantity, leverage, take_profit_pct=tp_pct) if stop_loss_price is None or take_profit_price is None: stop_loss_pct_margin = config.TRADING_CONFIG.get('STOP_LOSS_PERCENT', 0.08) if stop_loss_pct_margin is not None and stop_loss_pct_margin > 1: