Home > Blockchain >  Save previous bar values when using a loop in pine script
Save previous bar values when using a loop in pine script

Time:12-17

In pine script I'm calling a function that sums the previous bar value with an increment:

myFunction(myVar1) =>
    var int myVar2 = 0
    myVar2 := myVar1   nz(myVar2[1],1)

The increment value is added using a loop that calls the function and the result is stored in an array:

myArray = array.new_int(0)

var int myVar1 = 1
myVar1 := 1

while myVar1 <= 3
    array.push(myArray, myFunction(myVar1))
    myVar1  = 1

The result in the first bar was expected. Since there is no previous bar the previous value is replaced by 1 nz(myVar2[1],1)

plot(myArray.get(myArray, 0))
plot(myArray.get(myArray, 1))
plot(myArray.get(myArray, 2))

Result: [2, 3, 4]

But in the second bar:

Result: [5, 6, 7]
My expected result: [3, 5, 7]

Since it runs the loop for the first bar first and then runs the loop again in the second bar it uses for myVar2[1] the last value 4 saved when running the last loop in the first bar.

How can the previous bar values be stored correctly when using a loop so that the expected results can be achieved:

First bar: [2, 3, 4]
Second bar: [3, 5, 7]
Third bar: [4, 7, 10]

CodePudding user response:

Answer to your comment: You could save the current array in another array. That way, you always have access to the array values of the previous bar.

//@version=5
indicator("My Script", overlay=false)

var int     myVar1    = na
var int[]   myArray   = array.new_int(3) // Current array
var int[]   prevArray = array.new_int(3) // Previous array

myFunction(myVar1) =>
    var int myVar2 = 0
    myVar2 := myVar1   nz(myVar2[1],1)
    
myVar1 := 1

prevArray := array.copy(myArray) // Save current array
array.clear(myArray)             // Clear current array

while myVar1 <= 3
    array.push(myArray, myFunction(myVar1))
    myVar1  = 1

// Show previous array
plot(array.get(prevArray, 0), 'prevArray[0]')
plot(array.get(prevArray, 1), 'prevArray[1]')
plot(array.get(prevArray, 2), 'prevArray[2]')

// Show current array
plot(array.get(myArray, 0), 'myArray[0]')
plot(array.get(myArray, 1), 'myArray[1]')
plot(array.get(myArray, 2), 'myArray[2]')
  • Related