0

I understand about the series subscript, when in global scope, but just trying to get my head around how series work in functions. A good example is the built in "rma" script.

pine_rma(src, length) =>
    alpha = 1/length
    sum = 0.0
    sum := na(sum[1]) ? ta.sma(src, length) : alpha * src + (1 - alpha) * nz(sum[1])

The sum variable is local to the rma function, and sum is reassigned on each call; but what I don't understand is if there are multiple times it's called, say with different sources, the sum[] series is different for each each call (assuming there's a single scope for the "rma" function?)

From the docs https://www.tradingview.com/pine-script-docs/en/v5/language/User-defined_functions.html I get how they're scoped - but really don't see how a local series that's written each bar can be used with multiple callers/source parameter values?

any help appreicated!

sambomartin
  • 6,663
  • 7
  • 40
  • 64

1 Answers1

1

The Execution of Pine Script™ functions and historical context inside function blocks section of the usrman explains what's going on. In Pine, each function call maintains its own historical context.

Should use the ta.rma() built-in, btw. Will execute much faster than the long form equivalent you show.

PineCoders-LucF
  • 8,288
  • 2
  • 12
  • 21
  • thank you. that was really helpful. one follow up question.. whilst acknowledging the built in script should be used. in the example above, is the sum (local series variable in pine_rma) unique to the src and length. "The history of series variables used inside Pine Script™ functions is created through each successive call to the function. If the function is not called on each bar the script runs on" - but in the example above, if i call pine_rma twice with two different src value, surely sum[1] wouldn't make sense on the following bar? – sambomartin Nov 23 '22 at 12:57
  • 1
    The Pine runtime maintains as many different historical contexts as you have function calls in your script. If you call the same function from two different places in your script, they each maintain their own historical context, regardless of the arguments used in each function call. This entails that unless you refer to a global scope array ID to modify that array's elements from within a function, values cannot be shared between different function calls. – PineCoders-LucF Nov 23 '22 at 14:13