Reputation: 6941
I'd like to build a collection of several last highs and access all of them like I could in an array. How do I do that? My code looks like this:
var float lastHigh = 0
if (highfound)
lastHigh := high
Now I try this:
x := lastHigh[3]
... but x is only the LAST lastHigh value then (like it would be lastHigh[1]). So lastHigh is just a "flat" variable, right? How can I collect more than one last high?
Upvotes: 1
Views: 2149
Reputation: 2821
I've come up with the next approach:
//@version=4
study("Three last highs", overlay=true)
// here goes the logic for finding the high
// NOTE: if you are updating this function,
// then it should return either new value for the array or n/a.
// Because the non-n/a value will be added to the array and the oldest removed
getNewHighOrNa() =>
pivothigh(high, 3, 3)
newHigh = getNewHighOrNa()
// ======= Array lifecicle =========
ARRAY_LENGTH = 5
arrayCell = label(na)
if bar_index < ARRAY_LENGTH
arrayCell := label.new(0, 0)
label.set_y(arrayCell, 0)
else
if na(newHigh)
val = label.get_y(arrayCell[1])
for i = 2 to ARRAY_LENGTH
v = label.get_y(arrayCell[i])
label.set_y(arrayCell[i-1], v)
arrayCell := arrayCell[ARRAY_LENGTH]
label.set_y(arrayCell, val)
else
arrayCell := arrayCell[ARRAY_LENGTH]
label.set_y(arrayCell, newHigh)
// ==================================
// Array getter by index. Note, that numeration is right to left
// so 0 is the last bar (current) and 1 it's a left to current bar
get(index) => label.get_y(arrayCell[index])
// example of using of the array for calculation average of all elements of the array
mean() =>
sum = 0.0
for i = 0 to ARRAY_LENGTH - 1
sum := sum + get(i) / ARRAY_LENGTH
sum
plot(mean(), title="Mean", color=color.green)
// example of finding of max value in the array
max_high() =>
max = get(0)
for i = 1 to ARRAY_LENGTH - 1
v = get(i)
if v > max
max := v
max
plot(max_high(), title="MAX", color=color.red)
// the rest is just checking that the code works:
plot(get(0))
plot(get(1))
plot(get(2))
plot(get(3))
plot(get(4))
// mark the bars where we found new highs
plotshape(not na(newHigh), style=shape.flag)
I tried to make it easier, but because of pine's restriction, didn't managed it. But this code works and you are getting 3 last local highs and can iterate over them. Hope I've got your question right.
Upvotes: 1
Reputation: 383
Assuming your highfound
function, not demonstrated in the original question, results either false or true, your code should work by removing the :
from the x
variable:
x = lastHigh[3]
The following worked just fine for me:
//@version=4
study("My Script")
var float lastHigh = 0
if (close>open)
lastHigh := high
x = lastHigh[3]
plot(x, color=color.red)
Upvotes: 1