CTZ RSI Divergence Pro

CryptoTradingZone · study · 492 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
indicator("CTZ RSI Divergence Pro", "CTZ RSI Div", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════════
// CTZ RSI DIVERGENCE PRO — drawn on the price chart
// Local highs / lows are defined by candle closes (or wicks). Each new
// confirmed high / low is compared with earlier ones inside the lookback,
// and RSI divergence is drawn straight onto price:
//   Regular bull  (green)  : price lower low,   RSI higher low
//   Regular bear  (red)    : price higher high, RSI lower high
//   Hidden bull   (blue)   : price higher low,  RSI lower low
//   Hidden bear   (orange) : price lower high,  RSI higher high
// Dotted line = divergence forming on the live bar, not confirmed yet.
// ═══════════════════════════════════════════════════════════════════
 
// ═════════ Inputs ═════════
grpR = "RSI"
rsiLen  = input.int(14, "RSI length", minval = 2, group = grpR)
rsiType = input.string("Wilders", "RSI type", options = ["Wilders", "Cutler (SMA)", "EMA"], group = grpR)
sigLen  = input.int(12, "Signal line (EMA)", minval = 2, group = grpR)
 
grpP = "Divergence"
divSrc  = input.string("Close", "Div source", options = ["Close", "Wicks (high / low)"], group = grpP,
     tooltip = "Close: local highs / lows are found on candle closes (fewer false signals). Wicks: on highs and lows.")
confMode = input.string("Closes left / right", "High / low confirmation", options = ["Closes left / right", "Close beyond wick (zigzag)"], group = grpP,
     tooltip = "Closes left / right (matches CT): a high is a close above the closes on each side, confirmed only once the right-side candles have CLOSED. Close beyond wick (zigzag): highs and lows alternate, each confirmed by a close beyond the opposite wick.")
useExt  = input.bool(false, "Use external indicator data source", group = grpP, inline = "ext",
     tooltip = "Measure divergence on another indicator's output (e.g. CVD, OBV) instead of RSI. Zones and test price stay on RSI.")
extSrc  = input.source(close, "", group = grpP, inline = "ext")
pivL    = input.int(2, "Closes to the left", minval = 1, maxval = 20, group = grpP)
pivR    = input.int(2, "Closes to the right (confirmation)", minval = 1, maxval = 20, group = grpP,
     tooltip = "A local high / low is confirmed after this many candles close without beating it.")
lbMax   = input.int(22, "Div lookback (max bars between highs / lows)", minval = 5, maxval = 300, group = grpP)
lbMin   = input.int(2, "Min bars between highs / lows", minval = 1, maxval = 50, group = grpP)
midFilt = input.bool(false, "Regular bull only below 50, regular bear only above 50", group = grpP)
showPot = input.bool(true, "Show divergence forming (dotted)", group = grpP)
potWick = input.bool(true, "Forming high / low needs a close beyond its wick", group = grpP,
     tooltip = "A high still waiting for its right-side closes only counts as forming once a later candle has closed below its low (and the reverse for lows).")
liveCand = input.bool(false, "Live candle can be a forming high / low", group = grpP,
     tooltip = "Off (matches CT): only closed candles can start a forming divergence. On: earlier warning, more false signals.")
 
grpS = "Plot"
showRB  = input.bool(true, "Regular", group = grpS, inline = "reg")
cRB     = input.color(#7CFC00, "Bull", group = grpS, inline = "reg")
cRBe    = input.color(#ff1744, "Bear", group = grpS, inline = "reg")
showHB  = input.bool(true, "Hidden", group = grpS, inline = "hid")
cHB     = input.color(#2962ff, "Bull", group = grpS, inline = "hid")
cHBe    = input.color(#ff6d00, "Bear", group = grpS, inline = "hid")
lw      = input.int(2, "Line width", minval = 1, maxval = 5, group = grpS)
showLbl = input.bool(true, "Divergence arrows", group = grpS)
showAnc = input.bool(true, "Anchor dots (where each divergence starts)", group = grpS)
showPiv = input.bool(true, "Mark every confirmed high / low (white arrows)", group = grpS)
 
grpZ = "RSI zones (candle background)"
altHi   = input.float(85, "Alert level high", group = grpZ)
critHi  = input.float(80, "Critical bull level", group = grpZ)
ctlHi   = input.float(62, "Control bull level", group = grpZ)
ctlLo   = input.float(38, "Control bear level", group = grpZ)
critLo  = input.float(20, "Critical bear level", group = grpZ)
altLo   = input.float(15, "Alert level low", group = grpZ)
showCtl = input.bool(false, "Control zones", group = grpZ, inline = "ctl")
cCtlB   = input.color(color.new(#00bcd4, 93), "Bull", group = grpZ, inline = "ctl")
cCtlS   = input.color(color.new(#9c27b0, 93), "Bear", group = grpZ, inline = "ctl")
showCrt = input.bool(true, "Critical zones", group = grpZ, inline = "crt")
cCrtB   = input.color(color.new(#00bcd4, 85), "Bull", group = grpZ, inline = "crt")
cCrtS   = input.color(color.new(#9c27b0, 85), "Bear", group = grpZ, inline = "crt")
showAlt = input.bool(true, "Mark alert level crosses", group = grpZ)
 
grpI = "Infobox"
showBox = input.bool(true, "Show infobox", group = grpI)
boxPos  = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpI)
testLo  = input.float(30, "Test price for RSI (low)", minval = 1, maxval = 99, group = grpI,
     tooltip = "Price the current candle must close at for RSI to reach this level. Wilders and EMA only.")
testHi  = input.float(70, "Test price for RSI (high)", minval = 1, maxval = 99, group = grpI)
 
grpA = "Alerts (create one alert with 'Any alert() function call')"
alHiLo = input.bool(true, "High / low confirmation", group = grpA)
alPot  = input.bool(true, "Potential divergence", group = grpA)
alConf = input.bool(true, "Confirmed divergence", group = grpA)
alZero = input.bool(true, "Midline (50) cross", group = grpA)
alSig  = input.bool(true, "Signal line cross", group = grpA)
 
// ═════════ RSI ═════════
float ch  = close - close[1]
float up  = math.max(ch, 0.0)
float dn  = math.max(-ch, 0.0)
float uR  = ta.rma(up, rsiLen)
float dR  = ta.rma(dn, rsiLen)
float uS  = ta.sma(up, rsiLen)
float dS  = ta.sma(dn, rsiLen)
float uE  = ta.ema(up, rsiLen)
float dE  = ta.ema(dn, rsiLen)
float aU  = rsiType == "Cutler (SMA)" ? uS : rsiType == "EMA" ? uE : uR
float aD  = rsiType == "Cutler (SMA)" ? dS : rsiType == "EMA" ? dE : dR
float rsi = aD == 0 ? 100.0 : aU == 0 ? 0.0 : 100.0 - 100.0 / (1.0 + aU / aD)
float sig = ta.ema(rsi, sigLen)
 
// price the live candle must close at for RSI = T (inverse of the RSI smoothing)
f_testPrice(float T) =>
    float out = na
    if rsiType != "Cutler (SMA)" and not na(aU[1]) and not na(aD[1])
        float a  = rsiType == "EMA" ? 2.0 / (rsiLen + 1) : 1.0 / rsiLen
        float U  = aU[1]
        float D  = aD[1]
        float RS = T / (100.0 - T)
        float upNeed = (RS * (1.0 - a) * D - (1.0 - a) * U) / a
        if upNeed >= 0
            out := close[1] + upNeed
        else
            float dnNeed = ((1.0 - a) * U / RS - (1.0 - a) * D) / a
            out := close[1] - dnNeed
    out
float tpLo = f_testPrice(testLo)
float tpHi = f_testPrice(testHi)
 
// ═════════ Local highs / lows ═════════
float srcL   = divSrc == "Close" ? close : low
float srcH   = divSrc == "Close" ? close : high
float osc    = useExt ? extSrc : rsi          // what the divergence is measured on
bool  zzMode = confMode == "Close beyond wick (zigzag)"
int   lbEff  = lbMax + pivL                   // lookback counted to the left edge of the new high / low
 
// "Closes left / right": classic pivots on closes
float pl   = ta.pivotlow(srcL, pivL, pivR)
float ph   = ta.pivothigh(srcH, pivL, pivR)
float oscP = osc[pivR]
 
// mode "Close beyond wick": highs and lows alternate.
// Tracking a high: the bar with the highest source so far; confirmed when a candle CLOSES BELOW that bar's low wick.
// Tracking a low : the bar with the lowest source so far;  confirmed when a candle CLOSES ABOVE that bar's high wick.
var int   zDir = 0
var int   zB   = na
var float zP   = na
var float zO   = na
var float zW   = na
bool  zHi  = false
bool  zLo  = false
int   zEvB = na
float zEvP = na
float zEvO = na
if zzMode and not na(osc)
    if zDir == 0
        zDir := 1
        zB := bar_index
        zP := srcH
        zO := osc
        zW := low
    else if zDir == 1
        if srcH > zP
            zB := bar_index
            zP := srcH
            zO := osc
            zW := low
        else if close < zW
            zHi  := true
            zEvB := zB
            zEvP := zP
            zEvO := zO
            zDir := -1
            zB := bar_index
            zP := srcL
            zO := osc
            zW := high
    else
        if srcL < zP
            zB := bar_index
            zP := srcL
            zO := osc
            zW := high
        else if close > zW
            zLo  := true
            zEvB := zB
            zEvP := zP
            zEvO := zO
            zDir := 1
            zB := bar_index
            zP := srcH
            zO := osc
            zW := low
 
// one set of events for both modes; confirmed on CLOSED candles only (the live candle shows it as forming)
bool  evL  = barstate.isconfirmed and (zzMode ? zLo : not na(pl))
int   evLB = zzMode ? zEvB : bar_index - pivR
float evLP = zzMode ? zEvP : pl
float evLO = zzMode ? zEvO : oscP
bool  evH  = barstate.isconfirmed and (zzMode ? zHi : not na(ph))
int   evHB = zzMode ? zEvB : bar_index - pivR
float evHP = zzMode ? zEvP : ph
float evHO = zzMode ? zEvO : oscP
 
var array<int>   lB = array.new<int>()
var array<float> lP = array.new<float>()
var array<float> lR = array.new<float>()
var array<int>   hB = array.new<int>()
var array<float> hP = array.new<float>()
var array<float> hR = array.new<float>()
var string lastDiv  = "–"
var int    lastDivB = na
var color  lastDivC = color.gray
 
f_arrow(int b, bool bull, color c, string tip) =>
    if showLbl
        label.new(b, close, "", yloc = bull ? yloc.belowbar : yloc.abovebar, style = bull ? label.style_triangleup : label.style_triangledown,
             color = c, size = size.small, tooltip = tip)
    true
f_dot(int b, float y, color c) =>
    if showAnc
        label.new(b, y, "●", style = label.style_none, textcolor = c, size = size.small)
    true
f_piv(int b, bool low_) =>
    if showPiv
        label.new(b, close, "", yloc = low_ ? yloc.belowbar : yloc.abovebar, style = low_ ? label.style_triangleup : label.style_triangledown,
             color = color.new(color.white, 0), size = size.tiny)
    true
 
bool newRB = false
bool newHB = false
bool newRS = false
bool newHS = false
 
// new confirmed low: compared with every earlier low inside the lookback, all matches drawn
if evL
    int n = lB.size()
    if n > 0
        for i = n - 1 to 0
            int pb  = lB.get(i)
            int gap = evLB - pb
            if gap > lbEff
                break
            if gap >= lbMin
                float pp = lP.get(i)
                float pr = lR.get(i)
                bool isR = showRB and evLP < pp and evLO > pr and (not midFilt or evLO < 50)
                bool isH = showHB and evLP > pp and evLO < pr
                if isR or isH
                    color c = isR ? cRB : cHB
                    line.new(pb, pp, evLB, evLP, color = c, width = lw)
                    f_dot(pb, pp, c)
                    newRB := newRB or isR
                    newHB := newHB or isH
    if newRB
        f_arrow(evLB, true, cRB, "Regular bull divergence")
    else if newHB
        f_arrow(evLB, true, cHB, "Hidden bull divergence")
    else
        f_piv(evLB, true)
    lB.push(evLB)
    lP.push(evLP)
    lR.push(evLO)
    if lB.size() > 40
        lB.shift()
        lP.shift()
        lR.shift()
 
// new confirmed high
if evH
    int n = hB.size()
    if n > 0
        for i = n - 1 to 0
            int pb  = hB.get(i)
            int gap = evHB - pb
            if gap > lbEff
                break
            if gap >= lbMin
                float pp = hP.get(i)
                float pr = hR.get(i)
                bool isR = showRB and evHP > pp and evHO < pr and (not midFilt or evHO > 50)
                bool isH = showHB and evHP < pp and evHO > pr
                if isR or isH
                    color c = isR ? cRBe : cHBe
                    line.new(pb, pp, evHB, evHP, color = c, width = lw)
                    f_dot(pb, pp, c)
                    newRS := newRS or isR
                    newHS := newHS or isH
    if newRS
        f_arrow(evHB, false, cRBe, "Regular bear divergence")
    else if newHS
        f_arrow(evHB, false, cHBe, "Hidden bear divergence")
    else
        f_piv(evHB, false)
    hB.push(evHB)
    hP.push(evHP)
    hR.push(evHO)
    if hB.size() > 40
        hB.shift()
        hP.shift()
        hR.shift()
 
if newRB or newHB or newRS or newHS
    lastDiv  := newRB ? "Regular bull" : newRS ? "Regular bear" : newHB ? "Hidden bull" : "Hidden bear"
    lastDivC := newRB ? cRB : newRS ? cRBe : newHB ? cHB : cHBe
    lastDivB := newRB or newHB ? evLB : evHB
 
// data window outputs (1 on the bar a divergence is confirmed) for strategies / other scripts
plot(newRB ? 1 : 0, "Regular bull divergence", display = display.data_window)
plot(newRS ? 1 : 0, "Regular bear divergence", display = display.data_window)
plot(newHB ? 1 : 0, "Hidden bull divergence", display = display.data_window)
plot(newHS ? 1 : 0, "Hidden bear divergence", display = display.data_window)
 
// ═════════ Divergence forming (not confirmed yet) ═════════
// A high still waiting for its right-side closes: beats the closes on its left and every close since.
// k = bars back. Closed candle: k up to pivR - 1. Live candle: k up to pivR (the high it would confirm on close).
f_candHigh(int maxK, int minK) =>
    int res = -1
    for k = maxK to minK
        if res == -1 and maxK >= minK
            bool ok = true
            for j = 1 to pivL
                if srcH[k + j] >= srcH[k]
                    ok := false
            if ok and k > 0
                for j = 0 to k - 1
                    if srcH[j] > srcH[k]
                        ok := false
            if ok and potWick and k > 0
                bool beyond = false
                for j = 0 to k - 1
                    if close[j] < low[k]
                        beyond := true
                ok := beyond
            if ok
                res := k
    res
f_candLow(int maxK, int minK) =>
    int res = -1
    for k = maxK to minK
        if res == -1 and maxK >= minK
            bool ok = true
            for j = 1 to pivL
                if srcL[k + j] <= srcL[k]
                    ok := false
            if ok and k > 0
                for j = 0 to k - 1
                    if srcL[j] < srcL[k]
                        ok := false
            if ok and potWick and k > 0
                bool beyond = false
                for j = 0 to k - 1
                    if close[j] > high[k]
                        beyond := true
                ok := beyond
            if ok
                res := k
    res
 
int   kMax = barstate.isconfirmed ? pivR - 1 : pivR
int   kMin = liveCand ? 0 : 1
int   kH   = f_candHigh(kMax, kMin)
int   kL   = f_candLow(kMax, kMin)
bool  haveL = zzMode ? zDir == -1 : kL >= 0
bool  haveH = zzMode ? zDir == 1 : kH >= 0
int   cLB   = zzMode ? zB : bar_index - math.max(kL, 0)
float cLP   = zzMode ? zP : srcL[math.max(kL, 0)]
float cLO   = zzMode ? zO : osc[math.max(kL, 0)]
int   cHB2  = zzMode ? zB : bar_index - math.max(kH, 0)
float cHP   = zzMode ? zP : srcH[math.max(kH, 0)]
float cHO   = zzMode ? zO : osc[math.max(kH, 0)]
bool  potRB = false
bool  potHB = false
bool  potRS = false
bool  potHS = false
int   potLB = na
float potLP = na
int   potHBr = na
float potHP = na
if haveL and not na(cLB) and lB.size() > 0
    for i = lB.size() - 1 to 0
        int pb  = lB.get(i)
        int gap = cLB - pb
        if gap > lbEff
            break
        if gap >= lbMin and not (potRB or potHB)
            float pp = lP.get(i)
            float pr = lR.get(i)
            potRB := showRB and cLP < pp and cLO > pr and (not midFilt or cLO < 50)
            potHB := showHB and cLP > pp and cLO < pr
            if potRB or potHB
                potLB := pb
                potLP := pp
if haveH and not na(cHB2) and hB.size() > 0
    for i = hB.size() - 1 to 0
        int pb  = hB.get(i)
        int gap = cHB2 - pb
        if gap > lbEff
            break
        if gap >= lbMin and not (potRS or potHS)
            float pp = hP.get(i)
            float pr = hR.get(i)
            potRS := showRB and cHP > pp and cHO < pr and (not midFilt or cHO > 50)
            potHS := showHB and cHP < pp and cHO > pr
            if potRS or potHS
                potHBr := pb
                potHP := pp
 
// only one forming divergence at a time (like CT): keep the most recent forming high / low
if (potRB or potHB) and (potRS or potHS)
    if cLB >= cHB2
        potRS := false
        potHS := false
    else
        potRB := false
        potHB := false
 
var line potLineL = na
var line potLineH = na
if barstate.islast
    line.delete(potLineL)
    line.delete(potLineH)
    potLineL := na
    potLineH := na
    if showPot and (potRB or potHB)
        potLineL := line.new(potLB, potLP, cLB, cLP, color = potRB ? cRB : cHB, width = lw, style = line.style_dotted)
    if showPot and (potRS or potHS)
        potLineH := line.new(potHBr, potHP, cHB2, cHP, color = potRS ? cRBe : cHBe, width = lw, style = line.style_dotted)
 
// ═════════ Zones ═════════
color zc = na
if showCrt and rsi >= critHi
    zc := cCrtB
else if showCrt and rsi <= critLo
    zc := cCrtS
else if showCtl and rsi >= ctlHi
    zc := cCtlB
else if showCtl and rsi <= ctlLo
    zc := cCtlS
bgcolor(zc, title = "RSI zone")
 
bool xAltHi = ta.crossover(rsi, altHi)
bool xAltLo = ta.crossunder(rsi, altLo)
plotshape(showAlt and xAltHi, "RSI above alert high", shape.diamond, location.abovebar, color.new(color.yellow, 0), size = size.tiny)
plotshape(showAlt and xAltLo, "RSI below alert low", shape.diamond, location.belowbar, color.new(color.yellow, 0), size = size.tiny)
 
// ═════════ Infobox ═════════
f_pos(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_zone(float v) =>
    v >= altHi ? "Alert high" : v >= critHi ? "Critical bull" : v >= ctlHi ? "Control bull" : v > ctlLo ? "Neutral" : v > critLo ? "Control bear" : v > altLo ? "Critical bear" : "Alert low"
 
var table infoBox = table.new(f_pos(boxPos), 2, 8, bgcolor = color.new(color.black, 20), border_width = 1, border_color = color.new(color.white, 85))
if showBox and barstate.islast
    color lc = color.new(color.white, 30)
    color rc = rsi >= ctlHi ? #00bcd4 : rsi <= ctlLo ? #d05ce3 : color.white
    string pot = potRB ? "Regular bull" : potRS ? "Regular bear" : potHB ? "Hidden bull" : potHS ? "Hidden bear" : "–"
    color potC = potRB ? cRB : potRS ? cRBe : potHB ? cHB : potHS ? cHBe : lc
    table.cell(infoBox, 0, 0, "CTZ RSI DIV", text_color = color.white, bgcolor = color.new(#1e293b, 0), text_size = size.small)
    table.cell(infoBox, 1, 0, rsiType + " " + str.tostring(rsiLen) + " · " + timeframe.period, text_color = lc, bgcolor = color.new(#1e293b, 0), text_size = size.small)
    table.cell(infoBox, 0, 1, "RSI", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 1, str.tostring(rsi, "0.00"), text_color = rc, text_size = size.small)
    table.cell(infoBox, 0, 2, "Signal", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 2, str.tostring(sig, "0.00") + (rsi > sig ? "  ▲ above" : "  ▼ below"), text_color = rsi > sig ? cRB : cRBe, text_size = size.small)
    table.cell(infoBox, 0, 3, "Zone", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 3, f_zone(rsi), text_color = rc, text_size = size.small)
    table.cell(infoBox, 0, 4, "Last divergence", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 4, na(lastDivB) ? "–" : lastDiv + " · " + str.tostring(bar_index - lastDivB) + " bars ago", text_color = lastDivC, text_size = size.small)
    table.cell(infoBox, 0, 5, "Forming now", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 5, pot, text_color = potC, text_size = size.small)
    table.cell(infoBox, 0, 6, "RSI " + str.tostring(testLo) + " at", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 6, na(tpLo) ? "–" : str.tostring(tpLo, format.mintick), text_color = color.white, text_size = size.small)
    table.cell(infoBox, 0, 7, "RSI " + str.tostring(testHi) + " at", text_color = lc, text_size = size.small, text_halign = text.align_left)
    table.cell(infoBox, 1, 7, na(tpHi) ? "–" : str.tostring(tpHi, format.mintick), text_color = color.white, text_size = size.small)
 
// ═════════ Alerts ═════════
bool potBull = potRB or potHB
bool potBear = potRS or potHS
bool x50Up   = ta.crossover(rsi, 50)
bool x50Dn   = ta.crossunder(rsi, 50)
bool xSigUp  = ta.crossover(rsi, sig)
bool xSigDn  = ta.crossunder(rsi, sig)
if barstate.isconfirmed
    if alHiLo and evL
        alert("CTZ RSI Div: local LOW confirmed at " + str.tostring(evLP, format.mintick), alert.freq_once_per_bar_close)
    if alHiLo and evH
        alert("CTZ RSI Div: local HIGH confirmed at " + str.tostring(evHP, format.mintick), alert.freq_once_per_bar_close)
    if alConf and (newRB or newHB or newRS or newHS)
        alert("CTZ RSI Div: CONFIRMED " + lastDiv + " divergence", alert.freq_once_per_bar_close)
    if alPot and potBull and not potBull[1]
        alert("CTZ RSI Div: potential " + (potRB ? "regular" : "hidden") + " BULL divergence forming", alert.freq_once_per_bar_close)
    if alPot and potBear and not potBear[1]
        alert("CTZ RSI Div: potential " + (potRS ? "regular" : "hidden") + " BEAR divergence forming", alert.freq_once_per_bar_close)
    if alZero and x50Up
        alert("CTZ RSI Div: RSI crossed ABOVE 50", alert.freq_once_per_bar_close)
    if alZero and x50Dn
        alert("CTZ RSI Div: RSI crossed BELOW 50", alert.freq_once_per_bar_close)
    if alSig and xSigUp
        alert("CTZ RSI Div: RSI crossed ABOVE its signal line", alert.freq_once_per_bar_close)
    if alSig and xSigDn
        alert("CTZ RSI Div: RSI crossed BELOW its signal line", alert.freq_once_per_bar_close)

← 返回列表