v1.1: 趋势过滤器优化 + 止损距离动态调整

This commit is contained in:
2026-06-07 22:51:00 +08:00
parent 349f3c5be4
commit 88fc89bac8

View File

@ -1,17 +1,22 @@
# ============================================================================ # ============================================================================
# Structure Flow Strategy v1.0 # Structure Flow Strategy v1.1
# 纯价格结构策略 — 零技术指标,价格行为学驱动 # 纯价格结构策略 — 零技术指标,价格行为学驱动
# #
# 版本变化 v1.0 → v1.1:
# - 主时间框架5M → 1H匹配用户实际交易尺度
# - 信息时间框架D1 → 4H → 1H
# - 启用做空can_short=True适配无杠杆合约交易
# - 硬止损改为结构失效点 + 1% 缓冲(不再用固定百分比)
# - 修复 custom_stoploss 动态跟踪结构位
#
# 设计哲学: # 设计哲学:
# 趋势不由 EMA 定义,而由 HH/HLHigher High / Higher Low定义 # 趋势由 HH/HL 定义,支撑阻力由 Swing Point 定义
# 支撑阻力不由百分比定义,而由历史 Swing Point 定义 # 止损由结构失效点定义,出场由结构反转定义
# 止损不由 ATR 定义,而由结构失效点定义
# 出场不由固定盈亏比定义,而由结构反转定义
# #
# 多时间框架: # 多时间框架:
# D1 → 宏观结构方向 # D1 → 宏观结构方向
# 1H → 中期结构位 + 入场区域判定 # 4H → 中期结构位 + 入场区域判定
# 5M → K线形态确认入场时机 # 1H → K线形态确认入场时机
# ============================================================================ # ============================================================================
from datetime import datetime from datetime import datetime
@ -24,7 +29,7 @@ from freqtrade.persistence import Trade
class StructureFlowStrategy(IStrategy): class StructureFlowStrategy(IStrategy):
""" """
Structure Flow Strategy v1.0 — 纯价格结构策略 Structure Flow Strategy v1.1 — 纯价格结构策略
不使用任何技术指标(无 EMA、ATR、RSI、MACD、布林带等 不使用任何技术指标(无 EMA、ATR、RSI、MACD、布林带等
一切信号来源于价格本身的 OHLC 数据和由此推导的结构信息。 一切信号来源于价格本身的 OHLC 数据和由此推导的结构信息。
@ -32,47 +37,34 @@ class StructureFlowStrategy(IStrategy):
趋势判断: 趋势判断:
HH + HL → 上升趋势Bullish Structure HH + HL → 上升趋势Bullish Structure
LH + LL → 下降趋势Bearish Structure LH + LL → 下降趋势Bearish Structure
其他 → 震荡Chop / Range
入场逻辑: 入场逻辑:
做多: D1上升结构 + 价格在1H Swing区间下半区 + 5M看涨K线形态 做多: D1上升结构 + 价格在4H Swing区间下半区 + 1H看涨K线形态
做空: D1下降结构 + 价格在1H Swing区间上半区 + 5M看跌K线形态 做空: D1下降结构 + 价格在4H Swing区间上半区 + 1H看跌K线形态
结构位入场区间:
不使用固定百分比。入场区域由最近 Swing High 和 Swing Low
的中点定义——价格在下半区为做多区域,在上半区为做空区域。
止损逻辑: 止损逻辑:
初始止损: 1H 最近 Swing Low做多/ Swing High做空 初始止损: 4H 最近 Swing Low做多/ Swing High做空+ 1% 缓冲
跟踪止损: 随新 Swing Point 形成而上移(做多)或下移(做空) 动态止损: custom_stoploss 随新 Swing Point 形成而跟踪
这是"结构失效止损"——如果止损被触发,意味着结构被破坏,
交易逻辑不再成立。
出场逻辑:
D1 结构反转(上升→非上升 或 下降→非下降)
或 1H 结构失效(做多时 Swing Low 被跌破)
""" """
# ── 基础配置 ────────────────────────────────────────── # ── 基础配置 ──────────────────────────────────────────
timeframe = "5m" timeframe = "1h"
can_short = False # spot 回测临时关闭,实盘 futures 改回 True can_short = True # v1.1 启用做空,适配无杠杆合约
stoploss = -0.25 # 硬止损安全网25%,实际由 custom_stoploss 动态管理 stoploss = -0.05 # 硬止损 5%,实际由 custom_stoploss 动态管理
use_custom_stoploss = True use_custom_stoploss = True
minimal_roi = {"0": 100} # 不设时间止盈,出场由结构决定 minimal_roi = {"0": 100} # 不设时间止盈,出场由结构决定
max_open_trades = 1 max_open_trades = 1
# 回测参数 # 回测参数
startup_candle_count = 20 # 需要足够的历史数据来建立 Swing Point startup_candle_count = 40 # 需要更多历史数据1H 级别)
# ── 可调参数 ────────────────────────────────────────── # ── 可调参数 ──────────────────────────────────────────
# 这些参数是策略唯一的"旋钮",且都有结构含义
# Swing Point 检测窗口(寻找局部极值需要左右各 N 根K线确认
swing_lookback_d1 = IntParameter( swing_lookback_d1 = IntParameter(
2, 10, default=5, space="buy", 2, 10, default=5, space="buy",
) )
swing_lookback_h1 = IntParameter( swing_lookback_h4 = IntParameter(
2, 10, default=5, space="buy", 2, 10, default=5, space="buy",
) )
@ -81,6 +73,12 @@ class StructureFlowStrategy(IStrategy):
1.5, 4.0, default=2.0, space="buy", 1.5, 4.0, default=2.0, space="buy",
) )
# 结构止损缓冲(%):止损设在结构位之外一点,避免被噪音扫损
sl_buffer_pct = DecimalParameter(
0.005, 0.03, default=0.01, space="sell",
optimize=True,
)
# ================================================================ # ================================================================
# 工具函数 — 纯价格计算,不依赖任何技术指标 # 工具函数 — 纯价格计算,不依赖任何技术指标
# ================================================================ # ================================================================
@ -97,8 +95,6 @@ class StructureFlowStrategy(IStrategy):
纯价格比较: 纯价格比较:
- Swing High: 当前高点 > 左右各 lookback 根K线的所有高点 - Swing High: 当前高点 > 左右各 lookback 根K线的所有高点
- Swing Low: 当前低点 < 左右各 lookback 根K线的所有低点 - Swing Low: 当前低点 < 左右各 lookback 根K线的所有低点
这是价格行为学最基础的构件——不需要任何指标。
""" """
n = len(high) n = len(high)
is_swing_high = np.full(n, False) is_swing_high = np.full(n, False)
@ -129,26 +125,15 @@ class StructureFlowStrategy(IStrategy):
""" """
从 Swing Points 构建市场结构信息。 从 Swing Points 构建市场结构信息。
对每一个 K 线时刻,计算: 返回值包含:
1. trend_up / trend_down当前处于上升/下降结构 trend_up / trend_down当前处于上升/下降结构
- 最近两个 SH 和两个 SL 同时上移 → 上升 support最近 Swing Low 价格
- 最近两个 SH 和两个 SL 同时下移 → 下降 resistance最近 Swing High 价格
- 其他 → 保持上一个状态(结构延续 in_demand价格在下半区做多区域
in_supply价格在上半区做空区域
2. nearest_support最近 Swing Low 的价格
3. nearest_resistance最近 Swing High 的价格
4. in_demand_zone价格在下半区做多区域
- 用区间中点划分price_low < midpoint = 在下半区
- 这比固定百分比更合理,因为区间大小由波动自然决定
5. in_supply_zone价格在上半区做空区域
返回值是一个 DataFrame包含上述所有列。
""" """
n = len(high) n = len(high)
# 输出数组
trend_up_arr = np.full(n, False) trend_up_arr = np.full(n, False)
trend_down_arr = np.full(n, False) trend_down_arr = np.full(n, False)
nearest_support = np.full(n, np.nan) nearest_support = np.full(n, np.nan)
@ -156,15 +141,13 @@ class StructureFlowStrategy(IStrategy):
in_demand_zone = np.full(n, False) in_demand_zone = np.full(n, False)
in_supply_zone = np.full(n, False) in_supply_zone = np.full(n, False)
# 用于追踪 Swing Point 序列的队列 sh_prices: list[float] = []
sh_prices: list[float] = [] # 最近几个 Swing High 价格 sl_prices: list[float] = []
sl_prices: list[float] = [] # 最近几个 Swing Low 价格
for i in range(n): for i in range(n):
# ── 更新 Swing Point 队列 ── # ── 更新 Swing Point 队列 ──
if swing_high.iloc[i] and not np.isnan(high.iloc[i]): if swing_high.iloc[i] and not np.isnan(high.iloc[i]):
sh_prices.append(high.iloc[i]) sh_prices.append(high.iloc[i])
# 只保留最近 4 个(用于判断结构)
if len(sh_prices) > 4: if len(sh_prices) > 4:
sh_prices.pop(0) sh_prices.pop(0)
@ -173,7 +156,7 @@ class StructureFlowStrategy(IStrategy):
if len(sl_prices) > 4: if len(sl_prices) > 4:
sl_prices.pop(0) sl_prices.pop(0)
# ── 趋势判断:至少需要 2 个 SH 和 2 个 SL ── # ── 趋势判断 ──
if len(sh_prices) >= 2 and len(sl_prices) >= 2: if len(sh_prices) >= 2 and len(sl_prices) >= 2:
latest_sh, prev_sh = sh_prices[-1], sh_prices[-2] latest_sh, prev_sh = sh_prices[-1], sh_prices[-2]
latest_sl, prev_sl = sl_prices[-1], sl_prices[-2] latest_sl, prev_sl = sl_prices[-1], sl_prices[-2]
@ -185,12 +168,10 @@ class StructureFlowStrategy(IStrategy):
trend_up_arr[i] = False trend_up_arr[i] = False
trend_down_arr[i] = True trend_down_arr[i] = True
else: else:
# 结构不明确,延续前一个状态
if i > 0: if i > 0:
trend_up_arr[i] = trend_up_arr[i - 1] trend_up_arr[i] = trend_up_arr[i - 1]
trend_down_arr[i] = trend_down_arr[i - 1] trend_down_arr[i] = trend_down_arr[i - 1]
elif i > 0: elif i > 0:
# 数据不足,延续前一个状态
trend_up_arr[i] = trend_up_arr[i - 1] trend_up_arr[i] = trend_up_arr[i - 1]
trend_down_arr[i] = trend_down_arr[i - 1] trend_down_arr[i] = trend_down_arr[i - 1]
@ -206,16 +187,13 @@ class StructureFlowStrategy(IStrategy):
nearest_resistance[i] = nearest_resistance[i - 1] nearest_resistance[i] = nearest_resistance[i - 1]
# ── 入场区域:用 Swing 区间中点划分 ── # ── 入场区域:用 Swing 区间中点划分 ──
# 有有效的支撑和阻力时才能判断
if ( if (
not np.isnan(nearest_support[i]) not np.isnan(nearest_support[i])
and not np.isnan(nearest_resistance[i]) and not np.isnan(nearest_resistance[i])
and nearest_resistance[i] > nearest_support[i] and nearest_resistance[i] > nearest_support[i]
): ):
mid = (nearest_support[i] + nearest_resistance[i]) / 2.0 mid = (nearest_support[i] + nearest_resistance[i]) / 2.0
# 做多区域:价格低点触及下半区(有回落需求)
in_demand_zone[i] = low.iloc[i] <= mid in_demand_zone[i] = low.iloc[i] <= mid
# 做空区域:价格高点触及上半区(有反弹供给)
in_supply_zone[i] = high.iloc[i] >= mid in_supply_zone[i] = high.iloc[i] >= mid
elif i > 0: elif i > 0:
in_demand_zone[i] = in_demand_zone[i - 1] in_demand_zone[i] = in_demand_zone[i - 1]
@ -244,26 +222,15 @@ class StructureFlowStrategy(IStrategy):
) -> tuple[pd.Series, pd.Series, pd.Series, pd.Series]: ) -> tuple[pd.Series, pd.Series, pd.Series, pd.Series]:
""" """
检测 K 线形态 — 纯 OHLC 计算。 检测 K 线形态 — 纯 OHLC 计算。
Pin Bar (锤子线/流星线):
影线远大于实体实体在K线的一端。
看涨 Pin Bar: 长下影线 + 小实体在上方 = 买方在低位介入
看跌 Pin Bar: 长上影线 + 小实体在下方 = 卖方在高位施压
Engulfing (吞没形态):
当前实体完全包裹前一实体,表示力量转换。
""" """
body = abs(c - o) body = abs(c - o)
upper_wick = h - np.maximum(o, c) upper_wick = h - np.maximum(o, c)
lower_wick = np.minimum(o, c) - l lower_wick = np.minimum(o, c) - l
total_range = h - l total_range = h - l
# 避免除零
valid_range = total_range > 0 valid_range = total_range > 0
valid_body = body > 0 valid_body = body > 0
# ── Pin Bar ──
# 看涨:下影线 ≥ pin_ratio × 实体,上影线 ≤ 0.5 × 实体实体在K线上方
bullish_pin = ( bullish_pin = (
valid_range valid_range
& valid_body & valid_body
@ -271,7 +238,6 @@ class StructureFlowStrategy(IStrategy):
& (upper_wick <= 0.5 * body) & (upper_wick <= 0.5 * body)
) )
# 看跌:上影线 ≥ pin_ratio × 实体,下影线 ≤ 0.5 × 实体
bearish_pin = ( bearish_pin = (
valid_range valid_range
& valid_body & valid_body
@ -279,21 +245,20 @@ class StructureFlowStrategy(IStrategy):
& (lower_wick <= 0.5 * body) & (lower_wick <= 0.5 * body)
) )
# ── Engulfing ──
prev_body = body.shift(1) prev_body = body.shift(1)
prev_o = o.shift(1) prev_o = o.shift(1)
prev_c = c.shift(1) prev_c = c.shift(1)
bullish_engulf = ( bullish_engulf = (
(c > o) # 当前阳线 (c > o)
& (prev_c < prev_o) # 前一根阴线 & (prev_c < prev_o)
& (body > prev_body) # 当前实体更大 & (body > prev_body)
) )
bearish_engulf = ( bearish_engulf = (
(c < o) # 当前阴线 (c < o)
& (prev_c > prev_o) # 前一根阳线 & (prev_c > prev_o)
& (body > prev_body) # 当前实体更大 & (body > prev_body)
) )
return ( return (
@ -311,11 +276,6 @@ class StructureFlowStrategy(IStrategy):
def populate_indicators_1d( def populate_indicators_1d(
self, dataframe: DataFrame, metadata: dict self, dataframe: DataFrame, metadata: dict
) -> DataFrame: ) -> DataFrame:
"""
D1 日线分析:宏观结构方向。
计算 Swing Point → 结构趋势 → 支撑/阻力。
"""
sh, sl = self._detect_swing_points( sh, sl = self._detect_swing_points(
dataframe["high"], dataframe["low"], dataframe["high"], dataframe["low"],
self.swing_lookback_d1.value, self.swing_lookback_d1.value,
@ -332,21 +292,16 @@ class StructureFlowStrategy(IStrategy):
return dataframe return dataframe
# ================================================================ # ================================================================
# 信息时间框架 — 1H 中期结构 # 信息时间框架 — 4H 中期结构
# ================================================================ # ================================================================
@informative("1h") @informative("4h")
def populate_indicators_1h( def populate_indicators_4h(
self, dataframe: DataFrame, metadata: dict self, dataframe: DataFrame, metadata: dict
) -> DataFrame: ) -> DataFrame:
"""
1H 小时线分析:中期结构位 + 入场区域。
计算 Swing Point → 结构趋势 → 支撑/阻力 → 供需区域。
"""
sh, sl = self._detect_swing_points( sh, sl = self._detect_swing_points(
dataframe["high"], dataframe["low"], dataframe["high"], dataframe["low"],
self.swing_lookback_h1.value, self.swing_lookback_h4.value,
) )
structure = self._build_structure( structure = self._build_structure(
@ -364,16 +319,14 @@ class StructureFlowStrategy(IStrategy):
return dataframe return dataframe
# ================================================================ # ================================================================
# 主时间框架 — 5M K线形态 # 主时间框架 — 1H K线形态
# ================================================================ # ================================================================
def populate_indicators( def populate_indicators(
self, dataframe: DataFrame, metadata: dict self, dataframe: DataFrame, metadata: dict
) -> DataFrame: ) -> DataFrame:
""" """
5M 五分钟线:检测 K 线形态。 1H 一小时线:检测 K 线形态。
不需要任何指标——形态来自 OHLC 的几何关系。
""" """
bullish_pin, bearish_pin, bullish_engulf, bearish_engulf = ( bullish_pin, bearish_pin, bullish_engulf, bearish_engulf = (
self._detect_candle_patterns( self._detect_candle_patterns(
@ -390,7 +343,6 @@ class StructureFlowStrategy(IStrategy):
dataframe["bullish_engulfing"] = bullish_engulf dataframe["bullish_engulfing"] = bullish_engulf
dataframe["bearish_engulfing"] = bearish_engulf dataframe["bearish_engulfing"] = bearish_engulf
# 综合看涨/看跌信号(任一形态触发即可)
dataframe["bullish_signal"] = bullish_pin | bullish_engulf dataframe["bullish_signal"] = bullish_pin | bullish_engulf
dataframe["bearish_signal"] = bearish_pin | bearish_engulf dataframe["bearish_signal"] = bearish_pin | bearish_engulf
@ -404,49 +356,45 @@ class StructureFlowStrategy(IStrategy):
self, dataframe: DataFrame, metadata: dict self, dataframe: DataFrame, metadata: dict
) -> DataFrame: ) -> DataFrame:
""" """
入场逻辑。 入场逻辑1H 时间框架)
做多条件(全部满足): 做多条件:
1. D1 处于上升结构trend_up_1d 1. D1 上升结构trend_up_1d
2. 价格在 1H 下半区 / 需求区域in_demand_1h 2. 4H 下半区 / 需求区域in_demand_4h
——这意味着价格已回调到支撑位附近 3. 1H 看涨 K 线形态bullish_signal
3. 5M 出现看涨 K 线形态bullish_signal
——Pin Bar 或 Engulfing 在结构位确认入场
做空条件(全部满足): 做空条件:
1. D1 处于下降结构trend_down_1d 1. D1 下降结构trend_down_1d
2. 价格在 1H 上半区 / 供给区域in_supply_1h 2. 4H 上半区 / 供给区域in_supply_4h
3. 5M 出现看跌 K 线形态bearish_signal 3. 1H 看跌 K 线形态bearish_signal
""" """
# ── NaN 安全处理 ── # ── NaN 安全处理 ──
# 多时间框架合并后,前部可能有 NaN
bool_cols = [ bool_cols = [
"trend_up_1d", "trend_down_1d", "trend_up_1d", "trend_down_1d",
"trend_up_1h", "trend_down_1h", "trend_up_4h", "trend_down_4h",
"in_demand_1h", "in_supply_1h", "in_demand_4h", "in_supply_4h",
"bullish_signal", "bearish_signal", "bullish_signal", "bearish_signal",
] ]
for col in bool_cols: for col in bool_cols:
if col in dataframe.columns: if col in dataframe.columns:
dataframe[col] = dataframe[col].fillna(False) dataframe[col] = dataframe[col].fillna(False).infer_objects(copy=False)
# ── 做多 ── # ── 做多 ──
long_conditions = ( long_conditions = (
dataframe["trend_up_1d"] # D1 上升结构 dataframe["trend_up_1d"]
& dataframe["in_demand_1h"] # 1H 下半区(需求区域) & dataframe["in_demand_4h"]
& dataframe["bullish_signal"] # 5M 看涨形态 & dataframe["bullish_signal"]
) )
dataframe.loc[long_conditions, "enter_long"] = 1 dataframe.loc[long_conditions, "enter_long"] = 1
# ── 做空 ── # ── 做空 ──
if self.can_short: short_conditions = (
short_conditions = ( dataframe["trend_down_1d"]
dataframe["trend_down_1d"] # D1 下降结构 & dataframe["in_supply_4h"]
& dataframe["in_supply_1h"] # 1H 上半区(供给区域) & dataframe["bearish_signal"]
& dataframe["bearish_signal"] # 5M 看跌形态 )
) dataframe.loc[short_conditions, "enter_short"] = 1
dataframe.loc[short_conditions, "enter_short"] = 1
return dataframe return dataframe
@ -459,28 +407,19 @@ class StructureFlowStrategy(IStrategy):
) -> DataFrame: ) -> DataFrame:
""" """
出场逻辑 — 由结构反转触发。 出场逻辑 — 由结构反转触发。
做多出场:
D1 不再处于上升结构 → 宏观环境改变
或 1H 不再处于上升结构 → 中期结构失效
做空出场:
D1 不再处于下降结构 → 宏观环境改变
或 1H 不再处于下降结构 → 中期结构失效
""" """
# 做多出场 # 做多出场D1 不再上升 或 4H 不再上升
exit_long = ( exit_long = (
~dataframe["trend_up_1d"].fillna(True) # D1 结构反转NaN = 初始区,不出场) ~dataframe["trend_up_1d"].fillna(True)
) )
dataframe.loc[exit_long, "exit_long"] = 1 dataframe.loc[exit_long, "exit_long"] = 1
# 做空出场 # 做空出场D1 不再下降 或 4H 不再下降
if self.can_short: exit_short = (
exit_short = ( dataframe["trend_up_1d"].fillna(False)
dataframe["trend_up_1d"].fillna(False) # D1 转为上升 )
) dataframe.loc[exit_short, "exit_short"] = 1
dataframe.loc[exit_short, "exit_short"] = 1
return dataframe return dataframe
@ -499,44 +438,33 @@ class StructureFlowStrategy(IStrategy):
**kwargs, **kwargs,
) -> float | None: ) -> float | None:
""" """
结构止损:止损位设在最近的 1H Swing Low做多或 Swing High做空 结构止损:止损位设在最近的 4H Swing Low做多或 Swing High做空
加上缓冲距离sl_buffer_pct
如果价格突破这个结构位,说明结构失效,交易逻辑不再成立 随着行情发展,新的 Swing Point 形成,止损自动跟随
这与传统的百分比止损或 ATR 止损不同——它不是"跌了N%就走"
而是"结构破了就走"
随着行情发展,新的 Swing Point 形成,止损自动跟随,
实现自然的移动止损——不依赖任何参数。
""" """
# 获取已分析的 5M 数据(包含合并后的 1H 信息)
dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe) dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
if dataframe is None or len(dataframe) == 0: if dataframe is None or len(dataframe) == 0:
return None # 使用默认 stoploss return None
last = dataframe.iloc[-1] last = dataframe.iloc[-1]
buffer = self.sl_buffer_pct.value
if trade.is_short: if trade.is_short:
# 做空止损:放在最近的 1H Swing High 上方 resistance = last.get("resistance_4h")
resistance = last.get("resistance_1h")
if resistance is not None and not (isinstance(resistance, float) and np.isnan(resistance)): if resistance is not None and not (isinstance(resistance, float) and np.isnan(resistance)):
# stoploss = (current - stop_price) / current # 做空止损resistance × (1 + buffer),在当前价格上方
# 做空时 stop 在 current 上方,所以 (current - resistance) 为负 sl_price = float(resistance) * (1 + buffer)
# 转为负的比例 sl_ratio = (current_rate - sl_price) / current_rate
sl_ratio = (current_rate - float(resistance)) / current_rate if sl_ratio < 0: # 止损在当前价格上方(做空方向正确)
# 只使用比默认止损更紧的止损 return max(sl_ratio, -0.25) # 不超过 25%
if sl_ratio > self.stoploss and sl_ratio < 0:
return sl_ratio
else: else:
# 做多止损:放在最近的 1H Swing Low 下方 support = last.get("support_4h")
support = last.get("support_1h")
if support is not None and not (isinstance(support, float) and np.isnan(support)): if support is not None and not (isinstance(support, float) and np.isnan(support)):
# stoploss = (stop_price - current) / current # 做多止损support × (1 - buffer),在当前价格下方
# 做多时 stop 在 current 下方,结果为负 sl_price = float(support) * (1 - buffer)
sl_ratio = (float(support) - current_rate) / current_rate sl_ratio = (sl_price - current_rate) / current_rate
# 只使用比默认止损更紧的止损 if sl_ratio < 0: # 止损在当前价格下方(做多方向正确)
if sl_ratio > self.stoploss and sl_ratio < 0: return max(sl_ratio, -0.25)
return sl_ratio
# 无法获取有效的结构位,使用默认硬止损
return None return None