Pine Script中正确获取高低枢轴点价格用于价格穿越判断
Pine Script 正确获取枢轴点价格并判断突破
问题根源
你之前的错误在于对ta.pivothigh的返回值理解有误:ta.pivothigh(high, pivot_offset, pivot_offset)会在确认枢轴点的那根K线上,直接返回枢轴点所在K线的最高价(也就是前pivot_offset根K线的high值),不需要额外去取high[pivot_offset]。你之前的写法会导致价格对应到错误的K线位置。
正确保存枢轴点价格
如果需要把历史枢轴点价格保存起来用于后续判断,可以用var声明的数组来存储,这样数组会在脚本运行期间保留数据:
//@version=5 indicator("枢轴点跟踪", overlay=true) pivot_offset = input.int(2, "枢轴偏移量") // 检测高低枢轴点 ph = ta.pivothigh(high, pivot_offset, pivot_offset) pl = ta.pivotlow(low, pivot_offset, pivot_offset) // 声明存储枢轴点的数组(var保持数组不重置) var float[] pivot_highs = array.new_float() var float[] pivot_lows = array.new_float() // 当检测到新的枢轴高点时,添加到数组 if not na(ph) array.push(pivot_highs, ph) // 当检测到新的枢轴低点时,添加到数组 if not na(pl) array.push(pivot_lows, pl)
正确绘制枢轴点形状
要让形状显示在枢轴点实际所在的K线上,只需要在plotshape里加上offset=-pivot_offset,和你最初的正确写法一致,因为ph本身就是枢轴点的价格:
// 绘制枢轴高点 plotshape(ph, style=shape.circle, location=location.abovebar, color=color.red, size=size.tiny, offset=-pivot_offset) // 绘制枢轴低点 plotshape(pl, style=shape.circle, location=location.belowbar, color=color.green, size=size.tiny, offset=-pivot_offset)
判断价格突破枢轴点
如果要判断当前价格是否突破历史枢轴点,可以通过两种方式实现:
- 突破最近的枢轴点:
// 获取最近的枢轴高点(数组最后一个元素) last_ph = array.size(pivot_highs) > 0 ? array.get(pivot_highs, array.size(pivot_highs)-1) : na // 判断收盘价突破最近枢轴高点 break_high = close > last_ph and not na(last_ph) // 标记突破信号 plotshape(break_high, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
- 遍历所有历史枢轴点判断突破:
如果需要检查价格是否突破任意历史枢轴点,可以用循环遍历数组:
// 判断是否突破任意枢轴高点 any_break_high = false if array.size(pivot_highs) > 0 for i = 0 to array.size(pivot_highs)-1 if close > array.get(pivot_highs, i) any_break_high := true break // 找到一个突破就停止循环
完整示例代码
//@version=5 indicator("枢轴点跟踪与突破判断", overlay=true) pivot_offset = input.int(2, "枢轴偏移量") // 检测高低枢轴点 ph = ta.pivothigh(high, pivot_offset, pivot_offset) pl = ta.pivotlow(low, pivot_offset, pivot_offset) // 存储枢轴点的数组 var float[] pivot_highs = array.new_float() var float[] pivot_lows = array.new_float() // 添加新枢轴点到数组 if not na(ph) array.push(pivot_highs, ph) if not na(pl) array.push(pivot_lows, pl) // 绘制枢轴点 plotshape(ph, style=shape.circle, location=location.abovebar, color=color.red, size=size.tiny, offset=-pivot_offset) plotshape(pl, style=shape.circle, location=location.belowbar, color=color.green, size=size.tiny, offset=-pivot_offset) // 判断突破最近枢轴高点 last_ph = array.size(pivot_highs) > 0 ? array.get(pivot_highs, array.size(pivot_highs)-1) : na break_high = close > last_ph and not na(last_ph) // 判断突破最近枢轴低点 last_pl = array.size(pivot_lows) > 0 ? array.get(pivot_lows, array.size(pivot_lows)-1) : na break_low = close < last_pl and not na(last_pl) // 绘制突破信号 plotshape(break_high, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, title="突破枢轴高点") plotshape(break_low, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, title="突破枢轴低点")
内容的提问来源于stack exchange,提问作者Marek Baranko
相关产品推荐
相关产品推荐

