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

如何在Pine Script中固定25小时内的最低价作为止损?

Pine Script固定开仓时止损最低价的解决办法

你当前的问题核心是:开多单后,ta.lowest(low,25)会随着新K线生成不断重新计算,导致止损位持续变动。要实现固定25周期最低价作为止损,关键是在开仓瞬间锁定当时的最低价,后续不再更新这个值。

下面提供两种可行的实现方式:

方法1:用valuewhen捕捉开仓时的最低价

valuewhen函数可以精准抓取指定条件触发时的目标数值,刚好用来记录开仓瞬间的25周期最低价:

//@version=5
strategy("固定止损策略", overlay=true)

// 替换为你实际的止损阈值和多单触发条件
stoploss = input.float(2.0, "止损阈值")
long_condition = input.bool(true, "多单触发条件")

// 实时计算25周期最低价
current_25low = ta.lowest(low, 25)

// 仅在开仓信号触发时,记录当时的25周期最低价
entry_fixed_low = valuewhen(strategy.position_size == 0 and long_condition and (4.2 >= stoploss and stoploss >= 1.7), current_25low, 0)

// 开仓逻辑:无持仓+满足条件时开多单
if (4.2 >= stoploss and stoploss >= 1.7) and long_condition and strategy.position_size == 0
    strategy.entry("LONG", strategy.long)

// 平仓时使用固定的开仓最低价作为止损
strategy.exit("exit", "LONG", loss=entry_fixed_low, profit=close * 4)

方法2:用var变量存储开仓时的最低价

var定义的变量只会初始化一次,我们只在开仓时给它赋值,后续保持该值不变:

//@version=5
strategy("固定止损策略", overlay=true)

stoploss = input.float(2.0, "止损阈值")
long_condition = input.bool(true, "多单触发条件")

// 初始化空变量,用于存储开仓时的最低价
var float fixed_stop_low = na

// 实时计算25周期最低价
current_25low = ta.lowest(low, 25)

// 开仓时给变量赋值,同时执行开单操作
if (4.2 >= stoploss and stoploss >= 1.7) and long_condition and strategy.position_size == 0
    fixed_stop_low := current_25low
    strategy.entry("LONG", strategy.long)

// 有持仓时,使用固定值作为止损触发平仓
if strategy.position_size > 0
    strategy.exit("exit", "LONG", loss=fixed_stop_low, profit=close * 4)

关键注意点

  • 必须添加strategy.position_size == 0的判断,确保仅在开仓前记录最低价,避免持仓期间被新K线的最低价覆盖。
  • 请将代码中的long_condition替换为你实际的多单触发逻辑(比如均线金叉、指标信号等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:05:25