Flow Control: Volume, CVD & Delta [Artio]

Artio_Scalping_Life · study · 1003 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// FLOW CONTROL v3.4 [Artio] — bilingual public edition of ARTIO FLOW v3.3.
// EN default / RU optional. Core market calculations and thresholds inherited from v3.3.
// This script measures estimated signed lower-candle volume, not actual taker aggressor flags.
// Its control state is descriptive, not a trading or execution signal.
// Minute chart is the default decision horizon; 12 seconds remain optional.
// CONTROL = observed price result + estimated delta over the SAME completed prefix.
// OI/funding are labelled context, NEVER independent directional votes.
// Price and CVD divergence endpoints are drawn together; confirmation is NOT backdated.
// Funding adapter is OFF until an external Funding Rate plot is explicitly selected.
// Full native-volume history + estimated candle-side colors + visible CVD, one instance.
// Pulse 1S and CVD source are independent; unavailable 12s never deletes candle history.
// CVD uses one fixed data timeframe for the entire run. No per-bar source stitching.
// Volume display may use log2(1+RVOL). CVD is affine-scaled ONCE for the visible viewport.
// No clipping, no per-bar CVD normalization, no artificial buy/sell from the chart candle.
// All analytical values are calculated BEFORE and independently of viewport decoration.
indicator("Flow Control: Volume, CVD & Delta [Artio]", shorttitle="Flow Control [Artio]", overlay=false, max_bars_back=3000, max_labels_count=150, max_lines_count=150, max_polylines_count=100, precision=2)
 
// 00 — A small number of meaningful controls.
string G0 = "00 · General / Основное"
string uiLanguage = input.string("English", "Language / Язык", options=["English", "Русский"], group=G0, tooltip="English by default; select Русский to translate the dashboard, states, explanations and LIVE alerts. Pine requires static settings and plot titles. / По умолчанию английский; русский переводит панель, статусы и уведомления.")
string screen = input.string("DESK · VOL + CVD", "Display / Экран", options=["DESK · VOL + CVD", "VOLUME · history", "CVD · native line", "NOW · window volume", "BAR · candle volume"], group=G0, tooltip="Default combined layout: full candle-volume history, CVD lane and compact dashboard. Column height measures relative volume; color uses estimated lower-timeframe direction. Missing direction is neutral, never invented.")
string preset = input.string("AUTO", "Profile / Профиль", options=["AUTO", "SCALPER", "INTRADAY", "SWING", "MACRO"], group=G0)
int pulseSecInput = input.int(12, "Scalper window, seconds / Окно, с", minval=5, maxval=30, group=G0)
int visibleBars = input.int(300, "NOW view: recent chart bars", minval=30, maxval=500, group=G0, tooltip="Limits computation-intensive NOW-window calculations only; does not truncate ordinary volume history or CVD. Second-based observations require accessible intrabar history.")
bool allCvdPeriods = input.bool(true, "CVD: show previous periods", group=G0, tooltip="Displays available historical CVD segments. Resets and data gaps break the line; no missing delta is fabricated.")
bool showCvdBand = input.bool(true, "CVD within combined pane", group=G0)
bool showExplanation = input.bool(false, "Detailed explanation / Разбор", group=G0)
bool showHelp = input.bool(false, "Show dashboard guide", group=G0)
 
string G1 = "01 · Data / Данные"
string cvdPrecision = input.string("AUTO · balanced history", "Delta / CVD source precision", options=["AUTO · balanced history", "PRECISE · 1S scalping", "HISTORY · 15S scalping"], group=G1, tooltip="AUTO uses 5S on 1–5m charts and 1S on seconds charts. CVD has one fixed intrabar source; optional 12s pulse is independently sampled at 1S. Finer resolution reduces historical depth.")
string dashHorizon = input.string("Chart candle", "Dashboard observation horizon", options=["AUTO · window / candle", "Current window only", "Chart candle"], group=G1, tooltip="Default is chart candle. On a developing bar, use completed intrabar prefixes and compare equivalent elapsed portions of previous bars. Optional short window is separate from cumulative CVD and FLOW-3.")
int intrabarBudget = input.int(100000, "Lower-timeframe intrabar budget", minval=20000, maxval=200000, step=10000, group=G1)
float neutralDelta = input.float(10.0, "Delta neutrality threshold, ±%", minval=5, maxval=40, step=1, group=G1, tooltip="Interpretation threshold only; this is not a trading probability. Near-zero delta does not make the volume small.")
string anchorInput = input.string("AUTO", "CVD reset / Сброс", options=["AUTO", "UTC day", "UTC week", "UTC month", "No calendar reset"], group=G1, tooltip="AUTO does not calendar-reset CVD on higher timeframes. Manual reset occurs at the first chart bar of the new period, not intrabar.")
bool diagnostics = input.bool(false, "Additional diagnostics", group=G1)
 
string G2 = "02 · Appearance / Вид"
string ribbonPosition = input.string(position.top_left, "Dashboard position", options=[position.top_left, position.top_center, position.top_right, position.bottom_left, position.bottom_center, position.bottom_right], group=G2)
string fontInput = input.string("Normal", "Text size", options=["Compact", "Normal", "Large"], group=G2)
bool showRibbon = input.bool(true, "Show compact dashboard", group=G2)
string volumeScale = input.string("LOG · preserve spikes", "Volume scale", options=["LOG · preserve spikes", "Linear"], group=G2, tooltip="LOG visualizes log2(1+RVOL) without clipping. Grid labels are genuine multiples; numerical data and CVD remain untransformed.")
color cCvd = input.color(#67E8F9, "CVD line color", group=G2)
bool latestTag = input.bool(true, "Label last value", group=G2)
bool showGrid = input.bool(true, "Show 1× baseline and multiples", group=G2)
bool showDivergence = input.bool(true, "Divergence: price/CVD lines and labels", group=G2, tooltip="Connects matched price and CVD swing endpoints; DIV marker is placed on the confirmation bar. Divergence does not imply a certain reversal.")
color cLow = input.color(#64748B, "Low volume color", group=G2)
color cNormal = input.color(#94A3B8, "Normal volume color", group=G2)
color cHigh = input.color(#FACC15, "High volume color", group=G2)
color cVeryHigh = input.color(#FB923C, "Very high volume color", group=G2)
color cExtreme = input.color(#C084FC, "Spike color", group=G2)
color cBuy = input.color(#34D399, "Estimated buying pressure color", group=G2)
color cSell = input.color(#FB7185, "Estimated selling pressure color", group=G2)
color panelBg = input.color(#111827, "Dashboard background", group=G2)
color panelFg = input.color(#F8FAFC, "Dashboard text", group=G2)
 
string G3 = "03 · Alerts / Уведомления"
bool liveAlerts = input.bool(false, "LIVE: alert on new completed-window state", group=G3, tooltip="Window is complete, but host chart candle may still be open. Observational alert only, not an entry signal. Feed corrections and reloads can alter history.")
 
 
string GC = "04 · CONTROL / Price response"
float controlMoveATR = input.float(0.10, "Minimum price move, previous ATR", minval=0.02, maxval=0.5, step=0.01, group=GC, tooltip="A descriptive threshold, not optimized for trading. Strong estimated delta with little price progress indicates conflict, not a countertrade instruction.")
int controlMinSamples = input.int(2, "LIVE: minimum completed intrabars", minval=1, maxval=6, group=GC, tooltip="On a minute chart AUTO uses 5S. Two completed lower bars typically mean about 10 seconds until the first directional status; incomplete data does not generate a direction.")
bool controlClosed = input.bool(false, "Status tile: closed candles only", group=GC, tooltip="Status tile uses the previous completed chart candle, including matching VOL, estimated delta and price movement. CVD and OI continue their normal mode.")
bool showPriceDivergence = input.bool(true, "DIV: also draw on price chart", group=GC)
bool showCandidate = input.bool(true, "DIV?: provisional LIVE divergence", group=GC, tooltip="Dashed line and question mark: observed LIVE price exceeds the previous confirmed extreme but CVD disagrees. Provisional and can disappear before close.")
int divergenceKeep = input.int(3, "Keep recent confirmed divergences", minval=1, maxval=5, group=GC)
int divergenceTTL = input.int(12, "DIV tile notification lifetime (bars)", minval=1, maxval=80, group=GC, tooltip="Historical DIV remains visible, but tile badge ages out. A divergence cannot reverse the tile direction by itself.")
bool showCvdNumbers = input.bool(false, "Show native CVD scale endpoints", group=GC)
float tileWidth = input.float(12.0, "Status tile width, % of pane", minval=9, maxval=24, step=0.5, group=GC, tooltip="Pine sizes are percentages of pane, not pixels. Around 12% works on a wide pane; narrower panes may need 16–18%.")
float rowHeight = input.float(11.0, "Dashboard row height, % of pane", minval=7, maxval=16, step=0.5, group=GC)
 
string GO = "05 · Open Interest / OI"
bool useOI = input.bool(true, "Show Open Interest", group=GO)
string oiOverride = input.string("", "OI ticker override (blank = chart _OI)", group=GO, tooltip="Defaults to <exchange:contract>_OI. Never replaces unavailable OI with another exchange. Volume and CVD can work independently.")
string oiUnits = input.string("native", "OI feed units (label only)", group=GO, tooltip="Label only, not a conversion. Verify the feed units; do not assume USD notional. Notional OI can also change as price moves.")
int oiFreshMinutes = input.int(5, "Max OI source-bar age, minutes", minval=2, maxval=60, group=GO, tooltip="Checks the source BAR timestamp, not the actual timestamp of an exchange OI change. OI is slower context, not a 12-second flow feed.")
 
string GF = "06 · Funding / External feed"
bool useFunding = input.bool(false, "I selected a genuine Funding Rate plot", group=GF, tooltip="First add TradingView’s Funding Rate indicator for the matching contract, select its numeric plot below and enable the adapter. OFF by default; chart close is never treated as funding automatically.")
float fundingSource = input.source(close, "External Funding Rate plot", group=GF)
string fundingScale = input.string("Percent: 0.01 = 0.01%", "External funding units", options=["Percent: 0.01 = 0.01%", "Fraction: 0.0001 = 0.01%"], group=GF)
float fundingHours = input.float(0, "Funding period, hours (0 = unverified)", minval=0, maxval=24, step=0.5, group=GF, tooltip="Settlement interval depends on the instrument; never assume 8h. Verify the funding source, scale and period after changing markets. No automatic 8h normalization.")
float fundingWarn = input.float(0.05, "Funding |rate| warning threshold, %", minval=0.001, maxval=1.0, step=0.005, group=GF, tooltip="Cost warning only, never a reversal or directional signal. Highlighting requires a verified period.")
 
// Dual-language runtime strings. Input titles, plot names and alertcondition titles remain constant as required by Pine v6.
f_t(string en, string ru) =>
    uiLanguage == "Русский" ? ru : en
 
// Helpers. Reference samples never contain their own observation.
f_num(float x) =>
    na(x) ? "—" : str.tostring(x, "#.##")
f_signed(float x) =>
    na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.##")
f_price_pct(float x) =>
    na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.####")
f_med(array<float> a) =>
    array.size(a) > 0 ? array.median(a) : na
f_clip(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
f_grade(float r) =>
    na(r) ? f_t("NO BASELINE", "НЕТ ОЦЕНКИ") : r < 0.75 ? f_t("LOW", "МАЛО") : r < 1.5 ? f_t("NORMAL", "ОБЫЧНО") : r < 3.0 ? f_t("HIGH", "МНОГО") : r < 6.0 ? f_t("VERY HIGH", "ОЧЕНЬ МНОГО") : f_t("SPIKE", "ВСПЛЕСК")
f_color(float r) =>
    na(r) ? cLow : r < 0.75 ? cLow : r < 1.5 ? cNormal : r < 3.0 ? cHigh : r < 6.0 ? cVeryHigh : cExtreme
f_duration(int sec) =>
    sec < 60 ? str.tostring(sec) + f_t("s", "с") : sec < 3600 ? str.tostring(sec / 60.0, "#.##") + f_t("m", "м") : sec < 86400 ? str.tostring(sec / 3600.0, "#.##") + f_t("h", "ч") : str.tostring(sec / 86400.0, "#.##") + f_t("d", "д")
f_delta() =>
    var int side = 0
    side := close > open ? 1 : close < open ? -1 : close > close[1] ? 1 : close < close[1] ? -1 : side
    not na(volume) and volume >= 0 ? volume * side : na
f_price_dir(float difference, float tolerance) =>
    na(difference) or na(tolerance) ? 0 : difference > tolerance ? 1 : difference < -tolerance ? -1 : 0
f_story(float r, float dp, int direction) =>
    string s = f_t("No comparable data", "Нет сопоставимых данных")
    if not na(r)
        if na(dp)
            s := f_t("Volume known; reliable estimated delta unavailable", "Объём известен; надёжной оценки дельты нет")
        else if dp >= neutralDelta
            s := direction > 0 ? f_t("BUY PRESSURE & PRICE ↑ · aligned", "ПОКУПКИ И ЦЕНА ↑ · движение согласовано") : direction < 0 ? f_t("BUY PRESSURE, PRICE ↓ · conflict", "ПОКУПКИ, НО ЦЕНА ↓ · конфликт") : f_t("BUY PRESSURE · no upside progress", "ПОКУПКИ ЕСТЬ, РОСТА НЕТ")
        else if dp <= -neutralDelta
            s := direction < 0 ? f_t("SELL PRESSURE & PRICE ↓ · aligned", "ПРОДАЖИ И ЦЕНА ↓ · движение согласовано") : direction > 0 ? f_t("SELL PRESSURE, PRICE ↑ · conflict", "ПРОДАЖИ, НО ЦЕНА ↑ · конфликт") : f_t("SELL PRESSURE · no downside progress", "ПРОДАЖИ ЕСТЬ, ПАДЕНИЯ НЕТ")
        else
            s := direction > 0 ? f_t("PRICE ↑ · delta near neutral", "ЦЕНА ↑ · дельта без явного перекоса") : direction < 0 ? f_t("PRICE ↓ · delta near neutral", "ЦЕНА ↓ · дельта без явного перекоса") : f_t("PRICE FLAT · delta near neutral", "ЦЕНА СТОИТ · дельта без явного перекоса")
        if r < 0.75 and direction != 0 and not na(dp)
            s += f_t(" · LOW VOLUME", " · МАЛО ОБЪЁМА")
    s
 
f_side_color(float dp) =>
    na(dp) ? color.new(cNormal, 55) : dp >= neutralDelta ? cBuy : dp <= -neutralDelta ? cSell : cNormal
f_arrow(float x) =>
    na(x) ? "—" : x > 0 ? "↑" : x < 0 ? "↓" : "→"
f_vy(float r) =>
    na(r) ? na : volumeScale == "Linear" ? r : math.log(1.0 + math.max(0.0, r)) / math.log(2.0)
f_cy(float raw, float lo, float span, float y0, float height) =>
    na(raw) ? na : y0 + (raw - lo) / span * height
f_plot_segment(array<chart.point> pts, array<polyline> drawn, color col) =>
    if array.size(pts) >= 2
        array.push(drawn, polyline.new(pts, curved=false, closed=false, xloc=xloc.bar_time, line_color=col, line_width=2))
        if array.size(drawn) > 90
            polyline.delete(array.shift(drawn))
    array.clear(pts)
 
 
// 1/-1 aligned; 3/-3 aligned on low participation; 2 conflict; 0 no clear side; 9 missing.
// Neither CVD, OI nor funding is counted as another independent vote.
f_control(float dp, float moveAtr, float rv, bool valid) =>
    int result = 9
    if valid and not na(dp) and not na(moveAtr)
        int p = moveAtr >= controlMoveATR ? 1 : moveAtr <= -controlMoveATR ? -1 : 0
        int d = dp >= neutralDelta ? 1 : dp <= -neutralDelta ? -1 : 0
        if d != 0 and p == d
            result := not na(rv) and rv < 0.75 ? d * 3 : d
        else if d != 0 and p != d
            result := 2
        else
            result := 0
    result
f_rate(float x) =>
    na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.####")
f_ctl_boundary(int a, int z, int b, int count, int stepMs) =>
    b == count ? z : a + int(math.floor((z - a) * b / float(count) / stepMs)) * stepMs
f_delta_change(float current, float old, int currentT, int oldT, int spanMs) =>
    not na(current) and not na(old) and old > 0 and not na(currentT) and not na(oldT) and currentT - oldT == spanMs ? 100.0 * (current / old - 1.0) : na
 
type DivEvent
    int sign
    int t1
    int t2
    int detected
    int detectedBar
    int seg
    float p1
    float p2
    float c1
    float c2
 
// Presets change measured window, baseline and the CVD anchor; not merely the labels.
float tfSec = timeframe.in_seconds()
bool supported = chart.is_standard and not na(tfSec) and (timeframe.isintraday and tfSec <= 14400 or timeframe.isdaily and timeframe.multiplier == 1 or timeframe.isweekly and timeframe.multiplier == 1 or timeframe.ismonthly and timeframe.multiplier == 1)
if barstate.isfirst and not supported
    runtime.error("Use standard time candles: 1S–4H, 1D, 1W or 1M. No Heikin Ashi, Renko or Range.")
string autoProfile = timeframe.ismonthly ? "MACRO" : (timeframe.isdaily or timeframe.isweekly) ? "SWING" : tfSec <= 300 ? "SCALPER" : "INTRADAY"
string profile = preset == "AUTO" ? autoProfile : preset
bool scalp = profile == "SCALPER"
bool intra = profile == "INTRADAY"
bool swing = profile == "SWING"
bool compatible = scalp ? tfSec <= 300 : intra ? timeframe.isintraday and tfSec > 300 and tfSec <= 14400 : swing ? timeframe.isdaily or timeframe.isweekly : timeframe.ismonthly
if barstate.isfirst and preset != "AUTO" and not compatible
    runtime.error("Profile does not match chart timeframe. Choose AUTO or SCALPER 1S–5m, INTRADAY 15m–4h, SWING 1D–1W, MACRO 1M.")
// Keep the data timeframe compatible even if a user manually selects a different profile.
string ltf = tfSec <= 300 ? "1S" : tfSec <= 14400 ? "1" : timeframe.isdaily ? "5" : timeframe.isweekly ? "60" : "240"
int ltfSec = int(timeframe.in_seconds(ltf))
int wantedWindow = scalp ? pulseSecInput : intra ? (tfSec <= 3600 ? 300 : 900) : swing ? (timeframe.isweekly ? 86400 : 3600) : 86400
int windowSec = math.max(ltfSec, int(math.ceil(wantedWindow / float(ltfSec))) * ltfSec)
int windowMs = windowSec * 1000
int ltfMs = ltfSec * 1000
int pulseLookback = scalp ? 150 : intra ? 96 : swing ? 72 : 60
int minPulseSamples = scalp ? 30 : intra ? 24 : swing ? 20 : 18
int barLookback = scalp ? (tfSec <= 60 ? 240 : 144) : intra ? (tfSec <= 3600 ? 168 : 120) : swing ? (timeframe.isweekly ? 104 : 180) : 60
int minBarSamples = scalp ? 40 : intra ? 40 : swing ? 30 : 18
string anchor = anchorInput == "AUTO" ? (scalp ? "UTC day" : intra ? "UTC week" : "No calendar reset") : anchorInput
bool combinedView = screen == "DESK · VOL + CVD"
bool historyView = combinedView or screen == "VOLUME · history"
bool cvdBand = combinedView and showCvdBand
bool cvdView = screen == "CVD · native line"
bool barView = screen == "BAR · candle volume"
bool openBar = barstate.isrealtime and not barstate.isconfirmed
bool nearRight = bar_index >= last_bar_index - visibleBars - 2
 
[tsOpen, tsClose, vs, ds, os, cs] = request.security_lower_tf(syminfo.tickerid, ltf, [time, time_close, volume, f_delta(), open, close], ignore_invalid_timeframe=true, calc_bars_count=intrabarBudget)
int n = array.size(vs)
int sourceCutoff = openBar ? math.min(timenow, time_close) : time_close
float closedV = 0.0
float closedD = 0.0
bool sourceValuesOK = true
int closedCount = 0
int lastClosedTime = na
// First pass validates a chart bar. A partial first LTF-history bar is never silently trusted.
if n > 0
    for j = 0 to n - 1
        int a = array.get(tsOpen, j)
        int z = array.get(tsClose, j)
        if not na(z) and z <= sourceCutoff
            float v = array.get(vs, j)
            float d = array.get(ds, j)
            bool ok = not na(a) and z > a and not na(v) and v >= 0 and not na(d) and math.abs(d) <= v * 1.000001 and not na(array.get(os, j)) and not na(array.get(cs, j))
            sourceValuesOK := sourceValuesOK and ok
            if ok
                closedV += v
                closedD += d
            closedCount += 1
            lastClosedTime := z
float coverage = not na(volume) and volume > 0 and closedCount > 0 ? closedV / volume : na
bool fullSourceOK = closedCount > 0 and sourceValuesOK and (volume == 0 ? closedV == 0 : not na(coverage) and coverage >= 0.95 and coverage <= 1.05)
bool currentSourceOK = openBar ? closedCount > 0 and sourceValuesOK : fullSourceOK
 
// Fixed-size ring survives chart-bar changes. Pine rollback prevents repeated live appends
// from becoming duplicates: each update starts at the last COMMITTED chart bar state.
int ringCap = (pulseLookback + 3) * int(windowSec / ltfSec) + 8
var array<int> ringA = array.new_int(ringCap, na)
var array<int> ringZ = array.new_int(ringCap, na)
var array<float> ringV = array.new_float(ringCap, na)
var array<float> ringD = array.new_float(ringCap, na)
var array<float> ringO = array.new_float(ringCap, na)
var array<float> ringC = array.new_float(ringCap, na)
var array<bool> ringOK = array.new_bool(ringCap, false)
var int ringHead = 0
var int ringSize = 0
var int latestStored = na
int seedBars = int(math.ceil((pulseLookback + 3.0) * windowSec / tfSec)) + visibleBars + 10
bool seedRange = bar_index >= last_bar_index - seedBars
if seedRange and n > 0
    for j = 0 to n - 1
        int a = array.get(tsOpen, j)
        int z = array.get(tsClose, j)
        if not na(z) and z <= sourceCutoff and (na(latestStored) or z > latestStored)
            float v = array.get(vs, j)
            float d = array.get(ds, j)
            bool ok = currentSourceOK and not na(a) and z - a == ltfMs and not na(v) and v >= 0 and not na(d) and math.abs(d) <= v * 1.000001 and not na(array.get(os, j)) and not na(array.get(cs, j))
            array.set(ringA, ringHead, a)
            array.set(ringZ, ringHead, z)
            array.set(ringV, ringHead, v)
            array.set(ringD, ringHead, d)
            array.set(ringO, ringHead, array.get(os, j))
            array.set(ringC, ringHead, array.get(cs, j))
            array.set(ringOK, ringHead, ok)
            ringHead := (ringHead + 1) % ringCap
            ringSize := math.min(ringCap, ringSize + 1)
            latestStored := z
 
// Pulse reference = preceding NON-OVERLAPPING, complete windows ending before our window.
// A gap is missing data, NOT a zero-volume second. No interpolation or extrapolation.
int endTs = openBar ? latestStored : time_close
float lagSec = openBar and not na(endTs) ? math.max(0.0, (timenow - endTs) / 1000.0) : 0.0
bool fresh = not openBar or not na(lagSec) and lagSec <= math.max(3.0, 2.0 * ltfSec)
int windows = pulseLookback + 2
array<float> winV = array.new_float(windows, 0.0)
array<float> winD = array.new_float(windows, 0.0)
array<int> winCoverage = array.new_int(windows, 0)
array<bool> winBad = array.new_bool(windows, false)
array<float> winO = array.new_float(windows, na)
array<float> winC = array.new_float(windows, na)
array<int> winFirst = array.new_int(windows, na)
array<int> winLast = array.new_int(windows, na)
if nearRight and ringSize > 0 and not na(endTs)
    for back = 0 to ringSize - 1
        int ix = (ringHead - 1 - back + ringCap) % ringCap
        int a = array.get(ringA, ix)
        int z = array.get(ringZ, ix)
        if z > endTs
            continue
        int k = int(math.floor((endTs - z) / float(windowMs)))
        if k >= windows
            break
        int start = endTs - (k + 1) * windowMs
        int finish = endTs - k * windowMs
        if a >= start and z <= finish
            bool ok = array.get(ringOK, ix)
            array.set(winBad, k, array.get(winBad, k) or not ok)
            if ok
                array.set(winV, k, array.get(winV, k) + array.get(ringV, ix))
                array.set(winD, k, array.get(winD, k) + array.get(ringD, ix))
                array.set(winCoverage, k, array.get(winCoverage, k) + z - a)
                int first = array.get(winFirst, k)
                int last = array.get(winLast, k)
                if na(first) or a < first
                    array.set(winFirst, k, a)
                    array.set(winO, k, array.get(ringO, ix))
                if na(last) or z > last
                    array.set(winLast, k, z)
                    array.set(winC, k, array.get(ringC, ix))
        else
            array.set(winBad, k, true)
 
f_complete(int k) =>
    not array.get(winBad, k) and array.get(winCoverage, k) == windowMs and array.get(winFirst, k) == endTs - (k + 1) * windowMs and array.get(winLast, k) == endTs - k * windowMs
array<float> referenceV = array.new_float()
array<float> referenceMove = array.new_float()
if nearRight
    for k = 1 to pulseLookback
        if f_complete(k)
            array.push(referenceV, array.get(winV, k))
            array.push(referenceMove, math.abs(array.get(winC, k) - array.get(winO, k)))
int pulseSamples = array.size(referenceV)
float pulseMedian = f_med(referenceV)
bool windowComplete = nearRight and f_complete(0)
bool pulseReady = windowComplete and fresh and pulseSamples >= minPulseSamples and not na(pulseMedian) and pulseMedian > 0
float pulseV = windowComplete and fresh ? array.get(winV, 0) : na
float pulseD = windowComplete and fresh ? array.get(winD, 0) : na
float pulseRvol = pulseReady ? pulseV / pulseMedian : na
float pulseDP = not na(pulseV) and pulseV > 0 ? 100.0 * pulseD / pulseV : na
float pulseMove = windowComplete and fresh ? array.get(winC, 0) - array.get(winO, 0) : na
float pulseMovePct = windowComplete and fresh and array.get(winO, 0) > 0 ? 100.0 * pulseMove / array.get(winO, 0) : na
float pulseTolerance = math.max(syminfo.mintick * 2.0, nz(f_med(referenceMove), 0.0) * 0.30)
int pulseDirection = f_price_dir(pulseMove, pulseTolerance)
bool previousComplete = nearRight and f_complete(1)
float previousV = previousComplete ? array.get(winV, 1) : na
float acceleration = not na(pulseV) and previousComplete and previousV > 0 ? pulseV / previousV : na
string accelWord = na(acceleration) ? (not na(pulseV) and pulseV > 0 and previousV == 0 ? f_t("AFTER QUIET", "ПОСЛЕ ТИШИНЫ") : f_t("PACE —", "ТЕМП —")) : acceleration >= 1.35 ? f_t("VOLUME ACCEL ↑", "ОБЪЁМ ↑") : acceleration <= 0.75 ? f_t("VOLUME ACCEL ↓", "ОБЪЁМ ↓") : f_t("VOLUME STABLE", "ОБЪЁМ ≈")
 
// Full chart-bar volume: independent of delta availability.
// Current data are appended only AFTER evaluation below.
var array<float> barVolumes = array.new_float()
float barMedian = f_med(barVolumes)
float closedBarRvol = array.size(barVolumes) >= minBarSamples and not na(barMedian) and barMedian > 0 and not na(volume) ? volume / barMedian : na
float atrPrevious = ta.atr(14)[1]
// Diagnostics track actual available history, not a guessed reason for missing seconds.
var int firstChartRvolTime = na
var int firstLtfTime = na
var int chartRvolBars = 0
if not na(closedBarRvol) and na(firstChartRvolTime)
    firstChartRvolTime := time
if n > 0 and na(firstLtfTime)
    firstLtfTime := time
if barstate.isconfirmed and not na(closedBarRvol)
    chartRvolBars += 1
 
// Equal-progress history for the optional BAR view. No volume / elapsed extrapolation.
int maxBins = 60
bool secondsBins = tfSec < 60
bool twelveBins = scalp and tfSec >= 60 and tfSec <= 300
int bins = secondsBins ? int(math.max(1.0, tfSec / ltfSec)) : twelveBins ? int(math.ceil(tfSec / pulseSecInput)) : 20
bins := math.min(maxBins, bins)
int profileCap = math.min(barLookback, 240)
var array<float> phaseHistory = array.new_float(profileCap * maxBins, na)
var array<int> phaseBars = array.new_int(profileCap, -1000000)
var int phaseHead = 0
f_boundary(int a, int z, int b, int count) =>
    twelveBins ? math.min(z, a + b * pulseSecInput * 1000) : a + int((z - a) * b / float(count))
int reached = 0
if openBar and not na(lastClosedTime) and not na(time_close)
    for b = 1 to bins
        if f_boundary(time, time_close, b, bins) <= lastClosedTime
            reached := b
int sliceCutoff = reached > 0 ? f_boundary(time, time_close, reached, bins) : time
float sliceV = 0.0
float sliceD = 0.0
float sliceOpen = na
float sliceClose = na
int sliceLast = na
bool sliceOK = false
if openBar and reached > 0 and currentSourceOK and n > 0
    for j = 0 to n - 1
        if array.get(tsClose, j) <= sliceCutoff
            sliceV += array.get(vs, j)
            sliceD += array.get(ds, j)
            if na(sliceOpen)
                sliceOpen := array.get(os, j)
            sliceClose := array.get(cs, j)
            sliceLast := array.get(tsClose, j)
    sliceOK := not na(sliceLast) and sliceCutoff - sliceLast < ltfMs
array<float> phaseRef = array.new_float()
if openBar and reached > 0
    for r = 0 to profileCap - 1
        int age = bar_index - array.get(phaseBars, r)
        if age > 0 and age <= barLookback
            float sample = array.get(phaseHistory, r * maxBins + reached - 1)
            if not na(sample)
                array.push(phaseRef, sample)
float phaseMedian = f_med(phaseRef)
float sliceRvol = sliceOK and array.size(phaseRef) >= math.min(minBarSamples, 20) and not na(phaseMedian) and phaseMedian > 0 ? sliceV / phaseMedian : na
float candleRvol = openBar ? sliceRvol : closedBarRvol
float candleDP = openBar ? (sliceOK and sliceV > 0 ? 100.0 * sliceD / sliceV : na) : (fullSourceOK and closedV > 0 ? 100.0 * closedD / closedV : na)
float candleMove = openBar ? (sliceOK ? sliceClose - sliceOpen : na) : close - open
float candleMovePct = openBar ? (sliceOK and sliceOpen > 0 ? 100.0 * candleMove / sliceOpen : na) : (open > 0 ? 100.0 * candleMove / open : na)
int candleDirection = f_price_dir(candleMove, math.max(syminfo.mintick * 2.0, nz(atrPrevious) * 0.10))
 
// 03B — Fixed historical flow source. This is price-classified volume, NOT taker flags.
string flowLtf = tfSec < 60 ? "1S" : tfSec <= 300 ? (cvdPrecision == "PRECISE · 1S scalping" ? "1S" : cvdPrecision == "HISTORY · 15S scalping" ? "15S" : "5S") : ltf
[fT0, fT1, fV, fD, fO, fC] = request.security_lower_tf(syminfo.tickerid, flowLtf, [time, time_close, volume, f_delta(), open, close], ignore_invalid_timeframe=true, calc_bars_count=intrabarBudget)
float flowV = 0.0
float flowD = 0.0
float flowBuy = 0.0
float flowSell = 0.0
bool flowValuesOK = true
int flowCount = 0
int flowLastTime = na
if array.size(fV) > 0
    for j = 0 to array.size(fV) - 1
        int z = array.get(fT1, j)
        if not na(z) and z <= sourceCutoff
            float v = array.get(fV, j)
            float d = array.get(fD, j)
            bool ok = not na(v) and v >= 0 and not na(d) and math.abs(d) <= v * 1.000001
            flowValuesOK := flowValuesOK and ok
            if ok
                flowV += v
                flowD += d
                flowBuy += math.max(d, 0.0)
                flowSell += math.max(-d, 0.0)
            flowCount += 1
            flowLastTime := z
float flowCoverage = not na(volume) and volume > 0 ? flowV / volume : na
bool flowFullOK = flowCount > 0 and flowValuesOK and (volume == 0 ? flowV == 0 : not na(flowCoverage) and flowCoverage >= 0.95 and flowCoverage <= 1.05)
// A live CVD may contain completed sub-bars only. A low-coverage live candle is NOT colored.
bool flowObservedOK = openBar ? flowCount > 0 and flowValuesOK : flowFullOK
bool candleSideOK = flowFullOK and flowV > 0
float flowDP = candleSideOK ? 100.0 * flowD / flowV : na
float buyPct = candleSideOK ? 100.0 * flowBuy / flowV : na
float sellPct = candleSideOK ? 100.0 * flowSell / flowV : na
float unknownPct = candleSideOK ? math.max(0.0, 100.0 - buyPct - sellPct) : na
 
// 03C — CONTROL observes the chart candle, not the trader's execution-terminal timeframe.
// A fixed-source equal-progress profile is separate from the optional old 1S pulse.
int controlStepMs = int(timeframe.in_seconds(flowLtf)) * 1000
int controlBins = math.max(1, math.min(20, int(math.floor((time_close - time) / float(controlStepMs)))))
int controlCap = math.min(barLookback, 240)
var array<float> controlProfiles = array.new_float(controlCap * 20, na)
var array<int> controlProfileBars = array.new_int(controlCap, -1000000)
var int controlProfileHead = 0
int controlReached = 0
if not na(flowLastTime)
    for b = 1 to controlBins
        if f_ctl_boundary(time, time_close, b, controlBins, controlStepMs) <= flowLastTime
            controlReached := b
int controlEnd = openBar ? (controlReached > 0 ? f_ctl_boundary(time, time_close, controlReached, controlBins, controlStepMs) : time) : time_close
float controlV = 0.0
float controlD = 0.0
float controlO = na
float controlC = na
int controlLast = na
int controlN = 0
bool controlContinuous = true
if array.size(fV) > 0
    for j = 0 to array.size(fV) - 1
        int a = array.get(fT0, j)
        int z = array.get(fT1, j)
        if not na(z) and z <= controlEnd
            float v = array.get(fV, j)
            float d = array.get(fD, j)
            bool valid = not na(a) and not na(v) and v >= 0 and not na(d) and math.abs(d) <= v * 1.000001 and not na(array.get(fO, j)) and not na(array.get(fC, j))
            // Live prefix is deliberately strict: no invented zero-volume missing seconds.
            controlContinuous := controlContinuous and valid and (controlN == 0 ? a == time : a == controlLast) and z - a == controlStepMs
            if valid
                controlV += v
                controlD += d
                if controlN == 0
                    controlO := array.get(fO, j)
                controlC := array.get(fC, j)
            controlN += 1
            controlLast := z
bool controlFresh = not openBar or not na(controlLast) and sourceCutoff - controlLast <= math.max(controlStepMs * 2, int((time_close - time) / controlBins) + controlStepMs)
bool controlLiveOK = controlContinuous and controlN >= controlMinSamples and controlLast == controlEnd and controlFresh and controlV > 0
bool controlObserved = openBar ? controlLiveOK : flowFullOK and flowV > 0
array<float> controlReference = array.new_float()
if openBar and controlReached > 0
    for r = 0 to controlCap - 1
        int age = bar_index - array.get(controlProfileBars, r)
        if age > 0 and age <= barLookback
            float sample = array.get(controlProfiles, r * 20 + controlReached - 1)
            if not na(sample)
                array.push(controlReference, sample)
float controlMedian = f_med(controlReference)
float controlRV = openBar ? (controlLiveOK and array.size(controlReference) >= math.min(20, minBarSamples) and controlMedian > 0 ? controlV / controlMedian : na) : closedBarRvol
float controlDP = controlObserved ? 100.0 * (openBar ? controlD / controlV : flowD / flowV) : na
float controlMove = controlObserved ? (openBar ? controlC - controlO : close - open) : na
float controlMovePct = controlObserved and (openBar ? controlO : open) > 0 ? 100.0 * controlMove / (openBar ? controlO : open) : na
float controlMoveInATR = controlObserved and atrPrevious > 0 ? controlMove / atrPrevious : na
// Price tick floor prevents sub-tick noise being described as a winning side.
if not na(controlMove) and math.abs(controlMove) < syminfo.mintick * 2
    controlMoveInATR := 0.0
 
// Raw CVD. The line never passes through an arctangent or a rolling min/max transform.
int DAY = 86400000
int dayId = int(math.floor(time / float(DAY)))
int weekId = int(math.floor((time + 3 * DAY) / float(7 * DAY)))
int monthId = year(time, "Etc/UTC") * 12 + month(time, "Etc/UTC")
bool reset = anchor == "UTC day" ? dayId != dayId[1] : anchor == "UTC week" ? weekId != weekId[1] : anchor == "UTC month" ? monthId != monthId[1] : false
var float cvd = na
var int segment = 0
var int segmentStart = na
bool newSegment = flowObservedOK and (na(cvd[1]) or reset)
if flowObservedOK
    if newSegment
        cvd := flowD
        segment += 1
        segmentStart := time
    else
        cvd := cvd[1] + flowD
else if openBar and not reset and not na(cvd[1])
    // Hold the already known cumulative value until the first completed flow sub-bar.
    cvd := cvd[1]
else
    cvd := na
 
// One last confirmed divergence, never a forest of historical arrows.
int left = scalp ? 4 : intra ? 3 : 2
int right = scalp or intra ? 2 : 1
float pivotLow = ta.pivotlow(low, left, right)
float pivotHigh = ta.pivothigh(high, left, right)
var float prevLow = na
var float prevLowCvd = na
var int prevLowBar = na
var int prevLowSegment = na
var float prevHigh = na
var float prevHighCvd = na
var int prevHighBar = na
var int prevHighSegment = na
var array<DivEvent> divEvents = array.new<DivEvent>()
var int prevLowTime = na
var int prevHighTime = na
var line divLine = na
var label divTag = na
bool bullDiv = false
bool bearDiv = false
if barstate.isconfirmed and not na(pivotLow) and not na(cvd[right])
    int pBar = bar_index - right
    bool comparable = not na(prevLowBar) and pBar - prevLowBar >= 3 and pBar - prevLowBar <= 80 and segment[right] == prevLowSegment and segment == segment[right] and flowObservedOK
    bullDiv := comparable and pivotLow < prevLow - math.max(syminfo.mintick, nz(atrPrevious[right]) * 0.1) and cvd[right] > prevLowCvd + nz(barMedian[right], closedV[right]) * 0.25
    if bullDiv
        array.push(divEvents, DivEvent.new(1, prevLowTime, time[right], time, bar_index, segment[right], prevLow, pivotLow, prevLowCvd, cvd[right]))
        if array.size(divEvents) > divergenceKeep
            array.shift(divEvents)
    if cvdView and showDivergence and bullDiv and nearRight
        line.delete(divLine)
        label.delete(divTag)
        divLine := line.new(prevLowBar, prevLowCvd, pBar, cvd[right], color=cBuy, width=2)
        divTag := label.new(bar_index, cvd, f_t("Price: lower low\nCVD: higher low", "Цена: новый минимум\nCVD: минимум выше"), style=label.style_label_up, color=panelBg, textcolor=cBuy, size=size.small, tooltip=f_t("Confirmed on this candle; pivot occurred ", "Подтверждено на этой свече; экстремум был ") + str.tostring(right) + f_t(" bars earlier. Divergence is not a guaranteed reversal.", " свечи назад. Это расхождение, а не гарантированный разворот."))
    prevLowTime := time[right]
    prevLow := pivotLow
    prevLowCvd := cvd[right]
    prevLowBar := pBar
    prevLowSegment := segment[right]
if barstate.isconfirmed and not na(pivotHigh) and not na(cvd[right])
    int pBar = bar_index - right
    bool comparable = not na(prevHighBar) and pBar - prevHighBar >= 3 and pBar - prevHighBar <= 80 and segment[right] == prevHighSegment and segment == segment[right] and flowObservedOK
    bearDiv := comparable and pivotHigh > prevHigh + math.max(syminfo.mintick, nz(atrPrevious[right]) * 0.1) and cvd[right] < prevHighCvd - nz(barMedian[right], closedV[right]) * 0.25
    if bearDiv
        array.push(divEvents, DivEvent.new(-1, prevHighTime, time[right], time, bar_index, segment[right], prevHigh, pivotHigh, prevHighCvd, cvd[right]))
        if array.size(divEvents) > divergenceKeep
            array.shift(divEvents)
    if cvdView and showDivergence and bearDiv and nearRight
        line.delete(divLine)
        label.delete(divTag)
        divLine := line.new(prevHighBar, prevHighCvd, pBar, cvd[right], color=cSell, width=2)
        divTag := label.new(bar_index, cvd, f_t("Price: higher high\nCVD: lower high", "Цена: новый максимум\nCVD: максимум ниже"), style=label.style_label_down, color=panelBg, textcolor=cSell, size=size.small, tooltip=f_t("Confirmed on this candle; pivot occurred ", "Подтверждено на этой свече; экстремум был ") + str.tostring(right) + f_t(" bars earlier. Divergence is not a guaranteed reversal.", " свечи назад. Это расхождение, а не гарантированный разворот."))
    prevHighTime := time[right]
    prevHigh := pivotHigh
    prevHighCvd := cvd[right]
    prevHighBar := pBar
    prevHighSegment := segment[right]
if newSegment or (not na(divTag) and label.get_x(divTag) < last_bar_index - visibleBars)
    line.delete(divLine)
    label.delete(divTag)
    divLine := na
    divTag := na
 
// 04A — Interpret, do not manufacture a "probability" by counting correlated metrics.
float localV = 0.0
float localD = 0.0
bool localOK = not na(cvd)
for k = 0 to 2
    bool good = (k == 0 ? controlObserved : flowFullOK[k]) and segment[k] == segment and not na(flowV[k])
    localOK := localOK and good
    if good
        localV += k == 0 and openBar ? controlV : flowV[k]
        localD += k == 0 and openBar ? controlD : flowD[k]
float localFlow = localOK and localV > 0 ? 100.0 * localD / localV : na
float controlCvd = controlObserved ? (newSegment ? controlD : not na(cvd[1]) ? cvd[1] + controlD : na) : na
int recentDiv = 0
int recentDivAge = na
if array.size(divEvents) > 0
    DivEvent ev = array.get(divEvents, array.size(divEvents) - 1)
    if ev.seg == segment and bar_index - ev.detectedBar <= divergenceTTL
        recentDiv := ev.sign
        recentDivAge := bar_index - ev.detectedBar
// LIVE candidate uses the current observed PRICE and CVD from the same prefix.
// No use of an old wick with a later delta. No historical candidate markers.
int candidate = 0
if showCandidate and openBar and controlObserved and not na(controlCvd) and not newSegment
    float priceGate = math.max(syminfo.mintick, nz(atrPrevious) * 0.1)
    float deltaGate = nz(barMedian, volume) * 0.25
    if prevHighSegment == segment and bar_index - prevHighBar <= 80 and controlC > prevHigh + priceGate and controlCvd < prevHighCvd - deltaGate
        candidate := -1
    if prevLowSegment == segment and bar_index - prevLowBar <= 80 and controlC < prevLow - priceGate and controlCvd > prevLowCvd + deltaGate
        candidate := 1
 
// OI is a fixed 1m SOURCE snapshot on ALL chart timeframes, not 60 chart bars.
// Only a closed source minute is used. Timestamp checks reject sparse/misaligned history.
// No fallback to a different exchange, no notional-$ conversion, no synthetic OI.
string oiSymbol = str.length(oiOverride) > 0 ? oiOverride : ticker.standard(syminfo.tickerid) + "_OI"
[oiValue0, oiTime0, oiHour0, oiHourT0, oiDay0, oiDayT0] = request.security(oiSymbol, "1", [close[1], time_close[1], close[61], time_close[61], close[1441], time_close[1441]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off, ignore_invalid_symbol=true, calc_bars_count=5000)
bool oiValid = useOI and not na(oiValue0) and oiValue0 >= 0 and not na(oiTime0) and oiTime0 <= sourceCutoff and sourceCutoff - oiTime0 <= oiFreshMinutes * 60000
float oiValue = oiValid ? oiValue0 : na
float oi1h = oiValid ? f_delta_change(oiValue0, oiHour0, oiTime0, oiHourT0, 3600000) : na
float oi24h = oiValid ? f_delta_change(oiValue0, oiDay0, oiTime0, oiDayT0, 86400000) : na
// Funding cannot be fetched from an invented _FR ticker. Explicit official-plot adapter.
float fundingPctRaw = fundingScale == "Fraction: 0.0001 = 0.01%" ? fundingSource * 100.0 : fundingSource
bool fundingLooksLikeClose = fundingSource == close and fundingSource[1] == close[1] and fundingSource[2] == close[2]
bool fundingValid = useFunding and not fundingLooksLikeClose and not na(fundingPctRaw) and math.abs(fundingPctRaw) <= 5.0
float fundingPct = fundingValid ? fundingPctRaw : na
bool fundingCostWarning = fundingValid and fundingHours > 0 and math.abs(fundingPct) >= fundingWarn
 
// 04 — One compact snapshot. Switching horizon is EXPLICIT in every current cell.
bool dashPulse = not controlClosed and not barView and (dashHorizon == "Current window only" or dashHorizon == "AUTO · window / candle" and pulseReady)
bool accumulatedReading = false
string chartScope = timeframe.ismonthly ? f_t("1M", "1М") : timeframe.isweekly ? f_t("1W", "1Н") : timeframe.isdaily ? f_t("1D", "1Д") : f_duration(int(tfSec))
string shownScope = dashPulse ? f_duration(windowSec) : chartScope
bool usePreviousClosed = controlClosed and openBar
float shownRvol = dashPulse ? pulseRvol : usePreviousClosed ? closedBarRvol[1] : controlRV
float shownDP = dashPulse ? pulseDP : usePreviousClosed ? controlDP[1] : controlDP
float shownMovePct = dashPulse ? pulseMovePct : usePreviousClosed ? controlMovePct[1] : controlMovePct
float shownATR = dashPulse ? (atrPrevious > 0 ? pulseMove / atrPrevious : na) : usePreviousClosed ? controlMoveInATR[1] : controlMoveInATR
bool shownValid = dashPulse ? pulseReady : usePreviousClosed ? controlObserved[1] : controlObserved
int shownDirection = na(shownATR) ? 0 : shownATR >= controlMoveATR ? 1 : shownATR <= -controlMoveATR ? -1 : 0
int controlState = f_control(shownDP, shownATR, shownRvol, shownValid)
float displayedLocalFlow = usePreviousClosed ? localFlow[1] : localFlow
int controlDivSign = usePreviousClosed ? recentDiv[1] : recentDiv
int controlDivAge = usePreviousClosed ? recentDivAge[1] : recentDivAge
int displayCandidate = controlClosed ? 0 : candidate
float chartRvol = historyView ? closedBarRvol : barView ? candleRvol : pulseRvol
float columnDP = historyView ? flowDP : barView ? candleDP : pulseDP
color directionColor = f_side_color(columnDP)
color volumeColor = f_color(shownRvol)
color flowColor = f_side_color(shownDP)
 
// All volume history is a normal plot: no 120-bar cut, no 500-object histogram cap.
// log2(1+x) is invertible and UNCLIPPED. Only the visual ordinate changes.
plot(historyView and not openBar ? f_vy(closedBarRvol) : na, "VOL · relative volume; color = estimated delta", color=directionColor, style=plot.style_columns, histbase=0, display=display.pane)
plot(historyView and openBar ? f_vy(closedBarRvol) : na, "VOL · developing candle, accumulated", color=color.new(directionColor, 55), style=plot.style_columns, histbase=0, display=display.pane)
plot(barView ? f_vy(candleRvol) : na, "VOL · equivalent elapsed prefix", color=directionColor, style=plot.style_columns, histbase=0, display=display.pane)
plot(not historyView and not barView and not cvdView ? f_vy(pulseRvol) : na, "VOL · completed time window", color=directionColor, style=plot.style_columns, histbase=0, show_last=visibleBars, display=display.pane)
plot(not cvdView and showGrid ? f_vy(1.0) : na, "BASELINE 1×", color=color.new(cNormal, 25), linewidth=1, display=display.pane)
 
int lastDay = int(math.floor(last_bar_time / float(DAY)))
int lastWeek = int(math.floor((last_bar_time + 3 * DAY) / float(7 * DAY)))
int lastMonth = year(last_bar_time, "Etc/UTC") * 12 + month(last_bar_time, "Etc/UTC")
bool sameDisplayAnchor = anchor == "UTC day" ? dayId == lastDay : anchor == "UTC week" ? weekId == lastWeek : anchor == "UTC month" ? monthId == lastMonth : true
float visibleCvd = allCvdPeriods or sameDisplayAnchor ? cvd : na
plot(cvdView and not newSegment ? visibleCvd : na, "CVD · original volume units", color=cCvd, linewidth=2, style=plot.style_linebr, format=format.volume, display=display.pane + display.price_scale + display.data_window)
 
// Independent CVD band: all visible points share ONE affine transform.
// Panning/zooming may rescale the drawing, but NEVER changes CVD or a divergence.
bool insideViewport = time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
bool lastInViewport = time == chart.right_visible_bar_time
var float viewportMax = 0.0
var float viewportCvdHigh = na
var float viewportCvdLow = na
var array<int> visibleTime = array.new_int()
var array<float> visibleC = array.new_float()
var array<int> visibleSegment = array.new_int()
var array<int> visibleDiv = array.new_int()
if insideViewport
    if not na(chartRvol)
        viewportMax := math.max(viewportMax, chartRvol)
    if not na(visibleCvd)
        viewportCvdHigh := na(viewportCvdHigh) ? visibleCvd : math.max(viewportCvdHigh, visibleCvd)
        viewportCvdLow := na(viewportCvdLow) ? visibleCvd : math.min(viewportCvdLow, visibleCvd)
    if cvdBand
        array.push(visibleTime, time)
        array.push(visibleC, visibleCvd)
        array.push(visibleSegment, segment)
        array.push(visibleDiv, bullDiv ? 1 : bearDiv ? -1 : 0)
float volumeHeight = math.max(f_vy(viewportMax), f_vy(4.0))
float cvdY0 = volumeHeight * 1.17
float cvdHeight = volumeHeight * 0.61
float cvdRawRange = nz(viewportCvdHigh) - nz(viewportCvdLow)
float cvdSpan = math.max(cvdRawRange * 1.10, math.max(math.abs(nz(viewportCvdHigh)), 1.0) * 0.000001)
float cvdLo = (nz(viewportCvdHigh) + nz(viewportCvdLow)) * 0.5 - cvdSpan * 0.5
float topOfPlot = cvdBand ? volumeHeight * 1.90 : volumeHeight * 1.15
float panelHeaderFraction = f_clip(rowHeight * 3.0 / 100.0 + (showExplanation ? 0.08 : 0.0) + (showHelp ? 0.06 : 0.0) + (diagnostics ? 0.06 : 0.0), 0.15, 0.66)
float headerPad = topOfPlot * panelHeaderFraction / (1.0 - panelHeaderFraction)
bool ribbonAtTop = str.contains(ribbonPosition, "top")
float highEdge = cvdView ? nz(viewportCvdHigh) + cvdSpan * (showRibbon and ribbonAtTop ? panelHeaderFraction / (1.0 - panelHeaderFraction) : 0.08) : topOfPlot + (showRibbon and ribbonAtTop ? headerPad : 0.0)
float lowEdge = cvdView ? nz(viewportCvdLow) - cvdSpan * (showRibbon and not ribbonAtTop ? 0.35 : 0.08) : (showRibbon and not ribbonAtTop ? -headerPad : -volumeHeight * 0.03)
// Invisible anchors reserve real space; the header never sits ON the CVD line.
plot(lastInViewport ? highEdge : na, "Layout · upper space", color=color.new(cNormal, 100), display=display.pane, editable=false)
plot(lastInViewport ? lowEdge : na, "Layout · lower space", color=color.new(cNormal, 100), display=display.pane, editable=false)
 
var array<line> guides = array.new_line()
var array<label> guideTags = array.new_label()
var array<polyline> cvdPaths = array.new<polyline>()
var label currentTag = na
if barstate.islast
    for ln in guides
        line.delete(ln)
    for lb in guideTags
        label.delete(lb)
    for pl in cvdPaths
        polyline.delete(pl)
    array.clear(guides)
    array.clear(guideTags)
    array.clear(cvdPaths)
    label.delete(currentTag)
    if not cvdView and showGrid
        array<float> levels = array.from(1.0, 4.0, 16.0, 64.0, 256.0, 1024.0, 4096.0, 16384.0, 65536.0, 262144.0, 1048576.0)
        for level in levels
            if f_vy(level) <= volumeHeight
                float y = f_vy(level)
                color gc = level == 1.0 ? color.new(cNormal, 25) : color.new(cNormal, 72)
                array.push(guides, line.new(chart.left_visible_bar_time, y, chart.right_visible_bar_time, y, xloc=xloc.bar_time, color=gc, style=level == 1.0 ? line.style_solid : line.style_dotted))
                string gt = level == 1.0 ? f_t("1× BASELINE", "1× НОРМА") + (volumeScale == "Linear" ? "" : " · LOG") : str.tostring(level, "#") + "×"
                array.push(guideTags, label.new(chart.left_visible_bar_time, y, gt, xloc=xloc.bar_time, style=label.style_label_left, color=panelBg, textcolor=cNormal, size=size.small))
    if not cvdView and showHelp
        string volLegend = "VOL ×" + (volumeScale == "Linear" ? "" : " · LOG")
        array.push(guideTags, label.new(chart.left_visible_bar_time, volumeHeight * 1.07, volLegend, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(panelBg, 100), textcolor=panelFg, size=size.small, tooltip=f_t("Height is candle volume / historical median; green/red means estimated directional bias. Neutral or missing data remain grey. Developing candle is translucent.", "Высота = объём / медиана предыдущих свечей. Зелёный = оценочный перевес покупок; красный = продаж; серый = баланс, бледно-серый = нет пригодной дельты. Открытый столбик полупрозрачный.")))
    if latestTag and not cvdView and insideViewport and not na(chartRvol)
        string tagText = f_num(chartRvol) + "×" + (historyView and openBar ? "*" : "")
        string tt = historyView and openBar ? f_t("Accumulated volume / FULL-candle baseline. Candle is developing.", "Набрано / норма ПОЛНОЙ свечи. Свеча открыта; это не окончательная оценка.") : f_t("Closed candle volume / historical baseline.", "Закрытая свеча: объём / норма.")
        if historyView and candleSideOK
            tt += f_t("\nEstimate: buys ", "\nОценка: покупки ") + f_num(buyPct) + f_t("%, sells ", "%, продажи ") + f_num(sellPct) + f_t("%; unclassified ", "%; не классифицировано ") + f_num(unknownPct) + "%.\nΔ " + f_signed(flowDP) + "%; LTF " + flowLtf + "."
        else if historyView
            tt += f_t("\nEstimated delta unavailable or source volume mismatched. Direction is not inferred from chart candle color.", "\nДельта этой свечи недоступна или объёмы LTF не согласованы. Направление не подставляется по цвету цены.")
        currentTag := label.new(bar_index, f_vy(chartRvol), tagText, style=label.style_label_down, color=panelBg, textcolor=panelFg, size=size.small, tooltip=tt)
    if cvdBand
        array.push(guides, line.new(chart.left_visible_bar_time, cvdY0, chart.right_visible_bar_time, cvdY0, xloc=xloc.bar_time, color=color.new(cNormal, 82)))
        array<chart.point> points = array.new<chart.point>()
        int priorSegment = na
        int lastDivergenceIndex = na
        int parts = 0
        int validPoints = 0
        if array.size(visibleTime) > 0
            for i = 0 to array.size(visibleTime) - 1
                float v = array.get(visibleC, i)
                int sg = array.get(visibleSegment, i)
                bool split = na(v) or (not na(priorSegment) and sg != priorSegment)
                if split
                    if array.size(points) >= 2
                        parts += 1
                    f_plot_segment(points, cvdPaths, cCvd)
                if not na(v)
                    float y = f_cy(v, cvdLo, cvdSpan, cvdY0, cvdHeight)
                    chart.point p = chart.point.from_time(array.get(visibleTime, i), y)
                    array.push(points, p)
                    validPoints += 1
                    if array.get(visibleDiv, i) != 0
                        lastDivergenceIndex := i
                    // A polyline supports up to 10,000 points. Preserve the shared endpoint.
                    if array.size(points) >= 8500
                        parts += 1
                        f_plot_segment(points, cvdPaths, cCvd)
                        array.push(points, p)
                priorSegment := na(v) ? na : sg
            if array.size(points) >= 2
                parts += 1
            f_plot_segment(points, cvdPaths, cCvd)
        string caption = f_t("CVD ≈  |  FLOW-3 ", "CVD ≈  |  ПОТОК-3 ") + f_arrow(localFlow) + " " + f_signed(localFlow) + "%" + (parts > 90 ? f_t(" · last 90 segments", " · 90 сегм.") : "")
        if validPoints < 2
            caption += validPoints == 0 ? f_t(" — no data", " — нет данных") : f_t(" · one point", " · одна точка")
        array.push(guideTags, label.new(chart.left_visible_bar_time, volumeHeight * 1.84, caption, xloc=xloc.bar_time, style=label.style_label_left, color=color.new(panelBg, 100), textcolor=cCvd, size=size.small, tooltip=f_t("Estimated from ", "Оценка по ") + flowLtf + f_t(". One affine scale per visible range, separate from volume; data gaps and resets are not connected. Native CVD remains available in Data Window. Last 90 path segments are retained.", ". Одна линейная шкала для всего видимого диапазона; отдельная от объёма. Пропуски и сбросы НЕ соединяются. Исходный CVD доступен в окне данных и отдельном экране. При большом числе разрывов сохраняются последние 90 частей.")))
        if showCvdNumbers and not na(viewportCvdHigh)
            array.push(guideTags, label.new(chart.right_visible_bar_time, cvdY0 + cvdHeight, str.tostring(cvdLo + cvdSpan, format.volume), xloc=xloc.bar_time, style=label.style_label_right, color=panelBg, textcolor=cNormal, size=size.small))
            array.push(guideTags, label.new(chart.right_visible_bar_time, cvdY0, str.tostring(cvdLo, format.volume), xloc=xloc.bar_time, style=label.style_label_right, color=panelBg, textcolor=cNormal, size=size.small))
            if cvdLo <= 0 and cvdLo + cvdSpan >= 0
                float zeroY = f_cy(0.0, cvdLo, cvdSpan, cvdY0, cvdHeight)
                array.push(guides, line.new(chart.left_visible_bar_time, zeroY, chart.right_visible_bar_time, zeroY, xloc=xloc.bar_time, color=color.new(cNormal, 70), style=line.style_dotted))
    if latestTag and cvdView and insideViewport and not na(cvd)
        currentTag := label.new(bar_index, cvd, "CVD " + str.tostring(cvd, format.volume), style=label.style_label_right, color=panelBg, textcolor=cCvd, size=size.small)
 
// Paired DIV geometry. A/B lines are retrospective structure; DIV tag is discovery time.
var array<line> eventLines = array.new_line()
var array<label> eventLabels = array.new_label()
if barstate.islast
    for ln in eventLines
        line.delete(ln)
    for lb in eventLabels
        label.delete(lb)
    array.clear(eventLines)
    array.clear(eventLabels)
    if showDivergence and array.size(divEvents) > 0
        for ev in divEvents
            bool visibleEvent = ev.t1 >= chart.left_visible_bar_time and ev.t2 <= chart.right_visible_bar_time
            color dc = ev.sign > 0 ? cBuy : cSell
            string pair = ev.sign > 0 ? f_t("PRICE LL / CVD HL", "ЦЕНА LL / CVD HL") : f_t("PRICE HH / CVD LH", "ЦЕНА HH / CVD LH")
            string tip = pair + f_t("\nA → B: swing points. Confirmed ", "\nA → B: экстремумы. Подтверждено ") + str.format_time(ev.detected, "dd.MM HH:mm", "Etc/UTC") + f_t(" UTC, after ", " UTC, через ") + str.tostring(right) + f_t(" bars to the right.\nDivergence is not a reversal entry.", " бар(а) справа.\nЭто расхождение, не готовый разворот.")
            if visibleEvent and showPriceDivergence
                array.push(eventLines, line.new(ev.t1, ev.p1, ev.t2, ev.p2, xloc=xloc.bar_time, color=dc, width=3, force_overlay=true))
                array.push(eventLabels, label.new(ev.t1, ev.p1, "A", xloc=xloc.bar_time, style=ev.sign > 0 ? label.style_label_up : label.style_label_down, color=panelBg, textcolor=dc, size=size.small, force_overlay=true))
                array.push(eventLabels, label.new(ev.t2, ev.p2, ev.sign > 0 ? "B · LL" : "B · HH", xloc=xloc.bar_time, style=ev.sign > 0 ? label.style_label_up : label.style_label_down, color=panelBg, textcolor=dc, size=size.small, tooltip=tip, force_overlay=true))
                if ev.detected <= chart.right_visible_bar_time
                    array.push(eventLabels, label.new(ev.detected, ev.p2, ev.sign > 0 ? "DIV ↑" : "DIV ↓", xloc=xloc.bar_time, style=label.style_label_left, color=dc, textcolor=panelBg, size=size.normal, tooltip=tip, force_overlay=true))
            if visibleEvent and cvdBand and (allCvdPeriods or ev.seg == segment)
                float y1 = f_cy(ev.c1, cvdLo, cvdSpan, cvdY0, cvdHeight)
                float y2 = f_cy(ev.c2, cvdLo, cvdSpan, cvdY0, cvdHeight)
                array.push(eventLines, line.new(ev.t1, y1, ev.t2, y2, xloc=xloc.bar_time, color=dc, width=3))
                array.push(eventLabels, label.new(ev.t1, y1, "A", xloc=xloc.bar_time, style=ev.sign > 0 ? label.style_label_up : label.style_label_down, color=panelBg, textcolor=dc, size=size.small))
                array.push(eventLabels, label.new(ev.t2, y2, ev.sign > 0 ? "B · HL" : "B · LH", xloc=xloc.bar_time, style=ev.sign > 0 ? label.style_label_up : label.style_label_down, color=panelBg, textcolor=dc, size=size.small, tooltip=tip))
    if showDivergence and displayCandidate != 0 and insideViewport
        int ct1 = candidate > 0 ? prevLowTime : prevHighTime
        float cp1 = candidate > 0 ? prevLow : prevHigh
        float cc1 = candidate > 0 ? prevLowCvd : prevHighCvd
        color cc = cHigh
        if ct1 >= chart.left_visible_bar_time
            if showPriceDivergence
                array.push(eventLines, line.new(ct1, cp1, time, controlC, xloc=xloc.bar_time, color=cc, style=line.style_dashed, width=2, force_overlay=true))
                array.push(eventLabels, label.new(time, controlC, candidate > 0 ? "DIV? ↑" : "DIV? ↓", xloc=xloc.bar_time, style=label.style_label_left, color=cc, textcolor=panelBg, size=size.normal, tooltip=f_t("Provisional LIVE divergence; can disappear. Price and CVD share the same completed prefix.", "LIVE-кандидат, не подтверждён. Может исчезнуть. Цена и CVD взяты на одном завершённом срезе текущей свечи."), force_overlay=true))
            if cvdBand
                array.push(eventLines, line.new(ct1, f_cy(cc1, cvdLo, cvdSpan, cvdY0, cvdHeight), time, f_cy(controlCvd, cvdLo, cvdSpan, cvdY0, cvdHeight), xloc=xloc.bar_time, color=cc, style=line.style_dashed, width=2))
 
// 05 — Four columns, three compact rows; the right column forms one filled tile.
// The tile is descriptive, not a LONG/SHORT order, calibrated probability or forecast.
string font = fontInput == "Compact" ? size.small : fontInput == "Large" ? size.large : size.normal
int rowCount = 3 + (showExplanation ? 1 : 0) + (showHelp ? 1 : 0) + (diagnostics ? 1 : 0)
var table ribbon = table.new(ribbonPosition, 4, rowCount, bgcolor=na, frame_width=0, border_width=0)
if barstate.isfirst
    table.merge_cells(ribbon, 3, 0, 3, 1)
    if rowCount > 3
        for r = 3 to rowCount - 1
            table.merge_cells(ribbon, 0, r, 3, r)
if barstate.islast
    float cellW = (100.0 - tileWidth) / 3.0
    bool thin = math.abs(controlState) == 3
    color stateColor = controlState == 1 or controlState == 3 ? cBuy : controlState == -1 or controlState == -3 ? cSell : controlState == 2 ? cHigh : cLow
    color tileColor = thin ? color.new(stateColor, 38) : stateColor
    string stateArrow = controlState == 1 or controlState == 3 ? "↑" : controlState == -1 or controlState == -3 ? "↓" : controlState == 2 ? "↔" : controlState == 9 ? "—" : "→"
    string stateName = controlState == 1 ? f_t("BUY PRESSURE", "ПОКУПКИ") : controlState == -1 ? f_t("SELL PRESSURE", "ПРОДАЖИ") : thin ? f_t("THIN", "ТОНКО") : controlState == 2 ? f_t("CONFLICT", "КОНФЛИКТ") : controlState == 9 ? f_t("NO DATA", "НЕТ ДАННЫХ") : f_t("BALANCED", "БАЛАНС")
    string timing = dashPulse ? shownScope + f_t(" WINDOW", " ОКНО") : usePreviousClosed or not openBar ? chartScope + f_t(" CLOSED", " ЗАКР") : chartScope + " · " + f_duration(int(math.max(0, controlEnd - time) / 1000)) + "/" + chartScope + " LIVE"
    string volText = "VOL " + f_num(shownRvol) + "×" + (na(shownRvol) ? "" : " · " + (shownRvol >= 3.0 and shownRvol < 6.0 ? f_t("HIGH+", "МНОГО+") : f_grade(shownRvol)))
    string deltaText = "Δ ≈ " + f_signed(shownDP) + "%"
    string priceText = f_t("P ", "Ц ") + f_price_pct(shownMovePct) + "%"
    string localText = na(displayedLocalFlow) ? f_t("FLOW-3 —", "ПОТОК-3 —") : f_t("FLOW-3 ", "ПОТОК-3 ") + f_arrow(displayedLocalFlow) + " " + f_signed(displayedLocalFlow) + "%"
    string divText = displayCandidate != 0 ? (displayCandidate > 0 ? "DIV? ↑ LIVE" : "DIV? ↓ LIVE") : controlDivSign != 0 ? (controlDivSign > 0 ? "DIV ↑ · " : "DIV ↓ · ") + str.tostring(controlDivAge) + f_t("b", "б") : "DIV —"
    string oiText = na(oiValue) ? "OI —" : "OI " + f_arrow(oi1h) + " " + str.tostring(oiValue, format.volume)
    string oiChanges = f_t("1h ", "1ч ") + f_signed(oi1h) + f_t("% | 24h ", "% | 24ч ") + f_signed(oi24h) + "%"
    string fundText = "F " + (na(fundingPct) ? "—" : f_rate(fundingPct) + "%") + (fundingValid ? fundingHours > 0 ? " /" + f_num(fundingHours) + f_t("h", "ч") : " /?" : "") + (fundingCostWarning ? " !" : "")
    string tileTip = f_t("Price and estimated delta cover the same observation: ", "Цена и оценочная дельта — за один горизонт: ") + timing + f_t(".\nGreen/red: directional pressure agrees with price move. Yellow: conflict. Grey: neutral/missing.\nOI/funding are context only, and DIV does not override the tile. Not a trade entry or profit forecast.", ".\nЗелёный/красный: давление получает ценовой результат. Жёлтый: давление и результат расходятся. Серый: нет явной стороны или данных.\nOI и funding НЕ голосуют за направление. DIV не переворачивает квадрат автоматически. Это не вероятность заработка и не разрешение на вход.")
    string volumeTip = f_t("Historical bars = full candle volume / prior median; developing bar = volume accumulated. LIVE header = completed prefix relative to same-phase historical prefixes. No elapsed-time extrapolation.", "История снизу = ПОЛНЫЙ объём свечей / предыдущая медиана. Открытый столбик — НАБРАНО.\nVOL сверху в LIVE = объём завершённого среза / медиана ТАКОГО ЖЕ среза предыдущих свечей. Не экстраполяция по времени. При нехватке базы: —.")
    string deltaTip = f_t("Δ≈ uses candle-classified intrabar volume, not true taker flags. Source: ", "Δ≈ — оценка направления младших свечей, не биржевые taker-флаги. Источник: ") + flowLtf + f_t(". Horizon: ", ". Горизонт: ") + timing + "."
    string localTip = f_t("FLOW-3 = combined estimated delta / volume for the observed prefix and two preceding closed bars. One local measure, not three independent signals; unavailable across gaps/resets.", "ПОТОК-3 = сумма дельт / сумма объёма за текущий наблюдаемый срез + 2 предыдущие закрытые свечи. Это характеристика локального наклона CVD, не три независимых сигнала. Между сегментами / пропусками: —.")
    string divTip = f_t("DIV? is provisional LIVE mismatch; DIV is confirmed and annotated at discovery time. Age is since discovery; A/B price and CVD lines show the two compared pivots.", "DIV? — текущий неподтверждённый конфликт экстремума и CVD. DIV без ? — подтверждённое расхождение; число б = возраст после ОБНАРУЖЕНИЯ. Линии A/B на цене и CVD показывают причину.")
    string oiTip = oiSymbol + f_t(" | units: ", " | единицы: ") + oiUnits + f_t(".\nChanges use completed source minutes, not chart bars. OI snapshot: ", ".\nИзменения — по закрытым минутам источника, не по свечам графика. OI snapshot: ") + (na(oiTime0) ? "—" : str.format_time(oiTime0, "dd.MM HH:mm", "Etc/UTC")) + f_t(" UTC.\nRising OI does not identify the dominant side, falling OI does not prove liquidations. Notional units may change with price; feed is never substituted across exchanges.", " UTC.\nРост OI не показывает, кого больше: у каждого контракта две стороны. Падение не доказывает ликвидации. Валютный номинал может меняться вместе с ценой. Источник не подменяется другой биржей.")
    string fundTip = f_t("External Funding Rate numeric plot. OFF/unknown = unavailable. Positive usually means longs pay shorts, negative the reverse. It is cost context, not price prediction.\nVerify scale, instrument, period and plot on each symbol change; underlying actual update timestamp is unavailable.", "Внешний числовой plot официального Funding Rate. OFF / неизвестно = —. Знак +: обычно платят long; знак −: обычно платят short. Это стоимость, не прогноз направления.\nПериод и масштаб должен подтвердить пользователь. Время последнего реального обновления внешнего plot недоступно. После смены монеты проверь источник/период.")
    if showRibbon
        table.cell(ribbon, 0, 0, timing, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=cNormal, text_size=size.small, text_halign=text.align_left, tooltip=tileTip)
        table.cell(ribbon, 1, 0, deltaText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=flowColor, text_size=font, tooltip=deltaTip)
        table.cell(ribbon, 2, 0, priceText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=na(shownMovePct) ? cNormal : shownMovePct > 0 ? cBuy : shownMovePct < 0 ? cSell : cNormal, text_size=font, tooltip=tileTip)
        table.cell(ribbon, 3, 0, stateArrow, width=tileWidth, bgcolor=tileColor, text_color=panelBg, text_size=size.huge, tooltip=tileTip)
        table.cell(ribbon, 0, 1, volText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=volumeColor, text_size=font, text_halign=text.align_left, tooltip=volumeTip)
        table.cell(ribbon, 1, 1, localText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=f_side_color(displayedLocalFlow), text_size=size.small, tooltip=localTip)
        table.cell(ribbon, 2, 1, divText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=displayCandidate != 0 or controlDivSign != 0 ? cHigh : cNormal, text_size=font, tooltip=divTip)
        table.cell(ribbon, 0, 2, oiText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=panelFg, text_size=font, text_halign=text.align_left, tooltip=oiTip)
        table.cell(ribbon, 1, 2, oiChanges, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=panelFg, text_size=size.small, tooltip=oiTip)
        table.cell(ribbon, 2, 2, fundText, width=cellW, height=rowHeight, bgcolor=panelBg, text_color=fundingCostWarning ? cHigh : cNormal, text_size=size.small, tooltip=fundTip)
        table.cell(ribbon, 3, 2, stateName, width=tileWidth, height=rowHeight, bgcolor=tileColor, text_color=panelBg, text_size=size.small, tooltip=tileTip)
        int row = 3
        if showExplanation
            table.cell(ribbon, 0, row, f_story(shownRvol, shownDP, shownDirection), height=8, bgcolor=panelBg, text_color=panelFg, text_size=size.small, text_halign=text.align_left)
            row += 1
        if showHelp
            string helpText = chart.right_visible_bar_time < last_bar_time ? f_t("HISTORICAL VIEW · tile shows latest chart bar, not cursor", "ИСТОРИЯ НА ЭКРАНЕ · квадрат = последний бар, НЕ курсор") : f_t("VOL: quantity | color: Δ≈ | A/B: price vs CVD | DIV?: LIVE candidate | F/OI: context", "VOL: количество | цвет: Δ≈ | A/B: цена против CVD | DIV?: LIVE-кандидат | F/OI: контекст")
            table.cell(ribbon, 0, row, helpText, height=6, bgcolor=panelBg, text_color=cNormal, text_size=size.small, text_halign=text.align_left)
            row += 1
        if diagnostics
            string detail = profile + " | CVD " + flowLtf + " n=" + str.tostring(flowCount) + " | CTRL n=" + str.tostring(controlN) + " ref=" + str.tostring(array.size(controlReference)) + " | OI " + (oiValid ? "bar OK" : "—") + " | Funding " + (fundingValid ? "EXTERNAL" : "OFF/NA")
            table.cell(ribbon, 0, row, detail, height=6, bgcolor=panelBg, text_color=cNormal, text_size=size.small, text_halign=text.align_left)
    else
        table.clear(ribbon, 0, 0, 3, rowCount - 1)
 
// Data window keeps detailed measurements out of the main picture.
plot(pulseRvol, "DATA · window RVOL, ×", display=display.data_window)
plot(pulseV, "DATA · window volume", display=display.data_window, format=format.volume)
plot(pulseMedian, "DATA · prior window median", display=display.data_window, format=format.volume)
plot(pulseDP, "DATA · window estimated delta, %", display=display.data_window)
plot(pulseMovePct, "DATA · matching window price move, %", display=display.data_window)
plot(acceleration, "DATA · window volume acceleration", display=display.data_window)
plot(candleRvol, "DATA · candle/prefix RVOL, ×", display=display.data_window)
plot(closedBarRvol, "DATA · full / accumulated volume vs full median, ×", display=display.data_window)
plot(barMedian, "DATA · full-candle volume baseline", display=display.data_window, format=format.volume)
plot(openBar ? 0 : 1, "DATA · confirmed candle, 1 yes / 0 no", display=display.data_window)
plot(candleDP, "DATA · optional prefix estimated delta, %", display=display.data_window)
plot(flowDP, "DATA · candle estimated delta (bar color), %", display=display.data_window)
plot(buyPct, "DATA · estimated buy-classified %, candle", display=display.data_window)
plot(sellPct, "DATA · estimated sell-classified %, candle", display=display.data_window)
plot(unknownPct, "DATA · unclassified volume, %", display=display.data_window)
plot(flowObservedOK ? flowD : na, "DATA · candle estimated delta for CVD", display=display.data_window, format=format.volume)
plot(flowCoverage * 100.0, "DATA · CVD intrabar volume coverage, %", display=display.data_window)
plot(pulseSamples, "DATA · completed reference windows", display=display.data_window)
plot(windowComplete ? 100 : 100.0 * array.get(winCoverage, 0) / windowMs, "DATA · window time coverage, %", display=display.data_window)
plot(cvd, "DATA · native CVD", display=display.data_window, format=format.volume)
plot(coverage, "DATA · intrabar/chart volume ratio", display=display.data_window)
 
plot(controlState, "DATA · CONTROL state (9 missing, 2 conflict, ±1 aligned, ±3 thin)", display=display.data_window)
plot(shownRvol, "DATA · CONTROL RVOL same prefix", display=display.data_window)
plot(shownDP, "DATA · CONTROL delta %, same prefix", display=display.data_window)
plot(shownMovePct, "DATA · CONTROL price %, same prefix", display=display.data_window)
plot(displayedLocalFlow, "DATA · FLOW-3 %", display=display.data_window)
plot(oiValue, "DATA · OI native units, snapshot", display=display.data_window, format=format.volume)
plot(oi1h, "DATA · OI 1h %", display=display.data_window)
plot(oi24h, "DATA · OI 24h %", display=display.data_window)
plot(fundingPct, "DATA · Funding external %", display=display.data_window)
 
// LIVE alerts are opt-in. Emit only on a new COMPLETE window endpoint and a changed state.
varip int lastAlertEnd = na
varip int lastAlertState = na
int volumeClass = na(pulseRvol) ? -1 : pulseRvol < 0.75 ? 0 : pulseRvol < 1.5 ? 1 : pulseRvol < 3 ? 2 : pulseRvol < 6 ? 3 : 4
int sideClass = na(pulseDP) ? 0 : pulseDP >= neutralDelta ? 1 : pulseDP <= -neutralDelta ? -1 : 0
int liveState = volumeClass * 100 + (sideClass + 1) * 10 + pulseDirection + 1
if liveAlerts and barstate.isrealtime and pulseReady and (na(lastAlertEnd) or endTs >= lastAlertEnd + windowMs) and (na(lastAlertState) or liveState != lastAlertState)
    alert("Flow Control [Artio] | " + ticker.standard(syminfo.tickerid) + f_t(" | last ", " | последние ") + f_duration(windowSec) + " | " + f_grade(pulseRvol) + " " + f_num(pulseRvol) + "x | " + f_story(pulseRvol, pulseDP, pulseDirection) + " | TV PRICE PROXY", alert.freq_all)
    lastAlertEnd := endTs
    lastAlertState := liveState
alertcondition(uiLanguage == "English" and bullDiv, "CVD bullish divergence · EN", "Flow Control [Artio]: bullish price/CVD divergence confirmed on this bar. Not an entry signal. {{ticker}} {{interval}}")
alertcondition(uiLanguage == "Русский" and bullDiv, "CVD бычья дивергенция · RU", "Flow Control [Artio]: подтверждена бычья дивергенция цены и CVD. Не сигнал входа. {{ticker}} {{interval}}")
alertcondition(uiLanguage == "English" and bearDiv, "CVD bearish divergence · EN", "Flow Control [Artio]: bearish price/CVD divergence confirmed on this bar. Not an entry signal. {{ticker}} {{interval}}")
alertcondition(uiLanguage == "Русский" and bearDiv, "CVD медвежья дивергенция · RU", "Flow Control [Artio]: подтверждена медвежья дивергенция цены и CVD. Не сигнал входа. {{ticker}} {{interval}}")
 
// Commit full-bar and partial-bar reference data only after every current evaluation.
if barstate.isconfirmed
    if not na(volume) and volume >= 0
        array.push(barVolumes, volume)
        if array.size(barVolumes) > barLookback
            array.shift(barVolumes)
    if fullSourceOK and n > 0 and not na(time_close)
        float acc = 0.0
        int cursor = 0
        for b = 0 to bins - 1
            int boundary = f_boundary(time, time_close, b + 1, bins)
            int lastInSlice = na
            while cursor < n
                if array.get(tsClose, cursor) > boundary
                    break
                acc += array.get(vs, cursor)
                lastInSlice := array.get(tsClose, cursor)
                cursor += 1
            // A sparse interval is not silently recorded as a zero profile value.
            bool usable = not na(lastInSlice) and boundary - lastInSlice < ltfMs
            array.set(phaseHistory, phaseHead * maxBins + b, usable ? acc : na)
        array.set(phaseBars, phaseHead, bar_index)
        phaseHead := (phaseHead + 1) % profileCap
 
// Commit CONTROL profiles after evaluation: CURRENT observation is never its own baseline.
if barstate.isconfirmed and flowFullOK and array.size(fV) > 0 and not na(time_close)
    float accControl = 0.0
    int cursorControl = 0
    int expectedControl = time
    bool prefixControlOK = true
    for b = 0 to controlBins - 1
        int boundaryControl = f_ctl_boundary(time, time_close, b + 1, controlBins, controlStepMs)
        while cursorControl < array.size(fV)
            int z = array.get(fT1, cursorControl)
            if na(z) or z > boundaryControl
                break
            int a = array.get(fT0, cursorControl)
            float v = array.get(fV, cursorControl)
            prefixControlOK := prefixControlOK and not na(a) and a == expectedControl and z - a == controlStepMs and not na(v) and v >= 0
            if not na(v)
                accControl += v
            expectedControl := z
            cursorControl += 1
        bool usableControl = prefixControlOK and expectedControl == boundaryControl
        array.set(controlProfiles, controlProfileHead * 20 + b, usableControl ? accControl : na)
    // Clear unused cells if a variable-duration calendar bar has fewer bins.
    if controlBins < 20
        for b = controlBins to 19
            array.set(controlProfiles, controlProfileHead * 20 + b, na)
    array.set(controlProfileBars, controlProfileHead, bar_index)
    controlProfileHead := (controlProfileHead + 1) % controlCap
 
// Platform references (checked 2026-10-04):
// https://www.tradingview.com/pine-script-docs/visuals/plots/
// https://www.tradingview.com/pine-script-docs/concepts/other-timeframes-and-data/
// https://www.tradingview.com/pine-script-docs/concepts/time/
 
// https://www.tradingview.com/support/solutions/43000725058-cumulative-volume-delta/
// https://www.tradingview.com/pine-script-docs/visuals/lines-and-boxes/
// https://www.tradingview.com/pine-script-docs/visuals/tables/
 
// v3.3 references:
// https://www.tradingview.com/script/Rpmobpw5-Request/
// https://www.tradingview.com/pine-script-docs/concepts/inputs/
// https://www.tradingview.com/support/solutions/43000685269-open-interest/
// https://www.tradingview.com/support/solutions/43000762390-funding-rate-a-guide-to-market-sentiment/

← 返回列表