In pine script, I have an array called levels. In there, I am adding several values and sorting it out. Now I want to find the closest value from that array to the current price. How do I do that?
levels = array.new_float(size = 3, initial_value = na)
// push all value into array
array.push(levels, valOne)
array.push(levels, valTwo)
array.push(levels, valThree)
.......
// sort the array
array.sort(levels, order.ascending)
// get s r value
supportForLong = array.min(levels) // I want to find the closest value in level and not min
resistanceForLong = array.max(levels)
plot(supportForLong, color = black)
plot(resistanceForLong, color = black)
// clear all element for next iteration
array.clear()
Version 1
There is currently no array function to accomplish this, but we can build a custom function to do so. It returns the index of the first occurrence of the value in the array, starting from the beginning of the array:
You could use it like so:
Version 2
Not too sure what I was thinking there, but:
array.indexof()
andarray.lastindexof()
. So you could use the built-inarray.indexof(levels, close)
instead ofarrayFind(levels, close)
.The correct answer to your question would be:
This would return the index of the closest match of a value in an array.