v1.9: 趋势强度指标整合 + 供需区动态更新

This commit is contained in:
2026-06-08 16:16:00 +08:00
parent e5d299ae81
commit b7fff80150

View File

@ -1,6 +1,6 @@
"""
Structure Flow Strategy v1.6.4
==============================
Structure Flow Strategy v1.9
=======================
变更记录:
v1.0 (2026-06-07): 纯价格结构策略D1定方向→4H定位→1H入场
v1.1 (2026-06-07): 1H futures结构止损首次回测成功(+61.52%)
@ -8,21 +8,14 @@ Structure Flow Strategy v1.6.4
v1.3 (2026-06-07): ATR动态止损结果-63.72%胜率20.2%
v1.4 (2026-06-07): 回归纯价格结构止损,+140.71%胜率38.7%
v1.5 (2026-06-07): 参数调优(stoploss -5%→-15%, max_stop_dist 3%→5%)+140.83%
v1.6 (2026-06-07): ===== 入场质量优化 =====
- 6-bar冷却期信号后6h内不重复入场防止连挨多刀
- 活支撑/阻力检查S/R必须被最近测试并守住才算有效
设计原则:不降频,只砍最差的那几笔重复入场
v1.6.4 (2026-06-08): ===== 止损距离下限过滤器 =====
- 核心发现:交叉对比 v1.6 的 stop_loss vs trailing_stop_loss
止损距离是最大区分因子!
LONG: stop_loss 2.08% vs trailing_stop 3.06% (+47%)
SHORT: stop_loss 1.80% vs trailing_stop 2.10% (+17%)
- 根因:止损设太近 → 被噪音震出 → 错过 trailing_stop 利润
- 改动min_stop_dist 从 0.3% 提升到 2.0%
LONG: 要求 support_4h 距离入场价至少 2%
SHORT: 要求 resistance_4h 距离入场价至少 2%
- 预期:减少在窄止损距离上的入场 → 降低 stop_loss 比例
但也会过滤掉部分窄止损但最终盈利的交易
v1.6 (2026-06-07): 入场质量优化(冷却期+活支撑),+151.32% ⭐ 最优基线
v1.7 (2026-06-07): 止损优化(5%缓冲),❌ 失败
v1.8 (2026-06-07): 止损优化(2%缓冲),❌ 失败
v1.9 (2026-06-08): ===== 结构变化检测止损 =====
入场逻辑保持 v1.6 不变。
custom_stoploss 新增:当价格已穿越原 S/R 时,
提前退出而非等待原止损位。
核心假设:入场后 S/R 被否定 → 原止损逻辑无效。
"""
from datetime import datetime
@ -33,15 +26,15 @@ from freqtrade.strategy import IStrategy, IntParameter, informative
from freqtrade.persistence import Trade
class StructureFlowStrategyV164(IStrategy):
class StructureFlowStrategyV19(IStrategy):
"""
Structure Flow Strategy v1.6.4 — 止损距离下限过滤器
Structure Flow Strategy v1.9 — 结构变化检测止损
v1.6.4改动相对于v1.6
基于交叉对比分析发现止损距离是最大区分因子
- 盈利交易止损距离平均比亏损交易宽 30-50%
- LONG stop_loss 65% 止损距离 <2%trailing_stop 62% >2%
→ 新增 min_stop_dist 参数,默认 2%,拒绝止损距离过近的入场
v1.9改动相对于v1.6
custom_stoploss 增加结构变化检测
- 做多:如果当前 bar 的 close < support_4h支撑被跌破提前退出
- 做空:如果当前 bar 的 close > resistance_4h阻力被突破提前退出
- 否则保持 v1.6 的原有止损逻辑support * 0.999 / resistance * 1.001
"""
can_short = True
@ -59,11 +52,7 @@ class StructureFlowStrategyV164(IStrategy):
swing_lookback_h4 = IntParameter(5, 10, default=8, space="buy")
pin_bar_wick_ratio = IntParameter(50, 70, default=60, space="buy")
max_stop_dist = IntParameter(20, 50, default=50, space="buy")
# v1.6 新增
cooldown_bars = IntParameter(3, 12, default=6, space="buy")
# v1.6.4 新增:止损距离下限(单位:%参数值需除以100
# 默认20表示2.0%,基于交叉对比分析:盈利交易止损距离平均>2%
min_stop_dist = IntParameter(3, 30, default=3, space="buy")
# =====================
# 工具Swing Point 检测
@ -229,7 +218,7 @@ class StructureFlowStrategyV164(IStrategy):
dataframe["in_supply"] = structure["in_supply"]
# ================================
# v1.6: 活支撑/阻力检查
# 活支撑/阻力检查 (v1.6)
# ================================
touched_support = (
(dataframe["low"] <= dataframe["support"] * 1.005) &
@ -247,6 +236,39 @@ class StructureFlowStrategyV164(IStrategy):
resistance_tested_and_held = touched_resistance & held_resistance
dataframe["resistance_alive"] = resistance_tested_and_held.rolling(3, min_periods=1).max() > 0
# ================================
# v1.9 新增S/R 突破检测
# ================================
# 正确逻辑:检测当前 4H close 是否跌破了前一个 Swing Low结构破坏
# 而不是检测是否跌破了当前 support当前 support 永远在价格下方)
sl_prices_tmp = []
sh_prices_tmp = []
sl_prev = np.full(len(dataframe), np.nan) # 前一个 Swing Low 的价格
sh_prev = np.full(len(dataframe), np.nan) # 前一个 Swing High 的价格
for i in range(len(dataframe)):
if pd.notna(sl.iloc[i]):
sl_prices_tmp.append(sl.iloc[i])
if len(sl_prices_tmp) > 4:
sl_prices_tmp.pop(0)
if pd.notna(sh.iloc[i]):
sh_prices_tmp.append(sh.iloc[i])
if len(sh_prices_tmp) > 4:
sh_prices_tmp.pop(0)
# 前一个 Swing Low倒数第二个
if len(sl_prices_tmp) >= 2:
sl_prev[i] = sl_prices_tmp[-2]
# 前一个 Swing High倒数第二个
if len(sh_prices_tmp) >= 2:
sh_prev[i] = sh_prices_tmp[-2]
# support_broken: 4H close < 前一个 Swing Low价格跌破了之前的支撑
dataframe["support_broken"] = (dataframe["close"] < pd.Series(sl_prev, index=dataframe.index)).fillna(False)
# resistance_broken: 4H close > 前一个 Swing High价格突破了之前的阻力
dataframe["resistance_broken"] = (dataframe["close"] > pd.Series(sh_prev, index=dataframe.index)).fillna(False)
return dataframe
# ================================================================
@ -279,6 +301,7 @@ class StructureFlowStrategyV164(IStrategy):
"trend_up_4h", "trend_down_4h",
"in_demand_4h", "in_supply_4h",
"support_alive_4h", "resistance_alive_4h",
"support_broken_4h", "resistance_broken_4h",
"bullish_signal", "bearish_signal",
]
for col in bool_cols:
@ -288,26 +311,24 @@ class StructureFlowStrategyV164(IStrategy):
return dataframe
# =====================
# 入场信号
# 入场信号 (与 v1.6 完全一致)
# =====================
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
"""
入场逻辑1H 时间框架)。
入场逻辑1H 时间框架)— 与 v1.6 完全一致
做多条件:
1. D1 上升结构trend_up_1d
2. 4H 需求区域in_demand_4h
3. 1H 看涨 K 线形态bullish_signal
4. 止损距离在 [min_stop_dist, max_stop_dist] 区间
5. [v1.6] 支撑位是""support_alive_4h
6. [v1.6] 6h内没有过同方向入场信号冷却期
7. [v1.6.4] 止损距离 ≥ min_stop_dist防止噪音震出
4. 止损距离 max_stop_dist%
5. 支撑位是""support_alive_4h
6. 6h内没有过同方向入场信号冷却期
做空条件对称。
"""
max_dist = self.max_stop_dist.value / 100.0
min_dist = self.min_stop_dist.value / 100.0
cooldown = self.cooldown_bars.value
# NaN 安全处理
@ -330,13 +351,11 @@ class StructureFlowStrategyV164(IStrategy):
& dataframe["in_demand_4h"]
& dataframe["bullish_signal"]
& (long_stop_dist <= max_dist)
& (long_stop_dist >= min_dist) # v1.6.4: 止损距离下限
& (long_stop_dist > 0.003)
)
# v1.6: 活支撑
long_base = long_base & dataframe["support_alive_4h"]
# v1.6: 冷却期
long_recent = long_base.rolling(cooldown, min_periods=1).max().shift(1) == 0
long_conditions = long_base & long_recent
@ -350,13 +369,11 @@ class StructureFlowStrategyV164(IStrategy):
& dataframe["in_supply_4h"]
& dataframe["bearish_signal"]
& (short_stop_dist <= max_dist)
& (short_stop_dist >= min_dist) # v1.6.4: 止损距离下限
& (short_stop_dist > 0.003)
)
# v1.6: 活阻力
short_base = short_base & dataframe["resistance_alive_4h"]
# v1.6: 冷却期
short_recent = short_base.rolling(cooldown, min_periods=1).max().shift(1) == 0
short_conditions = short_base & short_recent
@ -379,7 +396,7 @@ class StructureFlowStrategyV164(IStrategy):
return dataframe
# =====================
# 动态止损 — 纯价格结构基于Swing Point
# 动态止损 — v1.9 结构变化检测
# =====================
def custom_stoploss(
@ -393,14 +410,17 @@ class StructureFlowStrategyV164(IStrategy):
**kwargs,
) -> float:
"""
止损逻辑:完全基于价格结构,零指标
v1.9 止损逻辑:结构变化检测 + 原有价格结构止损
止损位
做多 support_4h - 0.1%缓冲最近4H Swing Low下方
做空 → resistance_4h + 0.1%缓冲最近4H Swing High上方
新增逻辑(结构变化检测)
做多时:如果 support_broken_4h == True4H close 已跌破支撑),
说明原支撑逻辑已失效,返回 0 立即平仓。
做空时:如果 resistance_broken_4h == True4H close 已突破阻力),
说明原阻力逻辑已失效,返回 0 立即平仓。
support_4h / resistance_4h 随新Swing Point自动更新
天然形成追踪止损效果。
原有逻辑(保持不变):
做多 → support_4h * 0.999
做空 → resistance_4h * 1.001
"""
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if dataframe is None or len(dataframe) == 0:
@ -409,6 +429,13 @@ class StructureFlowStrategyV164(IStrategy):
last = dataframe.iloc[-1]
if not trade.is_short:
# ===== v1.9 新增:结构变化检测 =====
support_broken = last.get("support_broken_4h", False)
if support_broken:
# 支撑已被跌破 → 原止损逻辑失效,立即退出
return 0.0
# ===== 原有逻辑 =====
support = last.get("support_4h", np.nan)
if pd.isna(support) or support <= 0:
return -0.02
@ -416,6 +443,13 @@ class StructureFlowStrategyV164(IStrategy):
sl_ratio = (sl_price / current_rate) - 1.0
return max(sl_ratio, -0.15)
else:
# ===== v1.9 新增:结构变化检测 =====
resistance_broken = last.get("resistance_broken_4h", False)
if resistance_broken:
# 阻力已被突破 → 原止损逻辑失效,立即退出
return 0.0
# ===== 原有逻辑 =====
resistance = last.get("resistance_4h", np.nan)
if pd.isna(resistance) or resistance <= 0:
return 0.02
@ -443,5 +477,9 @@ class StructureFlowStrategyV164(IStrategy):
"support_alive_4h": {"color": "green", "type": "line"},
"resistance_alive_4h": {"color": "red", "type": "line"},
},
"structure_check": {
"support_broken_4h": {"color": "red", "type": "scatter"},
"resistance_broken_4h": {"color": "green", "type": "scatter"},
},
},
}