Tape + Delta Flow

Maximilianned · study · 487 行 · 点赞 109 · 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/
// © Maximilianned
 
//@version=6
// Tape + Delta Flow — Pine v6 rebuild
// Based on "Tape [LucF]" v9 (2021) — original concept & tape mechanics by LucF / PineCoders.
//
// WHAT'S NEW
//  • Pine v6. Correct clock: tape time uses an explicit timezone (default America/Mexico_City, or Exchange / Custom).
//  • Volume shown as whole contracts (no 8-decimal noise). Optional decimals + K/M compaction for crypto/stocks.
//  • Delta engine works on HISTORY too (intrabar lower-TF data), not just realtime ticks.
//  • Delta state machine: BUILDING / WANING / EMERGING (counter-flow) / TRENDLESS, with an "Action" line.
//  • Markers: build ▲▼ · emerging arrows · waning ✕ · CVD divergence "DIV" · absorption ■
//  • Large-print detection on the tape (auto = N× average print size), with bg highlight + optional alert.
//  • Non-repainting by default (signals on bar close).
 
indicator("Tape + Delta Flow", "Tape Δ", overlay = true)
 
// ═══════════════════════════ Constants ═══════════════════════════
int ST_FLAT        = 0
int ST_BULL_BUILD  = 1
int ST_BULL_WANE   = 2
int ST_BEAR_BUILD  = 3
int ST_BEAR_WANE   = 4
int ST_BULL_EMERGE = 5
int ST_BEAR_EMERGE = 6
 
// ═══════════════════════════ Inputs ═══════════════════════════
string GP_TAPE = "Tape (realtime)"
string i_layout    = input.string("Tape box", "Tape style", options = ["Tape box", "Scrolling ticker", "Off"], group = GP_TAPE, tooltip = "Tape box = classic vertical time & sales.\nScrolling ticker = one row of price + size; new prints push in from one side.")
int    i_tapeLines = input.int(15, "Tape box lines", minval = 1, maxval = 50, group = GP_TAPE)
bool   i_tapeTop   = input.string("Top", "New lines appear at", options = ["Top", "Bottom"], group = GP_TAPE) == "Top"
bool   i_showTime  = input.bool(true, "Show time", inline = "tz", group = GP_TAPE)
string i_tz        = input.string("America/Mexico_City", "", options = ["Exchange", "America/Mexico_City", "America/Chicago", "America/New_York", "Europe/London", "UTC", "Custom"], inline = "tz", group = GP_TAPE)
string i_tzCustom  = input.string("GMT-6", "Custom timezone", group = GP_TAPE, tooltip = "Used only when Timezone = Custom. IANA name (e.g. Asia/Singapore) or GMT offset (e.g. GMT-6).")
float  i_minPrint  = input.float(0.0, "Hide prints smaller than", minval = 0.0, group = GP_TAPE, tooltip = "Hidden prints still count in tape delta.")
float  i_bigMult   = input.float(4.0, "Large print = × avg print size", minval = 1.0, step = 0.5, group = GP_TAPE)
float  i_bigFixed  = input.float(0.0, "…or fixed large-print size (0 = auto)", minval = 0.0, group = GP_TAPE)
string i_tapePos   = input.string(position.bottom_left, "Tape position", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group = GP_TAPE)
 
string GP_TICK = "Scrolling ticker"
int    i_tickCells   = input.int(12, "Prints shown", minval = 3, maxval = 40, group = GP_TICK, tooltip = "~12-15 fit a normal-width chart at Normal text size.")
string i_tickPos     = input.string(position.bottom_center, "Position", options = [position.bottom_center, position.top_center, position.bottom_left, position.bottom_right, position.top_left, position.top_right], group = GP_TICK)
bool   i_tickFromR   = input.string("Right", "New prints enter from", options = ["Right", "Left"], group = GP_TICK) == "Right"
bool   i_tickStretch = input.bool(true, "Stretch across full chart width (equal boxes)", group = GP_TICK)
 
string GP_FMT = "Display"
string i_textSize = input.string(size.normal, "Text size", options = [size.tiny, size.small, size.normal, size.large], group = GP_FMT)
int    i_volDec   = input.int(0, "Volume decimals", minval = 0, maxval = 4, group = GP_FMT, tooltip = "0 for futures. Use 2-4 only for fractional-volume crypto.")
bool   i_compact  = input.bool(true, "Compact big numbers (K / M)", group = GP_FMT)
color  i_cBull    = input.color(#9eedc6, "Bull", inline = "c", group = GP_FMT)
color  i_cBear    = input.color(#ff004d, "Bear", inline = "c", group = GP_FMT)
color  i_cNeut    = input.color(#9598a1, "Neutral", inline = "c", group = GP_FMT)
color  i_cDiv     = input.color(#ffb300, "Absorb", inline = "c", group = GP_FMT)
color  i_cEmerge  = input.color(#ffffff, "Trend-change arrows", inline = "c2", group = GP_FMT)
color  i_cBullDiv = input.color(#10b2f0, "Bull DIV (below)", inline = "c2", group = GP_FMT)
color  i_cBearDiv = input.color(#f57f17, "Bear DIV (above)", inline = "c2", group = GP_FMT)
string i_bgStyle  = input.string("Solid", "Panel background", options = ["Solid", "Semi-transparent", "None"], inline = "bg", group = GP_FMT, tooltip = "Applies to tape box, ticker and dashboard.")
color  i_cPanelB  = input.color(#131722, "", inline = "bg", group = GP_FMT)
color  i_cPanel   = i_bgStyle == "Solid" ? color.new(i_cPanelB, 0) : i_bgStyle == "Semi-transparent" ? color.new(i_cPanelB, 40) : na
 
string GP_DELTA = "Delta engine"
string i_ltfSel   = input.string("Auto", "Intrabar timeframe", options = ["Auto", "1S", "5S", "10S", "15S", "30S", "1", "2", "3", "5", "10", "15", "30", "60"], group = GP_DELTA, tooltip = "Delta is built from lower-timeframe bars inside each chart bar. Smaller = finer but noisier and less history; larger = smoother, more history. Seconds (S) need a Premium+ plan. If the pick is larger than the chart timeframe, the chart timeframe is used.")
bool   i_useSec   = input.bool(false, "Auto uses seconds intrabars (Premium+)", group = GP_DELTA)
int    i_fastLen  = input.int(3, "Fast Δ pressure (EMA)", minval = 1, group = GP_DELTA)
int    i_slowLen  = input.int(12, "Slow Δ baseline (EMA)", minval = 2, group = GP_DELTA)
int    i_normLen  = input.int(50, "Normalization lookback", minval = 10, group = GP_DELTA, tooltip = "Pressure is expressed as a multiple of the average |bar delta| over this many bars — works on any instrument without retuning.")
int    i_rollLen  = input.int(10, "Rolling Δ window", minval = 2, group = GP_DELTA)
float  i_buildMin = input.float(0.40, "Building threshold (× avg |Δ|)", minval = 0.0, step = 0.05, group = GP_DELTA)
float  i_trendMin = input.float(0.15, "Trendless below (× avg |Δ|)", minval = 0.0, step = 0.05, group = GP_DELTA)
int    i_chopLen  = input.int(10, "Chop window (bars)", minval = 3, group = GP_DELTA)
float  i_chopFlip = input.float(0.60, "Chop if Δ sign-flip rate ≥", minval = 0.0, maxval = 1.0, step = 0.05, group = GP_DELTA)
string i_cvdReset = input.string("Session", "Session CVD reset", options = ["Session", "Never"], group = GP_DELTA)
 
string GP_SIG = "Signals"
bool   i_confirm    = input.bool(true, "Signals on bar close only (no repaint)", group = GP_SIG)
int    i_cool       = input.int(5, "Cooldown between same-side build signals", minval = 0, group = GP_SIG)
bool   i_showBuild  = input.bool(true, "▲▼ Delta building", group = GP_SIG)
bool   i_showEmerge = input.bool(true, "⇧⇩ Counter-flow emerging (early reversal)", group = GP_SIG)
bool   i_showWane   = input.bool(true, "✕ Delta waning (momentum fading)", group = GP_SIG)
bool   i_showDiv    = input.bool(true, "DIV  Price/CVD divergence", inline = "dv", group = GP_SIG)
int    i_divLen     = input.int(20, "lookback", minval = 5, inline = "dv", group = GP_SIG)
bool   i_showAbs    = input.bool(true, "■ Absorption bar", inline = "ab", group = GP_SIG)
float  i_absMult    = input.float(1.5, "|Δ| ≥ × avg", minval = 0.5, step = 0.1, inline = "ab", group = GP_SIG, tooltip = "Heavy delta one way while the bar closes the other way = aggressive orders absorbed by passive liquidity.")
bool   i_bgFlat     = input.bool(true, "Shade trendless zones", group = GP_SIG)
bool   i_barColor   = input.bool(true, "Color bars by delta state", group = GP_SIG)
bool   i_dash       = input.bool(true, "Show dashboard", inline = "db", group = GP_SIG)
string i_dashPos    = input.string(position.top_right, "", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], inline = "db", group = GP_SIG)
 
string GP_ALERT = "Alerts"
bool   i_alertBig = input.bool(false, "Alert on large tape prints", group = GP_ALERT, tooltip = "Delta-state alerts fire through 'Any alert() function call' or the individual alert conditions.")
 
// ═══════════════════════════ Helpers ═══════════════════════════
string TZ      = i_tz == "Exchange" ? syminfo.timezone : i_tz == "Custom" ? i_tzCustom : i_tz
string VOL_FMT = i_volDec == 0 ? "#,##0" : "#,##0." + str.repeat("0", i_volDec)
 
// Volume formatter: whole contracts by default, optional K/M compaction, optional sign.
f_vol(float v, bool signed) =>
    float  a    = math.abs(nz(v))
    string body = i_compact and a >= 1e6 ? str.tostring(a / 1e6, "0.00") + "M" : i_compact and a >= 1e5 ? str.tostring(a / 1e3, "0.0") + "K" : str.tostring(a, VOL_FMT)
    string sgn  = nz(v) > 0 ? (signed ? "+" : "") : nz(v) < 0 ? "−" : ""
    sgn + body
 
// Time left in the current bar.
f_countdown() =>
    int ms = time_close - timenow
    na(ms) or ms < 0 ? "—" : str.format_time(ms, ms >= 3600000 ? "HH:mm:ss" : "mm:ss", "UTC")
 
// Pick the intrabar timeframe.
f_ltf() =>
    int    s = timeframe.in_seconds()
    string r = i_ltfSel
    if i_ltfSel == "Auto"
        r := i_useSec ? (s <= 60 ? "1S" : s <= 300 ? "5S" : s <= 900 ? "15S" : s <= 3600 ? "30S" : s <= 14400 ? "1" : "5") : (s <= 3600 ? "1" : s <= 14400 ? "5" : s <= 86400 ? "15" : "60")
    if timeframe.in_seconds(r) > s
        r := timeframe.period
    r
 
// Bar delta from intrabars: polarity of each intrabar (close vs open, tick rule vs previous intrabar when flat).
f_intrabarDelta(array<float> o, array<float> c, array<float> v) =>
    var float lastSgn = 1.0
    var float lastC   = na
    float d = 0.0
    int   n = c.size()
    if n > 0
        for i = 0 to n - 1
            float oo = o.get(i)
            float cc = c.get(i)
            float sg = cc > oo ? 1.0 : cc < oo ? -1.0 : na(lastC) ? lastSgn : cc > lastC ? 1.0 : cc < lastC ? -1.0 : lastSgn
            d       += sg * nz(v.get(i))
            lastSgn := sg
            lastC   := cc
    [d, n]
 
f_stateName(int st) =>
    switch st
        1 => "▲▲ BULL BUILDING"
        2 => "▲ BULL WANING"
        3 => "▼▼ BEAR BUILDING"
        4 => "▼ BEAR WANING"
        5 => "⇧ BULL EMERGING"
        6 => "⇩ BEAR EMERGING"
        => "◆ TRENDLESS"
 
f_action(int st) =>
    switch st
        1 => "Longs favored · buy pullbacks, hold runners"
        2 => "Buyers fading · tighten longs, no new longs"
        3 => "Shorts favored · sell rallies, hold runners"
        4 => "Sellers fading · tighten shorts, no new shorts"
        5 => "Buyers hitting into down-flow · watch long reversal"
        6 => "Sellers hitting into up-flow · watch short reversal"
        => "No flow edge · stand aside or fade range edges"
 
f_stateColor(int st) =>
    switch st
        1 => i_cBull
        2 => color.new(i_cBull, 45)
        3 => i_cBear
        4 => color.new(i_cBear, 45)
        5 => color.new(i_cBull, 20)
        6 => color.new(i_cBear, 20)
        => i_cNeut
 
f_row(table t, int r, string k, string v, color c) =>
    table.cell(t, 0, r, k, bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize, text_halign = text.align_left)
    table.cell(t, 1, r, v, bgcolor = i_cPanel, text_color = c, text_size = i_textSize, text_halign = text.align_right)
 
// Large-print highlight: opaque blend on a solid panel, translucent tint otherwise.
f_tint(color c) =>
    na(i_cPanel) or i_bgStyle != "Solid" ? color.new(c, 72) : color.from_gradient(0.28, 0.0, 1.0, i_cPanel, c)
 
f_add(string msg, bool cond, string txt) =>
    cond ? msg + (msg != "" ? " + " : "") + txt : msg
 
// ═══════════════════════════ Delta engine ═══════════════════════════
float cumVol = ta.cum(nz(volume))
if barstate.islast and cumVol == 0
    runtime.error("No volume data for this symbol — delta cannot be calculated.")
 
string LTF = f_ltf()
[ltfO, ltfC, ltfV] = request.security_lower_tf(syminfo.tickerid, LTF, [open, close, volume])
[ibDelta, ibCount] = f_intrabarDelta(ltfO, ltfC, ltfV)
 
// Fallback when no intrabar data (beyond intrabar history limit): bar polarity × volume.
float fbSign = close > open ? 1.0 : close < open ? -1.0 : close > nz(close[1]) ? 1.0 : close < nz(close[1]) ? -1.0 : 0.0
float d      = ibCount > 0 ? ibDelta : fbSign * nz(volume)
 
float avgAbs = ta.sma(math.abs(d), i_normLen)
float fast   = ta.ema(d, i_fastLen)
float slow   = ta.ema(d, i_slowLen)
float fastN  = nz(avgAbs) > 0 ? nz(fast / avgAbs) : 0.0
float slowN  = nz(avgAbs) > 0 ? nz(slow / avgAbs) : 0.0
float dN     = nz(avgAbs) > 0 ? d / avgAbs : 0.0
float roll   = math.sum(d, i_rollLen)
 
float flip     = (d > 0 and nz(d[1]) < 0) or (d < 0 and nz(d[1]) > 0) ? 1.0 : 0.0
float flipRate = math.sum(flip, i_chopLen) / i_chopLen
 
var float cvdRun  = 0.0
var float cvdSess = 0.0
if i_cvdReset == "Session" and session.isfirstbar
    cvdSess := 0.0
cvdRun  += d
cvdSess += d
 
// ── State machine
bool weak   = math.abs(slowN) < i_trendMin and math.abs(fastN) < i_buildMin
bool choppy = flipRate >= i_chopFlip and math.abs(fastN) < i_buildMin
int  state  = ST_FLAT
if not (weak or choppy)
    // Out of balance with no established baseline, a strong fast push defines the bias.
    float bias     = math.abs(slowN) < i_trendMin ? math.sign(fastN) : math.sign(slowN)
    bool  strong   = math.abs(fastN) >= i_buildMin
    bool  sameSide = fastN * bias > 0
    if bias != 0
        if sameSide
            state := strong and math.abs(fastN) >= math.abs(slowN) ? (bias > 0 ? ST_BULL_BUILD : ST_BEAR_BUILD) : (bias > 0 ? ST_BULL_WANE : ST_BEAR_WANE)
        else
            state := strong ? (bias > 0 ? ST_BEAR_EMERGE : ST_BULL_EMERGE) : (bias > 0 ? ST_BULL_WANE : ST_BEAR_WANE)
 
int prev = nz(state[1], -1)
var int barsIn = 0
barsIn := state == prev ? barsIn + 1 : 1
 
// ═══════════════════════════ Signals ═══════════════════════════
bool conf = not i_confirm or barstate.isconfirmed
 
var int lastBuildDir = 0
var int lastBuildBar = na
bool okBull = lastBuildDir != 1  or na(lastBuildBar) or bar_index - lastBuildBar > i_cool
bool okBear = lastBuildDir != -1 or na(lastBuildBar) or bar_index - lastBuildBar > i_cool
 
bool sigBullBuild  = conf and state == ST_BULL_BUILD and prev != ST_BULL_BUILD and okBull
bool sigBearBuild  = conf and state == ST_BEAR_BUILD and prev != ST_BEAR_BUILD and okBear
bool sigBullWane   = conf and state == ST_BULL_WANE  and prev == ST_BULL_BUILD
bool sigBearWane   = conf and state == ST_BEAR_WANE  and prev == ST_BEAR_BUILD
bool sigBullEmerge = conf and state == ST_BULL_EMERGE and prev != ST_BULL_EMERGE
bool sigBearEmerge = conf and state == ST_BEAR_EMERGE and prev != ST_BEAR_EMERGE
bool sigFlat       = conf and state == ST_FLAT and prev != ST_FLAT and prev != -1
 
if sigBullBuild
    lastBuildDir := 1
    lastBuildBar := bar_index
if sigBearBuild
    lastBuildDir := -1
    lastBuildBar := bar_index
 
// Price/CVD divergence: price breaks the N-bar extreme, CVD does not.
float hh    = ta.highest(high, i_divLen)[1]
float ll    = ta.lowest(low, i_divLen)[1]
float cvdHH = ta.highest(cvdRun, i_divLen)[1]
float cvdLL = ta.lowest(cvdRun, i_divLen)[1]
var int lastBearDiv = na
var int lastBullDiv = na
bool sigBearDiv = conf and high > hh and cvdRun < cvdHH and (na(lastBearDiv) or bar_index - lastBearDiv >= i_divLen / 2)
bool sigBullDiv = conf and low  < ll and cvdRun > cvdLL and (na(lastBullDiv) or bar_index - lastBullDiv >= i_divLen / 2)
if sigBearDiv
    lastBearDiv := bar_index
if sigBullDiv
    lastBullDiv := bar_index
 
// Absorption: heavy delta one way, bar closes the other way.
bool sigBearAbs = conf and dN >=  i_absMult and close < open   // buyers absorbed
bool sigBullAbs = conf and dN <= -i_absMult and close > open   // sellers absorbed
 
// Last-signal memory for the dashboard (later lines win = higher priority).
var string lastSigTxt = "—"
var int    lastSigBar = na
var color  lastSigCol = i_cNeut
if sigBullAbs
    lastSigTxt := "Bull absorption", lastSigBar := bar_index, lastSigCol := i_cBull
if sigBearAbs
    lastSigTxt := "Bear absorption", lastSigBar := bar_index, lastSigCol := i_cBear
if sigBullDiv
    lastSigTxt := "Bull CVD div", lastSigBar := bar_index, lastSigCol := i_cBullDiv
if sigBearDiv
    lastSigTxt := "Bear CVD div", lastSigBar := bar_index, lastSigCol := i_cBearDiv
if sigBullWane
    lastSigTxt := "Bull waning", lastSigBar := bar_index, lastSigCol := color.new(i_cBull, 45)
if sigBearWane
    lastSigTxt := "Bear waning", lastSigBar := bar_index, lastSigCol := color.new(i_cBear, 45)
if sigBullEmerge
    lastSigTxt := "Bull emerging ⇧", lastSigBar := bar_index, lastSigCol := i_cEmerge
if sigBearEmerge
    lastSigTxt := "Bear emerging ⇩", lastSigBar := bar_index, lastSigCol := i_cEmerge
if sigBullBuild
    lastSigTxt := "Bull building", lastSigBar := bar_index, lastSigCol := i_cBull
if sigBearBuild
    lastSigTxt := "Bear building", lastSigBar := bar_index, lastSigCol := i_cBear
 
// ═══════════════════════════ Visuals ═══════════════════════════
plotshape(i_showBuild  and sigBullBuild,  "Bull Δ building",  shape.triangleup,   location.belowbar, i_cBull, size = size.tiny)
plotshape(i_showBuild  and sigBearBuild,  "Bear Δ building",  shape.triangledown, location.abovebar, i_cBear, size = size.tiny)
plotshape(i_showEmerge and sigBullEmerge, "Bull Δ emerging",  shape.arrowup,      location.belowbar, i_cEmerge, size = size.tiny)
plotshape(i_showEmerge and sigBearEmerge, "Bear Δ emerging",  shape.arrowdown,    location.abovebar, i_cEmerge, size = size.tiny)
plotshape(i_showWane   and sigBullWane,   "Bull Δ waning",    shape.xcross,       location.abovebar, color.new(i_cBull, 20), size = size.tiny)
plotshape(i_showWane   and sigBearWane,   "Bear Δ waning",    shape.xcross,       location.belowbar, color.new(i_cBear, 20), size = size.tiny)
plotshape(i_showDiv    and sigBearDiv,    "Bear CVD div",     shape.labeldown,    location.abovebar, i_cBearDiv, text = "DIV", textcolor = color.black, size = size.tiny)
plotshape(i_showDiv    and sigBullDiv,    "Bull CVD div",     shape.labelup,      location.belowbar, i_cBullDiv, text = "DIV", textcolor = color.black, size = size.tiny)
plotshape(i_showAbs    and sigBearAbs,    "Bear absorption",  shape.square,       location.abovebar, i_cDiv,  size = size.tiny)
plotshape(i_showAbs    and sigBullAbs,    "Bull absorption",  shape.square,       location.belowbar, i_cDiv,  size = size.tiny)
 
bgcolor(i_bgFlat and state == ST_FLAT ? color.new(i_cNeut, 90) : na, title = "Trendless zone")
barcolor(i_barColor ? f_stateColor(state) : na, title = "Delta state bars")
 
plot(d,       "Bar Δ",          display = display.data_window)
plot(fastN,   "Δ pressure ×avg", display = display.data_window)
plot(slowN,   "Δ baseline ×avg", display = display.data_window)
plot(roll,    "Rolling Δ",      display = display.data_window)
plot(cvdSess, "Session CVD",    display = display.data_window)
plot(state,   "Δ state (0-6)",  display = display.data_window)
 
// ═══════════════════════════ Tape (realtime) ═══════════════════════════
varip array<string> tpTime  = array.new<string>()
varip array<string> tpPrice = array.new<string>()
varip array<string> tpSize  = array.new<string>()
varip array<bool>   tpUp    = array.new<bool>()
varip array<bool>   tpBig   = array.new<bool>()
varip float lastPrice = na
varip float lastVol   = 0.0
varip bool  lastUp    = true
varip float tapeDelta = 0.0
varip float avgPrint  = na
varip int   printCnt  = 0
varip int   bigBuys   = 0
varip int   bigSells  = 0
varip bool  partial   = true
 
bool  TAPE_ON   = i_layout != "Off"
bool  TICKER    = i_layout == "Scrolling ticker"
int   CAP       = TICKER ? i_tickCells : i_tapeLines
// Ticker geometry: one summary cell (double width) + CAP print cells.
float TICK_W    = i_tickStretch ? 100.0 / (CAP + 2) : 0.0
int   SUM_COL   = i_tickFromR ? CAP : 0
 
var table tape   = table.new(i_tapePos, 3, i_tapeLines + 2, bgcolor = i_cPanel, border_width = 0)
var table ticker = table.new(i_tickPos, i_tickCells + 1, 1, bgcolor = i_cPanel, border_width = 1, border_color = color.new(i_cNeut, 82))
 
if barstate.isrealtime
    bool first = na(lastPrice)
    if first
        // Seed with the bar's existing volume so the first line isn't the whole bar's volume.
        lastVol := nz(volume)
        partial := true
        lastUp  := close >= open
    else if barstate.isnew
        lastVol   := 0.0
        tapeDelta := 0.0
        bigBuys   := 0
        bigSells  := 0
        partial   := false
 
    float newVol = math.max(nz(volume) - lastVol, 0.0)
    bool  up     = first ? lastUp : close > lastPrice ? true : close < lastPrice ? false : lastUp
    tapeDelta += up ? newVol : -newVol
 
    bool big = false
    if newVol > 0
        float thr = i_bigFixed > 0 ? i_bigFixed : i_bigMult * nz(avgPrint, newVol)
        big := (i_bigFixed > 0 or printCnt >= 20) and newVol >= thr
        printCnt += 1
        avgPrint := na(avgPrint) ? newVol : avgPrint + (newVol - avgPrint) * 0.02
        if big
            if up
                bigBuys += 1
            else
                bigSells += 1
            if i_alertBig
                alert(syminfo.ticker + " LARGE " + (up ? "BUY " : "SELL ") + f_vol(newVol, false) + " @ " + str.tostring(close, format.mintick), alert.freq_all)
 
        if TAPE_ON and newVol >= i_minPrint
            string arrow = first ? "" : close > lastPrice ? " ↑" : close < lastPrice ? " ↓" : ""
            string sT = str.format_time(timenow, "HH:mm:ss", TZ)
            string sP = str.tostring(close, format.mintick) + arrow
            string sV = (barstate.isnew and not first ? "↻ " : "") + (big ? "◆ " : "") + f_vol(newVol, false)
            // Arrays are always newest-first; layouts decide how to draw them.
            tpTime.unshift(sT), tpPrice.unshift(sP), tpSize.unshift(sV), tpUp.unshift(up), tpBig.unshift(big)
            while tpTime.size() > CAP
                tpTime.pop(), tpPrice.pop(), tpSize.pop(), tpUp.pop(), tpBig.pop()
 
    // Shared footer/summary values: bar move in ticks, live tape delta (÷ = price/delta divergence, ~ = partial bar)
    float mv    = close - open
    int   ticks = int(math.round(mv / syminfo.mintick))
    bool  dv    = mv != 0 and tapeDelta != 0 and math.sign(mv) != math.sign(tapeDelta)
    color mvCol = mv > 0 ? i_cBull : mv < 0 ? i_cBear : i_cNeut
    color tdCol = dv ? i_cDiv : tapeDelta > 0 ? i_cBull : tapeDelta < 0 ? i_cBear : i_cNeut
    string sTicks = (ticks > 0 ? "+" : "") + str.tostring(ticks) + "t"
    string sTD    = "Δ " + (partial ? "~" : "") + f_vol(tapeDelta, true) + (dv ? " ÷" : "")
 
    if TICKER
        // ── Scrolling ticker: one row, newest print next to the summary cell.
        table.clear(ticker, 0, 0, i_tickCells, 0)
        int n = tpTime.size()
        for k = 0 to CAP - 1
            int col = i_tickFromR ? CAP - 1 - k : k + 1
            if k < n
                bool  u  = tpUp.get(k)
                color tc = u ? i_cBull : i_cBear
                color bg = tpBig.get(k) ? f_tint(tc) : i_cPanel
                table.cell(ticker, col, 0, tpPrice.get(k) + "  " + tpSize.get(k), width = TICK_W, text_color = tc, bgcolor = bg, text_size = i_textSize)
            else
                table.cell(ticker, col, 0, "", bgcolor = i_cPanel, width = TICK_W, text_size = i_textSize)
        table.cell(ticker, SUM_COL, 0, "⏱ " + f_countdown() + "   " + sTicks + "   " + sTD, bgcolor = i_cPanel, width = TICK_W * 2, text_color = tdCol, text_size = i_textSize)
 
    else if TAPE_ON
        // ── Classic tape box.
        table.clear(tape, 0, 0, 2, i_tapeLines + 1)
        if i_showTime
            table.cell(tape, 0, 0, "TIME", bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize)
        table.cell(tape, 1, 0, "PRICE", bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize)
        table.cell(tape, 2, 0, "SIZE", bgcolor = i_cPanel,  text_color = i_cNeut, text_size = i_textSize)
        int n = tpTime.size()
        if n > 0
            for i = 0 to n - 1
                int   row = i_tapeTop ? i + 1 : n - i
                bool  u   = tpUp.get(i)
                color tc  = u ? i_cBull : i_cBear
                color bg  = tpBig.get(i) ? f_tint(tc) : i_cPanel
                if i_showTime
                    table.cell(tape, 0, row, tpTime.get(i), bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize)
                table.cell(tape, 1, row, tpPrice.get(i), text_color = tc, bgcolor = bg, text_size = i_textSize, text_halign = text.align_left)
                table.cell(tape, 2, row, tpSize.get(i),  text_color = tc, bgcolor = bg, text_size = i_textSize, text_halign = text.align_right)
        // Footer: time left in bar · bar move in ticks · live tape delta
        if i_showTime
            table.cell(tape, 0, n + 1, "⏱ " + f_countdown(), bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize)
        table.cell(tape, 1, n + 1, sTicks, bgcolor = i_cPanel, text_color = mvCol, text_size = i_textSize, text_halign = text.align_left)
        table.cell(tape, 2, n + 1, sTD, bgcolor = i_cPanel, text_color = tdCol, text_size = i_textSize, text_halign = text.align_right)
 
    lastPrice := close
    lastVol   := nz(volume)
    lastUp    := up
 
// ═══════════════════════════ Dashboard ═══════════════════════════
var table dash = table.new(i_dashPos, 2, 11, bgcolor = i_cPanel, border_width = 1, border_color = color.new(i_cNeut, 85))
if i_dash and barstate.islast
    color  sc     = f_stateColor(state)
    string accel  = math.abs(fastN) > math.abs(nz(fastN[1])) ? " · accelerating" : " · decelerating"
    string srcTxt = ibCount > 0 ? LTF + " intrabars" : "bar polarity"
    table.cell(dash, 0, 0, "DELTA FLOW", bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize, text_halign = text.align_left)
    table.cell(dash, 1, 0, syminfo.ticker + " · " + srcTxt, bgcolor = i_cPanel, text_color = i_cNeut, text_size = i_textSize, text_halign = text.align_right)
    f_row(dash, 1, "State",        f_stateName(state), sc)
    f_row(dash, 2, "Action",       f_action(state), sc)
    f_row(dash, 3, "Pressure",     (fastN >= 0 ? "+" : "") + str.tostring(fastN, "0.00") + "× avg" + accel, fastN > 0 ? i_cBull : fastN < 0 ? i_cBear : i_cNeut)
    f_row(dash, 4, "Bar Δ",        f_vol(d, true), d > 0 ? i_cBull : d < 0 ? i_cBear : i_cNeut)
    f_row(dash, 5, "Rolling Δ (" + str.tostring(i_rollLen) + ")", f_vol(roll, true), roll > 0 ? i_cBull : roll < 0 ? i_cBear : i_cNeut)
    f_row(dash, 6, "Session CVD",  f_vol(cvdSess, true), cvdSess > 0 ? i_cBull : cvdSess < 0 ? i_cBear : i_cNeut)
    f_row(dash, 7, "In state",     str.tostring(barsIn) + (barsIn == 1 ? " bar" : " bars"), i_cNeut)
    f_row(dash, 8, "Last signal",  na(lastSigBar) ? "—" : lastSigTxt + " · " + str.tostring(bar_index - lastSigBar) + " bars ago", lastSigCol)
    if barstate.isrealtime
        f_row(dash, 9,  "Tape Δ (live)", (partial ? "~" : "") + f_vol(tapeDelta, true) + " · ⏱ " + f_countdown(), tapeDelta > 0 ? i_cBull : tapeDelta < 0 ? i_cBear : i_cNeut)
        f_row(dash, 10, "Large prints B/S", str.tostring(bigBuys) + " / " + str.tostring(bigSells), bigBuys > bigSells ? i_cBull : bigSells > bigBuys ? i_cBear : i_cNeut)
    else
        f_row(dash, 9,  "Tape Δ (live)", "market closed", i_cNeut)
        f_row(dash, 10, "Large prints B/S", "—", i_cNeut)
 
// ═══════════════════════════ Alerts ═══════════════════════════
string evTxt = ""
evTxt := f_add(evTxt, sigBullBuild,  "BULL Δ BUILDING")
evTxt := f_add(evTxt, sigBearBuild,  "BEAR Δ BUILDING")
evTxt := f_add(evTxt, sigBullWane,   "BULL Δ WANING")
evTxt := f_add(evTxt, sigBearWane,   "BEAR Δ WANING")
evTxt := f_add(evTxt, sigBullEmerge, "BULL Δ EMERGING")
evTxt := f_add(evTxt, sigBearEmerge, "BEAR Δ EMERGING")
evTxt := f_add(evTxt, sigFlat,       "Δ TRENDLESS")
evTxt := f_add(evTxt, sigBullDiv,    "BULL CVD DIV")
evTxt := f_add(evTxt, sigBearDiv,    "BEAR CVD DIV")
evTxt := f_add(evTxt, sigBullAbs,    "BULL ABSORPTION")
evTxt := f_add(evTxt, sigBearAbs,    "BEAR ABSORPTION")
if evTxt != ""
    string msg = syminfo.ticker + " " + timeframe.period + " | " + evTxt + " | " + f_action(state) + " | Bar Δ " + f_vol(d, true) + " | CVD " + f_vol(cvdSess, true) + " | " + str.tostring(close, format.mintick)
    if i_confirm
        alert(msg, alert.freq_once_per_bar_close)
    else
        alert(msg, alert.freq_once_per_bar)
 
alertcondition(sigBullBuild,  "Bull Δ building",  "{{ticker}} {{interval}}: Bull delta BUILDING @ {{close}}")
alertcondition(sigBearBuild,  "Bear Δ building",  "{{ticker}} {{interval}}: Bear delta BUILDING @ {{close}}")
alertcondition(sigBullWane,   "Bull Δ waning",    "{{ticker}} {{interval}}: Bull delta WANING — tighten longs @ {{close}}")
alertcondition(sigBearWane,   "Bear Δ waning",    "{{ticker}} {{interval}}: Bear delta WANING — tighten shorts @ {{close}}")
alertcondition(sigBullEmerge, "Bull Δ emerging",  "{{ticker}} {{interval}}: Buyers emerging vs down-flow @ {{close}}")
alertcondition(sigBearEmerge, "Bear Δ emerging",  "{{ticker}} {{interval}}: Sellers emerging vs up-flow @ {{close}}")
alertcondition(sigFlat,       "Δ trendless",      "{{ticker}} {{interval}}: Delta TRENDLESS — no flow edge @ {{close}}")
alertcondition(sigBullDiv,    "Bull CVD div",     "{{ticker}} {{interval}}: Bullish price/CVD divergence @ {{close}}")
alertcondition(sigBearDiv,    "Bear CVD div",     "{{ticker}} {{interval}}: Bearish price/CVD divergence @ {{close}}")
alertcondition(sigBullAbs,    "Bull absorption",  "{{ticker}} {{interval}}: Sellers absorbed (bull) @ {{close}}")
alertcondition(sigBearAbs,    "Bear absorption",  "{{ticker}} {{interval}}: Buyers absorbed (bear) @ {{close}}")

← 返回列表