RSI 7 Dynamic Div | Sand Lines

vankosi87 · study · 313 行 · 点赞 15 · 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/
// © vankosi87
//@version=6
indicator(title = "RSI 7 Dynamic Div | Sand Lines", shorttitle = "RSI7 Dyn", overlay = false,
     format = format.price, precision = 2, max_lines_count = 500,
     max_labels_count = 500, max_bars_back = 2000)
 
// Based on the user's RSI Div v6 source in "RSI di.odt".
// This version uses the CHART timeframe. No request.security / lookahead.
// LIVE = a developing candidate, not a confirmed signal. It can disappear.
// Confirmed pivots are accepted ONLY at the close of the confirmation bar.
// Lines join the pivot bars; the "C" marker identifies the later signal bar.
 
//------------------------------------------------------------------------------
// RSI Settings -- original formula; default RSI length changed from 14 to 7.
//------------------------------------------------------------------------------
int rsiLengthInput = input.int(7, minval = 1, maxval = 1000, title = "RSI Length", group = "RSI Settings")
float rsiSourceInput = input.source(close, "Source", group = "RSI Settings")
bool calculateDivergence = input.bool(true, "Calculate Divergence", group = "RSI Settings")
 
float change = ta.change(rsiSourceInput)
float up = ta.rma(math.max(change, 0), rsiLengthInput)
float down = ta.rma(-math.min(change, 0), rsiLengthInput)
float rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
 
rsiPlot = plot(rsi, "RSI", color = #7E57C2, linewidth = 2)
rsiUpperBand = hline(70, "RSI Upper Band", color = #787B86)
midline = hline(50, "RSI Middle Band", color = color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color = #787B86)
fill(rsiUpperBand, rsiLowerBand, color = color.rgb(126, 87, 194, 90), title = "RSI Background Fill")
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0),
     bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(color.red, 100),
     bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
 
//------------------------------------------------------------------------------
// Moving Average -- the source's default SMA(14) and all MA/BB options retained.
//------------------------------------------------------------------------------
string maTypeInput = input.string("SMA", "Type",
     options = ["None", "SMA", "SMA + Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"],
     group = "Moving Average", display = display.data_window)
int maLengthInput = input.int(14, "Length", minval = 1, maxval = 1000,
     group = "Moving Average", display = display.data_window)
float bbMultInput = input.float(2.0, "BB StdDev", minval = 0.001, maxval = 50, step = 0.5,
     group = "Moving Average", display = display.data_window,
     tooltip = "Only applies to SMA + Bollinger Bands; band distance in standard deviations.")
bool enableMA = maTypeInput != "None"
bool isBB = maTypeInput == "SMA + Bollinger Bands"
 
ma(float source, simple int length, simple string MAtype) =>
    switch MAtype
        "SMA" => ta.sma(source, length)
        "SMA + Bollinger Bands" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA (RMA)" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "VWMA" => ta.vwma(source, length)
        => na
 
float selectedMA = ma(rsi, maLengthInput, maTypeInput)
float selectedStDev = ta.stdev(rsi, maLengthInput) * bbMultInput
float smoothingMA = enableMA ? selectedMA : na
float smoothingStDev = isBB ? selectedStDev : na
plot(smoothingMA, "RSI-based MA", color = color.yellow,
     display = enableMA ? display.all : display.none)
bbUpperBand = plot(smoothingMA + smoothingStDev, "Upper Bollinger Band", color = color.green,
     display = isBB ? display.all : display.none)
bbLowerBand = plot(smoothingMA - smoothingStDev, "Lower Bollinger Band", color = color.green,
     display = isBB ? display.all : display.none)
fill(bbUpperBand, bbLowerBand, color = isBB ? color.new(color.green, 90) : na,
     title = "Bollinger Bands Background Fill", display = isBB ? display.all : display.none)
 
//------------------------------------------------------------------------------
// Divergence Settings
// Range counting deliberately matches _inRange(plFound[1]) in the source:
// bars BETWEEN pivots = second.index - first.index - 1.
// The original inputs 5..60 therefore allow pivot separations of 6..61 bars.
//------------------------------------------------------------------------------
int lookbackLeft = input.int(5, "Pivot Left", minval = 1, maxval = 50, group = "Divergence Settings")
int lookbackRight = input.int(5, "Pivot Right", minval = 1, maxval = 50, group = "Divergence Settings",
     tooltip = "Confirmed signals wait for this many bars to the right, including the closing confirmation bar.")
int rangeLower = input.int(5, "Range Min (bars between pivots)", minval = 0, maxval = 1000,
     group = "Divergence Settings", tooltip = "Matches the original source: 5 means a pivot-to-pivot separation of 6 bars.")
int rangeUpper = input.int(60, "Range Max (bars between pivots)", minval = 1, maxval = 1000,
     group = "Divergence Settings", tooltip = "Matches the original source: 60 means a pivot-to-pivot separation of 61 bars.")
bool showRegular = input.bool(true, "Regular Divergences", group = "Divergence Settings")
bool showHidden = input.bool(true, "Hidden Divergences", group = "Divergence Settings")
bool showDeveloping = input.bool(true, "Developing Divergences (LIVE)", group = "Divergence Settings",
     tooltip = "Dashed preview between the last confirmed RSI pivot and a developing RSI pivot. Can move or disappear; no LIVE alerts.")
 
bool showPriceLines = input.bool(true, "Price / Sand Lines", group = "Display")
bool extendPrice = input.bool(true, "Extend latest price line per direction", group = "Display",
     tooltip = "Extend the latest confirmed bullish and bearish price lines, plus LIVE previews. Older confirmed lines remain as segments.")
bool showLabels = input.bool(true, "Divergence Labels", group = "Display")
bool showConfirmation = input.bool(true, "C marker on confirmation bar", group = "Display")
int historyLimit = input.int(80, "Confirmed divergences to retain", minval = 1, maxval = 200, group = "Display")
int lineWidth = input.int(2, "Line Width", minval = 1, maxval = 4, group = "Display")
color bullColor = input.color(color.green, "Regular Bullish", group = "Colors")
color bearColor = input.color(color.red, "Regular Bearish", group = "Colors")
color hiddenBullColor = input.color(color.blue, "Hidden Bullish", group = "Colors")
color hiddenBearColor = input.color(color.orange, "Hidden Bearish", group = "Colors")
 
if barstate.isfirst and rangeLower > rangeUpper
    runtime.error("Range Min must not exceed Range Max.")
 
//------------------------------------------------------------------------------
// Data structures and helpers. A price anchor is the low/high OF the RSI pivot
// bar, as in the original source -- not a separately detected price pivot.
//------------------------------------------------------------------------------
type Pivot
    int index = na
    int stamp = na
    float value = na
    float price = na
 
type DivDrawing
    line rsiLine = na
    line priceLine = na
    label rsiTag = na
    label priceTag = na
    bool bullish = false
 
var array<DivDrawing> confirmedDrawings = array.new<DivDrawing>()
 
f_kind(Pivot first, Pivot second, bool isLow) =>
    int result = 0
    if not na(first.index) and not na(second.index) and second.index > first.index
        int barsBetween = second.index - first.index - 1
        if barsBetween >= rangeLower and barsBetween <= rangeUpper
            if isLow
                if second.price < first.price and second.value > first.value
                    result := 1  // Regular bullish: price LL, RSI HL.
                else if second.price > first.price and second.value < first.value
                    result := 3  // Hidden bullish: price HL, RSI LL.
            else
                if second.price > first.price and second.value < first.value
                    result := 2  // Regular bearish: price HH, RSI LH.
                else if second.price < first.price and second.value > first.value
                    result := 4  // Hidden bearish: price LH, RSI HH.
    result
 
f_enabled(int kind) =>
    calculateDivergence and ((showRegular and (kind == 1 or kind == 2)) or (showHidden and (kind == 3 or kind == 4)))
 
f_color(int kind) =>
    switch kind
        1 => bullColor
        2 => bearColor
        3 => hiddenBullColor
        4 => hiddenBearColor
        => color.gray
 
f_name(int kind) =>
    switch kind
        1 => "Bull"
        2 => "Bear"
        3 => "H Bull"
        4 => "H Bear"
        => ""
 
f_delete(DivDrawing drawing) =>
    if not na(drawing.rsiLine)
        line.delete(drawing.rsiLine)
    if not na(drawing.priceLine)
        line.delete(drawing.priceLine)
    if not na(drawing.rsiTag)
        label.delete(drawing.rsiTag)
    if not na(drawing.priceTag)
        label.delete(drawing.priceTag)
    0
 
f_draw(Pivot first, Pivot second, int kind, bool developing) =>
    bool bullish = kind == 1 or kind == 3
    color c = developing ? color.new(f_color(kind), 30) : f_color(kind)
    string style = developing ? line.style_dashed : line.style_solid
    string tagStyle = bullish ? label.style_label_up : label.style_label_down
    string caption = (developing ? "LIVE " : "") + f_name(kind)
    string tip = developing ? "DEVELOPING - not confirmed. Can move, change type or disappear." : "CONFIRMED at bar close: " + str.format_time(na(time_close) ? time : time_close, "yyyy-MM-dd HH:mm", "UTC") + " UTC. Pivot: " + str.tostring(lookbackRight) + " bars earlier."
    tip += "\nRSI: " + str.tostring(first.value, "#.00") + " -> " + str.tostring(second.value, "#.00")
    tip += "\nPrice: " + str.tostring(first.price, format.mintick) + " -> " + str.tostring(second.price, format.mintick)
    DivDrawing drawing = DivDrawing.new()
    drawing.bullish := bullish
    drawing.rsiLine := line.new(x1 = first.stamp, y1 = first.value, x2 = second.stamp, y2 = second.value,
         xloc = xloc.bar_time, extend = extend.none, color = c, style = style, width = lineWidth)
    if showPriceLines
        drawing.priceLine := line.new(x1 = first.stamp, y1 = first.price, x2 = second.stamp, y2 = second.price,
             xloc = xloc.bar_time, extend = extendPrice ? extend.right : extend.none,
             color = c, style = style, width = lineWidth, force_overlay = true)
    if showLabels
        drawing.rsiTag := label.new(x = second.stamp, y = second.value, text = caption,
             xloc = xloc.bar_time, yloc = yloc.price, style = tagStyle,
             color = c, textcolor = color.white, size = size.tiny, tooltip = tip)
        if showPriceLines
            drawing.priceTag := label.new(x = second.stamp, y = second.price, text = caption,
                 xloc = xloc.bar_time, yloc = yloc.price, style = tagStyle,
                 color = c, textcolor = color.white, size = size.tiny, tooltip = tip, force_overlay = true)
    drawing
 
f_archive(DivDrawing drawing) =>
    // Keep only the latest confirmed price ray of each direction extended.
    // Anchor coordinates of older confirmed lines are never moved.
    int count = array.size(confirmedDrawings)
    if extendPrice and not na(drawing.priceLine) and count > 0
        for i = count - 1 to 0
            DivDrawing older = array.get(confirmedDrawings, i)
            if older.bullish == drawing.bullish and not na(older.priceLine)
                line.set_extend(older.priceLine, extend.none)
                break
    array.push(confirmedDrawings, drawing)
    while array.size(confirmedDrawings) > historyLimit
        f_delete(array.shift(confirmedDrawings))
    0
 
//------------------------------------------------------------------------------
// Pivot engine: all ta.pivot* calls execute on EVERY bar/update.
// right = 0 supplies an early candidate using only the left-hand RSI bars.
//------------------------------------------------------------------------------
float confirmedLowValue = ta.pivotlow(rsi, lookbackLeft, lookbackRight)
float confirmedHighValue = ta.pivothigh(rsi, lookbackLeft, lookbackRight)
float developingLowValue = ta.pivotlow(rsi, lookbackLeft, 0)
float developingHighValue = ta.pivothigh(rsi, lookbackLeft, 0)
 
var Pivot lastLow = Pivot.new()
var Pivot lastHigh = Pivot.new()
var Pivot pendingLow = Pivot.new()
var Pivot pendingHigh = Pivot.new()
var DivDrawing liveLowDrawing = DivDrawing.new()
var DivDrawing liveHighDrawing = DivDrawing.new()
 
bool bullCond = false
bool bearCond = false
bool hiddenBullCond = false
bool hiddenBearCond = false
 
if barstate.isconfirmed and not na(confirmedLowValue)
    Pivot currentLow = Pivot.new(bar_index - lookbackRight, time[lookbackRight], rsi[lookbackRight], low[lookbackRight])
    int kind = f_kind(lastLow, currentLow, true)
    bullCond := f_enabled(kind) and kind == 1
    hiddenBullCond := f_enabled(kind) and kind == 3
    if bullCond or hiddenBullCond
        f_archive(f_draw(lastLow, currentLow, kind, false))
    // Update the reference at EVERY confirmed pivot, even without divergence.
    lastLow := currentLow
    if not na(pendingLow.index) and pendingLow.index <= currentLow.index
        pendingLow := Pivot.new()
 
if barstate.isconfirmed and not na(confirmedHighValue)
    Pivot currentHigh = Pivot.new(bar_index - lookbackRight, time[lookbackRight], rsi[lookbackRight], high[lookbackRight])
    int kind = f_kind(lastHigh, currentHigh, false)
    bearCond := f_enabled(kind) and kind == 2
    hiddenBearCond := f_enabled(kind) and kind == 4
    if bearCond or hiddenBearCond
        f_archive(f_draw(lastHigh, currentHigh, kind, false))
    lastHigh := currentHigh
    if not na(pendingHigh.index) and pendingHigh.index <= currentHigh.index
        pendingHigh := Pivot.new()
 
// Track at most one unconfirmed RSI pivot per direction. Each update starts
// from the previous closed bar's state (normal Pine rollback; no varip).
if not na(developingLowValue)
    pendingLow := Pivot.new(bar_index, time, rsi, low)
else if not na(pendingLow.index)
    int age = bar_index - pendingLow.index
    if rsi <= pendingLow.value or age > lookbackRight or (age == lookbackRight and barstate.isconfirmed)
        pendingLow := Pivot.new()
 
if not na(developingHighValue)
    pendingHigh := Pivot.new(bar_index, time, rsi, high)
else if not na(pendingHigh.index)
    int age = bar_index - pendingHigh.index
    if rsi >= pendingHigh.value or age > lookbackRight or (age == lookbackRight and barstate.isconfirmed)
        pendingHigh := Pivot.new()
 
// LIVE previews are displayed only at the active chart edge. No historical
// sequence of provisional signals is invented or archived after reloading.
if barstate.islast
    f_delete(liveLowDrawing)
    f_delete(liveHighDrawing)
    liveLowDrawing := DivDrawing.new()
    liveHighDrawing := DivDrawing.new()
    if showDeveloping
        int lowKind = f_kind(lastLow, pendingLow, true)
        int highKind = f_kind(lastHigh, pendingHigh, false)
        if f_enabled(lowKind)
            liveLowDrawing := f_draw(lastLow, pendingLow, lowKind, true)
        if f_enabled(highKind)
            liveHighDrawing := f_draw(lastHigh, pendingHigh, highKind, true)
 
// Mark the ACTUAL confirmation bar, not the earlier pivot bar.
plotshape(showConfirmation and bullCond ? rsi : na, title = "Regular Bullish Confirmation", text = "C",
     style = shape.circle, location = location.absolute, color = bullColor, textcolor = bullColor, size = size.tiny)
plotshape(showConfirmation and bearCond ? rsi : na, title = "Regular Bearish Confirmation", text = "C",
     style = shape.circle, location = location.absolute, color = bearColor, textcolor = bearColor, size = size.tiny)
plotshape(showConfirmation and hiddenBullCond ? rsi : na, title = "Hidden Bullish Confirmation", text = "C",
     style = shape.circle, location = location.absolute, color = hiddenBullColor, textcolor = hiddenBullColor, size = size.tiny)
plotshape(showConfirmation and hiddenBearCond ? rsi : na, title = "Hidden Bearish Confirmation", text = "C",
     style = shape.circle, location = location.absolute, color = hiddenBearColor, textcolor = hiddenBearColor, size = size.tiny)
 
//------------------------------------------------------------------------------
// Alerts: ONLY confirmed divergences, on the confirmation bar's close.
// Create a TradingView alert and select Once Per Bar Close.
//------------------------------------------------------------------------------
alertcondition(bullCond, title = "Regular Bullish Divergence",
     message = "{{ticker}} ({{interval}}): CONFIRMED regular bullish RSI divergence. The pivot is earlier; this is the confirmation bar.")
alertcondition(bearCond, title = "Regular Bearish Divergence",
     message = "{{ticker}} ({{interval}}): CONFIRMED regular bearish RSI divergence. The pivot is earlier; this is the confirmation bar.")
alertcondition(hiddenBullCond, title = "Hidden Bullish Divergence",
     message = "{{ticker}} ({{interval}}): CONFIRMED hidden bullish RSI divergence. The pivot is earlier; this is the confirmation bar.")
alertcondition(hiddenBearCond, title = "Hidden Bearish Divergence",
     message = "{{ticker}} ({{interval}}): CONFIRMED hidden bearish RSI divergence. The pivot is earlier; this is the confirmation bar.")
alertcondition(bullCond or bearCond or hiddenBullCond or hiddenBearCond, title = "Any Confirmed Divergence",
     message = "{{ticker}} ({{interval}}): A new RSI divergence is CONFIRMED at this bar's close. Check its type on the chart.")

← 返回列表