如何在Supertrend MTF Heikin Ashi策略中添加10点移动止损及禁重入场条件?
如何为Supertrend MTF Heikin Ashi策略添加10点移动止损并控制入场逻辑
核心改动说明
针对你的需求,需完成三个关键调整:
- 移除原策略中因趋势变化直接平仓的逻辑,确保仅通过移动止损离场
- 添加10点(pips)的移动止损机制
- 实现止损触发后需等待趋势反转才能重新入场的控制逻辑
修改后的完整代码
//@version=5 strategy('Supertrend MTF Heikin Ashi', overlay=true) // 输入参数:新增移动止损点数设置 Mult = input.float(defval=0.5, title='ATR Factor', maxval=100, step=0.1) Period = input.int(defval=5, title='ATR Period', maxval=100) trailPips = input.int(defval=10, title='移动止损点数(Pips)') timeallowed = input.session("0945-1100", title = "允许入场时段") // 计算Pips对应的价格差:适配不同品种的最小跳动单位 pipSize = syminfo.mintick * (syminfo.type == "forex" ? 10 : 1) // 外汇品种1pip=10个最小跳动 trailOffset = trailPips * pipSize // Heikin Ashi 数据获取 h = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high) l = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low) c = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close) Atr = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ta.atr(Period)) // Supertrend 计算逻辑 Up = (h + l) / 2 - Mult * Atr Dn = (h + l) / 2 + Mult * Atr float TUp = na float TDown = na Trend = 0 TUp := c[1] > TUp[1] ? math.max(Up, TUp[1]) : Up TDown := c[1] < TDown[1] ? math.min(Dn, TDown[1]) : Dn Trend := c > TDown[1] ? 1 : c < TUp[1] ? -1 : nz(Trend[1], 1) Trailingsl = Trend == 1 ? TUp : TDown linecolor = Trend == 1 and nz(Trend[1]) == 1 ? color.lime : Trend == -1 and nz(Trend[1]) == -1 ? color.red : na uptrend = Trend == 1 downtrend = Trend == -1 iswithintime = time(timeframe.period, timeallowed) // 状态变量:跟踪止损是否触发 var bool stopLossTriggered = false // 跟踪上一次的趋势方向,用于判断反转 var int prevTrend = 1 // 趋势反转时重置止损触发状态 if Trend != prevTrend stopLossTriggered := false prevTrend := Trend // 入场逻辑:仅在允许时段、趋势信号有效且未触发止损时入场 if uptrend and iswithintime and not stopLossTriggered strategy.entry("long", strategy.long) // 设置多单移动止损 strategy.exit("long_exit", "long", trail_offset=trailOffset) if downtrend and iswithintime and not stopLossTriggered strategy.entry("short", strategy.short) // 设置空单移动止损 strategy.exit("short_exit", "short", trail_offset=trailOffset) // 止损触发时标记状态 if strategy.exitreason() == strategy.exit_reason.trailing_stop stopLossTriggered := true // 绘图部分 plot(Trailingsl, color=linecolor, linewidth=2, title='SuperTrend') bgcolor(uptrend == 1 ? color.new(color.teal, transp = 85) : color.new(color.red, transp = 85))
关键改动解释
移除趋势平仓逻辑:删除原代码中
if downtrend: strategy.close("long")和if uptrend: strategy.close("short")语句,确保只有移动止损触发时才会离场。移动止损实现:
- 通过
input.int添加可配置的移动止损点数参数 - 根据品种类型(外汇/其他)计算对应的价格偏移量
trailOffset,确保10pips的止损在不同品种上准确生效 - 使用
strategy.exit的trail_offset参数设置移动止损,价格向盈利方向移动时,止损会自动跟进
- 通过
入场控制逻辑:
- 新增
stopLossTriggered变量跟踪止损触发状态 - 当趋势发生反转(当前Trend与上一次Trend不同)时,重置
stopLossTriggered为false,允许再次入场 - 入场条件增加
not stopLossTriggered判断,确保止损触发后不会立即重新入场,必须等待趋势反转
- 新增
内容的提问来源于stack exchange,提问作者NITIN PATEL
相关产品推荐
相关产品推荐

