Search code examples
arrayslistpine-scripttradingview-apimoving-average

How to create array of variables in pine script


I have created in tradingview (pine script) three Exponential Moving Averages and I want to create an array from such EMA's.

I have tried this:

//@version=5
indicator("My script")
ema3 = ta.ema(close,3)
ema6 = ta.ema(close,6)
ema9 = ta.ema(close,9)


arr = array.new_float([ema3,ema6,ema9])

But I get this error:

Cannot call 'array.new_float' with argument 'size'='ema3,ema6,ema9'. An argument of '[series float, series float, series float]' type was used but a 'series int' is expected.

I need to create an array (or a list) containing those EMA's. For example, in Python I'd do:

arr = [ema3,ema6,ema9]

Can anyone help me please?


Solution

  • You can use the array.from() function.

    The function takes a variable number of arguments with one of the types: int, float, bool, string, label, line, color, box, table, linefill, and returns an array of the corresponding type.

    //@version=5
    indicator("My script")
    
    ema3 = ta.ema(close,3)
    ema6 = ta.ema(close,6)
    ema9 = ta.ema(close,9)
    
    arr = array.from(ema3, ema6, ema9)
    
    plot(array.get(arr, 0), color=color.green)  // ema3
    plot(ema3, color=color.red)                 // ema3