RSI Trendlines and Divergences

Uncle_the_shooter · study · 254 行 · 点赞 2,021 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Uncle_the_shooter
 
//@version=6
indicator('RSI Trendlines and Divergences', overlay = false, max_lines_count = 500)
 
// INPUTS 
rsiLength = input.int(14, 'RSI Length', group = 'RSI Settings')
smaLength = input.int(9, 'SMA Length', group = 'RSI Settings')
src = input.source(close, 'Source', group = 'RSI Settings')
leftBars = input.int(10, 'Left Bars for Pivot', group = 'Pivot Settings for Trend')
rightBars = input.int(10, 'Right Bars for Pivot', group = 'Pivot Settings for Trend')
extendBars = input.int(30, 'Extension after 2nd Pivot (Bars). 0 = None', minval = 0, group = 'Pivot Settings for Trend')
tolerance = input.float(3.0, 'Tolerance (RSI Points)', minval = 0.0, group = 'Pivot Settings for Trend')
// Divergence inputs
calculateDivergence = input.bool(true, title = 'Enable Divergence Detection', group = 'Divergence Settings')
divPivotLen = input.int(5, title = 'Pivot Length for Divergence', minval = 1, group = 'Divergence Settings')
// Color inputs
highLineColor = input.color(color.red, 'Upper Trendline Color', group = 'Style Settings')
highFillColor = input.color(color.new(color.red, 70), 'Upper Fill Color', group = 'Style Settings')
lowLineColor = input.color(color.green, 'Lower Trendline Color', group = 'Style Settings')
lowFillColor = input.color(color.new(color.green, 70), 'Lower Fill Color', group = 'Style Settings')
smaColor = input.color(color.yellow, 'SMA Color', group = 'Style Settings')
bullDivColor = input.color(color.green, 'Bullish Divergence Color', group = 'Style Settings')
bearDivColor = input.color(color.red, 'Bearish Divergence Color', group = 'Style Settings')
textColor = input.color(color.white, 'Text Color', group = 'Style Settings')
bandTransparency = input.int(40, title = 'Divergence Label Transparency', minval = 0, maxval = 100, group = 'Style Settings')
signalTransparency = input.int(80, title = 'Signal Highlight Transparency', minval = 0, maxval = 100, group = 'Style Settings')
 
// RSI & PIVOTS 
rsi = ta.rsi(src, rsiLength)
rsiSMA = ta.sma(rsi, smaLength)
pHigh = ta.pivothigh(rsi, leftBars, rightBars)
pLow = ta.pivotlow(rsi, leftBars, rightBars)
pHighPrice = ta.pivothigh(high, leftBars, rightBars)
pLowPrice = ta.pivotlow(low, leftBars, rightBars)
pHighDiv = ta.pivothigh(rsi, divPivotLen, divPivotLen)
pLowDiv = ta.pivotlow(rsi, divPivotLen, divPivotLen)
pHighPriceDiv = ta.pivothigh(high, divPivotLen, divPivotLen)
pLowPriceDiv = ta.pivotlow(low, divPivotLen, divPivotLen)
 
// STORAGE 
var array<line> linesHigh = array.new_line()
var array<line> linesLow = array.new_line()
var array<line> parallelsHigh = array.new_line()
var array<line> parallelsLow = array.new_line()
var array<linefill> fillsHigh = array.new_linefill()
var array<linefill> fillsLow = array.new_linefill()
var array<float> slopesHigh = array.new_float()
var array<float> slopesLow = array.new_float()
var array<int> x1High = array.new_int()
var array<int> x1Low = array.new_int()
var array<float> y1High = array.new_float()
var array<float> y1Low = array.new_float()
var array<bool> brokenHigh = array.new_bool()
var array<bool> brokenLow = array.new_bool()
var array<bool> signaledHigh = array.new_bool()
var array<bool> signaledLow = array.new_bool()
 
// FUNCTIONS 
f_trim(arrLines, arrSlopes, arrX, arrY, arrBroken, arrParallels, arrFills, arrSignaled) =>
    while array.size(arrLines) > 500
        ln = array.shift(arrLines)
        line.delete(ln)
        array.shift(arrSlopes)
        array.shift(arrX)
        array.shift(arrY)
        array.shift(arrBroken)
        array.shift(arrSignaled)
        par = array.shift(arrParallels)
        line.delete(par)
        fil = array.shift(arrFills)
        linefill.delete(fil)
 
f_remove(arrLines, arrSlopes, arrX, arrY, arrBroken, arrParallels, arrFills, arrSignaled, idx) =>
    ln = array.remove(arrLines, idx)
    line.delete(ln)
    array.remove(arrSlopes, idx)
    array.remove(arrX, idx)
    array.remove(arrY, idx)
    array.remove(arrBroken, idx)
    array.remove(arrSignaled, idx)
    par = array.remove(arrParallels, idx)
    line.delete(par)
    fil = array.remove(arrFills, idx)
    linefill.delete(fil)
 
f_check_break(ln, slope, x1, y1, brokenArr, signaledArr, idx, isHigh, arrFills) =>
    bool crossedDown = false
    bool crossedUp = false
    bool crossOccurred = false
    if idx < array.size(brokenArr)
        if not array.get(brokenArr, idx) and not array.get(signaledArr, idx)
            x2 = line.get_x2(ln)
            if bar_index >= x1 and bar_index <= x2
                prevY = y1 + slope * (bar_index - 1 - x1)
                yLine = y1 + slope * (bar_index - x1)
                // For upper lines (red): bullish signal (crossedUp) with tolerance
                crossedUp := isHigh and rsi > yLine + tolerance and rsi[1] <= prevY + tolerance
                // For lower lines (green): bearish signal (crossedDown) with tolerance
                crossedDown := not isHigh and rsi < yLine - tolerance and rsi[1] >= prevY - tolerance
                if crossedDown or crossedUp
                    crossOccurred := true
                    baseColor = isHigh ? highLineColor : lowLineColor
                    array.set(brokenArr, idx, true)
                    array.set(signaledArr, idx, true)
                    line.set_color(ln, baseColor)
                    linefill.set_color(array.get(arrFills, idx), isHigh ? highFillColor : lowFillColor)
    [crossedDown, crossedUp, crossOccurred]
 
// DIVERGENCE DETECTION 
var bool plFound = false
var bool phFound = false
var bool bullCond = false
var bool bearCond = false
 
_inRange(bool cond) =>
    bars = ta.barssince(cond)
    bars <= 60
 
if calculateDivergence
    plFound := not na(pLowDiv)
    phFound := not na(pHighDiv)
    rsiLbr = rsi[divPivotLen]
    priceLbr = low[divPivotLen]
    priceLh = high[divPivotLen]
    rsiLl = rsiLbr > ta.valuewhen(plFound, rsiLbr, 1) and _inRange(plFound[1])
    priceLl = priceLbr < ta.valuewhen(plFound, priceLbr, 1)
    bullCond := priceLl and rsiLl and plFound
    rsiLh = rsiLbr < ta.valuewhen(phFound, rsiLbr, 1) and _inRange(phFound[1])
    priceHh = priceLh > ta.valuewhen(phFound, priceLh, 1)
    bearCond := priceHh and rsiLh and phFound
    bearCond
 
// ON PIVOT HIGH 
if not na(pHigh)
    idx = bar_index - rightBars
    y = pHigh
    var float slope = 0.0
    newL = line.new(idx, y, idx, y, color = highLineColor, width = 2)
    newPar = line.new(idx, math.min(100, y + tolerance), idx, math.min(100, y + tolerance), color = color.new(color.red, 100), width = 2)
    newFill = linefill.new(newL, newPar, highFillColor)
    array.push(linesHigh, newL)
    array.push(parallelsHigh, newPar)
    array.push(fillsHigh, newFill)
    array.push(slopesHigh, 0.0)
    array.push(x1High, idx)
    array.push(y1High, y)
    array.push(brokenHigh, false)
    array.push(signaledHigh, false)
    if array.size(linesHigh) > 1
        last = array.get(linesHigh, array.size(linesHigh) - 2)
        lastPar = array.get(parallelsHigh, array.size(parallelsHigh) - 2)
        x1 = array.get(x1High, array.size(x1High) - 2)
        y1 = array.get(y1High, array.size(y1High) - 2)
        x2_pivot = idx
        y2_pivot = y
        x2_ext = x2_pivot + extendBars
        dx = x2_pivot - x1
        slope := dx != 0 ? (y2_pivot - y1) / float(dx) : 0.0
        y2_ext = y1 + slope * float(x2_ext - x1)
        y2_ext_clamped = math.max(0, math.min(100, y2_ext))
        y2_par_clamped = math.max(0, math.min(100, y2_ext + tolerance))
        line.set_x2(last, x2_ext)
        line.set_y2(last, y2_ext_clamped)
        line.set_x2(lastPar, x2_ext)
        line.set_y2(lastPar, y2_par_clamped)
        array.set(slopesHigh, array.size(slopesHigh) - 2, slope)
        if slope > 0
            f_remove(linesHigh, slopesHigh, x1High, y1High, brokenHigh, parallelsHigh, fillsHigh, signaledHigh, array.size(linesHigh) - 2)
    f_trim(linesHigh, slopesHigh, x1High, y1High, brokenHigh, parallelsHigh, fillsHigh, signaledHigh)
 
// ON PIVOT LOW
if not na(pLow)
    idx = bar_index - rightBars
    y = pLow
    var float slope = 0.0
    newL = line.new(idx, y, idx, y, color = lowLineColor, width = 2)
    newPar = line.new(idx, math.max(0, y - tolerance), idx, math.max(0, y - tolerance), color = color.new(color.green, 100), width = 2)
    newFill = linefill.new(newL, newPar, lowFillColor)
    array.push(linesLow, newL)
    array.push(parallelsLow, newPar)
    array.push(fillsLow, newFill)
    array.push(slopesLow, 0.0)
    array.push(x1Low, idx)
    array.push(y1Low, y)
    array.push(brokenLow, false)
    array.push(signaledLow, false)
    if array.size(linesLow) > 1
        last = array.get(linesLow, array.size(linesLow) - 2)
        lastPar = array.get(parallelsLow, array.size(parallelsLow) - 2)
        x1 = array.get(x1Low, array.size(x1Low) - 2)
        y1 = array.get(y1Low, array.size(y1Low) - 2)
        x2_pivot = idx
        y2_pivot = y
        x2_ext = x2_pivot + extendBars
        dx = x2_pivot - x1
        slope := dx != 0 ? (y2_pivot - y1) / float(dx) : 0.0
        y2_ext = y1 + slope * float(x2_ext - x1)
        y2_ext_clamped = math.max(0, math.min(100, y2_ext))
        y2_par_clamped = math.max(0, math.min(100, y2_ext - tolerance))
        line.set_x2(last, x2_ext)
        line.set_y2(last, y2_ext_clamped)
        line.set_x2(lastPar, x2_ext)
        line.set_y2(lastPar, y2_par_clamped)
        array.set(slopesLow, array.size(slopesLow) - 2, slope)
        if slope < 0
            f_remove(linesLow, slopesLow, x1Low, y1Low, brokenLow, parallelsLow, fillsLow, signaledLow, array.size(linesLow) - 2)
    f_trim(linesLow, slopesLow, x1Low, y1Low, brokenLow, parallelsLow, fillsLow, signaledLow)
 
// CHECKING FOR BREAKS
bool anyCrossedDown = false
bool anyCrossedUp = false
 
nHigh = array.size(linesHigh)
if nHigh > 0
    for i = 0 to nHigh - 1 by 1
        [crossedDown, crossedUp, crossOccurred] = f_check_break(array.get(linesHigh, i), array.get(slopesHigh, i), array.get(x1High, i), array.get(y1High, i), brokenHigh, signaledHigh, i, true, fillsHigh)
        if crossOccurred and crossedUp
            anyCrossedUp := true
            anyCrossedUp
 
nLow = array.size(linesLow)
if nLow > 0
    for i = 0 to nLow - 1 by 1
        [crossedDown, crossedUp, crossOccurred] = f_check_break(array.get(linesLow, i), array.get(slopesLow, i), array.get(x1Low, i), array.get(y1Low, i), brokenLow, signaledLow, i, false, fillsLow)
        if crossOccurred and crossedDown
            anyCrossedDown := true
            anyCrossedDown
 
// CROSSOVER SIGNALS (BACKGROUND HIGHLIGHT) 
bgcolor(anyCrossedUp ? color.new(lowLineColor, signalTransparency) : na, title = 'Bullish Crossover Background')
bgcolor(anyCrossedDown ? color.new(highLineColor, signalTransparency) : na, title = 'Bearish Crossover Background')
 
// DIVERGENCE PLOTS 
plotBullDiv = plot(calculateDivergence and plFound ? rsi[divPivotLen] : na, offset = -divPivotLen, title = 'Bullish Divergence', linewidth = 2, color = bullCond ? bullDivColor : color.new(color.white, 100))
plotBearDiv = plot(calculateDivergence and phFound ? rsi[divPivotLen] : na, offset = -divPivotLen, title = 'Bearish Divergence', linewidth = 2, color = bearCond ? bearDivColor : color.new(color.white, 100))
 
// DIVERGENCE LABELS 
plotshape(bullCond ? rsi[divPivotLen] : na, offset = -divPivotLen, title = 'Bullish Divergence Label', text = ' Bull ', style = shape.labelup, location = location.absolute, color = color.new(bullDivColor, bandTransparency), textcolor = textColor, display = calculateDivergence ? display.all : display.none)
plotshape(bearCond ? rsi[divPivotLen] : na, offset = -divPivotLen, title = 'Bearish Divergence Label', text = ' Bear ', style = shape.labeldown, location = location.absolute, color = color.new(bearDivColor, bandTransparency), textcolor = textColor, display = calculateDivergence ? display.all : display.none)
 
// ALERTS 
alertcondition(bullCond, title = 'Bullish Divergence Detected', message = 'Bullish divergence detected on RSI pivot, a few bars back.')
alertcondition(bearCond, title = 'Bearish Divergence Detected', message = 'Bearish divergence detected on RSI pivot, a few bars back.')
alertcondition(anyCrossedUp, title = 'Upper Trendline Crossover (Bullish)', message = 'RSI crossed above the upper trendline.')
alertcondition(anyCrossedDown, title = 'Lower Trendline Crossover (Bearish)', message = 'RSI crossed below the lower trendline.')
 
// PLOT RSI and SMA 
plot(rsi, color = color.gray, title = 'RSI', linewidth = 2)
plot(rsiSMA, color = smaColor, title = 'RSI SMA', linewidth = 1)
hline(70, 'Overbought', color = color.gray)
hline(50, 'Midline', color = color.gray, linestyle = hline.style_dashed)
hline(30, 'Oversold', color = color.gray)

← 返回列表