PineScript:如何获取高低枢轴点对应Bar索引及筛选特定枢轴点
问题1:获取指定长度的最新枢轴低点及更低的前序枢轴低点
先用ta.pivothlow()识别长度为3的枢轴低点,取最新的作为P1,再向前遍历历史枢轴低点,找到第一个比P1更低的作为P2。示例代码如下:
//@version=5 indicator("Pivot Low Example", overlay=true) // 定义左右各1根K线的枢轴低点(总长度3) pivotLowCond = ta.pivothlow(1, 1) // 存储枢轴低点的价格与对应Bar索引 var float[] pivotLowPrices = array.new_float() var int[] pivotLowBars = array.new_int() // 新增枢轴低点时同步存入数组,限制数组长度避免冗余 if pivotLowCond array.unshift(pivotLowPrices, low) array.unshift(pivotLowBars, bar_index) if array.size(pivotLowPrices) > 20 array.pop(pivotLowPrices) array.pop(pivotLowBars) // 获取最新的枢轴低点P1 P1 = na if array.size(pivotLowPrices) > 0 P1 = array.get(pivotLowPrices, 0) // 查找第一个比P1更低的前序枢轴低点P2 P2 = na P2_barIndex = na if not na(P1) for i = 1 to array.size(pivotLowPrices)-1 currentPrice = array.get(pivotLowPrices, i) if currentPrice < P1 P2 = currentPrice P2_barIndex = array.get(pivotLowBars, i) break // 可视化标记 if not na(P1) label.new(bar_index, P1, "P1", color=color.green, textcolor=color.white) if not na(P2) label.new(P2_barIndex, P2, "P2", color=color.red, textcolor=color.white)
问题2:获取枢轴点对应的Bar索引
无法直接从存储价格的浮点数组中获取Bar索引,必须单独创建整数数组来存储每个枢轴点对应的bar_index——浮点数组仅保存价格数值,没有与Bar索引的关联信息。
核心修改逻辑示例:
// 初始化成对数组:一个存枢轴价格,一个存对应Bar索引 var float[] pivotPrices = array.new_float() var int[] pivotBarIndexes = array.new_int() // 捕获到枢轴点时,同步向两个数组添加数据 if pivotCond // 替换为你自己的枢轴点判断条件 array.unshift(pivotPrices, pivotPrice) // pivotPrice为目标枢轴价格 array.unshift(pivotBarIndexes, bar_index) // 筛选特定枢轴点时,同步获取对应Bar索引 targetThreshold = close * 0.98 for i = 0 to array.size(pivotPrices)-1 price = array.get(pivotPrices, i) if price < targetThreshold correspondingBarIndex = array.get(pivotBarIndexes, i) label.new(correspondingBarIndex, price, "Target", color=color.orange)
注意:必须成对维护两个数组的元素顺序,新增或删除数据时同步操作,避免索引错位。
内容的提问来源于stack exchange,提问作者DoctorGremlin
相关产品推荐
相关产品推荐

