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

如何将TradingView Pine Script从V2转换为V3?附KDJ指标V2代码

将V2版KDJ指标Pine Script代码转换为V3版本

原V2版本代码

//@version=2
study("KDJ Indicator", shorttitle="V2_KDJ")
ilong = input(9, title="period")
isig = input(3, title="signal")

bcwsma(s,l,m) => 
    _s = s
    _l = l
    _m = m
    _bcwsma = (_m*_s+(_l-_m)*nz(_bcwsma[1]))/_l
    _bcwsma

c = close
h = highest(high, ilong)
l = lowest(low,ilong)
RSV = 100*((c-l)/(h-l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK-2 * pD

plot(pJ, color=#4caf50, transp=0)
plot(pK, color=#e91e63, transp=0)
plot(pD, color=#2962ff, transp=0)


bgcolor(pJ>pD? green : red, transp=90)

//h0 = hline(80, color=blue)
//h1 = hline(20, color=red)
h2 = hline(50, color=white)

bullcond = (pJ > 50) and ((crossover(pJ, pK) and pK > pD) or (crossover(pK, pD) and pJ > pK))
alertcondition(bullcond, title = '▲Bullish', message = '▲Bullish')
bearcond = (pJ < 50) and ((crossunder(pJ, pK) and pK < pD) or (crossunder(pK, pD) and pJ < pK))
alertcondition(bearcond, title = '▼Bearish', message = '▼Bearish')

转换后的V3版本代码

//@version=3
study("KDJ Indicator", shorttitle="V3_KDJ")
ilong = input(9, title="period")
isig = input(3, title="signal")

bcwsma(s,l,m) => 
    var float _bcwsma = na
    _s = s
    _l = l
    _m = m
    _bcwsma := (_m*_s + (_l-_m)*nz(_bcwsma))/_l
    _bcwsma

c = close
h = highest(high, ilong)
l_low = lowest(low, ilong)
RSV = 100 * ((c - l_low) / (h - l_low))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK - 2 * pD

plot(pJ, color=#4caf50, transp=0)
plot(pK, color=#e91e63, transp=0)
plot(pD, color=#2962ff, transp=0)

bgcolor(pJ > pD ? color.green : color.red, transp=90)

//h0 = hline(80, color=color.blue)
//h1 = hline(20, color=color.red)
h2 = hline(50, color=color.white)

bullcond = (pJ > 50) and ((crossover(pJ, pK) and pK > pD) or (crossover(pK, pD) and pJ > pK))
alertcondition(bullcond, title='▲Bullish', message='▲Bullish')
bearcond = (pJ < 50) and ((crossunder(pJ, pK) and pK < pD) or (crossunder(pK, pD) and pJ < pK))
alertcondition(bearcond, title='▼Bearish', message='▼Bearish')

关键修改说明

  • 版本声明从//@version=2改为//@version=3
  • 自定义函数bcwsma中,递归变量_bcwsma用var float声明,确保每次计算保留上一根K线的数值(V3中递归变量默认不持久化,需显式用var)
  • 原变量l与内置函数low重名,修改为l_low避免冲突
  • 颜色常量添加color.前缀(如green→color.green),符合V3语法规范
  • 函数内变量赋值使用:=替代=,匹配V3的赋值规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:42:39