Volume Pressure Atlas [MQLSoftware]

MQLSoftware · study · 471 行 · 点赞 157 · TradingView 原页

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

Pine Script

// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
// © MQLSoftware
//@version=6
//
// Volume Pressure Atlas [MQLSoftware]
//
// Question: under a stated OHLCV allocation model, where is assigned activity
// concentrated, and how balanced are its upward and downward components?
// Neither volume at price nor intrabar travel is observed by this script.
//
// PATH-TRAVEL MODEL (minimum path and uniform volume per distance)
//   Each bar is modelled as the SHORTEST continuous path consistent with its OHLC:
//   open -> low -> high -> close for bullish bars; open -> high -> low -> close
//   for bearish bars. Either extreme order ties for a doji, with no further
//   unobserved oscillation. Its volume is spread evenly over the DISTANCE travelled.
//   Consequences, all closed-form:
//   * Gross path length = 2 x range - |close - open| (the minimum possible).
//   * Price inside the body is crossed once, in the bar's direction. Price inside a
//     wick is crossed twice: once up, once down. This is one parsimonious model,
//     not evidence of the actual intrabar path or volume concentration.
//   * Per price row the engine therefore accumulates two separate components:
//       U = up-travel activity, D = down-travel activity, with U + D = row volume.
//   * Net = U - D comes only from bodies; wicks contribute equal U and D.
//   * Row imbalance E = |U - D| / (U + D) is a dimensionless share of assigned
//     activity. It is NOT a price-distance efficiency or measured trading result.
//     For one non-flat bar only, E = |C-O| / (2R-|C-O|).
//
// Retrospective period summaries: final rows are placed across the completed
// period. They were NOT available on those earlier bars. Loaded history, changed
// inputs, revised feed data and chart timeframe can change reconstructed profiles.
//
// WHAT IS DRAWN (per period, one "atlas")
//   * A vertical spine. Matched two-way travel min(U, D) is the slate CORE, drawn
//     symmetrically around the spine. The unmatched excess |U - D| is the coloured
//     WING on its own side: teal to the right (net up-travel), coral to the left
//     (net down-travel). Grey = matched allocation; colour = unmatched allocation.
//   * Activity-Imbalance Map: rows with elevated participation (row volume vs
//     the period's average active row), touched by several volume-bearing bars, whose
//     imbalance is at or BELOW the period's own reference imbalance are classed
//     "high activity · low imbalance" (sand core + zone band). Elevated rows whose
//     imbalance is far ABOVE it are "high activity · high imbalance" (vivid wing + side rail).
//     The two tests are log-symmetric: E <= Eref / contrast, E >= Eref x contrast.
//     Thresholds are relative to each period, so they adapt per symbol/timeframe.
//
// DATA LIMITATION
//   Standard OHLCV has no bid/ask aggressor data. U and D are an OHLCV path proxy of
//   up-travel and down-travel activity, NOT buy volume, sell volume, delta or order
//   flow. Forex/CFD feeds supply tick volume. Bars with zero or missing volume add
//   nothing; if the symbol reports no volume at all, the script says so and draws
//   nothing instead of fabricating weights.
//
// REPAINT POLICY
//   Bars enter a period only when confirmed. A committed atlas is built once, from
//   closed bars only, on the first bar of the next period and is never redrawn. The
//   developing atlas (dashed spine, faded) includes the forming bar and redraws until
//   the period ends — visual context only. The alert fires on commit only.
 
indicator("Volume Pressure Atlas [MQLSoftware]", shorttitle="VP Atlas", overlay=true, max_boxes_count=500, max_lines_count=100, max_labels_count=50)
 
// ─── CONSTANTS ────────────────────────────────────────────────────────────────
color VPA_UP_DEF   = #44AFA2  // mineral teal — net up-travel
color VPA_DN_DEF   = #D98064  // coral — net down-travel
color VPA_CORE_DEF = #6E7F91  // slate — matched two-way travel
color VPA_CONT_DEF = #AD9D74  // stone sand — high activity, low imbalance
 
// A period holds at most MAXB chart bars. Combinations that would exceed it step
// down to a shorter period; an irregular feed that still reaches it splits the
// period. Keeps memory and the commit workload bounded on every symbol.
int MAXB = 5000
 
// ─── INPUTS ───────────────────────────────────────────────────────────────────
var string G_P  = "Profile Period"
var string G_A  = "Activity Model"
var string G_E  = "Pressure & Imbalance"
var string G_V  = "Visual Appearance"
var string G_H  = "Historical Profiles"
var string G_AL = "Alerts"
 
string periodIn = input.string("Auto", "Period", group = G_P, options = ["Auto", "Day", "Week", "Month", "Quarter"], tooltip = "Each atlas covers one TradingView anchor period, following the symbol's exchange sessions. Auto: Day up to 15-minute charts, Week up to 1-hour, Month up to 4-hour, Quarter on Daily, Year above. A period at or below the chart timeframe moves up automatically; a period that could hold more than 5,000 chart bars (estimated for a 24/7 session) moves down.")
 
string densIn  = input.string("Balanced", "Rows per Atlas", group = G_A, options = ["Compact", "Balanced", "Fine"], tooltip = "Each atlas divides its own high-low range into a fixed number of equal price rows: Compact 24, Balanced 36, Fine 48. Finer rows reduce how many historical atlases fit the drawing budget.")
int minVisits  = input.int(3, "Repeat Threshold (bars per row)", group = G_A, minval = 1, maxval = 12, tooltip = "A row can only be classed 'high activity · low imbalance' when at least this many separate bars intersected it with usable volume. These are bar intersections, not observed separate visits.")
 
float partThr  = input.float(1.25, "Elevated Participation (x average row)", group = G_E, minval = 1.0, maxval = 3.0, step = 0.05, tooltip = "A row counts as elevated participation when its activity is at least this multiple of the period's average active row. Both activity classes require it.")
float effCon   = input.float(2.0, "Imbalance Contrast", group = G_E, minval = 1.25, maxval = 4.0, step = 0.25, tooltip = "How far a row's imbalance must sit from the period's reference imbalance (Eref = sum|U-D| / sum(U+D)). Low imbalance: E <= Eref / contrast. High imbalance: E >= Eref x contrast (no class when the threshold exceeds 1). Higher = stricter, fewer classified rows.")
bool showBands = input.bool(true, "High Activity · Low Imbalance Bands", group = G_E, tooltip = "Shades up to three strongest contiguous 'high activity · low imbalance' zones across the period. The newest committed atlas carries a short caption.")
bool showRails = input.bool(true, "High Activity · High Imbalance Rails", group = G_E, tooltip = "Marks contiguous 'high activity · high imbalance' rows with a rail on the outer edge of the wing side (teal right = up, coral left = down).")
 
string placeIn = input.string("Centered", "Placement", group = G_V, options = ["Centered", "Left"], tooltip = "Centered puts the spine in the middle of the period. Left anchors the coral side at the period start.")
int widthPct   = input.int(60, "Atlas Width (% of period)", group = G_V, minval = 20, maxval = 90, tooltip = "Full width of the atlas (both sides) as a share of the period's bar count. The widest row side reaches half of it.")
int fillStr    = input.int(100, "Fill Strength", group = G_V, minval = 30, maxval = 100, tooltip = "Scales the opacity of all fills. Lower it if the atlas competes with candles.")
color colUp    = input.color(VPA_UP_DEF, "Up-travel", group = G_V)
color colDn    = input.color(VPA_DN_DEF, "Down-travel", group = G_V)
color colCore  = input.color(VPA_CORE_DEF, "Matched", group = G_V)
color colCont  = input.color(VPA_CONT_DEF, "Low imbalance", group = G_V)
bool showTags  = input.bool(true, "Period Net Tags", group = G_V, tooltip = "Small tag above each spine: net up/down-travel share of the period's activity. Hover it for the period's details.")
bool showLeg   = input.bool(true, "Legend", group = G_V)
string legPos  = input.string("Bottom Right", "Legend Position", group = G_V, options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"])
 
int keepIn     = input.int(5, "Committed Atlases to Keep", group = G_H, minval = 1, maxval = 8, tooltip = "Completed periods kept on the chart. Capped automatically by the 500-box drawing budget: With developing enabled: Balanced fits 5, Fine 3, Compact 7. The 450-box working budget reserves 50 boxes.")
bool showLive  = input.bool(true, "Developing Atlas", group = G_H, tooltip = "Atlas of the current, unfinished period, including the forming bar. Dashed spine, faded fills. Redraws until the period ends — context, not a signal.")
 
bool alertOn   = input.bool(true, "Alert on Period Commit", group = G_AL, tooltip = "For alert() based alerts: one message when the next period's first chart bar closes, with the finalized allocation imbalance and any 'high activity · low imbalance' zones. Built from closed bars only.")
 
int rowsIn = densIn == "Compact" ? 24 : densIn == "Balanced" ? 36 : 48
 
// ─── PERIOD RESOLUTION ────────────────────────────────────────────────────────
f_up(string a) =>
    a == "60" ? "240" : a == "240" ? "D" : a == "D" ? "W" : a == "W" ? "M" : a == "M" ? "3M" : "12M"
 
f_down(string a) =>
    a == "12M" ? "3M" : a == "3M" ? "M" : a == "M" ? "W" : a == "W" ? "D" : a == "D" ? "240" : "60"
 
int CHART_SEC = timeframe.in_seconds()
string pick = periodIn == "Day" ? "D" : periodIn == "Week" ? "W" : periodIn == "Month" ? "M" : periodIn == "Quarter" ? "3M" : CHART_SEC <= 900 ? "D" : CHART_SEC <= 3600 ? "W" : CHART_SEC <= 14400 ? "M" : CHART_SEC <= 86400 ? "3M" : "12M"
string ANCH = pick
if timeframe.in_seconds(ANCH) <= CHART_SEC
    ANCH := f_up(ANCH)
if timeframe.in_seconds(ANCH) <= CHART_SEC
    ANCH := f_up(ANCH)
if timeframe.in_seconds(ANCH) <= CHART_SEC
    ANCH := f_up(ANCH)
if timeframe.in_seconds(ANCH) <= CHART_SEC
    ANCH := f_up(ANCH)
if timeframe.in_seconds(ANCH) / CHART_SEC > MAXB
    ANCH := f_down(ANCH)
if timeframe.in_seconds(ANCH) / CHART_SEC > MAXB
    ANCH := f_down(ANCH)
if timeframe.in_seconds(ANCH) / CHART_SEC > MAXB
    ANCH := f_down(ANCH)
if timeframe.in_seconds(ANCH) / CHART_SEC > MAXB
    ANCH := f_down(ANCH)
if timeframe.in_seconds(ANCH) / CHART_SEC > MAXB
    ANCH := f_down(ANCH)
string pName = ANCH == "60" ? "1-hour" : ANCH == "240" ? "4-hour" : ANCH == "D" ? "Daily" : ANCH == "W" ? "Weekly" : ANCH == "M" ? "Monthly" : ANCH == "3M" ? "Quarterly" : "Yearly"
bool newPeriod = timeframe.change(ANCH)
 
// Drawing budget: reserve 50 of Pine's 500 boxes; delete before replacement.
// Every atlas uses at most 2 boxes per row plus 3 zone bands.
int perAtlas = 2 * rowsIn + 3
int keepEff  = math.max(1, math.min(keepIn, int(math.floor((450 - (showLive ? perAtlas : 0)) / perAtlas))))
 
// ─── TYPES ────────────────────────────────────────────────────────────────────
type AtlasDraw
    array<box>   bxs
    array<line>  lns
    array<label> lbs
    array<box>   bands
    float  netPct = na
    float  effRef = na
    int    nCont  = 0
    int    nDrive = 0
    string zones  = ""
 
method wipe(AtlasDraw this) =>
    for b in this.bxs
        b.delete()
    for b in this.bands
        b.delete()
    for l in this.lns
        l.delete()
    for t in this.lbs
        t.delete()
    0
 
// ─── HELPERS ──────────────────────────────────────────────────────────────────
f_pos(string p) =>
    p == "Top Right" ? position.top_right : p == "Top Left" ? position.top_left : p == "Bottom Left" ? position.bottom_left : position.bottom_right
 
// opacity: fill-strength scaling, developing atlas faded to 70 %
f_tr(int t, bool isDev) =>
    float vis = (100 - t) * fillStr / 100.0 * (isDev ? 0.7 : 1.0)
    int(math.round(100 - vis))
 
// Equal rows over the period's range; never thinner than one tick.
f_grid(float lo, float hi, int rows) =>
    float r  = hi - lo
    float bh = math.max(r / rows, syminfo.mintick)
    int n = math.max(1, math.min(rows, int(math.ceil(r / bh - 1e-9))))
    [n, bh]
 
// Path-travel allocation of ONE bar into the rows (see header).
// U/D: up/down-travel activity per row · T: number of bars that traded through a row.
f_addBar(array<float> U, array<float> D, array<int> T, float lo, float bh, int rows, float o, float h, float l, float c, float v) =>
    if v > 0 and not na(o) and not na(h) and not na(l) and not na(c) and h >= l and o >= l and o <= h and c >= l and c <= h
        float r = h - l
        int iL = math.max(0, math.min(rows - 1, int(math.floor((l - lo) / bh))))
        int iH = math.max(0, math.min(rows - 1, int(math.floor((h - lo) / bh))))
        if r <= 0
            // zero-range bar: no travel, no direction — split evenly in its row
            U.set(iL, U.get(iL) + 0.5 * v)
            D.set(iL, D.get(iL) + 0.5 * v)
            T.set(iL, T.get(iL) + 1)
        else
            float bLo = math.max(l, math.min(o, c))
            float bHi = math.min(h, math.max(o, c))
            float b   = math.max(0.0, bHi - bLo)
            float k   = v / (2.0 * r - b)   // volume per unit of travelled distance
            bool bull = c > o
            bool bear = c < o
            int i = iL
            while i <= iH
                float a = lo + i * bh
                float z = a + bh
                if i == 0
                    a := math.min(a, l)
                if i == rows - 1
                    z := math.max(z, h)
                float ov = math.max(0.0, math.min(z, h) - math.max(a, l))     // range inside row
                float ob = math.max(0.0, math.min(z, bHi) - math.max(a, bLo)) // body inside row
                float ow = math.max(0.0, ov - ob)                              // wick inside row
                if ov > 0
                    U.set(i, U.get(i) + k * (ow + (bull ? ob : 0.0)))
                    D.set(i, D.get(i) + k * (ow + (bear ? ob : 0.0)))
                    T.set(i, T.get(i) + 1)
                i += 1
    0
 
// ─── STATE ────────────────────────────────────────────────────────────────────
var array<float> aO = array.new<float>()
var array<float> aH = array.new<float>()
var array<float> aL = array.new<float>()
var array<float> aC = array.new<float>()
var array<float> aV = array.new<float>()
var int   pStart    = na
var float pLo       = na
var float pHi       = na
var bool  sawVol    = false
var bool  splitNext = false
var bool  pPartial  = true
var array<AtlasDraw> hist = array.new<AtlasDraw>()
var AtlasDraw live = na
 
f_build(float lo, float bh, int rows, bool withForming) =>
    array<float> U = array.new<float>(rows, 0.0)
    array<float> D = array.new<float>(rows, 0.0)
    array<int>   T = array.new<int>(rows, 0)
    int n = aO.size()
    int j = 0
    while j < n
        f_addBar(U, D, T, lo, bh, rows, aO.get(j), aH.get(j), aL.get(j), aC.get(j), aV.get(j))
        j += 1
    if withForming
        f_addBar(U, D, T, lo, bh, rows, open, high, low, close, math.max(nz(volume), 0.0))
    [U, D, T]
 
// ─── CLASSIFY + RENDER ONE ATLAS ──────────────────────────────────────────────
// class per row: 0 ordinary · 1 high activity / low imbalance · +2 / -2 high activity · high imbalance
f_render(array<float> U, array<float> D, array<int> T, float lo, float bh, int rows, int xL, int xR, bool isDev, bool caption, bool partial) =>
    AtlasDraw d = AtlasDraw.new(array.new<box>(), array.new<line>(), array.new<label>(), array.new<box>())
    float gSum = 0.0
    float nSum = 0.0
    float aSum = 0.0
    float sMax = 0.0
    int act = 0
    for i = 0 to rows - 1
        float u = U.get(i)
        float w = D.get(i)
        if u + w > 0
            gSum += u + w
            nSum += u - w
            aSum += math.abs(u - w)
            sMax := math.max(sMax, math.max(u, w))
            act  += 1
    if gSum > 0 and sMax > 0
        float meanG = gSum / act
        float eRef  = aSum / gSum
        float loThr = eRef / effCon
        // log-symmetric to loThr: Eref / contrast  <->  Eref x contrast (no class when the threshold exceeds 1)
        float hiThr = eRef * effCon
        int span = math.max(1, xR - xL + 1)
        int hw   = math.max(1, int(math.round(span * widthPct / 200.0)))
        int x0   = placeIn == "Centered" ? xL + int(math.floor(span / 2.0)) : xL + hw
        float gap = bh * 0.12
        array<int> cls = array.new<int>(rows, 0)
        for i = 0 to rows - 1
            float u = U.get(i)
            float w = D.get(i)
            float g = u + w
            if g > 0
                float rel = g / meanG
                float e   = math.abs(u - w) / g
                int c = 0
                if rel >= partThr and T.get(i) >= minVisits and e <= loThr
                    c := 1
                else if rel >= partThr and e >= hiThr and u != w
                    c := u > w ? 2 : -2
                cls.set(i, c)
                float kk  = math.min(1.0, rel / partThr)
                float yB  = lo + i * bh + gap
                float yT  = lo + (i + 1) * bh - gap
                int ext  = int(math.round(hw * math.max(u, w) / sMax))
                int core = int(math.round(hw * math.min(u, w) / sMax))
                if core > 0
                    int tC = c == 1 ? 42 : int(math.round(88 - 28 * kk))
                    d.bxs.push(box.new(x0 - core, yT, x0 + core, yB, border_color = color.new(colCore, 100), bgcolor = color.new(c == 1 ? colCont : colCore, f_tr(tC, isDev))))
                if ext > core
                    int tW = math.abs(c) == 2 ? 0 : int(math.round(42 - 36 * kk))
                    if u > w
                        d.bxs.push(box.new(x0 + core, yT, x0 + ext, yB, border_color = color.new(colUp, 100), bgcolor = color.new(colUp, f_tr(tW, isDev))))
                    else
                        d.bxs.push(box.new(x0 - ext, yT, x0 - core, yB, border_color = color.new(colDn, 100), bgcolor = color.new(colDn, f_tr(tW, isDev))))
        // contiguous runs → zones
        array<int>   rS = array.new<int>()
        array<int>   rE = array.new<int>()
        array<float> rG = array.new<float>()
        int rails = 0
        int i2 = 0
        while i2 < rows
            int c0 = cls.get(i2)
            if c0 != 0
                int j = i2
                float gg = 0.0
                float runMax = 0.0
                while j < rows and cls.get(j) == c0
                    gg += U.get(j) + D.get(j)
                    runMax := math.max(runMax, c0 > 0 ? U.get(j) : D.get(j))
                    j += 1
                if c0 == 1
                    d.nCont := d.nCont + (j - i2)
                    rS.push(i2)
                    rE.push(j - 1)
                    rG.push(gg)
                else
                    d.nDrive := d.nDrive + (j - i2)
                    if showRails and rails < 4
                        int runWidth = int(math.round(hw * runMax / sMax))
                        int xr = c0 > 0 ? x0 + runWidth + 1 : math.max(0, x0 - runWidth - 1)
                        d.lns.push(line.new(xr, lo + j * bh - gap, xr, lo + i2 * bh + gap, color = color.new(c0 > 0 ? colUp : colDn, isDev ? 35 : 0), style = isDev ? line.style_dotted : line.style_solid, width = 2))
                        rails += 1
                i2 := j
            else
                i2 += 1
        int picked = 0
        while picked < 3 and rG.size() > 0
            int bi = 0
            for q = 0 to rG.size() - 1
                if rG.get(q) > rG.get(bi)
                    bi := q
            float zLo = lo + rS.get(bi) * bh
            float zHi = lo + (rE.get(bi) + 1) * bh
            if showBands
                d.bands.push(box.new(xL, zHi, xR, zLo, border_color = color.new(colCont, f_tr(72, isDev)), border_style = line.style_dotted, bgcolor = color.new(colCont, f_tr(91, isDev)), text = caption ? "high activity · low imbalance" : "", text_size = size.tiny, text_color = color.new(colCont, 25), text_halign = text.align_right, text_valign = text.align_center))
            d.zones := d.zones + (d.zones == "" ? "" : ", ") + str.tostring(zLo, format.mintick) + "–" + str.tostring(zHi, format.mintick)
            rS.remove(bi)
            rE.remove(bi)
            rG.remove(bi)
            picked += 1
        // spine + period tag
        float top = lo + rows * bh
        d.lns.push(line.new(x0, top, x0, lo, color = color.new(colCore, isDev ? 55 : 30), style = isDev ? line.style_dashed : line.style_solid, width = 1))
        d.netPct := 100.0 * nSum / gSum
        d.effRef := 100.0 * eRef
        if showTags
            bool upN = d.netPct >= 0.5
            bool dnN = d.netPct <= -0.5
            string arrow = upN ? "▲" : dnN ? "▼" : "◆"
            color tc = upN ? colUp : dnN ? colDn : colCore
            string tt = (partial ? "PARTIAL PERIOD / capped segment\n" : "") + (isDev ? "DEVELOPING " + pName + " period — redraws until the period closes." : "COMMITTED " + pName + " period — built from closed bars, final.") + "\nSigned allocation imbalance: " + str.tostring(d.netPct, "#.#") + "%" + "\nReference imbalance Eref: " + str.tostring(d.effRef, "#.#") + "%" + "\nHigh activity · low imbalance rows: " + str.tostring(d.nCont) + "\nHigh activity · high imbalance rows: " + str.tostring(d.nDrive) + "\n" + str.tostring(rows) + " rows · " + str.tostring(bh, format.mintick) + " per row" + "\nOHLCV path proxy — not bid/ask buy or sell volume."
            d.lbs.push(label.new(x0, top, (isDev ? "dev · " : "") + (partial ? "partial · " : "") + arrow + " " + str.tostring(math.abs(d.netPct), "#") + "%", style = label.style_label_down, color = color.new(tc, 100), textcolor = color.new(tc, isDev ? 30 : 5), size = size.small, tooltip = tt))
    d
 
// ─── PERIOD COMMIT (first bar of the next period; closed bars only) ───────────
bool startNew = newPeriod or splitNext
bool committedNow = false
string commitMsg  = ""
if startNew and not na(pStart) and aO.size() > 0 and not na(pLo)
    [nRows, bh] = f_grid(pLo, pHi, rowsIn)
    [U, D, T] = f_build(pLo, bh, nRows, false)
    if hist.size() > 0
        for b in hist.last().bands
            b.set_text("")
    // Retire the old developing drawing before a commit creates its replacement.
    if not na(live)
        live.wipe()
        live := na
    // free the oldest atlas BEFORE drawing the new one, so the box peak never
    // exceeds the budget (kept + developing + new) on a realtime period roll
    while hist.size() >= keepEff
        hist.shift().wipe()
    AtlasDraw dr = f_render(U, D, T, pLo, bh, nRows, pStart, bar_index - 1, false, true, pPartial or splitNext)
    if na(dr.netPct)
        dr.wipe()       // period without any volume: nothing to show
    else
        hist.push(dr)
        committedNow := true
        string ar = dr.netPct >= 0.5 ? "▲" : dr.netPct <= -0.5 ? "▼" : "◆"
        commitMsg := syminfo.ticker + " " + timeframe.period + " · " + pName + " atlas committed · OHLCV allocation imbalance " + ar + " " + str.tostring(math.abs(dr.netPct), "#.#") + "% · " + (dr.nCont > 0 ? str.tostring(dr.nCont) + " high-activity/low-imbalance row(s) at " + dr.zones : "no high-activity/low-imbalance zone") + (dr.nDrive > 0 ? " · " + str.tostring(dr.nDrive) + " high-activity/high-imbalance row(s)" : "")
    while hist.size() > keepEff
        hist.shift().wipe()
 
// ─── PERIOD RESET ─────────────────────────────────────────────────────────────
if startNew or barstate.isfirst
    pStart    := bar_index
    pLo       := na
    pHi       := na
    pPartial  := barstate.isfirst or (splitNext and not newPeriod)
    splitNext := false
    aO.clear()
    aH.clear()
    aL.clear()
    aC.clear()
    aV.clear()
 
// ─── ACCUMULATION (confirmed bars only) ───────────────────────────────────────
if barstate.isconfirmed
    float v = math.max(nz(volume), 0.0)
    if v > 0
        sawVol := true
    aO.push(open)
    aH.push(high)
    aL.push(low)
    aC.push(close)
    aV.push(v)
    pLo := na(pLo) ? low : math.min(pLo, low)
    pHi := na(pHi) ? high : math.max(pHi, high)
    if aO.size() >= MAXB
        splitNext := true
 
// ─── DEVELOPING ATLAS (last bar only — visual context) ────────────────────────
if barstate.islast
    if not na(live)
        live.wipe()
    live := na
    bool forming = not barstate.isconfirmed
    if showLive and not na(pStart) and (aO.size() > 0 or forming)
        float lo2 = forming ? (na(pLo) ? low : math.min(pLo, low)) : pLo
        float hi2 = forming ? (na(pHi) ? high : math.max(pHi, high)) : pHi
        if not na(lo2) and not na(hi2)
            [nRowsL, bhL] = f_grid(lo2, hi2, rowsIn)
            [UL, DL, TL] = f_build(lo2, bhL, nRowsL, forming)
            live := f_render(UL, DL, TL, lo2, bhL, nRowsL, pStart, bar_index, true, false, pPartial)
 
// ─── LEGEND / DATA STATE ──────────────────────────────────────────────────────
var table tbl = na
if barstate.islast
    if not na(tbl)
        tbl.delete()
    color fg = chart.fg_color
    bool hasVolume = sawVol or (not barstate.isconfirmed and nz(volume) > 0)
    if not hasVolume
        tbl := table.new(f_pos(legPos), 1, 2, bgcolor = color.new(chart.bg_color, 5), frame_color = color.new(fg, 75), frame_width = 1)
        tbl.cell(0, 0, "VOLUME PRESSURE ATLAS", text_color = color.new(fg, 30), text_size = size.small, text_halign = text.align_left)
        tbl.cell(0, 1, "Volume data unavailable on this symbol.\nThe atlas needs reported or tick volume\nand draws nothing without it.", text_color = color.new(colCont, 0), text_size = size.small, text_halign = text.align_left)
    else if showLeg
        tbl := table.new(f_pos(legPos), 2, 7, bgcolor = color.new(chart.bg_color, 8), frame_color = color.new(fg, 82), frame_width = 1)
        tbl.cell(0, 0, "VOLUME PRESSURE ATLAS · " + pName + " · OHLCV proxy", text_color = color.new(fg, 35), text_size = size.tiny, text_halign = text.align_left)
        tbl.merge_cells(0, 0, 1, 0)
        tbl.cell(0, 1, "███", text_color = colUp, text_size = size.tiny)
        tbl.cell(1, 1, "net up-travel  (right wing)", text_color = color.new(fg, 25), text_size = size.tiny, text_halign = text.align_left)
        tbl.cell(0, 2, "███", text_color = colDn, text_size = size.tiny)
        tbl.cell(1, 2, "net down-travel  (left wing)", text_color = color.new(fg, 25), text_size = size.tiny, text_halign = text.align_left)
        tbl.cell(0, 3, "███", text_color = color.new(colCore, 20), text_size = size.tiny)
        tbl.cell(1, 3, "matched allocation  (core)", text_color = color.new(fg, 25), text_size = size.tiny, text_halign = text.align_left)
        tbl.cell(0, 4, "███", text_color = colCont, text_size = size.tiny)
        tbl.cell(1, 4, "high activity · low imbalance", text_color = color.new(fg, 25), text_size = size.tiny, text_halign = text.align_left)
        tbl.cell(0, 5, "┃", text_color = colUp, text_size = size.tiny)
        tbl.cell(1, 5, "high activity · high imbalance  (rail)", text_color = color.new(fg, 25), text_size = size.tiny, text_halign = text.align_left)
        string devTxt = showLive ? "developing: no usable volume" : "developing: off"
        if not na(live)
            if not na(live.netPct)
                devTxt := "developing: net " + (live.netPct >= 0.5 ? "▲ " : live.netPct <= -0.5 ? "▼ " : "◆ ") + str.tostring(math.abs(live.netPct), "#") + "% · " + str.tostring(live.nCont) + " low-imbalance row(s)"
        tbl.cell(0, 6, devTxt, text_color = color.new(fg, 45), text_size = size.tiny, text_halign = text.align_left, tooltip = "Developing values include the forming bar and change until the period closes.")
        tbl.merge_cells(0, 6, 1, 6)
 
// ─── ALERTS (commit only — finalized data) ────────────────────────────────────
if committedNow and alertOn
    alert(commitMsg, alert.freq_once_per_bar_close)
 
alertcondition(committedNow and barstate.isconfirmed, "Atlas committed", "A closed-period atlas was committed at the close of the next period's first chart bar. Use an alert() based alert for the message with net pressure and zone prices.")

← 返回列表