Delta Flow Profile 3D [NeBlok]

NeBlok · study · 354 行 · 点赞 36 · 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/
// © James_Mason
 
// © NeBlok
//
// Delta Flow Profile 3D [NeBlok]
// ------------------------------------------------------------------------------------
// What it does
//  1. Estimates buy vs. sell volume for every bar from lower-timeframe (intrabar) data.
//     Each intrabar is classified by its body direction (tick rule on dojis).
//     If intrabar data isn't available for a bar, it falls back to bar geometry
//     (close location inside the high-low range).
//  2. Builds a diverging 3D delta profile over the lookback window:
//     net buying extends RIGHT of the axis, net selling extends LEFT.
//     POC (highest total volume row) is highlighted; rows outside the Value Area dim.
//  3. Flags "delta spikes" (bars whose delta is a statistical outlier, z-score) with glow pillars.
//  4. Each spike anchors an imbalance level at that bar's intrabar VWAP, drawn as a 3D plate
//     that extends right until price mitigates it.
// ------------------------------------------------------------------------------------
 
//@version=6
indicator("Delta Flow Profile 3D [NeBlok]", shorttitle = "DFP3D [NeBlok]", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100)
 
// ═════════════════════════════════════════ INPUTS ═════════════════════════════════════════
grpD = "Delta Engine"
deltaMethod = input.string("Intrabar", "Delta Method", options = ["Intrabar", "Bar Geometry"], group = grpD, tooltip = "Intrabar: classifies lower-timeframe bars as buying or selling (more accurate).\nBar Geometry: splits each bar's volume by where it closed in its range (works everywhere, less precise).\nIntrabar mode falls back to Bar Geometry on any bar without intrabar data.")
ltfInput    = input.timeframe("", "Intrabar Timeframe (blank = auto)", group = grpD)
 
grpP = "Profile"
lookback    = input.int(300, "Lookback Bars", minval = 20, maxval = 2000, group = grpP)
rows        = input.int(28, "Rows", minval = 5, maxval = 40, group = grpP)
profWidth   = input.int(45, "Max Bar Length (bars)", minval = 10, maxval = 150, group = grpP)
profOffset  = input.int(15, "Offset From Last Bar (bars)", minval = 2, maxval = 100, group = grpP)
vaPct       = input.float(70.0, "Value Area %", minval = 10.0, maxval = 100.0, group = grpP) / 100.0
showPOC     = input.bool(true, "Highlight POC + POC Line", group = grpP)
dimOutVA    = input.bool(true, "Dim Rows Outside Value Area", group = grpP)
showRowVals = input.bool(false, "Show Row Delta Values", group = grpP)
showHeader  = input.bool(true, "Show Summary Label", group = grpP)
 
grp3 = "3D Style"
depthX      = input.int(4, "Depth X (bars)", minval = 0, maxval = 20, group = grp3)
depthY      = input.float(0.6, "Depth Y (× row height)", minval = 0.0, maxval = 3.0, step = 0.1, group = grp3)
showFrame   = input.bool(true, "Show 3D Window Frame", group = grp3)
 
grpS = "Delta Spikes & Levels"
showSpikes    = input.bool(true, "Show Delta Spike Pillars", group = grpS)
zLen          = input.int(100, "Spike Baseline Length", minval = 10, group = grpS)
zThr          = input.float(2.5, "Spike Threshold (z-score)", minval = 0.5, step = 0.1, group = grpS, tooltip = "How many standard deviations a bar's delta must be from its baseline to count as a spike. Higher = fewer, stronger spikes.")
showLevels    = input.bool(true, "Show Imbalance Levels", group = grpS)
maxLevels     = input.int(20, "Max Levels", minval = 1, maxval = 40, group = grpS)
mitigation    = input.string("Wick", "Mitigation Trigger", options = ["Wick", "Close"], group = grpS)
keepMitigated = input.bool(true, "Keep Mitigated Levels (faded)", group = grpS)
 
grpC = "Colors"
bullCol  = input.color(#14b8a6, "Buy Delta", group = grpC)
bearCol  = input.color(#f23645, "Sell Delta", group = grpC)
pocCol   = input.color(#ffd600, "POC", group = grpC)
frameCol = input.color(#787b8680, "Frame / Axis", group = grpC)
 
// ═════════════════════════════════════════ TYPES & STORAGE ═════════════════════════════════════════
type Level
    float price
    int   left
    int   right
    bool  bull
    bool  active
 
var array<float> hArr = array.new<float>()   // bar highs
var array<float> lArr = array.new<float>()   // bar lows
var array<float> bArr = array.new<float>()   // buy volume
var array<float> sArr = array.new<float>()   // sell volume
var array<int>   xArr = array.new<int>()     // bar indexes
var array<int>   cArr = array.new<int>()     // 1 = intrabar data used, 0 = fallback
var array<Level> levels = array.new<Level>()
 
var array<box>      pBoxes  = array.new<box>()
var array<polyline> pPolys  = array.new<polyline>()
var array<line>     pLines  = array.new<line>()
var array<label>    pLabels = array.new<label>()
 
f_line(int x1, float y1, int x2, float y2, color c, int w, string st) =>
    pLines.push(line.new(x1, y1, x2, y2, xloc = xloc.bar_index, color = c, width = w, style = st))
 
f_fmtDelta(float d) =>
    (d >= 0 ? "+" : "") + str.tostring(d, format.volume)
 
// ═════════════════════════════════════════ DELTA ENGINE ═════════════════════════════════════════
chartSec = timeframe.in_seconds()
autoLTF  = chartSec <= 60 ? timeframe.period : chartSec <= 3600 ? "1" : chartSec <= 14400 ? "5" : chartSec <= 86400 ? "15" : "60"
ltfTF    = ltfInput == "" ? autoLTF : timeframe.in_seconds(ltfInput) > chartSec ? timeframe.period : ltfInput
 
[ltfO, ltfC, ltfV] = request.security_lower_tf(syminfo.tickerid, ltfTF, [open, close, volume], ignore_invalid_timeframe = true)
 
float buyV  = 0.0
float sellV = 0.0
float pvSum = 0.0
float vSum  = 0.0
int   nIntra   = ltfC.size()
bool  useIntra = deltaMethod == "Intrabar" and nIntra > 0
 
if useIntra
    float prevC = na
    for i = 0 to nIntra - 1
        float o = ltfO.get(i)
        float c = ltfC.get(i)
        float v = nz(ltfV.get(i))
        float dir = c > o ? 1.0 : c < o ? -1.0 : na(prevC) ? 0.0 : c > prevC ? 1.0 : c < prevC ? -1.0 : 0.0
        if dir > 0
            buyV += v
        else if dir < 0
            sellV += v
        else
            buyV  += v * 0.5
            sellV += v * 0.5
        pvSum += c * v
        vSum  += v
        prevC := c
else
    float v   = nz(volume)
    float rng = high - low
    buyV  := rng > 0 ? v * (close - low) / rng : v * 0.5
    sellV := v - buyV
    pvSum := hlc3 * v
    vSum  := v
 
float barDelta = buyV - sellV
float anchor   = vSum > 0 ? pvSum / vSum : hlc3   // intrabar VWAP of this bar
 
// ═════════════════════════════════════════ SPIKE DETECTION ═════════════════════════════════════════
float dMean = ta.sma(barDelta, zLen)
float dDev  = ta.stdev(barDelta, zLen)
float z     = dDev > 0 ? (barDelta - dMean) / dDev : 0.0
bool bullSpike = z >= zThr and barDelta > 0
bool bearSpike = z <= -zThr and barDelta < 0
bool inWindow  = bar_index > last_bar_index - lookback
 
if showSpikes and inWindow and (bullSpike or bearSpike)
    color sc = bullSpike ? bullCol : bearCol
    line.new(bar_index, high, bar_index, low, color = color.new(sc, 80), width = 8)
    line.new(bar_index, high, bar_index, low, color = color.new(sc, 20), width = 2)
 
// ═════════════════════════════════════════ ROLLING WINDOW ═════════════════════════════════════════
hArr.push(high)
lArr.push(low)
bArr.push(buyV)
sArr.push(sellV)
xArr.push(bar_index)
cArr.push(useIntra ? 1 : 0)
if hArr.size() > lookback
    hArr.shift()
    lArr.shift()
    bArr.shift()
    sArr.shift()
    xArr.shift()
    cArr.shift()
 
// ═════════════════════════════════════════ IMBALANCE LEVELS ═════════════════════════════════════════
bool bullLevelHit = false
bool bearLevelHit = false
 
for lv in levels
    if lv.active
        bool hit = mitigation == "Wick" ? (lv.bull ? low < lv.price : high > lv.price) : (lv.bull ? close < lv.price : close > lv.price)
        lv.right := bar_index
        if hit
            lv.active := false
            if lv.bull
                bullLevelHit := true
            else
                bearLevelHit := true
 
if not keepMitigated and levels.size() > 0
    for i = levels.size() - 1 to 0
        if not levels.get(i).active
            levels.remove(i)
 
if showLevels and (bullSpike or bearSpike)
    levels.unshift(Level.new(anchor, bar_index, bar_index, bullSpike, true))
    if levels.size() > maxLevels
        levels.pop()
 
// ═════════════════════════════════════════ VOLUME CHECK ═════════════════════════════════════════
float cumVol = ta.cum(nz(volume))
if barstate.islast and cumVol == 0
    runtime.error("No volume data on this symbol. The delta profile needs volume.")
 
// ═════════════════════════════════════════ RENDER (last bar only) ═════════════════════════════════════════
if barstate.islast
    for b in pBoxes
        b.delete()
    pBoxes.clear()
    for p in pPolys
        p.delete()
    pPolys.clear()
    for ln in pLines
        ln.delete()
    pLines.clear()
    for lb in pLabels
        lb.delete()
    pLabels.clear()
 
    int   n     = hArr.size()
    float top   = hArr.max()
    float bot   = lArr.min()
    float rowH  = n > 1 ? (top - bot) / rows : 0.0
 
    if n > 1 and rowH > 0
        // ── Distribute each bar's buy/sell volume across the rows its range covers
        array<float> rBuy  = array.new<float>(rows, 0.0)
        array<float> rSell = array.new<float>(rows, 0.0)
        for i = 0 to n - 1
            float h   = hArr.get(i)
            float l   = lArr.get(i)
            float bv  = bArr.get(i)
            float sv  = sArr.get(i)
            float rng = h - l
            if rng <= 0
                int r = math.max(0, math.min(rows - 1, int(math.floor((h - bot) / rowH))))
                rBuy.set(r, rBuy.get(r) + bv)
                rSell.set(r, rSell.get(r) + sv)
            else
                int r0 = math.max(0, math.min(rows - 1, int(math.floor((l - bot) / rowH))))
                int r1 = math.max(0, math.min(rows - 1, int(math.floor((h - bot) / rowH))))
                for r = r0 to r1
                    float rb = bot + r * rowH
                    float ov = math.min(h, rb + rowH) - math.max(l, rb)
                    if ov > 0
                        float f = ov / rng
                        rBuy.set(r, rBuy.get(r) + bv * f)
                        rSell.set(r, rSell.get(r) + sv * f)
 
        // ── Row totals, deltas, POC
        array<float> rTot = array.new<float>(rows, 0.0)
        array<float> rDel = array.new<float>(rows, 0.0)
        float totVol = 0.0
        float netDel = 0.0
        float maxAbs = 0.0
        int   poc    = 0
        for r = 0 to rows - 1
            float t = rBuy.get(r) + rSell.get(r)
            float d = rBuy.get(r) - rSell.get(r)
            rTot.set(r, t)
            rDel.set(r, d)
            totVol += t
            netDel += d
            maxAbs := math.max(maxAbs, math.abs(d))
            if t > rTot.get(poc)
                poc := r
 
        // ── Value Area (expand from POC toward the heavier neighbor)
        int   vaUp  = poc
        int   vaDn  = poc
        float vaVol = rTot.get(poc)
        while vaVol < totVol * vaPct and (vaUp < rows - 1 or vaDn > 0)
            float nextUp = vaUp < rows - 1 ? rTot.get(vaUp + 1) : -1.0
            float nextDn = vaDn > 0 ? rTot.get(vaDn - 1) : -1.0
            if nextUp >= nextDn
                vaUp  += 1
                vaVol += nextUp
            else
                vaDn  -= 1
                vaVol += nextDn
 
        int   xStart   = xArr.get(0)
        int   xAxis    = last_bar_index + profOffset + profWidth
        float dy       = rowH * depthY
        float gap      = rowH * 0.06
        float pocPrice = bot + (poc + 0.5) * rowH
 
        // ── 3D window frame
        if showFrame
            int xe = last_bar_index
            // front
            f_line(xStart, top, xe, top, frameCol, 1, line.style_solid)
            f_line(xStart, bot, xe, bot, frameCol, 1, line.style_solid)
            f_line(xStart, bot, xStart, top, frameCol, 1, line.style_solid)
            f_line(xe, bot, xe, top, frameCol, 1, line.style_solid)
            // back
            f_line(xStart + depthX, top + dy, xe + depthX, top + dy, frameCol, 1, line.style_solid)
            f_line(xStart + depthX, bot + dy, xe + depthX, bot + dy, frameCol, 1, line.style_solid)
            f_line(xStart + depthX, bot + dy, xStart + depthX, top + dy, frameCol, 1, line.style_solid)
            f_line(xe + depthX, bot + dy, xe + depthX, top + dy, frameCol, 1, line.style_solid)
            // connectors
            f_line(xStart, top, xStart + depthX, top + dy, frameCol, 1, line.style_solid)
            f_line(xe, top, xe + depthX, top + dy, frameCol, 1, line.style_solid)
            f_line(xStart, bot, xStart + depthX, bot + dy, frameCol, 1, line.style_solid)
            f_line(xe, bot, xe + depthX, bot + dy, frameCol, 1, line.style_solid)
 
        // ── Profile axis
        f_line(xAxis, bot, xAxis, top, frameCol, 1, line.style_dotted)
 
        // ── POC line across the window
        if showPOC
            f_line(xStart, pocPrice, xAxis, pocPrice, color.new(pocCol, 40), 1, line.style_dotted)
 
        // ── Imbalance level plates
        if showLevels and levels.size() > 0
            float ldy = dy * 0.5
            for lv in levels
                if lv.active or keepMitigated
                    color lc = lv.bull ? bullCol : bearCol
                    int   tr = lv.active ? 45 : 80
                    array<chart.point> lp = array.from(chart.point.from_index(lv.left, lv.price), chart.point.from_index(lv.right, lv.price), chart.point.from_index(lv.right + depthX, lv.price + ldy), chart.point.from_index(lv.left + depthX, lv.price + ldy))
                    pPolys.push(polyline.new(lp, closed = true, xloc = xloc.bar_index, line_color = color.new(lc, math.min(100, tr + 10)), fill_color = color.new(lc, tr)))
                    f_line(lv.left, lv.price, lv.right, lv.price, color.new(lc, lv.active ? 10 : 60), 1, line.style_solid)
 
        // ── 3D profile rows (top row first so lower rows overlap correctly)
        if maxAbs > 0
            for k = 0 to rows - 1
                int   r = rows - 1 - k
                float d = rDel.get(r)
                if rTot.get(r) > 0
                    int   len  = math.max(1, int(math.round(math.abs(d) / maxAbs * profWidth)))
                    int   xL   = d >= 0 ? xAxis : xAxis - len
                    int   xR   = d >= 0 ? xAxis + len : xAxis
                    float yB   = bot + r * rowH + gap
                    float yT   = bot + (r + 1) * rowH - gap
                    bool  inVA = r >= vaDn and r <= vaUp
                    bool  isPoc = showPOC and r == poc
                    color base = isPoc ? pocCol : d >= 0 ? bullCol : bearCol
                    int   tf   = dimOutVA and not inVA and not isPoc ? 55 : 10
 
                    // front face
                    pBoxes.push(box.new(xL, yT, xR, yB, xloc = xloc.bar_index, border_color = color.new(base, tf), border_width = 1, bgcolor = color.new(base, tf)))
 
                    // top + side faces (single extrusion polygon) + edge highlight
                    if depthX > 0 or dy > 0
                        array<chart.point> ep = array.from(chart.point.from_index(xL, yT), chart.point.from_index(xR, yT), chart.point.from_index(xR, yB), chart.point.from_index(xR + depthX, yB + dy), chart.point.from_index(xR + depthX, yT + dy), chart.point.from_index(xL + depthX, yT + dy))
                        pPolys.push(polyline.new(ep, closed = true, xloc = xloc.bar_index, line_color = color.new(base, math.min(100, tf + 20)), fill_color = color.new(base, math.min(100, tf + 40))))
                        f_line(xR, yT, xR + depthX, yT + dy, color.new(base, tf), 1, line.style_solid)
 
                    // optional value label
                    if showRowVals
                        int lx = d >= 0 ? xR + depthX + 1 : xL - 1
                        pLabels.push(label.new(lx, (yB + yT) / 2, f_fmtDelta(d), xloc = xloc.bar_index, style = d >= 0 ? label.style_label_left : label.style_label_right, color = #00000000, textcolor = color.new(base, 0), size = size.tiny))
 
        // ── Summary label
        if showHeader
            float cov = cArr.size() > 0 ? cArr.sum() / cArr.size() : 0.0
            string txt = "Delta Flow Profile [NeBlok]" + "\nNet Δ " + f_fmtDelta(netDel) + "\nPOC " + str.tostring(pocPrice, format.mintick) + "\nVA " + str.tostring(bot + vaDn * rowH, format.mintick) + " – " + str.tostring(bot + (vaUp + 1) * rowH, format.mintick) + "\nIntrabar coverage " + str.tostring(cov * 100, "#") + "% (" + ltfTF + ")"
            pLabels.push(label.new(xAxis, top + dy + rowH, txt, xloc = xloc.bar_index, style = label.style_label_down, color = #00000000, textcolor = chart.fg_color, size = size.small))
 
// ═════════════════════════════════════════ OUTPUTS & ALERTS ═════════════════════════════════════════
plot(barDelta, "Bar Delta", color = barDelta >= 0 ? bullCol : bearCol, display = display.data_window)
plot(z, "Delta Z-Score", display = display.data_window)
 
if bullSpike
    alert(syminfo.ticker + " | Bullish delta spike | Δ " + f_fmtDelta(barDelta) + " | Level " + str.tostring(anchor, format.mintick), alert.freq_once_per_bar_close)
if bearSpike
    alert(syminfo.ticker + " | Bearish delta spike | Δ " + f_fmtDelta(barDelta) + " | Level " + str.tostring(anchor, format.mintick), alert.freq_once_per_bar_close)
if bullLevelHit
    alert(syminfo.ticker + " | Price returned to a bullish imbalance level @ " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
if bearLevelHit
    alert(syminfo.ticker + " | Price returned to a bearish imbalance level @ " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)

← 返回列表