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

如何让追踪止损的Bar Index更新为交易开仓首K线的Bar Index

问题描述

我有一个嵌入策略脚本的追踪止损工具,可从指定的Bar Index或Bar Time开始绘制追踪止损线,并向Oanda发送警报更新止损。手动指定交易起始Bar Index时运行正常,但需要实现开仓时自动将旧的barIndex值覆盖为当前开仓首K线的Bar Index。

现有追踪止损核心代码

//Declare trailing variables
var trailPrice = 0.0
t_trailPrice = trailType == 'Long' ? ta.lowest(low, structureLookback) - atr : ta.highest(high, structureLookback) + atr

// Get symbol and broker
var symbol_1 = syminfo.basecurrency + '/' + syminfo.currency
var avPrefix = 'e=' + broker + ' s=' + symbol_1 + ' '

plot(strategy.opentrades.entry_bar_index(0), color=color.green)
//Check for trailing stop update
if (bar_index >= barIndex and barIndex != 0 or time >= barTime and barIndex == 0) and barstate.isconfirmed
    //Trail long stop
    if (t_trailPrice > trailPrice or trailPrice == 0.0) and trailType == 'Long'
        trailPrice := t_trailPrice
        // Tell autoview to update our stop loss
        clearOrder = avPrefix + 'c=order\n'
        slOrder = avPrefix + 'c=position b=long fsl=' + str.tostring(trailPrice)
        alert(message=clearOrder + slOrder, freq=alert.freq_once_per_bar_close)
    //Trail short stop
    if (t_trailPrice < trailPrice or trailPrice == 0.0) and trailType == 'Short'
        trailPrice := t_trailPrice
        // Tell autoview to update our stop loss
        clearOrder = avPrefix + 'c=order\n'
        slOrder = avPrefix + 'c=position b=short fsl=' + str.tostring(trailPrice)
        alert(message=clearOrder + slOrder, freq=alert.freq_once_per_bar_close)

// If long stop hit, reset trail stop
if trailPrice != 0.0 and low <= trailPrice and trailType == 'Long'
    trailPrice := na
    trailPrice

// If short stop hit, reset trail stop
if trailPrice != 0.0 and high >= trailPrice and trailType == 'Short'
    trailPrice := na
    trailPrice

//Draw data to chart
plot(trailPrice, color=color.new(color.yellow, 0), title='Trailing Stop')

plot(bar_index, color=color.new(color.blue, 0), title='Current Bar Index')

已尝试的失效方案

  • 在追踪止损脚本中插入代码,导致追踪止损线消失:
    // Get bar index if strategy.position_size != 0 
    barIndex := strategy.opentrades.entry_bar_index(0)
    
  • 在多单信号触发代码中覆盖barIndex和trailType,未实现预期效果:
    if validLong
        trailType := "Long"
        t_entry := close
        barIndex := bar_index // 也尝试过barIndex := strategy.opentrades.entry_bar_index(0)
        if longStopPrice < trailPrice
            longStopPrice := trailPrice
        t_stop := longStopPrice
        t_target := longTargetPrice
        t_direction := 1
        tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)
        strategy.entry(id='Long', direction=strategy.long, when=validLong, comment='(SL=' + str.tostring(truncate(toWhole(longStopDistance), 2)) + ' pips)')
        trailType := "Long"
        // 警报代码省略...
    
解决方案

问题根源在于barIndex的变量作用域和更新时机错误,导致追踪逻辑中断。以下是针对性修改:

1. 正确声明并初始化barIndex

在脚本顶部用var声明barIndex,确保跨bar保留状态:

var int barIndex = 0  // 初始值设为0,表示无有效开仓bar

2. 开仓时精准更新barIndex

仅在仓位从0变为非0的瞬间更新barIndex,避免重复赋值干扰追踪逻辑。修改多单信号代码:

if validLong
    trailType := "Long"
    t_entry := close
    t_stop := longStopPrice
    t_target := longTargetPrice
    t_direction := 1
    tradePositionSize := getPositionSize(toWhole(longStopDistance) * 10)
    
    // 执行开仓
    strategy.entry(id='Long', direction=strategy.long, when=validLong, comment='(SL=' + str.tostring(truncate(toWhole(longStopDistance), 2)) + ' pips)')
    
    // 仅当新仓位建立时更新barIndex
    if strategy.position_size[1] == 0 and strategy.position_size > 0
        barIndex := bar_index
        trailPrice := 0.0  // 重置追踪价格,确保从开仓bar开始计算
    
    // 原有警报代码保持不变

3. 修复追踪止损触发条件

简化并修正追踪逻辑的判断条件,确保仅在有效开仓bar之后执行:

//Check for trailing stop update
if barIndex != 0 and bar_index >= barIndex and barstate.isconfirmed
    //Trail long stop
    if (t_trailPrice > trailPrice or trailPrice == 0.0) and trailType == 'Long'
        trailPrice := t_trailPrice
        clearOrder = avPrefix + 'c=order\n'
        slOrder = avPrefix + 'c=position b=long fsl=' + str.tostring(trailPrice)
        alert(message=clearOrder + slOrder, freq=alert.freq_once_per_bar_close)
    //Trail short stop
    if (t_trailPrice < trailPrice or trailPrice == 0.0) and trailType == 'Short'
        trailPrice := t_trailPrice
        clearOrder = avPrefix + 'c=order\n'
        slOrder = avPrefix + 'c=position b=short fsl=' + str.tostring(trailPrice)
        alert(message=clearOrder + slOrder, freq=alert.freq_once_per_bar_close)

4. 平仓时重置变量

当仓位平仓时,重置barIndex和trailPrice,避免无仓位时触发错误逻辑:

// 平仓时重置追踪变量
if strategy.position_size == 0 and strategy.position_size[1] != 0
    barIndex := 0
    trailPrice := 0.0

关键逻辑说明

  • var关键字确保barIndex在bars之间保留状态,不会被自动重置
  • 仅在仓位切换瞬间更新barIndex,避免重复赋值导致追踪线中断
  • 重置trailPrice保证新仓位的追踪止损从开仓bar重新计算
  • 平仓后重置变量,防止无仓位时触发不必要的警报或绘图错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:40:23