How can we get the result for i=2 to be pushed onto index 0 of the array and i=3 to be pushed onto index 1? at the moment I am getting the SUM of i=2 i=3 in index 0 and 1 as it shows on the image below:
myArray = array.new_float(0)
var counter = 0
for i = 2 to 3
if close > ta.sma(close, i)
counter = 1
array.push(myArray, counter)
if barstate.islast
label.new(bar_index, 2, str.tostring(array.join(myArray, " - ")))
label.new(bar_index, 1, "array size: " str.tostring(array.size(myArray)))
//////////////////////////////////
and it should be:
and
Thank you in advance!
CodePudding user response:
I'm not completely sure how to easily change your code to get what you want, but you can use the matrix
to achieve this (as some kind of a dictionary workaround).
Basically what you can do is lose the counter
variable, and update the values directly to the matrix
.
//@version=5
indicator("My script", overlay = true)
var myMatrix = matrix.new<float>(2, 2, 0)
for i = 2 to 3
matrix.set(myMatrix, 0, i - 2, i)
if close > ta.sma(close, i)
matrix.set(myMatrix, 1, i - 2, matrix.get(myMatrix, 1, i - 2) 1)
if barstate.islast
label.new(bar_index, 3, str.tostring(myMatrix))
EDIT:
If you really wish to do the same with array
, you can use the same logic, but since pine scrip currently isn't supporting dictionaries, you'll need to use 2 separate arrays:
//@version=5
indicator("My script", overlay = true)
int start = 2
int end = 3
var my_array = array.new_float(end - start 1, 0)
loop_index_array = array.new_int(end - start 1, 0)
for i = start to end
array.set(loop_index_array, i - start, i)
if close > ta.sma(close, i)
array.set(my_array, i - start, array.get(my_array, i - start) 1)
if barstate.islast
label.new(bar_index, 3, str.tostring(my_array))
label.new(bar_index, 4, str.tostring(loop_index_array))