0

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.

Vendrel
  • 865
  • 9
  • 19

1 Answers1

1

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

vitruvius
  • 15,740
  • 3
  • 16
  • 26
  • Would you please look at it again? It seems no label displayed with the data in the array. (Copied your code without any modification.) – Vendrel Jul 25 '23 at 08:28
  • It works on my end. Try it on BTCUSD. – vitruvius Jul 25 '23 at 08:54
  • Would you mind to check it on GBPUSD? That's my key. Maybe a little different code is needed. (I don't see any flaws in the code above so I wouldn't get why…) – Vendrel Jul 25 '23 at 13:38
  • No problem there either. – vitruvius Jul 25 '23 at 14:15
  • On what timeframe are you running this? And what is your exchange? – vitruvius Jul 25 '23 at 14:15
  • 1H, Capitalcom. But actually, I want to store Support/Resistance levels (manually, for now) in this way, so that I can manage it somehow in a Strategy. So you don't specifically need to store the price history. (But, even my custom numbers was not stored/displayed.) – Vendrel Jul 25 '23 at 15:18
  • It is also there. Are you checking the last bar? – vitruvius Jul 25 '23 at 16:43
  • Yes, it's there now, I don't know how did I make it not working first time. But I can not re-interpret this template for my custom numbers. I posted another question with the actual case, simplified. https://stackoverflow.com/questions/76774410/writing-custom-data-into-an-array-and-reading-back-them-with-direct-addressing – Vendrel Jul 26 '23 at 19:20