Nexus RSI Divergence Pro

ahmad1darwich · study · 233 行 · 点赞 9 · 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/
// © ahmad1darwich
//@version=6
indicator("Nexus RSI Divergence Pro", shorttitle = "NX RSI Pro", overlay = false, max_bars_back = 500, max_lines_count = 300, max_labels_count = 300)
 
// ---------- Inputs ----------
string GRP_R = "RSI"
bool   autoInput    = input.bool(true, "Auto settings", group = GRP_R, tooltip = "Picks the RSI length and pivot length from the chart timeframe: 5m and below RSI 9 / pivots 3, intraday RSI 14 / pivots 5, 4h and above RSI 14 / pivots 8. Turn off to use the manual values.")
int    rsiLenInput  = input.int(14, "RSI length (manual)", minval = 2, group = GRP_R)
int    obInput      = input.int(70, "Overbought", minval = 50, maxval = 100, group = GRP_R)
int    osInput      = input.int(30, "Oversold", minval = 0, maxval = 50, group = GRP_R)
 
string GRP_D = "Divergence"
int    pivLenInput  = input.int(5, "Pivot length (manual)", minval = 2, maxval = 30, group = GRP_D, tooltip = "A divergence is confirmed this many bars after the RSI pivot forms. Nothing is drawn before that, so nothing repaints.")
int    minBarsInput = input.int(5, "Minimum bars between pivots", minval = 2, group = GRP_D)
int    maxBarsInput = input.int(60, "Maximum bars between pivots", minval = 5, maxval = 200, group = GRP_D)
float  minDiffInput = input.float(2.0, "Minimum RSI difference", minval = 0, step = 0.5, group = GRP_D, tooltip = "The two RSI pivots must differ by at least this many RSI points.")
bool   strictInput  = input.bool(true, "Strict: clean line of sight", group = GRP_D, tooltip = "Rejects a divergence when RSI or price cuts through the line joining the two pivots. This is the main precision filter.")
bool   onlyAInput   = input.bool(false, "Grade A only", group = GRP_D, tooltip = "Grade A = at least 2 of 3: pivot inside the overbought/oversold zone, RSI difference of 6 points or more, price extends at least 0.25 ATR beyond the previous extreme.")
bool   showRegInput = input.bool(true, "Regular (reversal)", group = GRP_D, inline = "t")
bool   showHidInput = input.bool(false, "Hidden (continuation)", group = GRP_D, inline = "t")
bool   onPriceInput = input.bool(true, "Also mark on the price chart", group = GRP_D)
 
string GRP_T = "Track record"
bool   showDashInput  = input.bool(true, "Show dashboard", group = GRP_T)
string dashPosInput   = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = GRP_T)
float  targetAtrInput = input.float(1.0, "Hit = move in ATR", minval = 0.2, step = 0.1, group = GRP_T, tooltip = "A regular divergence is a hit when price moves this many ATR its way before the same distance against it.")
int    expiryInput    = input.int(30, "Give up after (bars)", minval = 5, group = GRP_T)
 
string GRP_ST = "Style"
string themeInput = input.string("Neon", "Theme", options = ["Neon", "Classic", "Minimal", "Mono"], group = GRP_ST)
int    glassInput = input.int(35, "Label glass transparency", minval = 0, maxval = 90, group = GRP_ST)
bool   showSigInput = input.bool(true, "Momentum signal line", group = GRP_ST)
 
// ---------- Theme ----------
pick(color neon, color classic, color minimal, color mono) =>
    themeInput == "Neon" ? neon : themeInput == "Classic" ? classic : themeInput == "Minimal" ? minimal : mono
 
color bullC    = pick(#00E5A0, #089981, #26A69A, #D1D4DC)
color bearC    = pick(#FF3D71, #F23645, #EF5350, #787B86)
color accentC  = pick(#7C4DFF, #2962FF, #B2B5BE, #E0E3EB)
color textC    = pick(#9598A1, #787B86, #9598A1, #B2B5BE)
color hidBullC = pick(#00B8D9, #00897B, #4DB6AC, #B2B5BE)
color hidBearC = pick(#FFB300, #FF9800, #FFB74D, #9598A1)
 
// ---------- Auto settings ----------
int tfSec  = timeframe.in_seconds()
int rsiLen = autoInput ? (tfSec <= 300 ? 9 : 14) : rsiLenInput
int pivLen = autoInput ? (tfSec <= 300 ? 3 : tfSec < 14400 ? 5 : 8) : pivLenInput
 
// ---------- Types and state ----------
type Pending
    int   dir
    float entry
    float dist
    int   bar
 
var array<Pending> pending = array.new<Pending>()
var int hits  = 0
var int fails = 0
var int sigs  = 0
var string lastType  = "-"
var string lastGrade = "-"
var int    lastBar   = na
var color  lastC     = na
 
var float prevLowRsi    = na
var float prevLowPrice  = na
var int   prevLowBar    = na
var float prevHighRsi   = na
var float prevHighPrice = na
var int   prevHighBar   = na
 
// ---------- Calculations ----------
float rsi    = ta.rsi(close, rsiLen)
float rsiSig = ta.ema(rsi, 9)
float rsiPl  = ta.pivotlow(rsi, pivLen, pivLen)
float rsiPh  = ta.pivothigh(rsi, pivLen, pivLen)
float atr    = ta.atr(14)
// Price extreme next to the RSI pivot (one bar either side): price and RSI often turn a bar apart.
float nearLow  = ta.lowest(low, 3)
float nearHigh = ta.highest(high, 3)
 
bool regBull = false
bool hidBull = false
bool regBear = false
bool hidBear = false
bool gradeASig = false
 
mark(int x1, float y1, int x2, float y2, float p1, float p2, bool up, bool regular, string grade, color c) =>
    line.new(x1, y1, x2, y2, color = c, width = regular ? 2 : 1, style = regular ? line.style_solid : line.style_dashed)
    label.new(x2, y2, up ? "▲" : "▼", style = up ? label.style_label_up : label.style_label_down, color = color.new(c, 100), textcolor = c, size = size.small)
    if onPriceInput
        line.new(x1, p1, x2, p2, color = color.new(c, 20), width = 1, style = regular ? line.style_solid : line.style_dashed, force_overlay = true)
        label.new(x2, p2, (up ? "▲ " : "▼ ") + (regular ? "DIV " : "H-DIV ") + grade, style = up ? label.style_label_up : label.style_label_down, color = color.new(c, glassInput), textcolor = color.white, size = size.tiny, force_overlay = true)
 
// ---------- Bullish side (RSI pivot lows) ----------
if barstate.isconfirmed and not na(rsiPl) and not na(atr)
    float priceLow = nearLow[pivLen - 1]
    int   pivBar   = bar_index - pivLen
    if not na(prevLowRsi)
        int   gap    = pivBar - prevLowBar
        bool  gapOk  = gap >= minBarsInput and gap <= maxBarsInput
        float diff   = math.abs(rsiPl - prevLowRsi)
        bool  diffOk = diff >= minDiffInput
        bool  isReg  = priceLow < prevLowPrice and rsiPl > prevLowRsi
        bool  isHid  = priceLow > prevLowPrice and rsiPl < prevLowRsi
        bool  clean  = true
        if gapOk and diffOk and strictInput and (isReg or isHid) and gap > 1
            for k = 1 to gap - 1
                float rLine = rsiPl + (prevLowRsi - rsiPl) * k / gap
                float pLine = priceLow + (prevLowPrice - priceLow) * k / gap
                if rsi[pivLen + k] < rLine - 0.5 or close[pivLen + k] < pLine - atr * 0.1
                    clean := false
        if gapOk and diffOk and clean and (isReg or isHid)
            int pts = (rsiPl < osInput ? 1 : 0) + (diff >= 6 ? 1 : 0) + (math.abs(priceLow - prevLowPrice) >= atr * 0.25 ? 1 : 0)
            bool gA = pts >= 2
            if (isReg and showRegInput or isHid and showHidInput) and (gA or not onlyAInput)
                color  c  = isReg ? bullC : hidBullC
                string gs = gA ? "A" : "B"
                regBull := isReg
                hidBull := isHid
                gradeASig := gradeASig or gA
                mark(prevLowBar, prevLowRsi, pivBar, rsiPl, prevLowPrice, priceLow, true, isReg, gs, c)
                lastType  := isReg ? "▲ Bullish" : "▲ Hidden bull"
                lastGrade := gs
                lastBar   := bar_index
                lastC     := c
                if isReg
                    pending.push(Pending.new(dir = 1, entry = close, dist = atr * targetAtrInput, bar = bar_index))
                    sigs += 1
    prevLowRsi   := rsiPl
    prevLowPrice := priceLow
    prevLowBar   := pivBar
 
// ---------- Bearish side (RSI pivot highs) ----------
if barstate.isconfirmed and not na(rsiPh) and not na(atr)
    float priceHigh = nearHigh[pivLen - 1]
    int   pivBar    = bar_index - pivLen
    if not na(prevHighRsi)
        int   gap    = pivBar - prevHighBar
        bool  gapOk  = gap >= minBarsInput and gap <= maxBarsInput
        float diff   = math.abs(rsiPh - prevHighRsi)
        bool  diffOk = diff >= minDiffInput
        bool  isReg  = priceHigh > prevHighPrice and rsiPh < prevHighRsi
        bool  isHid  = priceHigh < prevHighPrice and rsiPh > prevHighRsi
        bool  clean  = true
        if gapOk and diffOk and strictInput and (isReg or isHid) and gap > 1
            for k = 1 to gap - 1
                float rLine = rsiPh + (prevHighRsi - rsiPh) * k / gap
                float pLine = priceHigh + (prevHighPrice - priceHigh) * k / gap
                if rsi[pivLen + k] > rLine + 0.5 or close[pivLen + k] > pLine + atr * 0.1
                    clean := false
        if gapOk and diffOk and clean and (isReg or isHid)
            int pts = (rsiPh > obInput ? 1 : 0) + (diff >= 6 ? 1 : 0) + (math.abs(priceHigh - prevHighPrice) >= atr * 0.25 ? 1 : 0)
            bool gA = pts >= 2
            if (isReg and showRegInput or isHid and showHidInput) and (gA or not onlyAInput)
                color  c  = isReg ? bearC : hidBearC
                string gs = gA ? "A" : "B"
                regBear := isReg
                hidBear := isHid
                gradeASig := gradeASig or gA
                mark(prevHighBar, prevHighRsi, pivBar, rsiPh, prevHighPrice, priceHigh, false, isReg, gs, c)
                lastType  := isReg ? "▼ Bearish" : "▼ Hidden bear"
                lastGrade := gs
                lastBar   := bar_index
                lastC     := c
                if isReg
                    pending.push(Pending.new(dir = -1, entry = close, dist = atr * targetAtrInput, bar = bar_index))
                    sigs += 1
    prevHighRsi   := rsiPh
    prevHighPrice := priceHigh
    prevHighBar   := pivBar
 
// Track record: each regular divergence is judged on later confirmed bars.
if barstate.isconfirmed and pending.size() > 0
    for i = pending.size() - 1 to 0
        Pending p = pending.get(i)
        if bar_index > p.bar
            bool won  = p.dir == 1 ? high >= p.entry + p.dist : low <= p.entry - p.dist
            bool lost = p.dir == 1 ? low <= p.entry - p.dist : high >= p.entry + p.dist
            if won and not lost
                hits += 1
                pending.remove(i)
            else if lost
                fails += 1
                pending.remove(i)
            else if bar_index - p.bar >= expiryInput
                pending.remove(i)
 
// ---------- Visuals ----------
color rsiC = color.from_gradient(rsi, osInput, obInput, bearC, bullC)
plot(rsi, "RSI glow", color = color.new(rsiC, 85), linewidth = 7, display = display.pane)
pRsi = plot(rsi, "RSI", color = rsiC, linewidth = 2)
pSig = plot(showSigInput ? rsiSig : na, "RSI signal", color = color.new(accentC, 50), linewidth = 1)
fill(pRsi, pSig, color = showSigInput ? (rsi > rsiSig ? color.new(bullC, 84) : color.new(bearC, 84)) : na, title = "Momentum fill")
pOb = plot(obInput, "Overbought level", color = na, display = display.none)
pOs = plot(osInput, "Oversold level", color = na, display = display.none)
fill(pRsi, pOb, rsi > obInput ? color.new(bearC, 65) : na, "Overbought heat")
fill(pRsi, pOs, rsi < osInput ? color.new(bullC, 65) : na, "Oversold heat")
// hline colors must be constants, so the levels are neutral gray; the theme lives in the fills.
hline(obInput, "Overbought", color = color.new(#787B86, 50), linestyle = hline.style_dashed)
hline(50, "Middle", color = color.new(#787B86, 75), linestyle = hline.style_dotted)
hline(osInput, "Oversold", color = color.new(#787B86, 50), linestyle = hline.style_dashed)
fill(pOb, pOs, color = color.new(accentC, 95), title = "Range fill")
bgcolor(rsi > obInput ? color.new(bearC, 93) : rsi < osInput ? color.new(bullC, 93) : na, title = "Extreme zone tint")
 
// ---------- Dashboard ----------
dashPos = dashPosInput == "Top right" ? position.top_right : dashPosInput == "Bottom right" ? position.bottom_right : dashPosInput == "Top left" ? position.top_left : position.bottom_left
var table dash = table.new(dashPos, 2, 7, border_width = 1, border_color = color.new(#787B86, 85), frame_color = color.new(accentC, 40), frame_width = 1)
 
row(int r, string k, string v, color vc) =>
    dash.cell(0, r, k, text_color = textC, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_left)
    dash.cell(1, r, v, text_color = vc, bgcolor = color.new(#131722, 10), text_size = size.small, text_halign = text.align_right, text_font_family = font.family_monospace)
 
if showDashInput and barstate.islast
    int judged = hits + fails
    string zone = rsi > obInput ? "Overbought" : rsi < osInput ? "Oversold" : rsi >= 50 ? "Bull side" : "Bear side"
    dash.cell(0, 0, "NEXUS", text_color = color.white, bgcolor = color.new(accentC, 15), text_size = size.small)
    dash.cell(1, 0, "RSI Divergence", text_color = color.white, bgcolor = color.new(accentC, 15), text_size = size.small)
    row(1, "RSI " + str.tostring(rsiLen), str.tostring(rsi, "#.0"), rsiC)
    row(2, "Zone", zone, rsiC)
    row(3, "Last", na(lastBar) ? "-" : lastType + " • " + str.tostring(bar_index - lastBar) + " bars", na(lastC) ? textC : lastC)
    row(4, "Grade", lastGrade, lastGrade == "A" ? bullC : textC)
    row(5, "Hits / fails", str.tostring(hits) + " / " + str.tostring(fails) + " of " + str.tostring(sigs), textC)
    row(6, "Hit rate", judged > 0 ? str.tostring(hits * 100.0 / judged, "#") + "%" : "-", judged > 0 ? color.from_gradient(hits * 100.0 / judged, 35, 65, bearC, bullC) : textC)
 
// ---------- Alerts ----------
alertcondition(regBull, "Bullish divergence", "Nexus RSI: bullish divergence on {{ticker}} {{interval}}")
alertcondition(regBear, "Bearish divergence", "Nexus RSI: bearish divergence on {{ticker}} {{interval}}")
alertcondition(hidBull, "Hidden bullish divergence", "Nexus RSI: hidden bullish divergence on {{ticker}} {{interval}}")
alertcondition(hidBear, "Hidden bearish divergence", "Nexus RSI: hidden bearish divergence on {{ticker}} {{interval}}")
alertcondition(gradeASig, "Grade A divergence", "Nexus RSI: grade A divergence on {{ticker}} {{interval}}")

← 返回列表