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

Tradingview Pine脚本Strategy.close()方法失效问题咨询

Tradingview Pine脚本Strategy.close()失效问题解决方案

问题根因

  • strategy.close() 第一个入参要求为对应入场订单的ID,你的代码中多单入场ID为"Buy"、空单入场ID为"Sell",但平仓时填的是不存在的ID"Exit",系统无法匹配到待平仓订单,因此不会执行平仓操作。
  • RSI阈值与平仓触发逻辑完全写反:
    • 你设定的规则是多头平仓条件为RSI高于70,空头平仓条件为RSI低于30
    • 但代码里错误把RSIoverSold设为70、RSIoverBought设为30,同时多单平仓条件写为RSI下穿30、空单平仓条件写为RSI上穿70,和需求完全不符。
  • 旧版Pine语法兼容问题:当前Tradingview默认使用v5版本语法,原生函数名、参数规范有调整,旧语法运行会触发报错。

修正后代码

//@version=5
strategy("Momentum Stochastic+Supertrend", overlay=true, default_qty_value=1)

//  stochastic指标设置
length = input(14, minval=1)
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3
k = ta.sma(ta.stoch(close, high, low, length), smoothK)
d = ta.sma(k, smoothD)

// RSI指标设置
RSIlength = input(14,title="RSI周期长度") 
RSIoverBought = 70 // 修正:RSI高于70为超买,触发多单平仓
RSIoverSold = 30 // 修正:RSI低于30为超卖,触发空单平仓
price = close
vrsi = ta.rsi(price, RSIlength)
longX = ta.crossover(vrsi, RSIoverBought) // 修正:多单平仓条件为RSI上穿70
shortX = ta.crossunder(vrsi, RSIoverSold) // 修正:空单平仓条件为RSI下穿30

// Supertrend指标设置
res = input.timeframe(title="Supertrend参考时间周期", defval="3")
Factor=input(3, minval=1,maxval = 100)
Pd=input(100, minval=1,maxval = 100)
tp = input(5000,title="止盈点数")
sl = input(3500,title="止损点数")

MUp=request.security(ticker.new(""), res, hl2-(Factor*ta.atr(Pd)))
MDn=request.security(ticker.new(""), res, hl2+(Factor*ta.atr(Pd)))
Mclose=request.security(ticker.new(""), res, close)

MTrendUp = 0.0
MTrendUp := Mclose[1]>MTrendUp[1]? math.max(MUp,MTrendUp[1]) : MUp
MTrendDown = 0.0
MTrendDown := Mclose[1]<MTrendDown[1]? math.min(MDn,MTrendDown[1]) : MDn

MTrend = 0
MTrend := Mclose > MTrendDown[1] ? 1: Mclose< MTrendUp[1]? -1: ta.nz(MTrend[1],1)
MTsl = MTrend==1? MTrendUp: MTrendDown

// 指标绘制
Mlinecolor = MTrend == 1 ? color.green : color.red
plot(MTsl, color = Mlinecolor , style = plot.style_line , linewidth = 2,title = "主SuperTrend线")

// 交易信号
golong = MTrend == 1 and ta.crossover(d, OverSold)
goshort = MTrend == -1 and ta.crossunder(d,OverBought)

strategy.entry("Buy", strategy.long,when=golong)
strategy.close("Buy", when=longX) // 修正:平仓对应多单ID "Buy"

strategy.entry("Sell", strategy.short,when=goshort)
strategy.close("Sell", when=shortX) // 修正:平仓对应空单ID "Sell"

// 如需同时启用止盈止损,可放开下方注释
// strategy.exit("Close Buy","Buy",profit=tp,loss=sl, when=longX)
// strategy.exit("Close Sell","Sell",profit=tp,loss=sl, when=shortX)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 18:15:08