在Pine Script背离指标中提取两个枢轴低点值并存储变量求助
在Pine Script中获取并存储两个枢轴低点数值的解决方案
以下是修改后的完整代码,通过数组实现存储最近两个枢轴低点的RSI数值,并可直接用于后续逻辑:
//@version=5 indicator("want to find divergence 2 pivot low value") rangeUpper = input(title='Max of Lookback Range', defval=60) rangeLower = input(title='Min of Lookback Range', defval=5) rsi = ta.rsi(close, 5) plot(rsi, title="RSI", linewidth=2, color=#8D1699) plotBull = input(title='Plot Bullish', defval=true) plFound = not na(ta.pivotlow(rsi, 2, 2)) phFound = not na(ta.pivothigh(rsi, 2, 2)) _inRange(cond) => bars = ta.barssince(cond == true) rangeLower <= bars and bars <= rangeUpper // 初始化数组存储最近两个枢轴低点的RSI值 var array<float> pivotLowValues = array.new_float(0) // 当检测到枢轴低点时,将对应的RSI值加入数组 if plFound // 添加当前枢轴低点的RSI值(rsi[2]对应pivotlow的实际位置) array.push(pivotLowValues, rsi[2]) // 保持数组最多存储2个最近的枢轴值,超过则移除最早的元素 if array.size(pivotLowValues) > 2 array.shift(pivotLowValues) // 获取两个枢轴低点数值,处理数组长度不足的情况 firstPivotValue = array.size(pivotLowValues) >= 2 ? array.get(pivotLowValues, 0) : na // 较早的枢轴值 secondPivotValue = array.size(pivotLowValues) >= 1 ? array.get(pivotLowValues, -1) : na // 最新的枢轴值 //------------------------------------------------------------------------------ // Regular Bullish // Osc: Higher Low oscHL = rsi[2] > ta.valuewhen(plFound, rsi[2], 1) and _inRange(plFound[1]) // Price: Lower Low priceLL = low[2] < ta.valuewhen(plFound, low[2], 1) bullCond = plotBull and priceLL and oscHL and plFound pltest = ta.pivotlow(rsi, 2, 2) // 示例:打印两个枢轴值(可根据需求替换为后续逻辑) if bullCond label.new(bar_index, rsi[2], str.format("Prev Pivot: %.2f\nCurr Pivot: %.2f", firstPivotValue, secondPivotValue), style=shape.labeldown, color=color.blue, textcolor=color.white) plot(plFound ? rsi[2] : na, offset=-2, title='Regular Bullish', linewidth=2, color=bullCond ? color.green : color.gray) plotshape(bullCond ? rsi[2] : na, offset=-2, title='Regular Bullish Label', text=' Bull ', style=shape.labelup, location=location.absolute, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
关键修改说明:
- 数组初始化:使用
var关键字声明数组,确保仅在指标加载时初始化一次,避免每次K线重建数组。 - 枢轴值存储逻辑:当
plFound为true时,将对应位置的RSI值(rsi[2],因为ta.pivotlow会滞后2根K线确认)加入数组。若数组长度超过2,移除最早的元素,保证始终保留最近两个枢轴低点数值。 - 变量赋值:通过
array.get获取数组中的元素,array.get(pivotLowValues, 0)是较早的枢轴值,array.get(pivotLowValues, -1)是最新的枢轴值,同时添加了长度判断避免出现na错误。 - 示例应用:在看涨背离条件触发时,用标签打印两个枢轴值,你可以根据需求将这些变量用于其他计算或信号逻辑。
内容的提问来源于stack exchange,提问作者jeon
相关产品推荐
相关产品推荐

