Volume Radar: Relative Volume & Delta [Artio]

Artio_Scalping_Life · study · 394 行 · 点赞 16 · TradingView 原页

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

Pine Script

//@version=6
// Volume Radar v4.3.0 | [Artio] | EN/RU + CFD/CME/Crypto AUTO + Time-of-Day RVOL
// Based on ARTIO VOL v4.2 and v4.1. Volume observation only, not a trade executor.
// IMPORTANT: Delta here is LTF candle-direction signed volume, NOT aggressor-level trade delta.
// CME Group includes COMEX, NYMEX and CBOT. Forex is grouped with OTC/CFD feed semantics.
// Market thresholds are conservative heuristics, NOT empirically optimized edge estimates.
indicator("Volume Radar: Relative Volume & Delta [Artio]", shorttitle="Volume Radar [Artio]", overlay=false, max_bars_back=3000, max_lines_count=40, max_labels_count=40, format=format.price, precision=2)
 
// Settings labels and options are const strings in Pine. Bilingual labels, localized data/UI.
string G0 = "00 · General / Основное"
string language = input.string("English", "Language / Язык", options=["English", "Русский"], group=G0)
bool ru = language == "Русский"
string marketInput = input.string("AUTO", "Market feed / Тип рынка", options=["AUTO", "CFD", "CME", "CRYPTO", "OTHER"], group=G0, tooltip="AUTO identifies crypto, CME Group futures or OTC/CFD-like feeds using TradingView instrument metadata. Forex is grouped with CFD/OTC for feed handling, NOT claimed to be a CFD. Override is available if the feed is misclassified. / AUTO определяет тип по метаданным. Forex отнесён к OTC/CFD по обработке фида, но не объявляется автоматически CFD.")
string preset = input.string("AUTO", "Timeframe profile / Профиль ТФ", options=["AUTO", "SCALPER", "INTRADAY", "SWING", "MACRO"], group=G0)
string precisionMode = input.string("AUTO", "Delta resolution / Точность дельты", options=["AUTO", "1S", "5S", "15S"], group=G0, tooltip="AUTO: on 1–5 minute charts uses 15s for CFD/OTC, 5s for CME and crypto; higher timeframes use 1/5/60/240 minute LTF. 1s charts always use 1s. / AUTO: на графиках 1–5 минут 15с для CFD/OTC, 5с для CME и крипты; на старших ТФ разрешение выбирается автоматически.")
string snapshotMode = input.string("LIVE + last closed", "Snapshot / Снимок", options=["LIVE + last closed", "LIVE only", "Closed only"], group=G0, tooltip="LIVE uses completed LTF bars within the unfinished candle. If invalid, the first mode displays ONE prior completed candle labeled CLOSED -1. It never relabels past data as live. / LIVE считает только завершённые младшие свечи. Если данных нет, первый режим показывает предыдущую закрытую свечу с меткой ЗАКР -1.")
string sensitivityMode = input.string("AUTO", "Sensitivity / Порог сигналов", options=["AUTO", "CUSTOM"], group=G0, tooltip="AUTO applies explicit market-specific heuristics to estimated delta and price response. CUSTOM uses your two values below. / AUTO: эвристические пороги по рынку. CUSTOM: ручные значения ниже.")
float manualDelta = input.float(10.0, "CUSTOM: delta dominance ±% / Перевес Δ", minval=5, maxval=40, step=1, group=G0)
float manualMoveATR = input.float(0.10, "CUSTOM: price move in prev. ATR / Цена ATR", minval=0.02, maxval=0.50, step=0.01, group=G0)
 
string GBASE = "01 · Volume baseline / База объёма"
string baselineMode = input.string("AUTO", "Volume baseline / База RVOL", options=["AUTO", "TIME OF DAY", "ROLLING"], group=GBASE, tooltip="AUTO: time-of-day baseline for 1m–4H when enough previous-day observations exist; rolling median otherwise. 1m uses 10-minute buckets; 5m uses 30-minute buckets; 1H uses 60-minute buckets. Current local calendar day never enters its own time-of-day baseline. LIVE adjusts equal-progress history with the same time-of-day volume factor, so it remains an estimate. / AUTO: норма по времени суток при достаточной истории, иначе обычная медиана. Данные сегодняшнего дня не попадают в норму сегодняшнего дня.")
int seasonMinInput = input.int(0, "Min. previous-day samples (0 AUTO) / История", minval=0, maxval=40, group=GBASE, tooltip="Minimum prior-day volume observations in the same local time bucket. Too little history falls back to rolling median. / Минимум наблюдений прошлых дней в том же временном интервале; иначе обычная медиана.")
 
string GQ = "02 · Feed quality / Качество данных"
int intrabarBudget = input.int(100000, "LTF bar request budget / Лимит LTF", minval=20000, maxval=200000, step=10000, group=GQ, tooltip="The provider/account plan may limit accessible intrabars below this requested number. / Доступная история LTF зависит от подписки TradingView.")
float volumeCoverageMin = input.float(0.95, "Minimum volume coverage / Покрытие", minval=0.95, maxval=1.0, step=0.01, group=GQ, tooltip="Sum of available LTF volume must agree with the chart volume within this tolerance. Missing time slots alone do not imply missing trades. 95% is a tolerance, NOT proof of total coverage. / Сумма объёма младших баров должна совпадать с объёмом свечи. Допуск не гарантирует полноту.")
bool strictSlots = input.bool(false, "Require every LTF time slot / Все слоты LTF", group=GQ, tooltip="May reject thin/sparse OTC or futures feeds. OFF never invents zero-volume candles. / Может блокировать редкие фиды. OFF не выдумывает нулевые свечи.")
int minLiveSamplesInput = input.int(0, "LIVE min. completed LTF bars (0 AUTO) / Мин.", minval=0, maxval=6, group=GQ)
bool diagnostics = input.bool(false, "Diagnostics row / Диагностика", group=GQ)
 
string GV = "03 · Display / Отображение"
bool showHeader = input.bool(true, "Show compact header / Строка", group=GV)
int fontSize = input.int(11, "Header font size (pt) / Шрифт", minval=8, maxval=16, group=GV)
color panelBg = input.color(#111827, "Header background / Фон", group=GV)
color panelFg = input.color(#E5E7EB, "Header text / Текст", group=GV)
color cBuy = input.color(#34D399, "Buy-side estimate / Покупки≈", group=GV)
color cSell = input.color(#FB7185, "Sell-side estimate / Продажи≈", group=GV)
color cNeutral = input.color(#94A3B8, "Balance / Нет оценки", group=GV)
color cConflict = input.color(#FACC15, "Conflict / Конфликт", group=GV)
 
// TradingView settings cannot be changed dynamically; only rendered text is localized.
f_txt(string en, string rus) =>
    ru ? rus : en
 
// AUTO market selection uses symbol metadata, never assumes a broker name implies real traded volume.
string venue = str.upper(syminfo.prefix)
bool isCmeGroup = syminfo.type == "futures" and (str.contains(venue, "CME") or str.contains(venue, "COMEX") or str.contains(venue, "NYMEX") or str.contains(venue, "CBOT"))
string detectedMarket = syminfo.type == "crypto" ? "CRYPTO" : isCmeGroup ? "CME" : (syminfo.type == "cfd" or syminfo.type == "forex") ? "CFD" : "OTHER"
string market = marketInput == "AUTO" ? detectedMarket : marketInput
// Preserve the data's real unit from TradingView, regardless of a manual market override.
string volFeed = syminfo.volumetype == "tick" ? f_txt("TICK VOL", "ТИК. ОБЪЁМ") : syminfo.volumetype == "base" ? f_txt("BASE VOL", "БАЗ. ОБЪЁМ") : syminfo.volumetype == "quote" ? f_txt("QUOTE VOL", "КОТИР. ОБЪЁМ") : syminfo.type == "futures" ? f_txt("FUT FEED VOL", "ОБЪЁМ ФЬЮЧ.") : f_txt("FEED VOL", "ОБЪЁМ ФИДА")
string marketName = market == "CFD" ? f_txt("CFD/OTC", "CFD/OTC") : market == "CME" ? "CME" : market == "CRYPTO" ? f_txt("CRYPTO", "КРИПТА") : f_txt("OTHER", "ДРУГОЕ")
// Transparent, cautious unoptimized heuristics, not guaranteed optimal thresholds.
float neutralDelta = sensitivityMode == "CUSTOM" ? manualDelta : market == "CFD" ? 14.0 : market == "CME" ? 12.0 : 10.0
float controlMoveATR = sensitivityMode == "CUSTOM" ? manualMoveATR : market == "CFD" ? 0.12 : market == "CME" ? 0.10 : 0.10
 
f_num(float x) =>
    na(x) ? "—" : str.tostring(x, "#.##")
f_signed(float x) =>
    na(x) ? "—" : (x > 0 ? "+" : "") + str.tostring(x, "#.##")
f_grade(float x) =>
    na(x) ? f_txt("NO BASELINE", "НЕТ НОРМЫ") : x < 0.75 ? f_txt("LOW", "МАЛО") : x < 1.5 ? f_txt("NORMAL", "ОБЫЧНО") : x < 3 ? f_txt("HIGH", "МНОГО") : x < 6 ? f_txt("VERY HIGH", "МНОГО+") : f_txt("SPIKE", "ВСПЛЕСК")
f_duration(int sec) =>
    sec < 60 ? str.tostring(sec) + f_txt("s", "с") : sec < 3600 ? str.tostring(sec / 60.0, "#.##") + f_txt("m", "м") : sec < 86400 ? str.tostring(sec / 3600.0, "#.##") + f_txt("h", "ч") : str.tostring(sec / 86400.0, "#.##") + f_txt("d", "д")
f_med(array<float> a) =>
    array.size(a) > 0 ? array.median(a) : na
 
// Direction of an LTF candle, not exchange buyer/seller aggressor flags.
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_side(float dp) =>
    na(dp) ? color.new(cNeutral, 60) : dp >= neutralDelta ? cBuy : dp <= -neutralDelta ? cSell : cNeutral
 
// States use estimated delta, prior-bar ATR and RVOL only.
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 := na(rv) ? d * 4 : rv < 0.75 ? d * 3 : d
        else if d != 0
            result := 2
        else
            result := 0
    result
 
f_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
 
// Core model supports only standard time-based charts.
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(f_txt("Use standard time candles: seconds–4H, 1D, 1W, 1M. No Heikin Ashi / Renko / Range.", "Нужны обычные временные свечи: секунды–4H, 1D, 1W, 1M. Не Heikin Ashi / Renko / 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 not compatible
    runtime.error(f_txt("Choose AUTO or a timeframe-compatible profile.", "Выбери AUTO или профиль, соответствующий таймфрейму."))
// For <1-minute charts, 1s is the highest supported script resolution.
string autoScalpLtf = market == "CFD" ? "15S" : "5S"
string scalpLtf = precisionMode == "AUTO" ? autoScalpLtf : precisionMode
string flowLtf = tfSec < 60 ? "1S" : tfSec <= 300 ? scalpLtf : tfSec <= 14400 ? "1" : timeframe.isdaily ? "5" : timeframe.isweekly ? "60" : "240"
int stepMs = int(timeframe.in_seconds(flowLtf) * 1000)
int barLookback = scalp ? (tfSec <= 60 ? 240 : market == "CME" ? 180 : 144) : intra ? (tfSec <= 3600 ? 168 : 120) : swing ? (timeframe.isweekly ? 104 : 180) : 60
int minBarSamples = scalp or intra ? (market == "CFD" ? 30 : 40) : swing ? 30 : 18
int targetLiveSamples = minLiveSamplesInput > 0 ? minLiveSamplesInput : market == "CFD" ? 2 : 3
int controlMinSamples = math.max(1, math.min(targetLiveSamples, int(math.floor(tfSec * 1000 / stepMs))))
string chartScope = timeframe.ismonthly ? f_txt("1M", "1МЕС") : timeframe.isweekly ? f_txt("1W", "1Н") : timeframe.isdaily ? f_txt("1D", "1Д") : tfSec < 60 ? str.tostring(int(tfSec)) + f_txt("s", "с") : tfSec < 3600 ? str.tostring(int(tfSec / 60)) + f_txt("m", "м") : str.tostring(int(tfSec / 3600)) + f_txt("h", "ч")
 
bool openBar = barstate.isrealtime and not barstate.isconfirmed
int cutoff = openBar ? math.min(timenow, time_close) : time_close
var array<float> pastVolumes = array.new_float()
float barMedian = f_med(pastVolumes)
// Same local time-of-day is a fairer reference for CME session peaks and 24/7 crypto.
// Bounded circular storage: at most 48 previous observations per time bucket.
// The current local calendar day is EXCLUDED from the baseline, preventing an
// early intraday spike from instantly redefining today's "normal" volume.
bool timeOfDayEligible = timeframe.isintraday and tfSec >= 60 and tfSec <= 14400
int seasonBucketMinutes = tfSec <= 60 ? 10 : tfSec <= 300 ? 30 : tfSec <= 1800 ? 60 : tfSec <= 3600 ? 60 : tfSec <= 7200 ? 120 : 240
int seasonBuckets = int(1440 / seasonBucketMinutes)
int minuteOfDay = hour(time, syminfo.timezone) * 60 + minute(time, syminfo.timezone)
int timeBucket = int(math.floor(minuteOfDay / seasonBucketMinutes))
int calendarDay = year(time, syminfo.timezone) * 10000 + month(time, syminfo.timezone) * 100 + dayofmonth(time, syminfo.timezone)
int seasonMinSamples = seasonMinInput > 0 ? seasonMinInput : tfSec <= 300 ? 12 : 6
int SEASON_CAP = 48
var array<float> seasonVol = array.new_float(seasonBuckets * SEASON_CAP, na)
var array<int> seasonDay = array.new_int(seasonBuckets * SEASON_CAP, 0)
var array<int> seasonHead = array.new_int(seasonBuckets, 0)
array<float> seasonComparable = array.new_float()
if timeOfDayEligible and baselineMode != "ROLLING"
    for s = 0 to SEASON_CAP - 1
        int slot = timeBucket * SEASON_CAP + s
        float observedVol = array.get(seasonVol, slot)
        int observedDay = array.get(seasonDay, slot)
        if observedDay > 0 and observedDay < calendarDay and not na(observedVol) and observedVol > 0
            array.push(seasonComparable, observedVol)
float seasonalMedian = f_med(seasonComparable)
bool seasonalReady = timeOfDayEligible and baselineMode != "ROLLING" and array.size(seasonComparable) >= seasonMinSamples and not na(seasonalMedian) and seasonalMedian > 0
float activeMedian = seasonalReady ? seasonalMedian : barMedian
string baselineName = seasonalReady ? f_txt("TIME OF DAY", "ВРЕМЯ СУТОК") : f_txt("ROLLING", "СКОЛЬЗЯЩАЯ")
float barRV = not na(activeMedian) and activeMedian > 0 and not na(volume) and (seasonalReady or array.size(pastVolumes) >= minBarSamples) ? volume / activeMedian : na
float atrPrevious = ta.atr(14)[1]
[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)
int n = array.size(fV)
float allV = 0.0
float closedV = 0.0
float closedD = 0.0
bool valuesOK = true
bool slotsOK = true
int expected = time
int closedN = 0
int lastClosed = na
// Reconcile ALL available volume (including a developing intrabar, if supplied)
// with the chart. Analysis below uses only completed LTF bars.
if n > 0
    for j = 0 to n - 1
        int a = array.get(fT0, j)
        int z = array.get(fT1, j)
        float v = array.get(fV, j)
        float d = array.get(fD, j)
        bool ok = not na(a) and not na(z) and a >= time and z <= time_close and z > a and a >= expected 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))
        valuesOK := valuesOK and ok
        slotsOK := slotsOK and ok and a == expected and z - a == stepMs
        expected := z
        if ok
            allV += v
            if z <= cutoff
                closedV += v
                closedD += d
                closedN += 1
                lastClosed := z
float sourceCoverage = not na(volume) and volume > 0 ? allV / volume : na
bool volumeMatches = n > 0 and valuesOK and (volume == 0 ? allV == 0 : not na(sourceCoverage) and sourceCoverage >= volumeCoverageMin and sourceCoverage <= 2.0 - volumeCoverageMin)
bool sourceOK = volumeMatches and (not strictSlots or slotsOK)
bool flowFullOK = not openBar and sourceOK and closedN > 0 and (not strictSlots or lastClosed == time_close)
int bins = math.max(1, math.min(20, int(math.floor((time_close - time) / float(stepMs)))))
int cap = math.min(barLookback, 240)
var array<float> profiles = array.new_float(cap * 20, na)
var array<int> profileBars = array.new_int(cap, -1000000)
var int profileHead = 0
int reached = 0
if not na(lastClosed)
    for b = 1 to bins
        if f_boundary(time, time_close, b, bins, stepMs) <= lastClosed
            reached := b
int observedEnd = openBar ? (reached > 0 ? f_boundary(time, time_close, reached, bins, stepMs) : time) : time_close
float controlV = 0.0
float controlD = 0.0
float controlO = na
float controlC = na
int controlN = 0
int controlLast = na
if n > 0
    for j = 0 to n - 1
        if array.get(fT1, j) <= observedEnd
            controlV += array.get(fV, j)
            controlD += array.get(fD, j)
            if controlN == 0
                controlO := array.get(fO, j)
            controlC := array.get(fC, j)
            controlLast := array.get(fT1, j)
            controlN += 1
bool freshPrefix = not na(controlLast) and cutoff >= controlLast and cutoff - controlLast <= math.max(stepMs * 2, int((time_close - time) / bins) + stepMs)
bool currentOK = sourceOK and controlN >= controlMinSamples and controlV > 0 and reached > 0 and freshPrefix and (not strictSlots or controlLast == observedEnd)
bool controlObserved = openBar ? currentOK : flowFullOK and closedV > 0
// No bar-volume/elapsed-time extrapolation. Same elapsed phase of previous bars.
array<float> phaseRef = array.new_float()
if openBar and reached > 0
    for r = 0 to cap - 1
        int age = bar_index - array.get(profileBars, r)
        float sample = array.get(profiles, r * 20 + reached - 1)
        if age > 0 and age <= barLookback and not na(sample)
            array.push(phaseRef, sample)
float phaseMedian = f_med(phaseRef)
// An equal-progress comparison is scaled by the seasonal/full-bar median ratio.
// This is an approximation of same-time LIVE pace, NOT same-slot 5s tick history.
float phaseScale = seasonalReady and not na(barMedian) and barMedian > 0 ? seasonalMedian / barMedian : 1.0
float expectedPhaseVol = na(phaseMedian) ? na : phaseMedian * phaseScale
float controlRV = openBar ? (currentOK and array.size(phaseRef) >= math.min(20, minBarSamples) and not na(expectedPhaseVol) and expectedPhaseVol > 0 ? controlV / expectedPhaseVol : na) : barRV
float controlDP = controlObserved ? 100.0 * (openBar ? controlD / controlV : closedD / closedV) : na
float controlMove = controlObserved ? (openBar ? controlC - controlO : close - open) : na
float controlMoveInATR = controlObserved and atrPrevious > 0 ? controlMove / atrPrevious : na
if not na(controlMove) and math.abs(controlMove) < syminfo.mintick * 2
    controlMoveInATR := 0.0
float flowV = openBar ? controlV : closedV
float flowD = openBar ? controlD : closedD
bool flowObservedOK = openBar ? currentOK : flowFullOK
float flowDP = flowObservedOK and flowV > 0 ? 100.0 * flowD / flowV : na
bool previousReady = controlObserved[1] and not na(barRV[1])
bool usePrevious = openBar and previousReady and (snapshotMode == "Closed only" or snapshotMode == "LIVE + last closed" and not controlObserved)
bool shownValid = usePrevious ? controlObserved[1] : controlObserved and not (openBar and snapshotMode == "Closed only")
float shownDP = shownValid ? (usePrevious ? controlDP[1] : controlDP) : na
float shownRV = shownValid ? (usePrevious ? barRV[1] : controlRV) : na
float shownATR = shownValid ? (usePrevious ? controlMoveInATR[1] : controlMoveInATR) : na
int state = f_control(shownDP, shownATR, shownRV, shownValid)
string timing = usePrevious ? chartScope + f_txt(" CLOSED -1", " ЗАКР -1") : not openBar ? chartScope + f_txt(" CLOSED", " ЗАКР") : shownValid ? chartScope + " · " + f_duration(int((observedEnd - time) / 1000)) + " LIVE" : chartScope + f_txt(" WAIT", " ЖДУ")
string stateArrow = state == 1 or state == 3 or state == 4 ? "↑" : state == -1 or state == -3 or state == -4 ? "↓" : state == 2 ? "↔" : state == 9 ? "—" : "→"
string stateName = state == 1 ? f_txt("BUYING≈", "ПОКУПКИ≈") : state == -1 ? f_txt("SELLING≈", "ПРОДАЖИ≈") : math.abs(state) == 3 ? f_txt("LOW VOLUME", "МАЛО ОБЪЁМА") : math.abs(state) == 4 ? f_txt("NO BASELINE", "НЕТ НОРМЫ") : state == 2 ? f_txt("CONFLICT", "КОНФЛИКТ") : state == 9 ? f_txt("NO DATA", "НЕТ ДАННЫХ") : f_txt("BALANCE", "БАЛАНС")
color stateBase = state == 1 or state == 3 or state == 4 ? cBuy : state == -1 or state == -3 or state == -4 ? cSell : state == 2 ? cConflict : cNeutral
color stateColor = math.abs(state) == 3 or math.abs(state) == 4 ? color.new(stateBase, 50) : stateBase
string snapshotTip = timing + f_txt(": volume, estimated delta (Δ≈) and price response cover the SAME completed time slice. Δ≈ uses LTF candle direction, NOT actual exchange taker flags. ", ": объём, оценочная дельта (Δ≈) и результат цены за ОДИН завершённый срез. Δ≈ основана на направлении младших свечей, НЕ на реальных флагах агрессора. ") + stateName + f_txt(". Observation, not a probability or an entry order. CLOSED -1 is the PRIOR candle.", ". Это наблюдение, не вероятность и не приказ на вход. ЗАКР -1 — ПРЕДЫДУЩАЯ свеча.") + f_txt(" Feed: ", " Фид: ") + volFeed + f_txt("; market profile: ", "; профиль: ") + marketName + f_txt("; RVOL baseline: ", "; база RVOL: ") + baselineName
// Commit only after evaluating the current observation.
if barstate.isconfirmed
    if not na(volume) and volume > 0
        array.push(pastVolumes, volume)
        if array.size(pastVolumes) > barLookback
            array.shift(pastVolumes)
        if timeOfDayEligible
            int writeHead = array.get(seasonHead, timeBucket)
            int writeSlot = timeBucket * SEASON_CAP + writeHead
            array.set(seasonVol, writeSlot, volume)
            array.set(seasonDay, writeSlot, calendarDay)
            array.set(seasonHead, timeBucket, (writeHead + 1) % SEASON_CAP)
    if flowFullOK and n > 0
        float acc = 0.0
        int cursor = 0
        int lastT = na
        for b = 0 to bins - 1
            int boundary = f_boundary(time, time_close, b + 1, bins, stepMs)
            while cursor < n
                if array.get(fT1, cursor) > boundary
                    break
                acc += array.get(fV, cursor)
                lastT := array.get(fT1, cursor)
                cursor += 1
            // Only store a prefix with actual observed data. Do not invent early zeros.
            bool usable = not na(lastT) and (not strictSlots or lastT == boundary)
            array.set(profiles, profileHead * 20 + b, usable ? acc : na)
        if bins < 20
            for b = bins to 19
                array.set(profiles, profileHead * 20 + b, na)
        array.set(profileBars, profileHead, bar_index)
        profileHead := (profileHead + 1) % cap
 
// END VOLUME CORE v4.3.0 — no CVD plot, hidden CVD state or OI lane.
 
string GVV = "04 · Volume pane / Объёмы"
string scaleMode = input.string("LOG", "Column scale / Масштаб столбиков", options=["LOG", "LINEAR"], group=GVV, tooltip="LOG uses log2(1+RVOL); the labels remain original x-multiples. This is only visual geometry. / LOG = log2(1+RVOL); подписи показывают реальные кратности.")
bool showGrid = input.bool(true, "Grid at 1x / 4x / 16x / Сетка", group=GVV)
bool showVolTile = input.bool(true, "Show state tile / Стрелка", group=GVV)
bool showTileText = input.bool(true, "Tile text / Подпись под стрелкой", group=GVV)
int arrowSize = input.int(26, "Tile arrow size (pt) / Стрелка", minval=18, maxval=36, group=GVV)
bool volAlerts = input.bool(false, "Price/delta alerts (closed) / Результат", group=GVV, tooltip="Separate closed-bar state-change alerts. / Алерты смены результата только по закрытию.")
bool activityAlerts = input.bool(false, "Volume surge alerts (closed) / Всплески", group=GVV, tooltip="Alert on crossing into high or spike RVOL. High/spike levels are relative to the active baseline. / Алерты при переходе через уровни повышенного объёма и всплеска.")
float highVolumeLevel = input.float(2.0, "High RVOL threshold / Много x", minval=1.5, maxval=5.0, step=0.25, group=GVV)
float spikeVolumeLevel = input.float(6.0, "Spike RVOL threshold / Всплеск x", minval=2.0, maxval=10.0, step=0.25, group=GVV)
bool lastValue = input.bool(true, "Last-column label / Подпись столбика", group=GVV)
 
f_vy(float v) =>
    na(v) ? na : scaleMode == "LINEAR" ? v : math.log(1.0 + math.max(0, v)) / math.log(2.0)
 
color columnColor = f_side(flowDP)
plot(not openBar ? f_vy(barRV) : na, "VOL · closed bar", style=plot.style_columns, color=columnColor, histbase=0, display=display.pane)
plot(openBar ? f_vy(barRV) : na, "VOL · incomplete bar accumulation", style=plot.style_columns, color=color.new(columnColor, 52), histbase=0, display=display.pane)
plot(0, "Zero baseline", color=color.new(cNeutral, 100), display=display.pane, editable=false)
 
// Cosmetic grid only. viewport bounds NEVER affect analytical values.
var float visibleMax = 1.0
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time and not na(barRV)
    visibleMax := math.max(visibleMax, barRV)
var array<line> gridLines = array.new_line()
var array<label> gridLabels = array.new_label()
var label lastLabel = na
 
if barstate.islast
    for ln in gridLines
        line.delete(ln)
    for lb in gridLabels
        label.delete(lb)
    array.clear(gridLines)
    array.clear(gridLabels)
    label.delete(lastLabel)
    if showGrid
        float lastGridY = na
        for level in array.from(1.0, 4.0, 16.0, 64.0, 256.0, 1024.0)
            bool separated = na(lastGridY) or (f_vy(level) - lastGridY) / math.max(f_vy(visibleMax), 1.0) >= 0.14
            if level <= visibleMax * 1.10 and separated
                float y = f_vy(level)
                lastGridY := y
                array.push(gridLines, line.new(chart.left_visible_bar_time, y, chart.right_visible_bar_time, y, xloc=xloc.bar_time, color=color.new(cNeutral, level == 1 ? 30 : 72), style=level == 1 ? line.style_solid : line.style_dotted))
                array.push(gridLabels, label.new(chart.left_visible_bar_time, y, str.tostring(level, "#") + "×" + (level == 1 ? f_txt(" BASE", " НОРМА") : ""), xloc=xloc.bar_time, style=label.style_label_left, color=color.new(panelBg, 10), textcolor=cNeutral, size=size.tiny))
    if lastValue and not na(barRV) and time <= chart.right_visible_bar_time
        lastLabel := label.new(time, f_vy(barRV), f_num(barRV) + "×" + (openBar ? "*" : ""), xloc=xloc.bar_time, style=label.style_label_down, color=panelBg, textcolor=columnColor, size=size.small, tooltip=f_txt("Bar RVOL = current volume / active baseline (same time of day or rolling previous candles). * = unfinished. LIVE speed uses comparable completed slices, seasonally adjusted if available; NOT a prediction.", "RVOL = объём свечи / активная норма (время суток или прошлые свечи). * = свеча не закрыта. LIVE-темп сравнивается с завершёнными историческими срезами и при наличии сезонной нормы корректируется, НЕ прогноз."))
 
var table header = table.new(position.top_left, 3, 2, bgcolor=na, border_width=0)
var table volTile = table.new(position.top_right, 1, 2, bgcolor=na, border_width=0)
 
if barstate.islast
    table.clear(header, 0, 0, 2, 1)
    table.clear(volTile, 0, 0, 0, 1)
    if showVolTile
        string vl = state == 2 ? f_txt("CONFLICT", "КОНФЛИКТ") : math.abs(state) == 3 ? f_txt("LOW VOL", "МАЛО") : math.abs(state) == 4 ? f_txt("NO BASE", "НОРМА?") : state == 1 ? f_txt("BUY≈", "ПОК≈") : state == -1 ? f_txt("SELL≈", "ПРОД≈") : state == 9 ? f_txt("NO Δ", "НЕТ Δ") : f_txt("BALANCE", "БАЛАНС")
        table.cell(volTile, 0, 0, " " + stateArrow + " ", text_size=arrowSize, text_color=panelBg, bgcolor=stateColor, tooltip="VOL: " + snapshotTip)
        if showTileText
            table.cell(volTile, 0, 1, vl, text_size=9, text_color=panelBg, bgcolor=stateColor, tooltip=snapshotTip)
    if showHeader
        table.cell(header, 0, 0, " VOL · " + marketName + " · " + timing + " " + scaleMode + (seasonalReady ? " TOD " : " ROLL "), text_color=cNeutral, bgcolor=panelBg, text_size=fontSize, tooltip=snapshotTip)
        table.cell(header, 1, 0, " " + f_num(shownRV) + "× " + f_grade(shownRV) + " ", text_color=shownRV >= 1.5 ? cConflict : panelFg, bgcolor=panelBg, text_size=fontSize, tooltip=f_txt("LIVE: completed slice vs matched prior slices, adjusted by time-of-day factor when available. CLOSED: full candle vs active time-of-day or rolling baseline. Not a forecast. Feed: ", "LIVE: завершённый срез против исторических срезов с поправкой по времени суток при наличии нормы. ЗАКР: полная свеча против активной нормы. Не прогноз. Фид: ") + volFeed)
        table.cell(header, 2, 0, " Δ≈ " + f_signed(shownDP) + "% ", text_color=f_side(shownDP), bgcolor=panelBg, text_size=fontSize, tooltip=snapshotTip)
    if diagnostics
        table.cell(header, 0, 1, " " + marketName + " / " + profile + " / LTF " + flowLtf + " n=" + str.tostring(n), text_color=cNeutral, bgcolor=panelBg, text_size=9, tooltip=volFeed + " | " + syminfo.type + " | " + syminfo.prefix + " | " + syminfo.session + " | RVOL " + baselineName)
        table.cell(header, 1, 1, f_txt("Volume coverage ", "Покрытие объёма ") + f_num(sourceCoverage * 100) + "%", text_color=cNeutral, bgcolor=panelBg, text_size=9)
        table.cell(header, 2, 1, " Δ±" + f_num(neutralDelta) + "% · ATR " + f_num(controlMoveATR) + " · " + str.tostring(array.size(phaseRef)) + f_txt(" refs", " срезов") + " · " + (seasonalReady ? "TOD " + str.tostring(array.size(seasonComparable)) : "ROLL"), text_color=cNeutral, bgcolor=panelBg, text_size=9)
 
// Stable, English-only data-window names are mandatory in Pine (plot titles are const).
plot(barRV, "DATA · Full-bar RVOL, x (* unfinished)", display=display.data_window)
plot(barMedian, "DATA · Rolling median candle volume", format=format.volume, display=display.data_window)
plot(activeMedian, "DATA · Active volume baseline", format=format.volume, display=display.data_window)
plot(seasonalReady ? 1 : 0, "DATA · Time-of-day baseline active", display=display.data_window)
plot(array.size(seasonComparable), "DATA · Previous-day same-time samples", display=display.data_window)
plot(shownRV, "DATA · Snapshot RVOL, x", display=display.data_window)
plot(flowDP, "DATA · Estimated LTF delta, %", display=display.data_window)
plot(sourceCoverage * 100, "DATA · LTF volume coverage, %", display=display.data_window)
plot(usePrevious ? 1 : 0, "DATA · Prior closed candle displayed", display=display.data_window)
plot(neutralDelta, "DATA · Auto/manual delta threshold, %", display=display.data_window)
plot(controlMoveATR, "DATA · Auto/manual price threshold, ATR", display=display.data_window)
plot(market == "CFD" ? 1 : market == "CME" ? 2 : market == "CRYPTO" ? 3 : 0, "DATA · Market: CFD=1 CME=2 CRYPTO=3 OTHER=0", display=display.data_window)
plot(state, "DATA · Observed VOL result code", display=display.data_window)
 
// Bar-close only. Alert() messages localize. Alertcondition titles remain English by Pine design.
bool buyEvent = volAlerts and barstate.isconfirmed and state == 1 and state[1] != 1
bool sellEvent = volAlerts and barstate.isconfirmed and state == -1 and state[1] != -1
bool conflictEvent = volAlerts and barstate.isconfirmed and state == 2 and state[1] != 2
alertcondition(buyEvent, "Volume Radar - Estimated buying response (closed)", "Volume Radar [Artio]: estimated LTF delta and price response aligned up. Observation, not a trade signal.")
alertcondition(sellEvent, "Volume Radar - Estimated selling response (closed)", "Volume Radar [Artio]: estimated LTF delta and price response aligned down. Observation, not a trade signal.")
alertcondition(conflictEvent, "Volume Radar - Delta/price conflict (closed)", "Volume Radar [Artio]: estimated LTF delta direction did not match the observed price response.")
// Dynamic alert() combines all qualified observations below into ONE message per bar.
 
// Standalone volume radar events. These work even when LTF delta is unavailable.
// A bar moving directly from normal to spike produces only the SPIKE event.
bool spikeEvent = activityAlerts and barstate.isconfirmed and not na(barRV) and barRV >= math.max(highVolumeLevel, spikeVolumeLevel) and (na(barRV[1]) or barRV[1] < math.max(highVolumeLevel, spikeVolumeLevel))
bool highEvent = activityAlerts and barstate.isconfirmed and not spikeEvent and not na(barRV) and barRV >= highVolumeLevel and (na(barRV[1]) or barRV[1] < highVolumeLevel)
alertcondition(highEvent, "RVOL elevated (closed)", "Volume Radar [Artio]: above high relative-volume threshold on a closed bar.")
alertcondition(spikeEvent, "RVOL spike (closed)", "Volume Radar [Artio]: unusual relative-volume spike on a closed bar.")
if buyEvent or sellEvent or conflictEvent or highEvent or spikeEvent
    string eventText = buyEvent ? f_txt("buy-side response", "результат покупок≈") : sellEvent ? f_txt("sell-side response", "результат продаж≈") : conflictEvent ? f_txt("delta/price conflict", "конфликт дельты и цены") : ""
    string activityText = spikeEvent ? f_txt("VOLUME SPIKE", "ВСПЛЕСК ОБЪЁМА") : highEvent ? f_txt("HIGH VOLUME", "МНОГО ОБЪЁМА") : ""
    string separator = eventText != "" and activityText != "" ? " + " : ""
    string eventLabel = activityText + separator + eventText
    alert("Volume Radar [Artio] · " + syminfo.tickerid + " · " + marketName + " · " + eventLabel + " · RVOL " + f_num(barRV) + "x · " + f_txt("estimated Δ ", "оценочная Δ ") + f_signed(shownDP) + "% · " + baselineName + f_txt(" · CLOSED. Observation, not an entry signal.", " · ЗАКР. Наблюдение, не сигнал входа."), alert.freq_once_per_bar_close)
 
// Reference: TradingView Pine Script v6 (reviewed 2026-10-28)
// https://www.tradingview.com/pine-script-docs/concepts/other-timeframes-and-data/
// https://www.tradingview.com/pine-script-docs/concepts/alerts/
// https://www.tradingview.com/pine-script-docs/concepts/chart-information/
// https://www.tradingview.com/pine-script-docs/concepts/time/

← 返回列表