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

TradingView Pine Script 多空开仓重置ATR Trailing Stop及止损止盈设置咨询

你当前代码的问题是var float trailingStop = na是全局持久化变量,跨持仓不会自动清空,导致上一笔交易的止损值会干扰新交易的计算。要实现开仓重置+3Commas的止盈、固定止损、移动止损组合功能,按下面修改即可:

修改步骤

  1. 先在止损设置组新增固定止损、止盈的配置参数:
// ————— Stop Loss Settings 下新增两行输入
i_fixedStopPerc = input(1.0, "固定止损比例(%)", group = GP3, step=0.1) * 0.01
i_takeProfitPerc = input(3.0, "止盈比例(%)", group = GP3, step=0.1) * 0.01
  1. 新增新开仓状态检测,识别多/空刚开仓的时间节点:
FLAT            = strategy.position_size == 0
LONG            = strategy.position_size > 0
SHORT           = strategy.position_size < 0
entry           = strategy.position_avg_price
// 新增开仓状态判断
isNewLong = LONG and not LONG[1]
isNewShort = SHORT and not SHORT[1]
  1. 调整跟踪止损的赋值逻辑,开仓时先重置止损初始值,持仓过程中再按ATR规则更新:
var float trailingStop = na

// 开仓时重置止损为初始值
if isNewLong and i_useTrailingStop
    // 初始止损可以选固定比例或者初始ATR计算,二选一即可
    initialStop = entry * (1 - i_fixedStopPerc)
    // 初始ATR版:initialStop = entry - atr * i_atrMultiplier
    trailingStop := initialStop
if isNewShort and i_useTrailingStop
    initialStop = entry * (1 + i_fixedStopPerc)
    // 初始ATR版:initialStop = entry + atr * i_atrMultiplier
    trailingStop := initialStop

// 持仓过程中更新移动止损,只向有利方向调整
if LONG and i_useTrailingStop and barstate.isconfirmed and not isNewLong
    trail = lowestLow - atr * i_atrMultiplier
    trailingStop := math.max(trail, trailingStop) // 多头止损只上移不下调
if SHORT and i_useTrailingStop and barstate.isconfirmed and not isNewShort
    trail = highestHigh + atr * i_atrMultiplier
    trailingStop := math.min(trail, trailingStop) // 空头止损只下移不上调
  1. 打开原来注释的出场逻辑,补充止盈参数:
// 多头出场
strategy.exit("EXIT LONG", "LONG", 
    stop = i_useTrailingStop ? trailingStop : entry * (1 - i_fixedStopPerc), 
    limit = entry * (1 + i_takeProfitPerc),
    when = LONG
)
// 空头出场
strategy.exit("EXIT SHORT", "SHORT", 
    stop = i_useTrailingStop ? trailingStop : entry * (1 + i_fixedStopPerc), 
    limit = entry * (1 - i_takeProfitPerc),
    when = SHORT
)

可选优化

如果你需要跟踪的是开仓之后的价格极值,而不是全局的N周期高低点,可以把高低点统计改成开仓后重置的版本:

var float lowestAfterLong = na
var float highestAfterShort = na
if isNewLong
    lowestAfterLong := low
if LONG
    lowestAfterLong := math.min(lowestAfterLong, low)
if isNewShort
    highestAfterShort := high
if SHORT
    highestAfterShort := math.max(highestAfterShort, high)

之后把移动止损计算里的lowestLow替换为lowestAfterLong,highestHigh替换为highestAfterShort即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:54:03