v2.0: v2架构重构 - 多TF结构分析 + 信号确认体系
This commit is contained in:
165
strategy.py
165
strategy.py
@ -1,21 +1,13 @@
|
||||
"""
|
||||
Structure Flow Strategy v1.9
|
||||
Structure Flow Strategy v2.0
|
||||
=======================
|
||||
变更记录:
|
||||
v1.0 (2026-06-07): 纯价格结构策略,D1定方向→4H定位→1H入场
|
||||
v1.1 (2026-06-07): 1H futures,结构止损,首次回测成功(+61.52%)
|
||||
v1.2 (2026-06-07): Entry Candle止损,bug导致50笔硬止损全亏
|
||||
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): 入场质量优化(冷却期+活支撑),+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 被否定 → 原止损逻辑无效。
|
||||
v1.6 (2026-06-07): 最优基线 — +3659.63%, 190笔, 69.3% trailing胜率
|
||||
v2.0 (2026-06-08): ===== B1: 入场延迟一根1H bar确认 =====
|
||||
信号触发后,不立即入场,等下一根1H bar收盘。
|
||||
如果收盘价仍在S/R附近(支撑上方1.5%以内 / 阻力下方1.5%以内),
|
||||
确认入场;否则放弃本次信号。
|
||||
目的:过滤假突破,减少被噪音震出的止损交易。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
@ -26,15 +18,14 @@ from freqtrade.strategy import IStrategy, IntParameter, informative
|
||||
from freqtrade.persistence import Trade
|
||||
|
||||
|
||||
class StructureFlowStrategyV19(IStrategy):
|
||||
class StructureFlowStrategyV20(IStrategy):
|
||||
"""
|
||||
Structure Flow Strategy v1.9 — 结构变化检测止损
|
||||
Structure Flow Strategy v2.0 — B1: 入场延迟确认
|
||||
|
||||
v1.9改动(相对于v1.6):
|
||||
custom_stoploss 增加结构变化检测:
|
||||
- 做多:如果当前 bar 的 close < support_4h(支撑被跌破),提前退出
|
||||
- 做空:如果当前 bar 的 close > resistance_4h(阻力被突破),提前退出
|
||||
- 否则保持 v1.6 的原有止损逻辑(support * 0.999 / resistance * 1.001)
|
||||
v2.0改动(相对于v1.6):
|
||||
1. 入场延迟1根bar:信号触发后,等下一根bar收盘确认
|
||||
2. 确认条件:收盘价仍在S/R附近(做多在support上方1.5%内,做空在resistance下方1.5%内)
|
||||
3. 保留v1.6所有逻辑:冷却期、活支撑/阻力、D1趋势过滤
|
||||
"""
|
||||
|
||||
can_short = True
|
||||
@ -53,6 +44,8 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
pin_bar_wick_ratio = IntParameter(50, 70, default=60, space="buy")
|
||||
max_stop_dist = IntParameter(20, 50, default=50, space="buy")
|
||||
cooldown_bars = IntParameter(3, 12, default=6, space="buy")
|
||||
# v2.0 新增:入场确认阈值 — close必须在S/R附近多少%以内才算确认
|
||||
entry_confirm_pct = IntParameter(10, 50, default=50, space="buy") # x/1000 = 1.0%~5.0%, default 5.0%
|
||||
|
||||
# =====================
|
||||
# 工具:Swing Point 检测
|
||||
@ -218,7 +211,7 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
dataframe["in_supply"] = structure["in_supply"]
|
||||
|
||||
# ================================
|
||||
# 活支撑/阻力检查 (v1.6)
|
||||
# v1.6 活支撑/阻力检查(保留)
|
||||
# ================================
|
||||
touched_support = (
|
||||
(dataframe["low"] <= dataframe["support"] * 1.005) &
|
||||
@ -236,39 +229,6 @@ class StructureFlowStrategyV19(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
|
||||
|
||||
# ================================================================
|
||||
@ -301,7 +261,6 @@ class StructureFlowStrategyV19(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:
|
||||
@ -311,12 +270,14 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
return dataframe
|
||||
|
||||
# =====================
|
||||
# 入场信号 (与 v1.6 完全一致)
|
||||
# 入场信号 — v2.0 延迟确认
|
||||
# =====================
|
||||
|
||||
def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
入场逻辑(1H 时间框架)— 与 v1.6 完全一致。
|
||||
入场逻辑(1H 时间框架)。
|
||||
|
||||
v2.0 核心改动:B1 — 入场延迟一根1H bar确认
|
||||
|
||||
做多条件:
|
||||
1. D1 上升结构(trend_up_1d)
|
||||
@ -325,11 +286,13 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
4. 止损距离 ≤ max_stop_dist%
|
||||
5. 支撑位是"活"的(support_alive_4h)
|
||||
6. 6h内没有过同方向入场信号(冷却期)
|
||||
|
||||
做空条件对称。
|
||||
7. [v2.0 NEW] 上一根bar触发了信号,当前bar收盘确认:
|
||||
做多:close 仍在 support_4h 上方 entry_confirm_pct% 以内
|
||||
做空:close 仍在 resistance_4h 下方 entry_confirm_pct% 以内
|
||||
"""
|
||||
max_dist = self.max_stop_dist.value / 100.0
|
||||
cooldown = self.cooldown_bars.value
|
||||
confirm_pct = self.entry_confirm_pct.value / 1000.0 # 1.0%~3.0%
|
||||
|
||||
# NaN 安全处理
|
||||
bool_cols = [
|
||||
@ -343,7 +306,11 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
if col in dataframe.columns:
|
||||
dataframe[col] = dataframe[col].fillna(False)
|
||||
|
||||
# ── 做多 ──
|
||||
# =====================
|
||||
# 原始v1.6入场条件(不变)
|
||||
# =====================
|
||||
|
||||
# ── 做多原始条件 ──
|
||||
long_stop_dist = (dataframe["open"] - dataframe["support_4h"]) / dataframe["open"]
|
||||
|
||||
long_base = (
|
||||
@ -352,16 +319,14 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
& dataframe["bullish_signal"]
|
||||
& (long_stop_dist <= max_dist)
|
||||
& (long_stop_dist > 0.003)
|
||||
& dataframe["support_alive_4h"]
|
||||
)
|
||||
|
||||
long_base = long_base & dataframe["support_alive_4h"]
|
||||
|
||||
# 冷却期
|
||||
long_recent = long_base.rolling(cooldown, min_periods=1).max().shift(1) == 0
|
||||
long_conditions = long_base & long_recent
|
||||
long_signal = long_base & long_recent
|
||||
|
||||
dataframe.loc[long_conditions, "enter_long"] = 1
|
||||
|
||||
# ── 做空 ──
|
||||
# ── 做空原始条件 ──
|
||||
short_stop_dist = (dataframe["resistance_4h"] - dataframe["open"]) / dataframe["open"]
|
||||
|
||||
short_base = (
|
||||
@ -370,14 +335,35 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
& dataframe["bearish_signal"]
|
||||
& (short_stop_dist <= max_dist)
|
||||
& (short_stop_dist > 0.003)
|
||||
& dataframe["resistance_alive_4h"]
|
||||
)
|
||||
|
||||
short_base = short_base & dataframe["resistance_alive_4h"]
|
||||
|
||||
short_recent = short_base.rolling(cooldown, min_periods=1).max().shift(1) == 0
|
||||
short_conditions = short_base & short_recent
|
||||
short_signal = short_base & short_recent
|
||||
|
||||
dataframe.loc[short_conditions, "enter_short"] = 1
|
||||
# =====================
|
||||
# v2.0: B1 — 入场延迟一根bar确认
|
||||
# =====================
|
||||
# 上一根bar的信号(shift(1))
|
||||
prev_long_signal = long_signal.shift(1).fillna(False)
|
||||
prev_short_signal = short_signal.shift(1).fillna(False)
|
||||
|
||||
# 确认条件:当前bar的close仍在S/R附近
|
||||
# 做多:close在support上方确认区间内(support * 1.0 ~ support * (1+confirm_pct))
|
||||
long_confirm = (
|
||||
(dataframe["close"] >= dataframe["support_4h"]) &
|
||||
(dataframe["close"] <= dataframe["support_4h"] * (1 + confirm_pct))
|
||||
)
|
||||
|
||||
# 做空:close在resistance下方确认区间内(resistance * (1-confirm_pct) ~ resistance * 1.0)
|
||||
short_confirm = (
|
||||
(dataframe["close"] <= dataframe["resistance_4h"]) &
|
||||
(dataframe["close"] >= dataframe["resistance_4h"] * (1 - confirm_pct))
|
||||
)
|
||||
|
||||
# 最终入场:上一根bar有信号 + 当前bar确认
|
||||
dataframe.loc[prev_long_signal & long_confirm, "enter_long"] = 1
|
||||
dataframe.loc[prev_short_signal & short_confirm, "enter_short"] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
@ -396,7 +382,7 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
return dataframe
|
||||
|
||||
# =====================
|
||||
# 动态止损 — v1.9 结构变化检测
|
||||
# 动态止损 — 纯价格结构(基于Swing Point)
|
||||
# =====================
|
||||
|
||||
def custom_stoploss(
|
||||
@ -410,17 +396,14 @@ class StructureFlowStrategyV19(IStrategy):
|
||||
**kwargs,
|
||||
) -> float:
|
||||
"""
|
||||
v1.9 止损逻辑:结构变化检测 + 原有价格结构止损。
|
||||
止损逻辑:完全基于价格结构,零指标(与v1.6相同)。
|
||||
|
||||
新增逻辑(结构变化检测):
|
||||
做多时:如果 support_broken_4h == True(4H close 已跌破支撑),
|
||||
说明原支撑逻辑已失效,返回 0 立即平仓。
|
||||
做空时:如果 resistance_broken_4h == True(4H close 已突破阻力),
|
||||
说明原阻力逻辑已失效,返回 0 立即平仓。
|
||||
止损位:
|
||||
做多 → support_4h - 0.1%缓冲
|
||||
做空 → resistance_4h + 0.1%缓冲
|
||||
|
||||
原有逻辑(保持不变):
|
||||
做多 → support_4h * 0.999
|
||||
做空 → resistance_4h * 1.001
|
||||
support_4h / resistance_4h 随新Swing Point自动更新,
|
||||
天然形成追踪止损效果。
|
||||
"""
|
||||
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
|
||||
if dataframe is None or len(dataframe) == 0:
|
||||
@ -429,13 +412,6 @@ class StructureFlowStrategyV19(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
|
||||
@ -443,13 +419,6 @@ class StructureFlowStrategyV19(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
|
||||
@ -477,9 +446,5 @@ class StructureFlowStrategyV19(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"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user