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

如何在PineScript中获取前后K线高低点并解决脚本显示问题

修正后的转折点脚本(显示最近两个高低点)

原脚本存在两个核心问题:一是高低点的判断逻辑完全错误,二是未实现“追踪最近两个高低点”的功能。以下是修正后的完整代码,可准确识别局部高低点并标记最近的两个:

//@version=5
indicator("最近两个高低点", shorttitle="TP", overlay=true)

// 1. 正确识别确认后的局部高低点
// 波谷:前一根K线的低点比前后K线的低点都低
isValley = low[1] < low[0] and low[1] < low[2]
// 波峰:前一根K线的高点比前后K线的高点都高
isPeak = high[1] > high[0] and high[1] > high[2]

// 2. 用数组追踪最近的2个高低点(存储价格和对应Bar索引)
var float[] peakPrices = array.new_float()
var int[] peakBars = array.new_int()
var float[] valleyPrices = array.new_float()
var int[] valleyBars = array.new_int()

// 更新波峰数组,只保留最近2个
if isPeak
    array.unshift(peakPrices, high[1])
    array.unshift(peakBars, bar_index[1])
    if array.size(peakPrices) > 2
        array.pop(peakPrices)
        array.pop(peakBars)

// 更新波谷数组,只保留最近2个
if isValley
    array.unshift(valleyPrices, low[1])
    array.unshift(valleyBars, bar_index[1])
    if array.size(valleyPrices) > 2
        array.pop(valleyPrices)
        array.pop(valleyBars)

// 3. 绘制最近两个高低点的标记
// 绘制波峰标记
for i = 0 to array.size(peakBars)-1
    barIdx = array.get(peakBars, i)
    price = array.get(peakPrices, i)
    plotshape(barIdx == bar_index ? price : na, color=color.red, style=shape.triangledown, size=size.medium, location=location.abovebar, title="最近高点" + str.tostring(i+1))

// 绘制波谷标记
for i = 0 to array.size(valleyBars)-1
    barIdx = array.get(valleyBars, i)
    price = array.get(valleyPrices, i)
    plotshape(barIdx == bar_index ? price : na, color=color.green, style=shape.triangleup, size=size.medium, location=location.belowbar, title="最近低点" + str.tostring(i+1))

// 可选:连线最近的两个高低点,更直观展示趋势
if array.size(peakBars) >= 2
    line.new(array.get(peakBars, 0), array.get(peakPrices, 0), array.get(peakBars, 1), array.get(peakPrices, 1), color=color.red, width=2)
if array.size(valleyBars) >= 2
    line.new(array.get(valleyBars, 0), array.get(valleyPrices, 0), array.get(valleyBars, 1), array.get(valleyPrices, 1), color=color.green, width=2)

关键调整说明

  • 修正判断逻辑:用前后K线的价格对比确认高低点,避免假信号;
  • 动态追踪最近两点:通过数组存储并自动清理超过2个的历史点,始终只显示最新的两个高低点;
  • 可视化优化:标记大小适中,可选连线功能辅助观察趋势。

自定义建议

  • 若想降低信号噪音,可加入ATR过滤(比如low[1] < low[0] - atr(10)*0.1);
  • 可修改size参数调整标记大小,或添加label.new显示高低点的具体价格。

内容的提问来源于stack exchange,提问作者Viraj Tharuka Ranathunga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 22:40:55