sambomartin
sambomartin

Reputation: 6813

Trying to understand how series work when scoped to a function in Pine Script

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!

Upvotes: 0

Views: 460

Answers (1)

PineCoders-LucF
PineCoders-LucF

Reputation: 8789

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.

Upvotes: 1

Related Questions