Pine Script v5中ta.highest结合math.max与ta.barssince报错求助
问题解决:Pine Script中ta.highest参数NaN错误
错误原因
ta.barssince(isCond1)在isCond1条件从未触发(比如图表起始阶段)时会返回NaN。你使用的math.max(1, p)无法处理NaN值——只要参数中存在NaN,math.max的结果依然是NaN,转成整数后仍是无效值,导致ta.highest抛出"长度参数为无效值NaN,必须大于0"的错误。
解决方法
用nz()函数处理ta.barssince的返回值,当结果为NaN时替换为1(或你需要的默认有效长度),确保传入ta.highest的长度参数始终是大于0的整数。
修改后的完整代码
//@version=5 indicator(title="Stochastic", shorttitle="Stoch", overlay = true, format=format.price, precision=2, max_bars_back=1000) periodK = input.int(14, title="%K Length", minval=1) smoothK = input.int(3, title="%K Smoothing", minval=1) periodD = input.int(3, title="%D Smoothing", minval=1) k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) d = int(ta.sma(k, periodD)) //plot(k, title="%K", color=#2962FF) plot(d, title="%D", color=#FF6D00) plot(31, '1', color.yellow) a = 31 bool isCond11 = ta.crossover(d, a) bool isCond21 = ta.crossunder(d, a) bool isCond1 = ta.cross(d, a) // 用nz处理NaN,默认值设为1 p = nz(ta.barssince(isCond1), 1) highp = ta.highest(d, int(math.max(1, p))) plot(int(math.max(1, p))) plot(highp)
关键修改说明
nz(ta.barssince(isCond1), 1):当ta.barssince返回NaN时,自动替换为1,保证p始终是有效数值。- 后续的
math.max(1, p)可以保留,进一步确保长度参数不小于1,双重保险。
内容的提问来源于stack exchange,提问作者Владислав Паршаков
相关产品推荐
相关产品推荐

