简体   繁体   English

在 pine 脚本中使用循环时保存以前的条形值

[英]Save previous bar values when using a loop in pine script

In pine script I'm calling a function that sums the previous bar value with an increment:在 pine 脚本中,我调用了一个 function ,它将前一个柱值与增量相加:

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:使用调用 function 的循环添加增量值,并将结果存储在数组中:

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)由于没有前一个柱,前一个值被替换为 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 .由于它首先为第一个 bar运行循环,然后在第二个 bar中再次运行循环,因此它用于myVar2[1]在第一个 bar中运行最后一个循环时保存的最后一个值4

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]

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]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM