You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script需求:从已定义平均值中找出最接近0的原值

在Pine Script中找出最接近0的平均值及其标识

你当前用math.min(math.abs(a1-0), ...)的方法只能得到最小的绝对值,无法获取原数值和对应标识。可以通过跟踪最小绝对值对应的原数值与标识来实现需求,以下是两种实现方式:

方式一:逐个比较(适合少量平均值)

//@version=5
indicator("Closest to Zero", overlay=false)

// 替换为你自己的平均值计算逻辑
A1 = -4.0
A2 = 6.0
A3 = 2.0

// 初始化候选值与标识
closestVal = A1
closestId = "A1"

// 与A2比较
if math.abs(A2) < math.abs(closestVal)
    closestVal := A2
    closestId := "A2"

// 与A3比较
if math.abs(A3) < math.abs(closestVal)
    closestVal := A3
    closestId := "A3"

// 在图表显示结果
var label resLabel = label.new(bar_index, high, "", yloc=yloc.abovebar)
label.set_text(resLabel, str.format("最接近0:{0}({1})", closestVal, closestId))

// 控制台打印结果(仅最后一根K线)
if barstate.islast
    println(str.format("最接近0的平均值:{0},标识:{1}", closestVal, closestId))

方式二:数组批量处理(适合多个平均值)

如果有更多平均值(如A4、A5),用数组遍历更高效:

//@version=5
indicator("Closest to Zero (Array)", overlay=false)

// 替换为你的实际平均值与标识
valueArray = array.new_float(3, -4.0, 6.0, 2.0)
idArray = array.new_string(3, "A1", "A2", "A3")

// 初始化候选值
closestVal = array.get(valueArray, 0)
closestId = array.get(idArray, 0)

// 遍历数组逐一比较
for i = 1 to array.size(valueArray) - 1
    currentVal = array.get(valueArray, i)
    currentId = array.get(idArray, i)
    if math.abs(currentVal) < math.abs(closestVal)
        closestVal := currentVal
        closestId := currentId

// 显示结果
var label resLabel = label.new(bar_index, high, "", yloc=yloc.abovebar)
label.set_text(resLabel, str.format("最接近0:{0}({1})", closestVal, closestId))

if barstate.islast
    println(str.format("最接近0的平均值:{0},标识:{1}", closestVal, closestId))

代码说明

  • 先初始化第一个平均值为候选值,之后依次与其他值比较绝对值
  • 若当前值的绝对值更小,则更新候选的数值与标识
  • 最终通过图表标签或控制台输出结果

内容的提问来源于stack exchange,提问作者S Anantha Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:43:09