问题描述
在 pine 脚本中,我有一个名为 levels 的数组.在那里,我添加了几个值并将其整理出来.现在我想从该数组中找到与当前价格最接近的值.我该怎么做?
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
目前没有数组函数来实现这一点,但我们可以构建一个自定义函数来做到这一点.它返回数组中值第一次出现的索引,从数组的开头开始:
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:
arrayFind(_id, _val) =>
int _return = na
for _i = 0 to array.size(_id) - 1
if array.get(_id, _i) == _val
_return := _i
break
_return
你可以这样使用它:
plot(arrayFind(levels, close))
版本 2
不太确定我在想什么,但是:
Version 2
Not too sure what I was thinking there, but:
- 我的回答在功能上不正确,因为它不符合您的要求.仅当数组中存在该确切值时,它才会找到一个值,而您要求的是数组中最接近值的索引.
- 现有的数组函数已经允许我们找到数组中某个值第一次或最后一次出现的索引:
array.indexof()
和array.lastindexof()
.所以你可以使用内置的array.indexof(levels, close)
而不是arrayFind(levels, close)
.
- My answer isn't functionally correct as it doesn't meet your requirements. It only finds a value if that exact value is in the array, whereas you asked for the index of the closest value in the array.
- Existing array functions already allow us to find the index of the first or last occurrence of a value in an array:
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:
arrayIndexOfClosest(_id, _val) =>
size = array.size(_id)
int _return = na
if size != 0
delta = abs(array.get(_id, 0) - _val)
_return := 0
for _i = 1 to size - 1
thisDelta = abs(array.get(_id, _i) - _val)
if thisDelta < delta
delta := thisDelta
_return := _i
_return
这将返回数组中值的最接近匹配的索引.
This would return the index of the closest match of a value in an array.
这篇关于如何在pinescript数组中找到最接近的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!