Pine脚本问题:枢轴点显示的K线编号与对应K线不一致
修正Pine脚本中枢轴点编号与对应K线不一致的问题
问题原因
ta.pivothigh()和ta.pivotlow()是在当前K线完成时,确认往前数lenPivot根K线为枢轴点的。你当前代码在检测到枢轴点时,直接使用了当前K线的counter值,但这个值和枢轴点对应K线的counter并非同一值,因此出现编号不一致的情况。
解决方法
用数组存储每根K线对应的counter值,当确认枢轴点时,取出对应K线位置的counter即可:
//@version=5 indicator('(_) number of bars and pivot points', overlay=true, max_labels_count = 500) // --- input --------------------- lenPivot = input.int(defval = 28, title = 'Pivot lenghts', minval = 1) // --- pivot --------------------- pivotH = ta.pivothigh(high, lenPivot, lenPivot) pivotL = ta.pivotlow(low, lenPivot, lenPivot) // --- count --------------------- countDays() => DoW = dayofweek na(DoW[1]) or DoW != DoW[1] var counter = 1 if countDays() counter := 1 else counter += 1 // 新增:用数组存储每根K线的counter值 var array<int> barCounterArray = array.new_int() array.push(barCounterArray, counter) // ----- labels ------------------ LabelBar = label.new(bar_index, 0, text = str.tostring(counter), yloc = yloc.belowbar, style = label.style_none, textcolor = color.orange, size = size.normal) if not na(pivotH) // 获取枢轴点对应K线的索引 pivotBarIdx = bar_index - lenPivot // 取出该K线对应的counter值 pivotCounter = array.get(barCounterArray, pivotBarIdx) LabelPivotH = label.new(pivotBarIdx, pivotH, text = str.tostring(pivotCounter), color = color.new(color.red, 50), style = label.style_label_down, textcolor = color.black, size = size.small) if not na(pivotL) pivotBarIdx = bar_index - lenPivot pivotCounter = array.get(barCounterArray, pivotBarIdx) LabelPivotL = label.new(pivotBarIdx, pivotL, text = str.tostring(pivotCounter), color = color.new(color.green, 50), style = label.style_label_up, textcolor = color.black, size = size.small)
关键修改说明
- 新增
barCounterArray数组,每根K线都将当前的counter存入数组,确保每根K线的编号都被准确记录。 - 当检测到枢轴点时,计算出枢轴点对应的K线索引(
bar_index - lenPivot),然后从数组中取出该索引对应的counter值,作为枢轴点的编号。
修改后,枢轴点的编号会和对应K线的编号完全一致,可满足你后续脚本处理的需求。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

