Page 1 of 1

Finding 2nd highest value

Posted: Mon Jan 02, 2023 12:15 am
by augerpro
I'm writing a script that would identify the two highest values over the lookback period, then draw a line through them. Finding the highest is easy enough with ta.highest, but how do you find the 2nd highest value?

Another question that probably has an easy answer but since I'm posting here already I'll ask here. How do I then calculate the slope of the line created above? I can do it the long way, but thought maybe some one here has a script already made, or maybe there is a PS function already existing.

Re: Finding 2nd highest value

Posted: Mon Jan 02, 2023 8:35 am
by augerpro
The only solution appears to require using an array. So here is my first attempt at arrays! What I am doing is creating an array with an index equal to the lookback period. Then I use array.max to find the highest and second highest values in the array. Now I just want to create a line connecting these, but I'm not sure how to find the correct bar number for each to set the x location. The existing plots were to verify it is tracking the highs and lows correctly and will be turned off when I can figure out how to draw the lines described above.

lookback = input.int(title="Minimum Bar Count", defval=6)

barvaluesh = high
barvaluesl = low
var ah = array.new_float(lookback,0)
var al = array.new_float(lookback,0)

highest = 0.0
secondhighest = 0.0
lowest = 0.0
secondlowest = 0.0
array.push(ah, barvaluesh)
if array.size(ah) >= lookback
highest := array.max(ah)
secondhighest := array.max(ah, 1)
array.shift(ah)

array.push(al, barvaluesl)
if array.size(al) >= lookback
lowest := array.min(al)
secondlowest := array.min(al, 1)
array.shift(al)



plot(highest, style=plot.style_linebr, color=color.yellow, title="highest")
plot(secondhighest, style=plot.style_linebr, color=color.blue, title="2nd highest")
plot(lowest, style=plot.style_linebr, color=color.yellow, title="lowest")
plot(secondlowest, style=plot.style_linebr, color=color.blue, title="2nd lowest")