策略满足平仓条件却未执行平仓操作求助
策略平仓失效问题排查与修复
核心问题:平仓指令的ID不匹配
你用strategy.close(id='Exit')尝试平仓,但开仓时的头寸ID是'Long',strategy.close需要指定对应开仓的头寸ID才能正确识别要平仓的仓位,而非随意命名的新ID——这是平仓逻辑完全不生效的直接原因。
次要问题:平仓条件未同步时间范围限制
开仓时加了timePeriod(2022年5月1日之后)的过滤,但平仓条件未同步该限制,若信号出现在时间范围外也不会触发,建议统一逻辑。
修复后的完整代码
//@version=5 strategy('Coinrule template - RSI and SMA', overlay=true, initial_capital=1000, process_orders_on_close=true, default_qty_type=strategy.percent_of_equity, default_qty_value=30, commission_type=strategy.commission.percent, commission_value=0.1) showDate = input(defval=true, title='Show Date Range') timePeriod = time >= timestamp(syminfo.timezone, 2022, 5, 1, 0, 0) notInTrade = strategy.position_size <= 0 // RSI length = input(14) rsi = ta.rsi(close, length) // SMA fastSMA = ta.sma(close, 9) slowSMA = ta.sma(close, 50) plot(fastSMA, color = color.green) plot(slowSMA, color = color.blue) bullish = ta.crossover(fastSMA, slowSMA) and rsi > 50 bearish = ta.crossover(slowSMA, fastSMA) and rsi < 50 // 开仓:指定头寸ID为'Long' strategy.entry(id='Long', direction = strategy.long, when = bullish and timePeriod) // 平仓:对应开仓的头寸ID'Long',同步时间范围限制 strategy.close(id='Long', when=bearish and timePeriod)
额外验证建议
可以添加可视化信号代码,直观确认开平仓条件是否触发:
plotshape(bullish, title="Buy", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY") plotshape(bearish, title="Sell", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")
内容的提问来源于stack exchange,提问作者FocusedOlive640
相关产品推荐
相关产品推荐

