CVD vs Price Divergence [Jireh]

Leeonidas187 · study · 197 行 · 点赞 25 · TradingView 原页

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

Pine Script

//@version=6
indicator("CVD vs Price Divergence [Jireh]", shorttitle = "CVD Div", overlay = false, max_lines_count = 300, max_labels_count = 300)
 
// =====================================================================
// CVD vs Price Divergence [Jireh]
// Footprint-based CVD and a price moving average drawn on the SAME scale
// in one pane, so divergences between order flow and price are easy to see.
// Both lines are normalized the same way (rolling z-score or session range),
// which fixes the scale problem of dragging a price EMA into a CVD pane.
// =====================================================================
 
// ---------- Delta ----------
grpD    = "Delta / CVD"
srcMode = input.string("Auto", "Delta source", options = ["Auto", "Footprint", "Approximate"], group = grpD, tooltip = "Footprint = real bid/ask delta (Premium/Ultimate). Approximate = estimated from where each candle closes in its range. Auto = footprint when available.")
fpTicks = input.int(100, "Footprint ticks per row", minval = 1, group = grpD, tooltip = "Only bar totals are used, so a large value keeps it light. Doesn't change the result.")
decayIn = input.string("Off", "CVD decay", options = ["Off", "Fast", "Moderate", "Slow"], group = grpD, tooltip = "Fades old delta so the line emphasizes recent flow. Fast ≈ 21 bars, Moderate ≈ 50, Slow ≈ 100.")
cvdSm   = input.int(1, "CVD smoothing (1 = off)", minval = 1, group = grpD)
 
// ---------- Price line ----------
grpP  = "Price line"
pSrc  = input.source(close, "Source", group = grpP)
pType = input.string("EMA", "MA type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], group = grpP)
pLen  = input.int(9, "Length", minval = 1, group = grpP)
 
// ---------- Scaling ----------
grpN     = "Scaling"
nMode    = input.string("Rolling", "Scaling mode", options = ["Rolling", "Session anchored"], group = grpN, tooltip = "Rolling: both lines as z-scores over the window, continuous across sessions. Session anchored: CVD resets at each session and both lines are scaled to their range since the reset.")
nLen     = input.int(100, "Rolling window (bars)", minval = 10, group = grpN)
anchorTF = input.timeframe("D", "Session anchor", group = grpN, tooltip = "Used in Session anchored mode. D = new Globex day (6:00 pm ET).")
 
// ---------- Divergences ----------
grpV     = "Divergences"
showDiv  = input.bool(true, "Show regular divergences", group = grpV, tooltip = "Bearish: price higher high, CVD lower high. Bullish: price lower low, CVD higher low.")
showHid  = input.bool(false, "Show hidden divergences", group = grpV, tooltip = "Bearish hidden: price lower high, CVD higher high. Bullish hidden: price higher low, CVD lower low.")
pivL     = input.int(5, "Pivot bars left", minval = 1, group = grpV)
pivR     = input.int(3, "Pivot bars right (confirmation delay)", minval = 1, group = grpV)
minGap   = input.int(5, "Min bars between pivots", minval = 1, group = grpV)
maxGap   = input.int(60, "Max bars between pivots", minval = 5, group = grpV)
showDivLbl = input.bool(true, "Label divergences", group = grpV)
 
// ---------- Spread ----------
grpS     = "Spread shading"
showFill = input.bool(true, "Shade between lines", group = grpS)
sprThr   = input.float(1.0, "Strong spread threshold (scaled units)", minval = 0.1, step = 0.1, group = grpS, tooltip = "Shading gets stronger when the lines are at least this far apart.")
 
// ---------- Colors ----------
grpC      = "Colors"
cvdCol    = input.color(#378ADD, "CVD line", group = grpC)
priceCol  = input.color(#B2B5BE, "Price line", group = grpC)
cvdLeadC  = input.color(#5BC75B, "CVD above price", group = grpC)
priceLeadC = input.color(#F928F5, "Price above CVD", group = grpC)
bullC     = input.color(#00E600, "Bullish divergence", group = grpC)
bearC     = input.color(#C90111, "Bearish divergence", group = grpC)
cvdW      = input.int(2, "CVD line width", minval = 1, maxval = 4, group = grpC)
priceW    = input.int(2, "Price line width", minval = 1, maxval = 4, group = grpC)
 
// =====================================================================
// Delta
// =====================================================================
fp    = request.footprint(fpTicks)
fpD   = na(fp) ? na : fp.delta()
rng   = high - low
apx   = rng > 0 ? nz(volume) * (2 * close - high - low) / rng : 0.0
useFP = srcMode == "Footprint" or (srcMode == "Auto" and not na(fpD))
d     = useFP ? nz(fpD) : apx
 
// =====================================================================
// CVD
// =====================================================================
alpha = decayIn == "Fast" ? 2.0 / 22 : decayIn == "Moderate" ? 2.0 / 51 : decayIn == "Slow" ? 2.0 / 101 : 0.0
isAnchored = nMode == "Session anchored"
reset = isAnchored and timeframe.change(anchorTF)
 
var float cvd = 0.0
if reset
    cvd := 0.0
cvd := alpha > 0 ? cvd * (1 - alpha) + d : cvd + d
cvdS = cvdSm > 1 ? ta.ema(cvd, cvdSm) : cvd
 
// =====================================================================
// Price line
// =====================================================================
maFn(float s, int len, string t) =>
    switch t
        "SMA" => ta.sma(s, len)
        "WMA" => ta.wma(s, len)
        "HMA" => ta.hma(s, len)
        "RMA" => ta.rma(s, len)
        => ta.ema(s, len)
 
pl = maFn(pSrc, pLen, pType)
 
// =====================================================================
// Normalization (same method for both lines)
// =====================================================================
zOf(float x) =>
    m  = ta.sma(x, nLen)
    sd = ta.stdev(x, nLen)
    sd > 0 ? (x - m) / sd : 0.0
 
zC = zOf(cvdS)
zP = zOf(pl)
 
var float cHi = na
var float cLo = na
var float pHi = na
var float pLo = na
if reset or na(cHi)
    cHi := cvdS
    cLo := cvdS
    pHi := pl
    pLo := pl
else
    cHi := math.max(cHi, cvdS)
    cLo := math.min(cLo, cvdS)
    pHi := math.max(pHi, pl)
    pLo := math.min(pLo, pl)
 
// Session range mapped to roughly -2..+2 so units match the z-score mode
rngN(float x, float lo, float hi) =>
    hi > lo ? ((x - lo) / (hi - lo) - 0.5) * 4 : 0.0
 
cN = isAnchored ? rngN(cvdS, cLo, cHi) : zC
pN = isAnchored ? rngN(pl, pLo, pHi) : zP
 
// =====================================================================
// Plots
// =====================================================================
hline(0, "Zero", color = color.new(color.gray, 70), linestyle = hline.style_dotted)
pC = plot(cN, "CVD (scaled)", color = cvdCol, linewidth = cvdW)
pP = plot(pN, "Price line (scaled)", color = priceCol, linewidth = priceW)
spr = cN - pN
fillCol = not showFill ? na : color.new(spr >= 0 ? cvdLeadC : priceLeadC, math.abs(spr) >= sprThr ? 65 : 90)
fill(pC, pP, color = fillCol, title = "Spread")
 
// =====================================================================
// Divergences (price pivots vs CVD at the same bars)
// =====================================================================
ph = ta.pivothigh(high, pivL, pivR)
pv = ta.pivotlow(low, pivL, pivR)
 
var float lastHP = na
var float lastHC = na
var int   lastHB = na
var float lastLP = na
var float lastLC = na
var int   lastLB = na
 
bearReg = false
bullReg = false
bearHid = false
bullHid = false
 
if not na(ph)
    b  = bar_index - pivR
    cA = cN[pivR]
    if not na(lastHP) and b - lastHB >= minGap and b - lastHB <= maxGap
        if showDiv and ph > lastHP and cA < lastHC
            bearReg := true
            line.new(lastHB, lastHC, b, cA, color = bearC, width = 2)
            if showDivLbl
                label.new(b, cA, "Bear", style = label.style_label_down, color = color.new(bearC, 100), textcolor = bearC, size = size.tiny)
        if showHid and ph < lastHP and cA > lastHC
            bearHid := true
            line.new(lastHB, lastHC, b, cA, color = bearC, width = 1, style = line.style_dashed)
            if showDivLbl
                label.new(b, cA, "H Bear", style = label.style_label_down, color = color.new(bearC, 100), textcolor = bearC, size = size.tiny)
    lastHP := ph
    lastHC := cA
    lastHB := b
 
if not na(pv)
    b  = bar_index - pivR
    cA = cN[pivR]
    if not na(lastLP) and b - lastLB >= minGap and b - lastLB <= maxGap
        if showDiv and pv < lastLP and cA > lastLC
            bullReg := true
            line.new(lastLB, lastLC, b, cA, color = bullC, width = 2)
            if showDivLbl
                label.new(b, cA, "Bull", style = label.style_label_up, color = color.new(bullC, 100), textcolor = bullC, size = size.tiny)
        if showHid and pv > lastLP and cA < lastLC
            bullHid := true
            line.new(lastLB, lastLC, b, cA, color = bullC, width = 1, style = line.style_dashed)
            if showDivLbl
                label.new(b, cA, "H Bull", style = label.style_label_up, color = color.new(bullC, 100), textcolor = bullC, size = size.tiny)
    lastLP := pv
    lastLC := cA
    lastLB := b
 
// =====================================================================
// Alerts (set to "Once per bar close")
// =====================================================================
alertcondition(bullReg, "Bullish divergence", "CVD Div: bullish divergence on {{ticker}} {{interval}}")
alertcondition(bearReg, "Bearish divergence", "CVD Div: bearish divergence on {{ticker}} {{interval}}")
alertcondition(bullHid, "Hidden bullish divergence", "CVD Div: hidden bullish divergence on {{ticker}} {{interval}}")
alertcondition(bearHid, "Hidden bearish divergence", "CVD Div: hidden bearish divergence on {{ticker}} {{interval}}")
alertcondition(ta.cross(cN, pN), "Lines cross", "CVD Div: CVD and price lines crossed on {{ticker}} {{interval}}")

← 返回列表