pine-scriptpine-script-v5tradingview-apiquantitative-finance

Get the last element of a user defined object array


pricePH = ta.pivothigh(10, 10)

type Candle
    int index
    float pivotHigh 
    float pivotLow

var CandleArray = array.new<Candle>(0)

if pricePH
    ph = Candle.new(time[10], high[10], low[10])
    array.push(CandleArray, ph)

var Candle xyz = na

if array.size(CandleArray) > 0
    xyz := array.get(CandleArray, array.size(CandleArray) - 1)

// It give the following error: Cannot call 'plot' with argument 'series'='xyz'. An argument of 'Candle' type was used but a 'series float' is expected.

plot(xyz, display = display.status_line)

//// Currently the only method to access the elements of the array is through a for-in loop

for newPH in CandleArray
    label.new(newPH.index, newPH.pivotHigh, str.tostring(newPH.pivotHigh), xloc.bar_time, style = label.style_label_down, color=color.blue)

Solution

  • xyz is a Candle type, you must tell your script which float to use.
    For example :

    plot(xyz.pivotHigh, display = display.status_line)
    

    Here is the complete working script (tested on EUR/USD) :

    //@version=5
    indicator("My script")
    plot(close)
    type Candle
        int  index
        float pivotHigh 
        float pivotLow
    
    var CandleArray = array.new<Candle>(0)
    
    if true
        ph = Candle.new(time[10], high[10], low[10])
        array.push(CandleArray, ph)
    
    xyz = array.last(CandleArray)
    plot(xyz.pivotHigh, display = display.status_line)