动态加仓

This commit is contained in:
zhangkun9038@dingtalk.com 2025-08-20 19:21:20 +08:00
parent 479639be29
commit e02129a717

View File

@ -95,6 +95,9 @@ class FreqaiPrimer(IStrategy):
entry_discount_bull_normal = DecimalParameter(0.005, 0.03, default=0.010, decimals=3, space="buy", optimize=True, load=True) # 牛市正常通道折扣 (默认1%)
entry_discount_ranging = DecimalParameter(0.001, 0.02, default=0.0075, decimals=3, space="buy", optimize=True, load=True) # 震荡市折扣 (默认0.75%)
entry_discount_bearish = DecimalParameter(0.001, 0.015, default=0.005, decimals=3, space="buy", optimize=True, load=True) # 熊市折扣 (默认0.5%)
# 🎯 加仓策略参数(统一标准,移除趋势判断)
ADD_PROGRESSION_FACTOR = 1.09 # 递进系数每次加仓阈值递增1.09倍
# --- 🛠️ 固定配置参数 ---
stoploss = -0.15
@ -1235,95 +1238,38 @@ class FreqaiPrimer(IStrategy):
current_entry_profit: float, current_exit_profit: float,
**kwargs) -> float | None | tuple[float | None, str | None]:
"""
动态调整仓位支持加仓减仓追踪止损和最大持仓时间限制
参数
- trade: 当前交易对象
- current_time: 当前时间
- current_rate: 当前价格
- current_profit: 当前总盈利
- min_stake: 最小下注金额
- max_stake: 最大下注金额
- current_entry_rate: 当前入场价格
- current_exit_rate: 当前退出价格
- current_entry_profit: 当前入场盈利
- current_exit_profit: 当前退出盈利
返回
- 调整金额正数为加仓负数为减仓 None
统一标准的仓位调整策略
- 移除所有趋势状态判断和趋势得分依赖
- 基于固定阈值和递进系数的加仓逻辑
- 每次加仓阈值递增初次阈值 × (递进系数^加仓次数)
"""
pair = trade.pair
dataframe = self.dp.get_pair_dataframe(pair, self.timeframe)
trend_score = self.get_market_trend(dataframe=dataframe, metadata={'pair': pair})
hold_time = (current_time - trade.open_date_utc).total_seconds() / 60
profit_ratio = (current_rate - trade.open_rate) / trade.open_rate
# 检测趋势状态(必须先定义才能使用)
trend_status = self.detect_trend_status(dataframe, {'pair': pair})
logger.info(f"{pair} 当前趋势状态: {trend_status}")
# 检测当前持仓订单数量
open_trades = len(self.active_trades) if hasattr(self, 'active_trades') else 0
# 统一参数设置(移除趋势状态判断)
max_entry_adjustments = self.MAX_ENTRY_POSITION_ADJUSTMENT # 最大加仓次数
exit_position_ratio = self.EXIT_POSITION_RATIO # 减仓阈值
trailing_stop_start = self.TRAILING_STOP_START # 追踪止损启动阈值
trailing_stop_distance = self.TRAILING_STOP_DISTANCE # 追踪止损距离
# 牛市绿色通道判断持仓≤2个且牛市趋势且绿色通道开关开启
is_green_channel = (trend_status == "bullish" and open_trades <= 2 and self.GREEN_CHANNEL_ENABLED)
# 统一入场金额(移除绿色通道判断)
initial_stake_amount = 75.0 # 固定75USDT入场
# 根据绿色通道调整入场金额
if is_green_channel:
initial_stake_amount = 25.0 # 绿色通道25USDT入场
logger.info(f"{pair} 🟢 牛市绿色通道25USDT入场当前持仓{open_trades}")
else:
initial_stake_amount = 75.0 # 正常通道75USDT入场
logger.info(f"{pair} 首次入场金额: {initial_stake_amount:.2f}, 当前持仓金额: {trade.stake_amount:.2f}, "
f"加仓次数: {trade.nr_of_successful_entries - 1}, 趋势得分: {trend_score:.2f}")
logger.info(f"{pair} 统一仓位管理: max_entries={max_entry_adjustments}, initial_stake={initial_stake_amount:.2f}")
# 根据趋势状态调整仓位管理参数
if trend_status == "bullish":
# 上涨趋势:积极加仓,放宽止盈
max_entry_adjustments = min(self.MAX_ENTRY_POSITION_ADJUSTMENT + 1, 5) # 允许更多加仓
add_position_threshold = self.ADD_POSITION_THRESHOLD * 1.3 # 更宽松的加仓条件
exit_position_ratio = self.EXIT_POSITION_RATIO * 1.4 # 更高的止盈目标
trailing_stop_start = self.TRAILING_STOP_START * 1.2 # 更高的启动阈值
trailing_stop_distance = self.TRAILING_STOP_DISTANCE * 1.5 # 更大的回撤容忍
logger.info(f"{pair} 🚀 上涨趋势仓位管理参数: max_entries={max_entry_adjustments}, add_thresh={add_position_threshold:.4f}, exit_ratio={exit_position_ratio:.2%}")
elif trend_status == "bearish":
# 下跌趋势:谨慎加仓,严格止盈
max_entry_adjustments = max(self.MAX_ENTRY_POSITION_ADJUSTMENT - 1, 1) # 减少加仓次数
add_position_threshold = self.ADD_POSITION_THRESHOLD * 0.7 # 更严格的加仓条件
exit_position_ratio = self.EXIT_POSITION_RATIO * 0.8 # 更低的止盈目标
trailing_stop_start = self.TRAILING_STOP_START * 0.8 # 更低的启动阈值
trailing_stop_distance = self.TRAILING_STOP_DISTANCE * 0.7 # 更严格的止损
logger.info(f"{pair} 📉 下跌趋势仓位管理参数: max_entries={max_entry_adjustments}, add_thresh={add_position_threshold:.4f}, exit_ratio={exit_position_ratio:.2%}")
else: # ranging
# 震荡趋势:使用标准参数
max_entry_adjustments = self.MAX_ENTRY_POSITION_ADJUSTMENT
add_position_threshold = self.ADD_POSITION_THRESHOLD
exit_position_ratio = self.EXIT_POSITION_RATIO
trailing_stop_start = self.TRAILING_STOP_START
trailing_stop_distance = self.TRAILING_STOP_DISTANCE
logger.info(f"{pair} ⚖️ 震荡趋势仓位管理参数: max_entries={max_entry_adjustments}, add_thresh={add_position_threshold:.4f}, exit_ratio={exit_position_ratio:.2%}")
# 加仓逻辑
# 🔢 计算递进加仓阈值
add_count = trade.nr_of_successful_entries - 1 # 已加仓次数
# 计算当前加仓阈值config中的ADD_POSITION_THRESHOLD × (递进系数^加仓次数)
current_add_threshold = self.ADD_POSITION_THRESHOLD * (self.ADD_PROGRESSION_FACTOR ** add_count)
# 统一加仓逻辑(移除所有趋势判断)
if trade.nr_of_successful_entries <= max_entry_adjustments + 1:
# 动态调整加仓阈值
if trend_status == "bullish":
add_threshold = 90 - 20 * (trend_score / 100) # 上涨趋势下更宽松
elif trend_status == "bearish":
add_threshold = 70 - 30 * (trend_score / 100) # 下跌趋势下更谨慎
else:
add_threshold = 80 - 30 * (trend_score / 100) # 震荡趋势标准
if profit_ratio <= current_add_threshold and hold_time > 5: # 仅检查跌幅和时间
# 统一加仓倍数
multipliers = [1, 2, 4, 8] # 固定倍数序列 [首次, 第二次, 第三次, 第四次]
if profit_ratio <= add_position_threshold and hold_time > 5 and trend_score <= add_threshold:
add_count = trade.nr_of_successful_entries - 1
# 根据趋势状态调整加仓倍数
if trend_status == "bullish":
multipliers = [1.5, 3, 6] # 上涨趋势下更保守的加仓
elif trend_status == "bearish":
multipliers = [1, 2, 4] # 下跌趋势下更激进的加仓(抄底)
else:
multipliers = [2, 4, 8] # 震荡趋势标准加仓
if add_count < len(multipliers):
multiplier = multipliers[add_count]
add_amount = initial_stake_amount * multiplier
@ -1334,36 +1280,31 @@ class FreqaiPrimer(IStrategy):
if add_amount > max_stake:
add_amount = max_stake
logger.info(f"{pair} 趋势状态: {trend_status}, 价格下跌 {profit_ratio*100:.2f}%,触发第 {add_count + 1} 次加仓 {add_amount:.2f}")
return (add_amount, f"Trend: {trend_status}, Price dropped {profit_ratio*100:.2f}%, add {add_amount:.2f}")
logger.info(f"{pair}{add_count + 1} 次加仓触发: "
f"跌幅 {profit_ratio*100:.2f}% <= 阈值 {current_add_threshold*100:.2f}%, "
f"加仓金额 {add_amount:.2f} (倍数{multiplier}x)")
return (add_amount, f"Add {add_count + 1}: Drop {profit_ratio*100:.2f}% <= {current_add_threshold*100:.2f}%, add {add_amount:.2f}")
# 减仓逻辑
# 统一减仓逻辑(移除趋势判断)
if profit_ratio >= exit_position_ratio:
# 根据趋势状态调整减仓比例
if trend_status == "bullish":
reduce_factor = 0.5 # 上涨趋势下只减仓50%
elif trend_status == "bearish":
reduce_factor = 1.0 # 下跌趋势下全部减仓
else:
reduce_factor = 0.8 # 震荡趋势下减仓80%
reduce_factor = 1.0 # 统一全部减仓
reduce_amount = -trade.stake_amount * reduce_factor
logger.info(f"{pair} 趋势状态: {trend_status}, 利润 {profit_ratio*100:.2f}%,减仓 {abs(reduce_amount):.2f} ({reduce_factor*100:.0f}%)")
return (reduce_amount, f"Trend: {trend_status}, Profit {profit_ratio*100:.2f}%, reduce {abs(reduce_amount):.2f}")
logger.info(f"{pair} 利润 {profit_ratio*100:.2f}% 达到减仓阈值 {exit_position_ratio*100:.2f}%,减仓 {abs(reduce_amount):.2f}")
return (reduce_amount, f"Profit {profit_ratio*100:.2f}% >= {exit_position_ratio*100:.2f}%, reduce {abs(reduce_amount):.2f}")
# 追踪止损逻辑
# 统一追踪止损逻辑(移除趋势判断)
if profit_ratio >= trailing_stop_start and not self.trailing_stop_enabled:
self.trailing_stop_enabled = True
trade.adjust_min_max_rates(current_rate, current_rate)
logger.info(f"{pair} 趋势状态: {trend_status}, 价格上涨超过 {trailing_stop_start*100:.1f}%,启动追踪止损")
logger.info(f"{pair} 价格上涨 {profit_ratio*100:.2f}% 超过 {trailing_stop_start*100:.1f}%,启动追踪止损")
return None
if self.trailing_stop_enabled:
max_rate = trade.max_rate or current_rate
trailing_stop_price = max_rate * (1 - trailing_stop_distance)
if current_rate < trailing_stop_price:
logger.info(f"{pair} 趋势状态: {trend_status}, 价格回落至 {trailing_stop_price:.6f},触发全部卖出")
return (-trade.stake_amount, f"Trend: {trend_status}, Trailing stop at {trailing_stop_price:.6f}")
logger.info(f"{pair} 价格回落至 {trailing_stop_price:.6f},触发全部卖出")
return (-trade.stake_amount, f"Trailing stop at {trailing_stop_price:.6f}")
trade.adjust_min_max_rates(current_rate, trade.min_rate)
return None