You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Inside Candle策略止损设置为入场触发K线的低点?

修改Inside Candle策略的止损逻辑(固定为入场触发对应的Inside Candle低点)

问题分析

原代码的止损会随着后续K线的变量更新,导致止损被后续Inside Candle的低点覆盖,无法固定为触发入场信号的那根Inside Candle的低点。需要将触发入场的Inside Candle低点值保存下来,入场时调用该固定值作为止损。

修改后的完整代码

//@version=5
strategy("Inside Candle Bar", overlay=true, process_orders_on_close=true)

// 交易时段设置
string sessionInput = input.session("0930-1415", "Session")
string daysInput = input.string("1234567", tooltip = "1 = Sunday, 7 = Saturday")
sessionString = sessionInput + ":" + daysInput
inSession = not na(time(timeframe.period, sessionString))
bgcolor(inSession ? color.rgb(178, 181, 190, 96) : na)

// 指标与Inside Candle定义
ema = ta.ema(close, 50)
IC = (high <= high[1] and low >= low[1])

// 存储触发入场的Inside Candle高低点(用var保持值直到下一次更新)
var float entryICLow = na
var float entryICHigh = na

// 标记符合多单条件的Inside Candle,并记录其高低点
ICwithEMALONG = IC and (close > ema)
ICwithEMASHORT = IC and (close < ema)

if ICwithEMALONG and inSession
    entryICLow = low[0] - (2 * syminfo.mintick)
    entryICHigh = high[0] + (2 * syminfo.mintick)

// 入场信号定义
EntryCandleLONG = IC[1] and (high[0] > high[1]) and (close[1] > ema) and inSession
EntryCandleSHORT = IC[1] and (low[0] < low[1]) and (close[1] < ema) and inSession

// 绘制EMA
plot(ema, "EMA", color.blue, linewidth = 2)

// K线颜色标记
barcolor(ICwithEMALONG ? color.white : na)
barcolor(ICwithEMASHORT ? color.white : na)
barcolor(EntryCandleLONG ? color.yellow : na)
barcolor(EntryCandleSHORT ? color.yellow : na)

// 多单入场与离场逻辑
if EntryCandleLONG
    strategy.entry("LONG", strategy.long)
    stoploss = entryICLow
    target = entryICHigh + ((entryICHigh - entryICLow) * 3)
    strategy.exit("LONGExit", from_entry="LONG", stop=stoploss, limit=target)

关键修改点

  • 新增var float entryICLow和entryICHigh变量,用var关键字确保变量值在未被重新赋值前保持不变,不会被后续K线覆盖
  • 在检测到符合多单条件的Inside Candle(ICwithEMALONG)时,将该K线的低点(调整最小变动单位后)存入entryICLow,高点存入entryICHigh
  • 将入场逻辑从Inside Candle K线的挂单,改为在突破Inside Candle高点的K线(EntryCandleLONG)执行入场,此时直接调用之前保存的entryICLow作为止损,确保止损固定为触发入场的那根Inside Candle的低点
  • 调整目标价计算,同样基于触发入场的Inside Candle的高低点,保持风险收益比一致

内容的提问来源于stack exchange,提问作者Trading Records

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:43:16