Pine 脚本 - 计算变化长度的指标

Pine script - Calculate indicator of changing length

我正在尝试计算具有变化长度的简单移动平均线(从特定点开始,每个柱将指标计算长度加 1),以便在 bar0 时指标长度为 1,在 bar1 时长度为2等

我不一定需要在图表上看到它,但我想不出其他方法来确保计算正确。

//@version=4
study("My Script")

src = close
a = sma(src, 5)
cal = barssince(a > 29000)
len = cal == 0 ? 1 : cal // there shouldn't be any 0 values from the above function but just to make sure.

plot(len) // works
b = sma(src, len) // this line also works (at least there are no errors) but plotting it on the chart doesn't work
plot(b)

错误(我还不能post图片): 学习错误 “sma”函数中 'length' 参数 (0.0) 的无效值。它必须 > 0.

通过在满足起始条件后计算柱与柱之间的 sma,您可以避免“Pine 无法确定系列的参考长度”错误,您将 运行 进入下一个错误。

src = input(close)
var bool started = false
var int n = 1
var float b = na

a = sma(src, 5)

if started == false and a > 29000
    started := true
    b := src
else if started == true
    n += 1
    b := ((b * (n - 1)) + src) / n

plot(b)