本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=5
indicator("RSI Divergence Detector-stockflow", overlay=true)
// ==== INPUTS ====
rsiLength = input.int(14, title="RSI Length")
pivotLeft = input.int(5, title="Pivot Left Bars")
pivotRight = input.int(5, title="Pivot Right Bars")
// ==== CALCULATIONS ====
// Compute RSI
rsiValue = ta.rsi(close, rsiLength)
// Identify pivot lows for divergence detection
pricePivotLow = ta.pivotlow(low, pivotLeft, pivotRight)
rsiPivotLow = ta.pivotlow(rsiValue, pivotLeft, pivotRight)
// Identify pivot highs for divergence detection
pricePivotHigh = ta.pivothigh(high, pivotLeft, pivotRight)
rsiPivotHigh = ta.pivothigh(rsiValue, pivotLeft, pivotRight)
// ==== STORE LAST PIVOTS ====
// Use 'var' so that these persist across bars
var float lastPriceLow = na
var float lastRSILow = na
var float lastPriceHigh = na
var float lastRSIHigh = na
// ==== DETECT BULLISH DIVERGENCE ====
// A bullish divergence is when the current confirmed price low is lower than the previous low
// while the RSI low is higher than its previous value.
if not na(pricePivotLow) and not na(rsiPivotLow)
if not na(lastPriceLow)
if (pricePivotLow < lastPriceLow) and (rsiPivotLow > lastRSILow)
// Place a label at the pivot bar (shifted back by pivotRight bars)
label.new(bar_index - pivotRight, low[pivotRight],
text="Bullish Divergence", style=label.style_label_up,
color=color.new(color.green, 0), textcolor=color.white, size=size.small)
// Update last pivot values
lastPriceLow := pricePivotLow
lastRSILow := rsiPivotLow
// ==== DETECT BEARISH DIVERGENCE ====
// A bearish divergence is when the current confirmed price high is higher than the previous high
// while the RSI high is lower than its previous value.
if not na(pricePivotHigh) and not na(rsiPivotHigh)
if not na(lastPriceHigh)
if (pricePivotHigh > lastPriceHigh) and (rsiPivotHigh < lastRSIHigh)
label.new(bar_index - pivotRight, high[pivotRight],
text="Bearish Divergence", style=label.style_label_down,
color=color.new(color.red, 0), textcolor=color.white, size=size.small)
// Update last pivot values
lastPriceHigh := pricePivotHigh
lastRSIHigh := rsiPivotHigh
// ==== OPTIONAL: PLOT RSI ====
// Plot the RSI in a separate pane for reference (you can disable this if desired)
// rsiPlot = input.bool(true, title="Plot RSI?")
// if rsiPlot
// indicator("RSI", overlay=false)
// plot(rsiValue, title="RSI", color=color.blue)
// hline(70, color=color.red)
// hline(30, color=color.green)