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

Pine Script多单策略正常,空单策略回测失效求助

BTC 1小时空单策略回测异常排查

核心问题定位与修复建议

1. 致命变量引用错误

空单策略里的平仓触发条件longCondition使用了未定义的ema500变量:

longCondition = ta.crossover(ema55, ema500)

代码中仅声明了ema55和ema200,这里应该改为ema200(和多单策略逻辑对齐)。这个错误会导致平仓逻辑完全失效,持仓无法按规则退出,直接干扰策略正常执行。

2. 开仓条件缺失持仓过滤

空单策略的shortCondition注释掉了strategy.opentrades==0限制:

shortCondition = ta.crossunder(ema55,ema200)//and strategy.opentrades==0

而多单策略保留了该条件,这会导致满足空单信号时,即使已有持仓也会重复开仓,触发金字塔规则(pyramiding=3),造成回测中持仓数量超出预期,打乱策略逻辑。

修复后的完整空单策略代码

//@version=5
strategy("BTC 1H cross SHORT strategy", overlay=true, default_qty_type = strategy.percent_of_equity, margin_long=100, margin_short=100,
 initial_capital = 10000, pyramiding = 3, calc_on_order_fills = true, process_orders_on_close = true, calc_on_every_tick=true)

ema55 = ta.ema(close, 55)
ema200 = ta.ema(close, 200)

// 恢复持仓过滤,避免重复开仓
shortCondition = ta.crossunder(ema55,ema200) and strategy.opentrades==0
// 修复变量引用错误
longCondition = ta.crossover(ema55, ema200)

start = timestamp(2022,6,1,0,0)
end = timestamp(2022,12,31,23,59)

tp = 3500
sl = 2500

if time >= start and time <= end
    if (shortCondition)
        strategy.entry("Short Entry 1H", strategy.short, qty = 1, comment = "Opened Short")
        strategy.exit(id = "Exit Short", from_entry = "Short Entry 1H",  limit = close[0]-tp, stop = close[0]+sl, comment_profit = "HIT profit", comment_loss = "HIT loss")
    
    if (longCondition and strategy.position_size > 0)
        strategy.cancel("Exit Short")
        strategy.close("Short Entry 1H", comment = "Closed short abruptly", immediately = true)

额外验证步骤

  • 可以在图表上添加信号标记,确认空单信号是否真实触发:
    plotshape(shortCondition, title="Short Signal", location=location.belowbar, color=color.red, style=shape.triangleup)
    
  • 检查回测时间段内ema55下穿ema200的K线是否存在,避免因数据区间无信号导致策略无操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 10:05:21