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

Pine Script策略问题:HedgeSellEnter/Exit失效及HedgeGap计算异常

Pine Script 对冲策略问题排查与修复

问题1:HedgeSellEnter 触发条件逻辑失效

原代码中HedgeSellEnter的表达式存在运算符优先级错误,and优先级高于三元运算符,导致实际逻辑为sellSignal ? dn : (na and stopLong != true and ...)——只有sellSignal为真时返回dn,否则直接返回na,后面两个条件完全不起作用。同时缺少STBUY持仓判断,无法保证仅在多单开仓后触发对冲。

修复代码:

// 三个条件需同时满足:sellSignal触发、stopLong为false、STBUY持仓存在
HedgeSellEnter = (sellSignal ? dn : na) and not stopLong and strategy.opentrades.size("STBUY") > 0
  • 用括号明确三元运算符的作用范围,确保sellSignal ? dn : na的结果先计算,再与后续条件做逻辑与
  • 直接通过strategy.opentrades.size("STBUY") > 0判断多单持仓,比依赖strategy.opentrades-1索引更可靠

问题2:HedgeSellExit 条件失效与HedgeGap计算错误

(1)HedgeGap计算时机错误

执行strategy.order("HEDGESELL")后立即计算HedgeGap时,strategy.opentrades还未更新(Pine Script中订单的持仓更新延迟到下一根K线),导致strategy.opentrades.entry_price(strategy.opentrades-1)无法正确获取STBUY的入场价。

(2)HedgeSellExit逻辑缺失

原条件未判断HEDGESELL持仓是否存在,且stopLong = true后无重置逻辑,会导致后续策略无法正常触发。

完整修复代码片段:

// Strategy - Buy Entry and Exit (5 Mins Chart)
var float HedgeEntry = 0
var float HedgeGap = 0
var float HedgeTarget = 0
var float HedgeTakeProfit = 0
var bool stopLong = false
var float STBUY_EntryPrice = 0  // 新增变量记录STBUY入场价

// Strategy - Long
if conditionBuy
    strategy.entry("STBUY", strategy.long, qty = lots, comment='Super Buy')
    STBUY_EntryPrice := strategy.opentrades.entry_price(0)  // 开仓时直接记录多单入场价
strategy.exit("Exit Buy", "STBUY", profit = longTakeProfit)

// 修正后的HedgeSellEnter
HedgeSellEnter = (sellSignal ? dn : na) and not stopLong and strategy.opentrades.size("STBUY") > 0

// 修正后的HedgeSellExit:需同时满足目标价条件、stopLong为false、对冲单持仓存在
HedgeSellExit = HedgeTarget > close and not stopLong and strategy.opentrades.size("HEDGESELL") > 0

if HedgeSellEnter
    strategy.close("STBUY")
    strategy.order("HEDGESELL", strategy.short, qty = lots*2, comment = 'Enter Hedge Sell')
    HedgeEntry := strategy.opentrades.entry_price(0)  // 记录对冲单入场价
    HedgeGap := STBUY_EntryPrice - HedgeEntry  // 用预存的多单入场价计算价差
    HedgeTarget := STBUY_EntryPrice - HedgeGap - longGap
else if HedgeSellExit
    strategy.close("HEDGESELL", comment = 'Exit Hedge Sell')
    stopLong := true
    // 若需后续重新触发策略,可在此添加stopLong := false重置逻辑

关键修复点:

  • 新增STBUY_EntryPrice变量,在STBUY开仓时直接记录入场价,避免依赖不稳定的strategy.opentrades索引
  • 给HedgeSellExit添加strategy.opentrades.size("HEDGESELL") > 0条件,确保仅在对冲单存在时触发平仓
  • 调整HedgeGap计算逻辑,使用预存的多单入场价,避免订单执行后持仓列表未更新导致的计算错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:10:37