Search code examples
pine-scriptpine-script-v5

How to write custom data into an Array then read them from it?


I would like to write individual numbers in an array, for example 9, 10, 11. Then read the numbers in a for cycle and work with the number? I have tried to understand this from the documentation, but have not been able to relate the examples there to this use case.

Please, write me a template for it.


Solution

  • Create an array with array.new_*() function. You may want to use the keyword var with it to make it initialized only once.

    Then you can use array.push() or array.set() to assign values to your array.

    Get the length of the array with array.size().

    Use that length to loop over your array.

    Access the items with array.get().

    Below example will push bar_index to an array and will display the last three bar indices.

    //@version=5
    indicator("My script", overlay=true)
    
    var my_array = array.new_int()
    array.push(my_array, bar_index)
    
    len = array.size(my_array)
    
    if (barstate.islast)
        if (len > 3)
            s = ""
            for i = len - 3 to len - 1
                num = array.get(my_array, i)
                s := s + str.tostring(num) + "\n"
            label.new(bar_index, high, s)
    

    enter image description here