PRO Session Volume Profile & Levels [Artio]

Artio_Scalping_Life · study · 1954 行 · 点赞 67 · TradingView 原页

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

Pine Script

//@version=6
indicator("Session Volume Profile & Levels [Artio]", "SVP[Artio]", overlay = true, behind_chart = true,     max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500,
     max_polylines_count = 100, max_bars_back = 500, dynamic_requests = true)
 
// ── Inputs ────────────────────────────────────────────────────────────────────
string G_DATA = "1 · Data and profile"
string profileMode = input.string("Auto: FP + proxy", "Profile source", options = ["Auto: FP + proxy", "TV footprint", "1m OHLCV proxy", "Off"], group = G_DATA,
     tooltip = "This edition requires Premium/Ultimate in every mode. Auto uses TV footprints and explicitly labelled proxy fallback. A proxy is not exchange volume-at-price. CFD data is not CME data.")
string referencePick = input.string("Auto", "Reference profile", options = ["Auto", "ASIA", "LONDON", "LONDON PRE-NY", "NY GOLD", "US PM", "GC DAY"], group = G_DATA)
float rowPrice = input.float(0.1, "Source row size in price units ($/oz for GC)", minval = 0.01, step = 0.10, group = G_DATA)
float vaPercent = input.float(70, "Value area, %", minval = 30, maxval = 95, step = 1, group = G_DATA)
int historyMinutes = input.int(24000, "Source 1m bars requested", minval = 1500, maxval = 200000, step = 1500, group = G_DATA,
     tooltip = "Requested 1m intrabars, not guaranteed calendar depth. 90–180 calendar days can exceed the intrabar allowance of the TradingView plan/feed. The map shows only data actually returned; increasing this value never invents missing history.")
float minCoverage = input.float(95, "Minimum profile coverage, %", minval = 50, maxval = 100, group = G_DATA)
int maxBins = input.int(4000, "Maximum source bins per session", minval = 500, maxval = 6000, group = G_DATA)
int ticksPerRow = math.max(1, int(math.round(rowPrice / syminfo.mintick)))
float rowStep = ticksPerRow * syminfo.mintick
 
bool showVolumePace = input.bool(true, "Session volume pace versus the same elapsed minutes", group = G_DATA,
     tooltip = "Compared with complete saved sessions of the same type. At least two samples required. Compare equal elapsed minutes, not a partial session with a full one. Not a forecast.")
 
string G_TIME = "2 · Analysis windows · local clocks"
string asiaSession = input.session("0900-1600", "Asia · Asia/Tokyo", group = G_TIME)
string londonSession = input.session("0800-1630", "London · Europe/London", group = G_TIME)
string nySession = input.session("0820-1330", "NY Gold · America/New_York", group = G_TIME)
string pmSession = input.session("1330-1700", "US PM · America/New_York", group = G_TIME)
bool londonSnapshot = input.bool(true, "Freeze London PRE-NY at NY Gold open", group = G_TIME)
string daySession = input.session("1800-1700", "Trading day · America/New_York", group = G_TIME,
     tooltip = "Default is a GC-oriented analysis window, not a universal schedule for gold products. Weekends and holidays depend on feed bars.")
 
string G_RULES = "3 · Observation rules · not predictions"
int acceptCloses = input.int(3, "Hold: consecutive closed 1m bars", minval = 2, maxval = 10, group = G_RULES)
int reclaimWindow = input.int(3, "Quick return: maximum minutes", minval = 1, maxval = 15, group = G_RULES)
float atrBuffer = input.float(0.08, "Level buffer: fraction of 1m ATR(14)", minval = 0.0, maxval = 0.5, step = 0.01, group = G_RULES)
int tickBuffer = input.int(2, "Minimum level buffer, ticks", minval = 1, maxval = 50, group = G_RULES)
int scenarioLife = input.int(45, "Setup life from return/hold, minutes", minval = 5, maxval = 180, group = G_RULES)
int levelLifeHours = input.int(96, "Level lifetime, hours", minval = 12, maxval = 120, group = G_RULES)
float minRoomR = input.float(1.5, "Minimum room to objective, R", minval = 0.5, maxval = 5, step = 0.1, group = G_RULES,
     tooltip = "Price geometry from the latest closed minute. Not profit, probability or position size. Excludes fees, spread and slippage.")
bool checkFirstLevel = input.bool(true, "Require room to first mapped level", group = G_RULES,
     tooltip = "Also checks distance from the latest close to the nearest completed POC/VA/H/L in the setup direction, using the same R threshold. Tested levels count as context obstacles, not proven resistance. Shared by status and alerts. Turn off to retain the old objective-only rule.")
bool manualPause = input.bool(false, "Manual pause: news / trading block", group = G_RULES,
     tooltip = "No live CPI/NFP/FOMC calendar is connected. A clock window does not prove that a news event is scheduled.")
 
bool enableAlerts = input.bool(true, "New-retest alerts on 1m chart only", group = G_RULES)
// Plan text is shown only when the optional on-chart table is enabled.
 
string G_VIS = "4 · Clean session map"
int historyDays = input.int(30, "History span, calendar days", minval = 1, maxval = 180, group = G_VIS,
     tooltip = "Selects completed Asia/London/NY/PM windows by age. Pine can draw at most 500 boxes, so the renderer keeps a safety budget and reports clipping in the status card. Full 1m history may also be shorter than this setting.")
int detailProfiles = input.int(24, "Detailed VP sessions", minval = 0, maxval = 24, group = G_VIS,
     tooltip = "Only the newest N completed/live windows draw the full VP histogram. Older retained windows stay as clean context boxes. 24 is a safe default ceiling for multi-band VP under Pine's 100-polyline limit.")
bool historyAsia = input.bool(true, "History: Asia", inline = "histSessions", group = G_VIS)
bool historyLondon = input.bool(true, "London", inline = "histSessions", group = G_VIS)
bool historyNY = input.bool(true, "NY", inline = "histSessions", group = G_VIS)
bool historyPM = input.bool(true, "PM", inline = "histSessions", group = G_VIS,
     tooltip = "Choose which completed session families consume the historical box budget. With fewer families enabled you can look much farther back inside Pine's 500-box ceiling.")
bool showRanges = input.bool(true, "Session boxes", group = G_VIS)
bool miniProfiles = input.bool(true, "Volume profile inside every session", group = G_VIS)
bool showSessionValue = input.bool(true, "Completed POC / VAH / VAL", group = G_VIS)
bool showActiveVA = input.bool(true, "Developing POC / VAH / VAL · DEV", group = G_VIS)
string profileSide = input.string("Left", "Profile side", options = ["Left", "Right"], group = G_VIS)
int sessionRows = input.int(500, "Maximum displayed profile rows", minval = 50, maxval = 1000, group = G_VIS,
     tooltip = "Fine step contour, not large boxes. Does not invent detail finer than the source grid. A 0.1 grid across $30 has about 300 rows, not an artificial 500.")
int sessionVPWidth = input.int(40, "Profile width, % of session", minval = 0, maxval = 100, group = G_VIS)
bool avoidProfileOverlap = input.bool(true, "Limit profile width before the next profile", group = G_VIS)
int rangeTransparency = input.int(99, "Session fill transparency, %", minval = 0, maxval = 100, group = G_VIS)
int profileTransparency = input.int(0, "Profile extra transparency, %", minval = 0, maxval = 100, group = G_VIS,
     tooltip = "Adds transparency on top of the selected profile colors. 0 keeps each color's own alpha; 100 makes the histogram invisible while levels/boxes remain.")
string sessionLabelMode = input.string("Codes top-left", "Session labels",
     options = ["Codes top-left", "Codes + bottom title", "Bottom title only", "Off"], group = G_VIS,
     tooltip = "Default keeps AS/LN/NY/PM inside the box at top-left. Codes + bottom title adds the full name near the lower-left corner. Bottom title only removes the code. Off hides all session text; boxes and profiles remain.")
int titlePadBars = input.int(1, "Bottom title left padding, bars", minval = 0, maxval = 6, group = G_VIS)
float titlePadY = input.float(3.0, "Bottom title vertical padding, % of box", minval = 0.0, maxval = 20.0, step = 0.5, group = G_VIS)
int titleFont = input.int(10, "Bottom title font, pt", minval = 8, maxval = 14, group = G_VIS)
bool showDayVWAP = input.bool(false, "Day VWAP · optional", group = G_VIS)
bool showSessionVWAP = input.bool(false, "Session VWAP · optional", group = G_VIS)
bool showPreNYMap = input.bool(true, "Extra London PRE-NY box · optional", group = G_VIS)
string profileStyle = input.string("Up/Down", "Profile display", options = ["Up/Down", "Total", "Up/Down + Delta"], group = G_VIS,
     tooltip = "Up/Down splits classified volume. Delta is a separate narrow signed-difference lane. TV footprints use TradingView classification, not direct CME aggressor tape. Proxy components remain labelled approximations.")
string G_COL = "5 · Profile colors"
color vpUp = input.color(color.new(#93969B, 45), "Up Volume outside value", group = G_COL)
color vpDown = input.color(color.new(#777A80, 45), "Down Volume outside value", group = G_COL)
color vaUp = input.color(color.new(#3C9344, 22), "Value Area Up", group = G_COL)
color vaDown = input.color(color.new(#9563C6, 22), "Value Area Down", group = G_COL)
color pocColor = input.color(#E88142, "POC · orange", group = G_COL)
color vahColor = input.color(#4265FF, "VAH · blue", group = G_COL)
color valColor = input.color(#E91E63, "VAL · pink", group = G_COL)
int pocWidth = input.int(2, "POC line width", minval = 1, maxval = 4, group = G_COL)
string G_LVL = "6 · Level history · after session close"
string extensionMode = input.string("Until touch", "Extend POC / VAH / VAL", options = ["Until touch", "To now", "Off"], group = G_LVL)
string extendCountMode = input.string("Manual", "Extend profile count", options = ["Auto from history", "Manual"], group = G_LVL,
     tooltip = "Auto attempts to extend the retained history, then clamps to the remaining Pine line-object budget. Manual uses the next setting.")
int extendProfilesManual = input.int(30, "Extend last N profiles · manual", minval = 0, maxval = 70, group = G_LVL)
bool extendPOC = input.bool(true, "Extend POC Right", group = G_LVL)
bool extendVAH = input.bool(true, "Extend VAH Right", group = G_LVL)
bool extendVAL = input.bool(true, "Extend VAL Right", group = G_LVL)
bool touchDots = input.bool(false, "First-test dot · optional", group = G_LVL)
bool extensionLabels = input.bool(true, "Extended line names · AS-VAL / LN-POC", group = G_LVL)
string extensionLabelScope = input.string("Current ends", "Label which extensions", options = ["Current ends", "All ends"], group = G_LVL,
     tooltip = "Current ends: labels extensions reaching the latest processed minute. With Until touch, past tested endpoints remain clean. All ends also labels historical test endpoints. To now may include tested levels; hover for first-test history.")
int extensionLabelFont = input.int(10, "Extended line name font, pt", minval = 8, maxval = 14, group = G_LVL)
bool extensionLabelDate = input.bool(false, "Add session date to extended line names", group = G_LVL,
     tooltip = "The exact session date, level price and first-test record are always in the hover tooltip, even with this option off.")
bool extensionLabelPrice = input.bool(false, "Add price to extended line names", group = G_LVL)
int extensionLabelOffset = input.int(2, "Extended name offset after endpoint, bars", minval = 0, maxval = 12, group = G_LVL)
bool extensionLabelStagger = input.bool(true, "Separate nearby line names horizontally", group = G_LVL,
     tooltip = "Uses up to four estimated text columns. Only the text shifts; price levels and their endpoints never move. Exact duplicate price/endpoints are grouped. Names that cannot fit are omitted, not stacked.")
string londonPre = input.session("0700-0800", "London PRE · London time", group = G_LVL)
string nyPre = input.session("0700-0820", "NY PRE · New York time", group = G_LVL)
string nyOpen = input.session("0820-0930", "NY OPEN · New York time", group = G_LVL,
     tooltip = "Configurable clock phases, not participant identification. Overlapping windows are listed together.")
string displayZone = input.string("Etc/UTC", "Text / audit timezone", group = G_LVL)
string G_PANE = "7 · Optional on-chart table · OFF by default"
string panelMode = input.string("OFF", "Panel", options = ["TRADE MAP", "AUDIT", "OFF"], group = G_PANE,
     tooltip = "OFF (default): no table and no separate pane. TRADE MAP or AUDIT optionally draws a table on the main chart at Panel position. Table selection does not change profiles, levels, calculations or alerts.")
string panelPosition = input.string("Top left", "Panel position", options = ["Top left", "Bottom left", "Top right", "Bottom right"], group = G_PANE)
int ledgerRows = input.int(4, "Sessions in AUDIT mode", minval = 3, maxval = 10, group = G_PANE)
int panelText = input.int(13, "Panel font size, pt", minval = 10, maxval = 18, group = G_PANE)
int deskWrap = input.int(34, "Trade-map cell wrap width, characters", minval = 26, maxval = 48, group = G_PANE)
string uiTheme = input.string("Dark", "Card theme", options = ["Dark", "Light"], group = G_PANE)
bool debugLogs = input.bool(false, "Diagnostic Pine logs", group = G_PANE)
bool showClocks = false
bool showSignalMarkers = false
bool colorCandles = false
 
string G_BRAIN = "8 · Context and volume · closed 1m data"
int contextMinutes = input.int(30, "Direction context window, minutes", minval = 20, maxval = 90, group = G_BRAIN)
int pauseMinutes = input.int(12, "Short pause window, minutes", minval = 5, maxval = 30, group = G_BRAIN)
int spikeLookback = input.int(60, "Volume baseline: PREVIOUS minutes", minval = 20, maxval = 180, group = G_BRAIN)
float spikeMultiple = input.float(1.8, "Elevated volume: baseline multiple", minval = 1.2, maxval = 6, step = 0.1, group = G_BRAIN)
// Volume pulse text appears only in the optional table; calculations remain enabled.
int pulseCooldown = input.int(4, "Minimum minutes between same-type volume events", minval = 1, maxval = 30, group = G_BRAIN)
 
// ── Data types ────────────────────────────────────────────────────────────────
// First observations are immutable. A later event never overwrites the first test.
type Audit
    float price
    int kind
    int lastSide = 0
    int touchAt = na
    string touchWho = ""
    int crossAt = na
    string crossWho = ""
    int crossDir = 0
    bool crossGap = false
    bool interrupted = false
    bool touchUncertain = false
    bool returnGap = false
    int returnAt = na
    string returnWho = ""
    int holdAt = na
    string holdWho = ""
    int run = 0
    int wickAt = na
    bool wickGap = false
    int sweepAt = na
    string sweepWho = ""
 
type Session
    int sid
    int start
    int expectedEnd
    int lastEnd
    float hi
    float lo
    float op
    float cl
    float pv
    float vol
    float delta
    int bars
    int covered
    int gaps
    bool partial
    bool overflow
    map<int, float> bins
    map<int, float> buys
    map<int, float> sells
    float poc
    float vah
    float val
    bool naked
    float ibHi
    float ibLo
    int fpMinutes = 0
    int proxyMinutes = 0
    array<float> cumulative = na
    array<int> interactionState = na
    array<int> interactionTime = na
    array<string> interactionActor = na
    array<Audit> audit = na
 
type ExtensionName
    int endpoint
    float price
    int kind
    string caption
    string note
    bool tested
    int members = 1
 
type MapReference
    Session source
    Audit detail
 
type Level
    int sid
    string tag
    float price
    int side
    int born
    int state
    int run
    int crossedAt
    int eventAt
    float extreme
    float eps
    int direction
    float invalid
    int acceptedAt
    int setupAt = na
    int readyAt = na
    float entry = na
    float target = na
    string targetTag = ""
    float initialR = na
    bool gapBreach = false
    string kind = ""
 
type Event
    int t
    float price
    int direction
    string message
    bool failure
    string compact
    int sid = -1
    int side = 0
    string code = ""
    float volumeRatio = na
    float rangeRatio = na
 
type Pulse
    int t
    float price
    int kind
    float rv
    float rr
 
type Rail
    float price
    string name
    color cc
    int rank
    string note
    int stroke
    string lineStyle
 
type ClockMark
    int t
    string message
    float y
 
 
// ── Session clock functions: IANA zones, not fixed UTC offsets ────────────────
f_name(int sid) =>
    switch sid
        0 => "ASIA"
        1 => "LONDON"
        2 => "NY GOLD"
        3 => "US PM"
        5 => "LONDON PRE-NY"
        => "GC DAY"
 
f_zone(int sid) =>
    sid == 0 ? "Asia/Tokyo" : (sid == 1 or sid == 5) ? "Europe/London" : "America/New_York"
 
f_window(int sid) =>
    switch sid
        0 => asiaSession
        1 => londonSession
        2 => nySession
        3 => pmSession
        => daySession
 
f_color(int sid) =>
    bool light = uiTheme == "Light"
    switch sid
        0 => light ? color.rgb(30, 90, 174) : color.rgb(111, 176, 255)
        1 => light ? color.rgb(136, 90, 8) : color.rgb(248, 201, 105)
        5 => light ? color.rgb(136, 90, 8) : color.rgb(248, 201, 105)
        2 => light ? color.rgb(0, 119, 89) : color.rgb(75, 220, 176)
        3 => light ? color.rgb(112, 60, 182) : color.rgb(191, 157, 255)
        => light ? color.rgb(59, 79, 107) : color.rgb(199, 215, 236)
 
f_key(string ss, string tz) =>
    int sh = int(str.tonumber(str.substring(ss, 0, 2)))
    int sm = int(str.tonumber(str.substring(ss, 2, 4)))
    int eh = int(str.tonumber(str.substring(ss, 5, 7)))
    int em = int(str.tonumber(str.substring(ss, 7, 9)))
    int nowMin = hour(time, tz) * 60 + minute(time, tz)
    int fromMin = sh * 60 + sm
    int toMin = eh * 60 + em
    bool overnight = toMin <= fromMin
    bool inside = overnight ? (nowMin >= fromMin or nowMin < toMin) : (nowMin >= fromMin and nowMin < toMin)
    int shiftDay = overnight and nowMin < fromMin ? 1 : 0
    inside ? timestamp(tz, year(time, tz), month(time, tz), dayofmonth(time, tz) - shiftDay, sh, sm) : na
 
f_end(int key, int sid) =>
    string ss = f_window(sid)
    string tz = f_zone(sid)
    int sh = int(str.tonumber(str.substring(ss, 0, 2)))
    int sm = int(str.tonumber(str.substring(ss, 2, 4)))
    int eh = int(str.tonumber(str.substring(ss, 5, 7)))
    int em = int(str.tonumber(str.substring(ss, 7, 9)))
    int plusDay = eh * 60 + em <= sh * 60 + sm ? 1 : 0
    timestamp(tz, year(key, tz), month(key, tz), dayofmonth(key, tz) + plusDay, eh, em)
 
// Same closed-minute descriptive metrics on 1m, 5m and 1H.
// Volume denominator and range denominator EXCLUDE the measured candle.
// RV60 is a recent-volume ratio, NOT time-of-day-normalized RVOL.
f_regime_code(float er, float driftATR, float shortER, float compression, float priorDriftATR) =>
    int mode = 0
    if not na(er) and not na(driftATR)
        bool pause = not na(shortER) and not na(compression) and shortER <= 0.30 and compression <= 0.65
        if pause and not na(priorDriftATR) and priorDriftATR <= -2.5
            mode := -2
        else if pause and not na(priorDriftATR) and priorDriftATR >= 2.5
            mode := 2
        else if er >= 0.35 and driftATR >= 2.0
            mode := 1
        else if er >= 0.35 and driftATR <= -2.0
            mode := -1
        else if er <= 0.25
            mode := 3
        else
            mode := 4
    mode
 
f_pulse_code(float rv, float rr, float o, float h, float l, float c) =>
    int kind = 0
    if not na(rv) and not na(rr) and rv >= spikeMultiple
        float span = math.max(h - l, syminfo.mintick)
        float body = math.abs(c - o) / span
        float locationInBar = (c - l) / span
        if rr >= 1.2 and body >= 0.55 and c > o and locationInBar >= 0.75
            kind := 1
        else if rr >= 1.2 and body >= 0.55 and c < o and locationInBar <= 0.25
            kind := -1
        else if rr <= 0.85
            kind := 2
        else
            kind := 3
    kind
 
f_micro_metrics() =>
    float baseVol = ta.sma(volume, spikeLookback)[1]
    float priorATR = ta.atr(14)[1]
    // Reject non-contiguous source windows; a weekend is not one extra minute.
    bool volContinuous = not na(time[spikeLookback]) and time - time[spikeLookback] == spikeLookback * 60000
    int contextNeed = math.max(contextMinutes, pauseMinutes * 4)
    bool contextContinuous = not na(time[contextNeed]) and time - time[contextNeed] == contextNeed * 60000
    float rv = volContinuous and not na(volume) and baseVol > 0 ? volume / baseVol : na
    float rr = priorATR > 0 and time - time[1] == 60000 ? (high - low) / priorATR : na
    float path = math.sum(math.abs(ta.change(close)), contextMinutes)
    float shortPath = math.sum(math.abs(ta.change(close)), pauseMinutes)
    float er = path > 0 ? math.abs(close - close[contextMinutes]) / path : 0.0
    float shortER = shortPath > 0 ? math.abs(close - close[pauseMinutes]) / shortPath : 0.0
    float shortRange = ta.highest(high, pauseMinutes) - ta.lowest(low, pauseMinutes)
    float pastRange = ta.highest(high[pauseMinutes], pauseMinutes * 3) - ta.lowest(low[pauseMinutes], pauseMinutes * 3)
    float compression = pastRange > 0 ? shortRange / pastRange : na
    float pastATR = ta.atr(14)[pauseMinutes]
    float priorDriftATR = pastATR > 0 ? (close[pauseMinutes] - close[pauseMinutes * 4]) / pastATR : na
    float driftATR = priorATR > 0 ? (close - close[contextMinutes]) / priorATR : na
    int mode = contextContinuous ? f_regime_code(er, driftATR, shortER, compression, priorDriftATR) : 0
    [rv, rr, mode, contextContinuous ? er : na]
 
// This function is used ONLY by the single lower-TF request below.
// Never call it on the chart as well: that would create a second footprint context.
f_payload() =>
    footprint fp = request.footprint(ticksPerRow, vaPercent)
    [rv, rr, regime, er] = f_micro_metrics()
    [time, time_close, open, high, low, close, volume, ta.atr(14),
     f_key(asiaSession, "Asia/Tokyo"), f_key(londonSession, "Europe/London"),
     f_key(nySession, "America/New_York"), f_key(pmSession, "America/New_York"),
     f_key(daySession, "America/New_York"), fp, rv, rr, regime, er]
 
// ── Histogram mathematics ─────────────────────────────────────────────────────
// Fixed absolute-price grid. Native row volume is redistributed ONLY within that
// native row by interval overlap. This is not reconstruction of individual trades.
f_add_interval(Session s, float dn, float up, float v) =>
    if not na(v) and v > 0 and not s.overflow
        float width = math.max(up - dn, syminfo.mintick)
        float upper = dn + width
        int first = int(math.floor(dn / rowStep))
        int last = int(math.floor((upper - rowStep * 1e-8) / rowStep))
        if last - first > maxBins
            s.overflow := true
        else
            for k = first to last
                float overlap = math.max(0.0, math.min(upper, (k + 1) * rowStep) - math.max(dn, k * rowStep))
                float allocation = v * overlap / width
                if allocation > 0
                    if not map.contains(s.bins, k) and map.size(s.bins) >= maxBins
                        s.overflow := true
                        break
                    float old = map.contains(s.bins, k) ? map.get(s.bins, k) : 0.0
                    map.put(s.bins, k, old + allocation)
    s.overflow
 
f_add_side(map<int, float> target, float dn, float up, float v) =>
    if not na(v) and v > 0
        float width = math.max(up - dn, syminfo.mintick)
        int a = int(math.floor(dn / rowStep))
        int b = int(math.floor((dn + width - rowStep * 1e-8) / rowStep))
        if b - a <= maxBins
            for k = a to b
                float overlap = math.max(0.0, math.min(dn + width, (k + 1) * rowStep) - math.max(dn, k * rowStep))
                if overlap > 0
                    map.put(target, k, (map.contains(target, k) ? map.get(target, k) : 0.0) + v * overlap / width)
 
f_bin(Session s, int k) =>
    map.contains(s.bins, k) ? map.get(s.bins, k) : 0.0
 
f_coverage(Session s) =>
    s.bars > 0 ? 100.0 * s.covered / s.bars : 0.0
 
f_profile(Session s) =>
    int count = map.size(s.bins)
    if count > 0 and not s.overflow
        array<int> keys = map.keys(s.bins)
        array.sort(keys, order.ascending)
        int lower = array.first(keys)
        int upper = array.last(keys)
        // Empty grid rows count as zero. Do not silently jump across price gaps.
        if upper - lower + 1 > maxBins
            s.overflow := true
            s.poc := na
            s.vah := na
            s.val := na
        else
            float total = 0.0
            float peak = -1.0
            int pk = lower
            for k in keys
                float v = f_bin(s, k)
                total += v
                if v > peak
                    peak := v
                    pk := k
            int left = pk
            int right = pk
            float included = peak
            float target = total * vaPercent / 100.0
            while included < target and (left > lower or right < upper)
                float lv = left > lower ? f_bin(s, left - 1) : -1.0
                float rv = right < upper ? f_bin(s, right + 1) : -1.0
                // Deterministic tie: lower row first. No future data used.
                if lv >= rv and left > lower
                    left -= 1
                    included += math.max(lv, 0.0)
                else
                    right += 1
                    included += math.max(rv, 0.0)
            s.poc := math.round_to_mintick((pk + 0.5) * rowStep - syminfo.mintick * 0.5)
            s.val := left * rowStep
            s.vah := (right + 1) * rowStep
    count
 
f_good_profile(Session s) =>
    not s.partial and not s.overflow and s.gaps == 0 and f_coverage(s) >= minCoverage and not na(s.poc)
 
f_new_session(int sid, int key, int t, float o, float h, float l, float c) =>
    Session.new(sid, key, f_end(key, sid), t, h, l, o, c, 0.0, 0.0, 0.0, 0, 0, 0,
         t > key, false, map.new<int, float>(), map.new<int, float>(), map.new<int, float>(), na, na, na, true, h, l, 0, 0, array.new<float>(), array.new<int>(3, 0), array.new<int>(3, na), array.new<string>(3, ""))
 
f_update(Session s, int t, int tc, float o, float h, float l, float c, float v, footprint fp) =>
    if s.bars > 0 and t > s.lastEnd
        s.gaps += int(math.round((t - s.lastEnd) / 60000.0))
    float prevC = s.cl
    s.hi := math.max(s.hi, h)
    s.lo := math.min(s.lo, l)
    s.cl := c
    s.lastEnd := tc
    s.bars += 1
    if t < s.start + 60 * 60000
        s.ibHi := math.max(s.ibHi, h)
        s.ibLo := math.min(s.ibLo, l)
    bool got = false
    bool allowFP = profileMode == "Auto: FP + proxy" or profileMode == "TV footprint"
    if allowFP and not na(fp)
        array<volume_row> rows = fp.rows()
        float fpVol = fp.total_volume()
        if array.size(rows) > 0 and fpVol > 0
            for row in rows
                float rv = row.total_volume()
                float rd = row.down_price()
                float up = row.up_price()
                f_add_interval(s, rd, up, rv)
                f_add_side(s.buys, rd, up, row.buy_volume())
                f_add_side(s.sells, rd, up, row.sell_volume())
            // Use the SAME 1m HLC3 VWAP definition in all volume modes.
            float useVolume = not na(v) and v > 0 ? v : fpVol
            s.pv += (h + l + c) / 3.0 * useVolume
            s.vol += useVolume
            s.delta += fp.delta()
            s.fpMinutes += 1
            got := true
    bool allowProxy = profileMode == "Auto: FP + proxy" or profileMode == "1m OHLCV proxy"
    if not got and allowProxy and not na(v) and v > 0
        f_add_interval(s, l, h, v)
        bool rising = c > o or (c == o and c >= prevC)
        f_add_side(rising ? s.buys : s.sells, l, h, v)
        s.delta += rising ? v : -v
        s.pv += (h + l + c) / 3.0 * v
        s.vol += v
        s.proxyMinutes += 1
        got := true
    // Price-only mode still calculates conventional volume-weighted VWAP,
    // but does not fabricate a volume-at-price histogram or delta.
    if profileMode == "Off" and not na(v) and v > 0
        s.pv += (h + l + c) / 3.0 * v
        s.vol += v
        got := true
    if got
        s.covered += 1
    array.push(s.cumulative, s.vol)
    s.bars
 
f_finish(Session s, array<Session> completed, array<Level> levels) =>
    if s.lastEnd < s.expectedEnd
        s.partial := true
    f_profile(s)
    s.audit := array.new<Audit>()
    for k = 0 to 4
        float price = k == 0 ? s.poc : k == 1 ? s.vah : k == 2 ? s.val : k == 3 ? s.hi : s.lo
        int side = na(price) ? 0 : s.cl > price ? 1 : s.cl < price ? -1 : k == 3 ? -1 : k == 4 ? 1 : 0
        array.push(s.audit, Audit.new(price, k, side))
    array.push(completed, s)
    // Keep a long lightweight archive for historical boxes/levels, but retain heavy
    // VAP maps only for recent sessions that can realistically be rendered.
    int fullKeep = math.max(24, detailProfiles + 8)
    if array.size(completed) > fullKeep
        int oldIdx = array.size(completed) - fullKeep - 1
        if oldIdx >= 0
            Session old = array.get(completed, oldIdx)
            map.clear(old.bins)
            map.clear(old.buys)
            map.clear(old.sells)
            if not na(old.cumulative)
                array.clear(old.cumulative)
    if array.size(completed) > 900
        array.shift(completed)
    // Incomplete start/end ranges cannot become trusted liquidity references.
    if not s.partial and s.gaps == 0
        string dateTag = str.format_time(s.start, "dd/MM", f_zone(s.sid))
        array.push(levels, Level.new(s.sid, f_name(s.sid) + " H " + dateTag, s.hi, 1,
             s.expectedEnd, 0, 0, na, na, s.hi, 0.0, 0, na, na))
        array.push(levels, Level.new(s.sid, f_name(s.sid) + " L " + dateTag, s.lo, -1,
             s.expectedEnd, 0, 0, na, na, s.lo, 0.0, 0, na, na))
    if debugLogs
        log.info("END {0}; bars={1}; covered={2}%; partial={3}; gaps={4}", f_name(s.sid), s.bars, f_coverage(s), s.partial, s.gaps)
    array.size(completed)
 
// Actor names mean time windows, NOT identification of actual counterparties.
f_inside_at(int t, string ss, string tz) =>
    int sh = int(str.tonumber(str.substring(ss, 0, 2)))
    int sm = int(str.tonumber(str.substring(ss, 2, 4)))
    int eh = int(str.tonumber(str.substring(ss, 5, 7)))
    int em = int(str.tonumber(str.substring(ss, 7, 9)))
    int a = sh * 60 + sm
    int b = eh * 60 + em
    int nowMin = hour(t, tz) * 60 + minute(t, tz)
    b <= a ? nowMin >= a or nowMin < b : nowMin >= a and nowMin < b
 
f_actor(int t) =>
    string out = ""
    for sid = 0 to 3
        if f_inside_at(t, f_window(sid), f_zone(sid))
            string name = sid == 0 ? "AS" : sid == 1 ? "LN" : sid == 2 ? (f_inside_at(t, nyOpen, "America/New_York") ? "NY OPEN" : "NY") : "PM"
            out += (out == "" ? "" : "+") + name
    if f_inside_at(t, londonPre, "Europe/London")
        out += (out == "" ? "" : "+") + "LN PRE"
    if f_inside_at(t, nyPre, "America/New_York")
        out += (out == "" ? "" : "+") + "NY PRE"
    out == "" ? "OFF" : out
 
f_event(array<Event> events, int t, Level lv, int direction, string eventMessage, bool failure) =>
    string symbol = failure ? "× " : direction > 0 ? "↑ " : direction < 0 ? "↓ " : "· "
    string compact = symbol + f_name(lv.sid) + (lv.side > 0 ? " H" : " L") + " · " + eventMessage
    // Anchor the observation at SOURCE MINUTE CLOSE, not its opening timestamp.
    array.push(events, Event.new(t + 60000, lv.price, direction,
         f_actor(t) + " → " + lv.tag + "\n" + eventMessage, failure, compact, lv.sid, lv.side, eventMessage))
    if array.size(events) > 100
        array.shift(events)
    lv.eventAt := t
    direction
 
// States: 0 untouched, 1 breach, 2 return, 3 acceptance, 4 retest / frozen map,
//         5 invalidated, 6 late/gap return, 7 touched, 8 expired/data gap,
//         9 objective visited, 10 objective AND invalidation in one minute.
// No expired/finished state transitions back into a live setup.
f_level_update(Level lv, int t, float o, float h, float l, float c, float atr,
     bool missingMinutes, float prevClose, array<Event> events) =>
    int retest = 0
    float freshEps = math.max(tickBuffer * syminfo.mintick, nz(atr, rowStep) * atrBuffer)
    bool liveSetup = lv.state == 2 or lv.state == 3 or lv.state == 4
    bool oldSetup = liveSetup and not na(lv.setupAt) and t - lv.setupAt >= scenarioLife * 60000
    bool oldBreach = lv.state == 1 and t - lv.crossedAt >= scenarioLife * 60000
    if (missingMinutes and (liveSetup or lv.state == 1)) or oldSetup or oldBreach
        lv.state := 8
        lv.direction := 0
        f_event(events, t, lv, 0, missingMinutes ? "DATA GAP" : "EXPIRED", false)
    if lv.state == 0 or lv.state == 7
        bool breach = lv.side == 1 ? h > lv.price + freshEps : l < lv.price - freshEps
        if breach
            lv.state := 1
            lv.crossedAt := t
            lv.eps := freshEps
            lv.extreme := lv.side == 1 ? h : l
            lv.run := 0
            bool wholeBarBeyond = lv.side == 1 ? l > lv.price + freshEps : h < lv.price - freshEps
            bool jumped = not na(prevClose) and (prevClose - lv.price) * lv.side <= freshEps and (o - lv.price) * lv.side > freshEps
            lv.gapBreach := wholeBarBeyond or jumped or missingMinutes
            f_event(events, t, lv, 0, lv.gapBreach ? "GAP BEYOND" : "BREACH", false)
        else if lv.state == 0
            bool touched = lv.side == 1 ? h >= lv.price : l <= lv.price
            if touched
                lv.state := 7
                f_event(events, t, lv, 0, "TOUCH", false)
    float signedClose = (c - lv.price) * lv.side
    bool outside = signedClose > lv.eps
    bool inside = signedClose < -lv.eps
    if lv.state == 1
        lv.extreme := lv.side == 1 ? math.max(lv.extreme, h) : math.min(lv.extreme, l)
        lv.run := outside ? lv.run + 1 : 0
        if inside
            bool rapid = t - lv.crossedAt <= reclaimWindow * 60000 and not lv.gapBreach
            lv.state := rapid ? 2 : 6
            lv.direction := rapid ? -lv.side : 0
            lv.invalid := lv.extreme + lv.side * lv.eps
            lv.setupAt := t
            lv.kind := "RETURN"
            f_event(events, t, lv, lv.direction, rapid ? "RETURN" : "LATE / GAP RETURN", false)
        else if lv.run >= acceptCloses
            lv.state := 3
            lv.direction := lv.side
            lv.invalid := lv.price - lv.side * lv.eps
            lv.acceptedAt := t
            lv.setupAt := t
            lv.kind := "BREAK"
            f_event(events, t, lv, lv.direction, "ACCEPT", false)
    else if lv.state == 2
        bool invalid = lv.side == 1 ? h >= lv.invalid : l <= lv.invalid
        if invalid
            lv.state := 5
            lv.direction := 0
            f_event(events, t, lv, 0, "RETURN FAILED", true)
        else if t > lv.setupAt
            bool touch = lv.side == 1 ? h >= lv.price - lv.eps : l <= lv.price + lv.eps
            if touch and inside
                lv.state := 4
                lv.readyAt := t
                lv.entry := c
                retest := lv.direction
                f_event(events, t, lv, lv.direction, "RETURN RETEST", false)
    else if lv.state == 3
        bool adverse = lv.side == 1 ? l <= lv.invalid : h >= lv.invalid
        if adverse
            lv.state := 5
            lv.direction := 0
            f_event(events, t, lv, 0, "ACCEPT FAILED", true)
        else if t > lv.acceptedAt
            bool touch = lv.side == 1 ? l <= lv.price + lv.eps : h >= lv.price - lv.eps
            if touch and outside
                lv.state := 4
                lv.readyAt := t
                lv.entry := c
                retest := lv.direction
                f_event(events, t, lv, lv.direction, "BREAK RETEST", false)
    else if lv.state == 4 and t > lv.readyAt
        bool hitInvalid = lv.direction == 1 ? l <= lv.invalid : h >= lv.invalid
        bool hitTarget = not na(lv.target) and (lv.direction == 1 ? h >= lv.target : l <= lv.target)
        if hitInvalid and hitTarget
            lv.state := 10
            lv.direction := 0
            f_event(events, t, lv, 0, "BOTH / ORDER UNKNOWN", true)
        else if hitInvalid
            lv.state := 5
            lv.direction := 0
            f_event(events, t, lv, 0, "RETEST INVALIDATED", true)
        else if hitTarget
            lv.state := 9
            lv.direction := 0
            f_event(events, t, lv, 0, "OBJECTIVE VISITED", false)
    retest
 
f_state(Level lv) =>
    switch lv.state
        0 => "untouched"
        1 => "breach"
        2 => "returned"
        3 => "accepted"
        4 => "retested"
        5 => "failed"
        6 => "late / gap"
        7 => "touched"
        8 => "expired / gap"
        9 => "objective visited"
        => "order unknown"
 
// Target selection is performed AFTER ALL levels consume the same closed minute.
// A target is then frozen at the retest. No target can silently move farther away.
f_objective(Level lv, float price, array<Session> completed, array<Level> levels) =>
    float goal = na
    string tag = ""
    if lv.kind == "RETURN"
        for s in completed
            if s.sid == lv.sid and s.expectedEnd == lv.born
                float p = f_good_profile(s) ? s.poc : (s.hi + s.lo) / 2.0
                if (p - price) * lv.direction > syminfo.mintick
                    goal := p
                    tag := f_name(s.sid) + (f_good_profile(s) ? " POC" : " MID / price only")
    for other in levels
        bool available = other.state == 0 or other.state == 7
        bool ahead = (other.price - price) * lv.direction > syminfo.mintick
        if available and ahead
            if na(goal) or math.abs(other.price - price) < math.abs(goal - price)
                goal := other.price
                tag := other.tag
    for s in completed
        bool ahead = not na(s.poc) and (s.poc - price) * lv.direction > syminfo.mintick
        if s.naked and ahead and f_good_profile(s)
            if na(goal) or math.abs(s.poc - price) < math.abs(goal - price)
                goal := s.poc
                tag := f_name(s.sid) + " nPOC"
    [goal, tag]
 
// Track POC in BOTH directions. OHLC intersection is a price test, not proof of stop fills.
// Immutable first test / first close across / first return; H/L additionally keep a quick sweep.
f_track_profile(Session s, int t, float hi, float lo, float cls, bool gap) =>
    if t >= s.expectedEnd and not s.partial and s.gaps == 0 and not na(s.audit)
        float eps = tickBuffer * syminfo.mintick
        string who = f_actor(t)
        for a in s.audit
            if not na(a.price) and (a.kind >= 3 or f_good_profile(s))
                if gap and na(a.touchAt)
                    a.interrupted := true
                int side = cls > a.price + eps ? 1 : cls < a.price - eps ? -1 : 0
                bool touch = lo <= a.price and hi >= a.price
                if touch and na(a.touchAt)
                    a.touchAt := t + 60000
                    a.touchWho := who
                    a.touchUncertain := a.interrupted
                bool across = side != 0 and a.lastSide != 0 and side != a.lastSide
                if across and na(a.crossAt)
                    a.crossAt := t + 60000
                    a.crossWho := who
                    a.crossDir := side
                    a.crossGap := gap or not touch
                if not na(a.crossAt) and na(a.returnAt) and side != 0
                    if side == a.crossDir
                        a.run += 1
                        if a.run >= acceptCloses and na(a.holdAt) and not gap
                            a.holdAt := t + 60000
                            a.holdWho := who
                    else if t + 60000 > a.crossAt
                        a.returnAt := t + 60000
                        a.returnWho := who
                        a.returnGap := gap or not touch
                if gap or side == 0
                    a.run := 0
                if a.kind >= 3
                    int edge = a.kind == 3 ? 1 : -1
                    bool beyond = edge == 1 ? hi > a.price + eps : lo < a.price - eps
                    if beyond and na(a.wickAt)
                        a.wickAt := t
                        a.wickGap := gap or (edge == 1 ? lo > a.price : hi < a.price)
                    bool backInside = (cls - a.price) * edge < -eps
                    if not na(a.wickAt) and na(a.sweepAt) and backInside and not a.wickGap and not gap and t - a.wickAt <= reclaimWindow * 60000
                        a.sweepAt := t + 60000
                        a.sweepWho := who
                if side != 0
                    a.lastSide := side
    0
 
f_source(Session s) =>
    s.fpMinutes > 0 and s.proxyMinutes > 0 ? "MIX: FP + PROXY" : s.fpMinutes > 0 ? "TV FOOTPRINT" : s.proxyMinutes > 0 ? "1m PROXY" : "PRICE / VWAP ONLY"
 
// Relative volume compares cumulative volume at the SAME elapsed minute.
// No linear extrapolation from a whole past session is used.
f_pace(Session s, array<Session> completed) =>
    float sumVolume = 0.0
    int samples = 0
    int elapsed = s.bars - 1
    if not s.partial and s.gaps == 0 and f_coverage(s) >= minCoverage and elapsed >= 0
        for past in completed
            if past.sid == s.sid and past.expectedEnd <= s.start and not past.partial and past.gaps == 0
                if f_coverage(past) >= minCoverage and array.size(past.cumulative) > elapsed
                    float pv = array.get(past.cumulative, elapsed)
                    if pv > 0
                        sumVolume += pv
                        samples += 1
    float relative = samples >= 2 and sumVolume > 0 ? s.vol / (sumVolume / samples) : na
    [relative, samples]
 
// Auto handoff: Asia <- previous day; London <- Asia; NY <- London PRE-NY;
// PM <- NY. Fallback is also closed BEFORE the active window starts.
// This selector affects context display, not the level state machine.
f_select_reference(array<Session> history, Session currentWindow, int nowT) =>
    Session chosen = na
    int bestRank = -1
    int sid = not na(currentWindow) ? currentWindow.sid : -1
    int preferred = sid == 3 ? 2 : sid == 2 ? 5 : sid == 1 ? 0 : sid == 0 ? 4 : -1
    for s in history
        bool recent = not na(nowT) and nowT >= s.expectedEnd and nowT - s.expectedEnd <= levelLifeHours * 3600000
        bool atHandoff = na(currentWindow) or s.expectedEnd <= currentWindow.start
        bool selected = referencePick == "Auto" ? atHandoff : f_name(s.sid) == referencePick
        if recent and selected and f_good_profile(s)
            int rank = referencePick != "Auto" ? 1 : s.sid == preferred ? 2 : s.sid != 4 ? 1 : 0
            if na(chosen)
                chosen := s
                bestRank := rank
            else if rank > bestRank or (rank == bestRank and s.expectedEnd > chosen.expectedEnd)
                chosen := s
                bestRank := rank
    chosen
 
// ── Persistent state ──────────────────────────────────────────────────────────
var array<Session> active = array.new<Session>(5, na)
var array<Session> completed = array.new<Session>()
var array<Level> levels = array.new<Level>()
var array<Event> events = array.new<Event>()
var array<ClockMark> clocks = array.new<ClockMark>()
var array<Pulse> pulses = array.new<Pulse>()
var map<int, int> pulseTimes = map.new<int, int>()
var float lastRV = na
var float lastRangeR = na
var int lastRegime = 0
var float lastER = na
var int lastPulseKind = 0
var int lastMinute = na
var int lastMinuteEnd = na
var float lastPrice = na
var float lastATR = na
var int firstMinute = na
 
if barstate.isfirst and (not chart.is_standard or not timeframe.isintraday or timeframe.in_seconds() < 60 or timeframe.in_seconds() > 3600)
    runtime.error("ARTIO: use standard candles, 1m–1H. Seconds, daily, Heikin Ashi, Renko and range charts are not supported.")
 
// Equal timeframe (1m chart -> 1m request) is supported by security_lower_tf.
// One request, one footprint context. No chart-TF OHLC substituted for minute boundaries.
[mt, mc, mo, mh, ml, mp, mv, ma, ka, kl, kn, km, kd, fps, rvs, rrs, regimes, ers] = request.security_lower_tf(
     syminfo.tickerid, "1", f_payload(), calc_bars_count = historyMinutes)
 
bool bullishRetest = false
bool bearishRetest = false
int minutesHere = array.size(mt)
if minutesHere > 0
    for j = 0 to minutesHere - 1
        int t = array.get(mt, j)
        int tc = array.get(mc, j)
        // Only closed source minutes are consumed. Realtime rollback is intentional:
        // Pine rebuilds the open chart candle from its committed preceding state.
        if (na(lastMinute) or t > lastMinute) and (not barstate.isrealtime or tc <= timenow)
            float o = array.get(mo, j)
            float h = array.get(mh, j)
            float l = array.get(ml, j)
            float c = array.get(mp, j)
            float v = array.get(mv, j)
            float a = array.get(ma, j)
            footprint fp = array.get(fps, j)
            float minuteRV = array.get(rvs, j)
            float minuteRangeR = array.get(rrs, j)
            lastRV := minuteRV
            lastRangeR := minuteRangeR
            lastRegime := array.get(regimes, j)
            lastER := array.get(ers, j)
            lastPulseKind := f_pulse_code(minuteRV, minuteRangeR, o, h, l, c)
            bool gapHere = not na(lastMinuteEnd) and t > lastMinuteEnd
            if gapHere
                lastPulseKind := 0
            int priorPulse = map.contains(pulseTimes, lastPulseKind) ? map.get(pulseTimes, lastPulseKind) : na
            if lastPulseKind != 0 and (na(priorPulse) or t - priorPulse >= pulseCooldown * 60000)
                array.push(pulses, Pulse.new(tc, c, lastPulseKind, minuteRV, minuteRangeR))
                if array.size(pulses) > 40
                    array.shift(pulses)
                map.put(pulseTimes, lastPulseKind, t)
            array<int> keys = array.from(array.get(ka, j), array.get(kl, j), array.get(kn, j), array.get(km, j), array.get(kd, j))
            if na(firstMinute)
                firstMinute := t
            // Freeze London's PRE-NY auction BEFORE adding the first NY minute.
            // The full overlapping London session continues independently.
            int nyKey = array.get(keys, 2)
            Session preLondon = array.get(active, 1)
            if londonSnapshot and not na(nyKey) and t == nyKey and not na(preLondon)
                Session snap = Session.new(5, preLondon.start, t, preLondon.lastEnd,
                     preLondon.hi, preLondon.lo, preLondon.op, preLondon.cl,
                     preLondon.pv, preLondon.vol, preLondon.delta, preLondon.bars,
                     preLondon.covered, preLondon.gaps, preLondon.partial, preLondon.overflow,
                     map.copy(preLondon.bins), map.copy(preLondon.buys), map.copy(preLondon.sells), na, na, na, true, preLondon.ibHi, preLondon.ibLo,
                     preLondon.fpMinutes, preLondon.proxyMinutes, array.copy(preLondon.cumulative), array.new<int>(3, 0), array.new<int>(3, na), array.new<string>(3, ""))
                f_finish(snap, completed, levels)
            // Finalize first. Levels become available only after their session has ended.
            for sid = 0 to 4
                Session s = array.get(active, sid)
                int key = array.get(keys, sid)
                if not na(s)
                    if na(key) or key != s.start
                        f_finish(s, completed, levels)
                        array.set(active, sid, na)
                        s := na
                if not na(key)
                    if na(s)
                        s := f_new_session(sid, key, t, o, h, l, c)
                        array.set(active, sid, s)
                        if debugLogs
                            log.info("START {0}; {1}", f_name(sid), str.format_time(t, "yyyy-MM-dd HH:mm", f_zone(sid)))
                    f_update(s, t, tc, o, h, l, c, v, fp)
            // Invalidate stale observations; no hidden reset to an 'untouched' state.
            while array.size(levels) > 0
                Level oldest = array.first(levels)
                if t - oldest.born > levelLifeHours * 3600000 or array.size(levels) > 100
                    array.shift(levels)
                else
                    break
            if array.size(levels) > 0
                for lv in levels
                    if t >= lv.born and t - lv.born <= levelLifeHours * 3600000
                        bool gap = not na(lastMinuteEnd) and t > lastMinuteEnd
                        int result = f_level_update(lv, t, o, h, l, c, a, gap, lastPrice, events)
                        bullishRetest := bullishRetest or result == 1
                        bearishRetest := bearishRetest or result == -1
            if array.size(completed) > 0
                for s in completed
                    f_track_profile(s, t, h, l, c, gapHere)
                    if gapHere
                        s.naked := false
                    if s.naked and not na(s.poc) and t >= s.expectedEnd and l <= s.poc and h >= s.poc
                        s.naked := false
            if array.size(levels) > 0
                for lv in levels
                    if lv.state == 4 and lv.readyAt == t
                        [goal, goalName] = f_objective(lv, c, completed, levels)
                        lv.target := goal
                        lv.targetTag := goalName
                        float risk = math.abs(lv.entry - lv.invalid)
                        lv.initialR := not na(goal) and risk >= syminfo.mintick ? math.abs(goal - lv.entry) / risk : na
            if array.size(events) > 0
                for k = array.size(events) - 1 to 0
                    Event recentEvent = array.get(events, k)
                    if recentEvent.t != tc
                        break
                    recentEvent.volumeRatio := minuteRV
                    recentEvent.rangeRatio := minuteRangeR
            if showClocks
                int lh = hour(t, "Europe/London")
                int lm = minute(t, "Europe/London")
                int nh = hour(t, "America/New_York")
                int nm = minute(t, "America/New_York")
                string clockText = lh == 10 and lm == 30 ? "LBMA AM" : lh == 15 and lm == 0 ? "LBMA PM" : nh == 8 and nm == 30 ? "US 08:30*" : nh == 13 and nm == 29 ? "GC SETTLE*" : ""
                if clockText != ""
                    array.push(clocks, ClockMark.new(t, clockText, h + nz(a, rowStep)))
                    if array.size(clocks) > 24
                        array.shift(clocks)
            lastMinute := t
            lastMinuteEnd := tc
            lastPrice := c
            lastATR := a
 
// ── References and scenario selection ────────────────────────────────────────
Session current = na
for sid = 0 to 3
    Session s = array.get(active, sid)
    if not na(s)
        current := s
Session reference = f_select_reference(completed, current, lastMinute)
 
Level candidate = na
bool hasLong = false
bool hasShort = false
float nearestAbove = na
float nearestBelow = na
string aboveName = "—"
string belowName = "—"
if array.size(levels) > 0 and not na(lastPrice)
    for lv in levels
        if lv.state == 0 or lv.state == 7
            if lv.price > lastPrice and (na(nearestAbove) or lv.price < nearestAbove)
                nearestAbove := lv.price
                aboveName := lv.tag
            if lv.price < lastPrice and (na(nearestBelow) or lv.price > nearestBelow)
                nearestBelow := lv.price
                belowName := lv.tag
        bool validState = lv.state == 2 or lv.state == 3 or lv.state == 4
        bool fresh = not na(lv.setupAt) and lastMinute - lv.setupAt < scenarioLife * 60000
        bool stopOnRightSide = lv.direction == 1 ? lastPrice > lv.invalid : lv.direction == -1 ? lastPrice < lv.invalid : false
        if fresh and validState and stopOnRightSide
            hasLong := hasLong or lv.direction == 1
            hasShort := hasShort or lv.direction == -1
            if na(candidate)
                candidate := lv
            else
                int rank = lv.state == 4 ? 2 : 1
                int oldRank = candidate.state == 4 ? 2 : 1
                if rank > oldRank or (rank == oldRank and lv.eventAt > candidate.eventAt)
                    candidate := lv
bool conflict = hasLong and hasShort
float objective = na
string objectiveName = "no objective"
float roomR = na
float initialR = na
if not na(candidate)
    if candidate.state == 4
        objective := candidate.target
        objectiveName := candidate.targetTag
        initialR := candidate.initialR
    else
        [previewGoal, previewName] = f_objective(candidate, lastPrice, completed, levels)
        objective := previewGoal
        objectiveName := previewName + " / PREVIEW"
    float riskNow = math.abs(lastPrice - candidate.invalid)
    bool ahead = not na(objective) and (objective - lastPrice) * candidate.direction > 0
    if ahead and riskNow >= syminfo.mintick
        roomR := math.abs(objective - lastPrice) / riskNow
 
// The first mapped level is a caution boundary, not proof of resting liquidity.
// Include tested levels: a prior touch does not make a price reference disappear.
f_first_level(float price, int direction, int nowT, array<Session> history) =>
    float found = na
    string identity = ""
    string testState = ""
    if direction != 0 and not na(price) and not na(nowT) and array.size(history) > 0
        for j = array.size(history) - 1 to 0
            Session s = array.get(history, j)
            bool eligible = s.expectedEnd <= nowT and nowT - s.expectedEnd <= levelLifeHours * 3600000
            if eligible and not s.partial and s.gaps == 0 and not na(s.audit)
                for k = 0 to 4
                    Audit a = array.get(s.audit, k)
                    bool quality = k >= 3 or f_good_profile(s)
                    float distance = (a.price - price) * direction
                    if quality and not na(a.price) and distance >= -syminfo.mintick * 0.1
                        if na(found) or distance < (found - price) * direction
                            found := a.price
                            string kind = k == 0 ? "POC" : k == 1 ? "VAH" : k == 2 ? "VAL" : k == 3 ? "HIGH" : "LOW"
                            identity := f_name(s.sid) + " " + str.format_time(s.start, "dd/MM", f_zone(s.sid)) + " " + kind
                            testState := a.interrupted ? "uncertain" : na(a.touchAt) ? "untested" : "tested"
    [found, identity, testState]
 
float firstLevel = na
string firstLevelTag = ""
string firstLevelState = ""
float firstLevelR = na
if not na(candidate) and not na(lastPrice)
    [nearPrice, nearTag, nearState] = f_first_level(lastPrice, candidate.direction, lastMinuteEnd, completed)
    firstLevel := nearPrice
    firstLevelTag := nearTag
    firstLevelState := nearState
    float currentRisk = math.abs(lastPrice - candidate.invalid)
    if not na(firstLevel) and currentRisk >= syminfo.mintick
        firstLevelR := math.max(0.0, (firstLevel - lastPrice) * candidate.direction) / currentRisk
bool firstLevelBlocked = checkFirstLevel and not na(firstLevelR) and firstLevelR < minRoomR
 
bool dataStale = barstate.isrealtime and (na(lastMinuteEnd) or timenow - lastMinuteEnd > 120000)
bool isExecutionChart = timeframe.in_seconds() == 60
bool actionable = not manualPause and not dataStale and not conflict and not na(candidate)
if actionable
    actionable := candidate.state == 4 and not na(initialR) and initialR >= minRoomR and not na(roomR) and roomR >= minRoomR and not firstLevelBlocked
string action = "WAIT · no fresh scenario"
color actionColor = color.rgb(157, 167, 179)
if manualPause
    action := "PAUSE · manual block"
else if dataStale
    action := "WAIT · source 1m is stale"
else if conflict
    action := "WAIT · LONG / SHORT conflict"
else if not na(candidate)
    string dir = candidate.direction == 1 ? "LONG" : "SHORT"
    if candidate.state == 2
        action := dir + "? Return → await retest"
    else if candidate.state == 3
        action := dir + "? Acceptance → await retest"
    else if na(roomR) or na(initialR)
        action := "WAIT · no target / geometry"
    else if initialR < minRoomR
        action := "SKIP · too little room at retest"
    else if firstLevelBlocked
        action := "WAIT · first mapped level is too close"
    else if roomR < minRoomR
        action := "DO NOT CHASE · little room left"
    else
        action := dir + " · RETEST CONFIRMED"
        actionColor := candidate.direction == 1 ? color.rgb(77, 199, 165) : color.rgb(238, 117, 125)
 
// Action alerts only at a NEW confirmed retest on the 1m chart. On a 1H chart,
// intrabar observations are displayed, not delivered as retroactive entry alerts.
bool newReady = false
if actionable
    newReady := candidate.readyAt == lastMinute
bool readyLong = newReady and isExecutionChart and barstate.isconfirmed and enableAlerts and candidate.direction == 1
bool readyShort = newReady and isExecutionChart and barstate.isconfirmed and enableAlerts and candidate.direction == -1
alertcondition(readyLong, "ARTIO · LONG ready", "ARTIO LONG: closed 1m retest, no directional conflict, sufficient configured room. Check chart and spread. {{ticker}} {{close}}")
alertcondition(readyShort, "ARTIO · SHORT ready", "ARTIO SHORT: closed 1m retest, no directional conflict, sufficient configured room. Check chart and spread. {{ticker}} {{close}}")
if readyLong or readyShort
    string msg = "ARTIO GOLD BRAIN | " + syminfo.ticker + " | " + (readyLong ? "LONG" : "SHORT")
    msg += " | " + candidate.kind + " | " + candidate.tag
    msg += " | retest=" + str.tostring(candidate.entry, format.mintick)
    msg += " | invalid=" + str.tostring(candidate.invalid, format.mintick)
    msg += " | objective=" + str.tostring(candidate.target, format.mintick)
    msg += " | R=" + str.tostring(candidate.initialR, "#.00")
    msg += " | first_level=" + str.tostring(firstLevel, format.mintick) + " | first_room_R=" + str.tostring(firstLevelR, "#.00")
    msg += " | observation, not an order"
    alert(msg, alert.freq_once_per_bar_close)
 
Session dayNow = array.get(active, 4)
float dayVWAP = not na(dayNow) and dayNow.vol > 0 and not dayNow.partial and dayNow.gaps == 0 and f_coverage(dayNow) >= minCoverage ? dayNow.pv / dayNow.vol : na
float sessionVWAP = not na(current) and current.vol > 0 and not current.partial and current.gaps == 0 and f_coverage(current) >= minCoverage ? current.pv / current.vol : na
bool dayReset = not na(dayNow) and time <= dayNow.start and time_close > dayNow.start
bool sessionReset = not na(current) and time <= current.start and time_close > current.start
plot(showDayVWAP and not dayReset ? dayVWAP : na, "GC day VWAP · 1m HLC3", color = uiTheme == "Dark" ? color.rgb(211, 225, 244) : color.rgb(42, 66, 99), linewidth = 2, style = plot.style_linebr, force_overlay = true)
plot(showSessionVWAP and not sessionReset ? sessionVWAP : na, "Session VWAP · 1m HLC3", color = not na(current) ? f_color(current.sid) : color.gray, linewidth = 1, style = plot.style_linebr, force_overlay = true)
plotshape(readyLong and showSignalMarkers, "New LONG retest", shape.triangleup, location.belowbar, color.rgb(77, 199, 165), size = size.tiny, text = "L", force_overlay = true)
plotshape(readyShort and showSignalMarkers, "New SHORT retest", shape.triangledown, location.abovebar, color.rgb(238, 117, 125), size = size.tiny, text = "S", force_overlay = true)
 
 
barcolor(colorCandles ? (close >= open ? color.rgb(41, 194, 149) : color.rgb(224, 83, 103)) : na, title = "Optional candle contrast")
 
// ── Visible chart geometry: only used for title placement ────────────────────
var array<int> viewTimes = array.new<int>()
var float viewHigh = na
var float viewLow = na
if time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
    viewHigh := na(viewHigh) ? high : math.max(viewHigh, high)
    viewLow := na(viewLow) ? low : math.min(viewLow, low)
    if array.size(viewTimes) < 80000
        array.push(viewTimes, time)
 
// ── Rendering: main-chart boxes / profiles / levels; optional table on the same chart.
color uiBG = uiTheme == "Dark" ? #141922 : #F6F8FB
color uiAlt = uiTheme == "Dark" ? #202836 : #E6ECF4
color uiFG = uiTheme == "Dark" ? #E7EDF5 : #192536
color uiMuted = uiTheme == "Dark" ? #A7B4C5 : #5C6B7C
var array<line> drawnLines = array.new<line>()
var array<box> drawnBoxes = array.new<box>()
var array<label> drawnLabels = array.new<label>()
var array<polyline> drawnPolys = array.new<polyline>()
var array<ExtensionName> extensionNames = array.new<ExtensionName>()
string panelAnchor = panelPosition == "Top left" ? position.top_left : panelPosition == "Bottom left" ? position.bottom_left : panelPosition == "Top right" ? position.top_right : position.bottom_right
bool traderPanel = panelMode == "TRADE MAP"
var table ledger = na
if barstate.isfirst and panelMode != "OFF"
    ledger := table.new(panelAnchor, traderPanel ? 3 : 7, traderPanel ? 7 : ledgerRows + 5,
         bgcolor = color.new(uiBG, 100), frame_color = color.new(uiAlt, 100), frame_width = 0, border_color = color.new(uiAlt, 70), border_width = 0)
    if traderPanel
        table.merge_cells(ledger, 0, 0, 2, 0)
        table.merge_cells(ledger, 0, 5, 2, 5)
        table.merge_cells(ledger, 0, 6, 2, 6)
    else
        table.merge_cells(ledger, 0, 0, 6, 0)
        table.merge_cells(ledger, 0, ledgerRows + 2, 6, ledgerRows + 2)
        table.merge_cells(ledger, 0, ledgerRows + 3, 6, ledgerRows + 3)
        table.merge_cells(ledger, 0, ledgerRows + 4, 6, ledgerRows + 4)
 
f_px(float p) =>
    na(p) ? "—" : str.tostring(p, format.mintick)
f_code(int id) =>
    id == 0 ? "AS" : id == 1 ? "LN" : id == 2 ? "NY" : id == 3 ? "PM" : id == 5 ? "LN PRE-NY" : "DAY"
f_endview(Session s) =>
    math.max(s.start + 60000, math.min(s.lastEnd, s.expectedEnd))
f_available(Session s) =>
    profileMode != "Off" and not s.overflow and map.size(s.bins) > 0 and not na(s.poc)
f_stamp(int at) =>
    na(at) ? "—" : str.format_time(at, "dd/MM HH:mm", displayZone)
f_who(int at, string who) =>
    who + " " + f_stamp(at)
f_levelkind(int k) =>
    k == 0 ? "POC" : k == 1 ? "VAH" : k == 2 ? "VAL" : k == 3 ? "H" : "L"
f_acolor(int k) =>
    k == 0 ? pocColor : k == 1 ? vahColor : k == 2 ? valColor : uiFG
 
f_audit_tip(Audit a) =>
    string out = f_levelkind(a.kind) + " " + f_px(a.price)
    out += "\n" + "First test: " + (na(a.touchAt) ? "none yet" : f_who(a.touchAt, a.touchWho))
    if not na(a.crossAt)
        out += "\n" + (a.crossGap ? "GAP " : "Close across ") + (a.crossDir > 0 ? "↑ " : "↓ ") + f_who(a.crossAt, a.crossWho)
    if not na(a.holdAt)
        out += "\n" + "Hold: " + f_who(a.holdAt, a.holdWho)
    if not na(a.returnAt)
        out += "\n" + (a.returnGap ? "GAP RETURN: " : "Return: ") + f_who(a.returnAt, a.returnWho)
    if not na(a.sweepAt)
        out += "\n" + "H/L breach + quick return: " + f_who(a.sweepAt, a.sweepWho)
    if a.interrupted
        out += "\nData gap before the first observed test: NOT a guarantee of the first market touch."
    out + "\nTimestamp = 1m close. Window is not a trader identity; test does not prove stop fills."
 
f_brief(Audit a, bool edge) =>
    string out = a.interrupted ? "no test* / GAP" : "untested"
    if not na(a.touchAt)
        out := (a.touchUncertain ? "obs. " : "test ") + f_who(a.touchAt, a.touchWho)
    else if not na(a.crossAt)
        out := "GAP " + f_who(a.crossAt, a.crossWho)
    if edge and not na(a.sweepAt)
        out := "sweep " + f_who(a.sweepAt, a.sweepWho)
    else if edge and not na(a.holdAt)
        out := "held " + f_who(a.holdAt, a.holdWho)
    out
 
f_tip(Session s, bool live) =>
    string out = f_name(s.sid) + " " + f_stamp(s.start) + " → " + f_stamp(f_endview(s))
    out += "\n" + f_source(s) + " · " + str.tostring(f_coverage(s), "#.0") + "%"
    out += "\nH " + f_px(s.hi) + " / L " + f_px(s.lo)
    out += "\nVAH " + f_px(s.vah) + " / POC " + f_px(s.poc) + " / VAL " + f_px(s.val)
    out += "\nV " + str.tostring(s.vol, format.volume) + " · Δ " + str.tostring(s.delta, format.volume)
    out += "\nDelta = source classification, not direct CME bid/ask tape."
    out += live ? "\nDEV values change. Tests begin only AFTER this window closes." : "\nFinal profile uses the whole window. Its levels were not known at the window start."
    if s.partial or s.gaps > 0
        out += "\nPARTIAL: incomplete window / missing minutes. No authoritative level audit."
    out
 
// Compact, unambiguous profile-level identity. Date is never omitted from tooltips.
f_line_id(int sid, int kind) =>
    (sid == 5 ? "LN-PRE" : f_code(sid)) + "-" + f_levelkind(kind)
 
f_name_text(Session s, int kind, float price) =>
    f_line_id(s.sid, kind) + (extensionLabelDate ? " " + str.format_time(s.start, "dd/MM", f_zone(s.sid)) : "") + (extensionLabelPrice ? " " + f_px(price) : "")
 
f_queue_extension(Session s, Audit a, int until) =>
    bool valid = extensionLabels and not na(a.price) and until > s.expectedEnd
    bool atCurrent = not na(lastMinuteEnd) and until >= lastMinuteEnd
    if valid and (extensionLabelScope == "All ends" or atCurrent)
        string caption = f_name_text(s, a.kind, a.price)
        string note = f_name(s.sid) + " · " + str.format_time(s.start, "dd/MM", f_zone(s.sid))
        note += "\n" + f_line_id(s.sid, a.kind) + " " + f_px(a.price) + " | source session closed " + f_stamp(s.expectedEnd)
        note += "\n" + f_audit_tip(a) + "\nTimes: " + displayZone
        note += "\nEnd: " + f_stamp(until) + " | mode: " + extensionMode
        int existing = -1
        if array.size(extensionNames) > 0
            for j = 0 to array.size(extensionNames) - 1
                ExtensionName n = array.get(extensionNames, j)
                if n.endpoint == until and math.abs(n.price - a.price) < syminfo.mintick * 0.1
                    existing := j
                    break
        if existing >= 0
            ExtensionName n = array.get(extensionNames, existing)
            if n.members < 3
                n.caption += " / " + caption
            else if n.members == 3
                n.caption += " / ..."
            n.members += 1
            n.note += "\n\n" + note
            n.kind := n.kind == a.kind ? n.kind : -1
            n.tested := n.tested and not na(a.touchAt)
        else
            array.push(extensionNames, ExtensionName.new(until, a.price, a.kind, caption, note, not na(a.touchAt)))
    0
 
// Thin text only, no badges/circles. In crowded areas stagger horizontally, never vertically.
// This is an estimated layout in bar/price space; Pine does not expose screen text bounds.
f_draw_extension_names() =>
    int painted = 0
    int omitted = 0
    if extensionLabels and array.size(extensionNames) > 0
        int barMs = int(timeframe.in_seconds() * 1000)
        int visibleBars = math.max(30, array.size(viewTimes))
        float span = not na(viewHigh) and not na(viewLow) ? viewHigh - viewLow : nz(lastATR, rowStep) * 25
        float gapY = math.max(syminfo.mintick * 2, span / 65.0 * extensionLabelFont / 10.0)
        int firstT = chart.left_visible_bar_time
        int rightT = chart.right_visible_bar_time + barMs
        array<float> distances = array.new<float>()
        for n in extensionNames
            array.push(distances, math.abs(n.price - nz(lastPrice, n.price)))
        array<int> priority = array.sort_indices(distances, order.ascending)
        array<int> usedLeft = array.new<int>()
        array<int> usedRight = array.new<int>()
        array<float> usedY = array.new<float>()
        int capacity = math.min(140, math.max(0, 490 - array.size(drawnLabels)))
        for idx in priority
            ExtensionName n = array.get(extensionNames, idx)
            if n.endpoint >= firstT and n.endpoint <= rightT
                int chars = str.length(n.caption) + 2
                int widthBars = math.max(5, int(math.ceil(visibleBars * chars / 175.0 * extensionLabelFont / 10.0)))
                int textSpan = widthBars * barMs
                bool placed = false
                int maxColumn = extensionLabelStagger ? 3 : 0
                if painted < capacity
                    for column = 0 to maxColumn
                        int x = n.endpoint + extensionLabelOffset * barMs + column * (textSpan + barMs * 2)
                        bool clear = true
                        if array.size(usedLeft) > 0
                            for j = 0 to array.size(usedLeft) - 1
                                bool horizontal = x < array.get(usedRight, j) and x + textSpan > array.get(usedLeft, j)
                                if horizontal and math.abs(n.price - array.get(usedY, j)) < gapY
                                    clear := false
                                    break
                        if not placed and clear
                            color ink = n.kind < 0 ? uiFG : f_acolor(n.kind)
                            ink := color.new(ink, n.tested ? 30 : 0)
                            // Transparent left-label shape keeps text to the right of its exact-price anchor.
                            label nameLabel = label.new(x, n.price, n.caption, xloc = xloc.bar_time, yloc = yloc.price,
                                 style = label.style_label_left, color = color.new(uiBG, 100), textcolor = ink,
                                 textalign = text.align_left, size = extensionLabelFont, tooltip = n.note, force_overlay = true)
                            array.push(drawnLabels, nameLabel)
                            array.push(usedLeft, x)
                            array.push(usedRight, x + textSpan)
                            array.push(usedY, n.price)
                            painted += 1
                            placed := true
                if not placed
                    omitted += 1
    [painted, omitted]
 
// ── Trader-facing presentation. It does NOT alter setup rules or alerts. ──────
f_desk_wrap(string value, int limit) =>
    string out = ""
    array<string> paragraphs = str.split(value, "\n")
    for p = 0 to array.size(paragraphs) - 1
        string lineText = ""
        if p > 0
            out += "\n"
        for word in str.split(array.get(paragraphs, p), " ")
            if word != ""
                if str.length(lineText) > 0 and str.length(lineText) + str.length(word) + 1 > limit
                    out += lineText + "\n"
                    lineText := word
                else
                    lineText += (lineText == "" ? "" : " ") + word
        out += lineText
    out
 
f_desk_name(int sid) =>
    switch sid
        0 => "Asia"
        1 => "London"
        2 => "NY Gold"
        3 => "US PM"
        5 => "London before NY"
        => "Trading day"
 
f_desk_tag(string tag) =>
    tag
 
f_desk_actor(int at) =>
    na(at) ? "--" : str.replace_all(f_actor(at), "+", " + ")
 
f_desk_regime(int mode) =>
    switch mode
        -2 => "Pause after a decline"
        2 => "Pause after a rise"
        -1 => "Directional decline"
        1 => "Directional rise"
        3 => "Two-way movement"
        4 => "Transitional movement"
        => "Not enough continuous minutes"
 
f_desk_event(string code) =>
    switch code
        "RETURN" => "Quick return inside H/L"
        "ACCEPT" => "Hold beyond H/L"
        "RETURN RETEST" => "Return: a later retest held"
        "BREAK RETEST" => "Continuation: a later retest held"
        "RETURN FAILED" => "Return failed"
        "ACCEPT FAILED" => "Breakout hold failed"
        "RETEST INVALIDATED" => "Post-retest setup invalidated"
        "OBJECTIVE VISITED" => "Objective visited"
        "BOTH / ORDER UNKNOWN" => "Objective and invalidation in one 1m: order unknown"
        "EXPIRED" => "Setup expired"
        "DATA GAP" => "Setup interrupted by missing data"
        "LATE / GAP RETURN" => "Late / GAP return: not a quick sweep"
        => code
 
f_desk_recent_event() =>
    Event chosen = na
    if not na(lastMinuteEnd) and array.size(events) > 0
        for j = array.size(events) - 1 to 0
            Event ev = array.get(events, j)
            if lastMinuteEnd - ev.t > 240 * 60000
                break
            if ev.code != "TOUCH" and ev.code != "BREACH" and ev.code != "GAP BEYOND" and ev.t <= lastMinuteEnd
                chosen := ev
                break
    chosen
 
// A compact card answers one decision at a time. Detailed history stays in AUDIT.
f_compact_tag(string value) =>
    string out = str.replace_all(value, "LONDON PRE-NY", "London pre-NY")
    out := str.replace_all(out, "NY GOLD", "NY")
    out := str.replace_all(out, "LONDON", "London")
    out := str.replace_all(out, "ASIA", "Asia")
    out := str.replace_all(out, "US PM", "US PM")
    out := str.replace_all(out, "GC DAY", "Day")
    out := str.replace_all(out, " H ", " HIGH ")
    str.replace_all(out, " L ", " LOW ")
 
f_decision_watch() =>
    Level watch = na
    float nearest = na
    if not na(lastPrice) and not na(lastMinuteEnd) and array.size(levels) > 0
        for j = array.size(levels) - 1 to 0
            Level lv = array.get(levels, j)
            bool eligible = (lv.state == 0 or lv.state == 7) and lv.born <= lastMinuteEnd and lastMinuteEnd - lv.born <= levelLifeHours * 3600000
            if eligible
                float distance = math.abs(lv.price - lastPrice)
                if na(nearest) or distance < nearest
                    watch := lv
                    nearest := distance
    watch
 
// Only completed, quality-checked levels enter the map. Developing profiles stay on-chart.
// Map neighbors use the selected session history, including tested references.
// This is context, not an extra entry trigger and not an order-book liquidity claim.
f_map_neighbor(array<Session> shown, int direction) =>
    MapReference found = na
    float nearest = na
    if not na(lastPrice) and not na(lastMinuteEnd)
        for origin in shown
            bool done = origin.expectedEnd <= lastMinuteEnd and not origin.partial and origin.gaps == 0 and not na(origin.audit)
            if done
                for a in origin.audit
                    bool good = a.kind >= 3 or f_good_profile(origin)
                    float distance = (a.price - lastPrice) * direction
                    if good and not na(a.price) and distance > syminfo.mintick * 0.1
                        bool nearer = na(nearest) or distance < nearest - syminfo.mintick * 0.1
                        bool samePrice = not na(nearest) and math.abs(distance - nearest) < syminfo.mintick * 0.1
                        if nearer or (samePrice and not na(found) and origin.expectedEnd > found.source.expectedEnd)
                            found := MapReference.new(origin, a)
                            nearest := distance
    found
 
f_map_test(Audit a) =>
    na(a.touchAt) ? (a.interrupted ? "TEST UNKNOWN / GAP" : "UNTESTED") : (a.touchUncertain ? "observed " : "tested ") + a.touchWho + " " + str.format_time(a.touchAt, "dd/MM HH:mm", displayZone)
 
f_map_neighbor_text(MapReference r, int direction) =>
    string result = "No completed level in loaded map"
    if not na(r)
        Session origin = r.source
        Audit a = r.detail
        result := f_line_id(origin.sid, a.kind) + " " + str.format_time(origin.start, "dd/MM", f_zone(origin.sid)) + " | " + f_px(a.price)
        result += "\n" + (direction > 0 ? "+" : "-") + f_px(math.abs(a.price - lastPrice)) + " price units | " + f_map_test(a)
    result
 
f_map_neighbor_tip(MapReference r) =>
    string tip = "Nearest completed level, not a promised destination or proven resistance. Selected map history only. Equal-price references prefer the newest completed window."
    if not na(r)
        tip += "\n\n" + f_tip(r.source, false) + "\n" + f_audit_tip(r.detail)
    tip
 
f_map_watch_identity(Level lv) =>
    string result = "--"
    if not na(lv)
        result := (lv.sid == 5 ? "LN-PRE" : f_code(lv.sid)) + (lv.side > 0 ? "-H" : "-L")
        for origin in completed
            if origin.sid == lv.sid and origin.expectedEnd == lv.born
                result += " " + str.format_time(origin.start, "dd/MM", f_zone(origin.sid))
                break
        result += " | " + f_px(lv.price)
    result
 
// The latest recorded interaction, with an explicit time. Past hold != current acceptance.
f_map_last_reaction(array<Session> shown) =>
    string result = "No recorded reaction in the last 4h"
    string detail = "First test and later stages are distinct observations. A past event is not the current market state. A price test does not prove stop execution."
    int newest = 0
    if not na(lastMinuteEnd)
        for origin in shown
            if not origin.partial and origin.gaps == 0 and not na(origin.audit)
                for a in origin.audit
                    int at = math.max(nz(a.touchAt, 0), nz(a.crossAt, 0), nz(a.holdAt, 0), nz(a.returnAt, 0), nz(a.sweepAt, 0))
                    bool good = a.kind >= 3 or f_good_profile(origin)
                    if good and at > newest and at <= lastMinuteEnd and lastMinuteEnd - at <= 240 * 60000
                        newest := at
                        string eventName = at == a.sweepAt ? "breach + return" : at == a.returnAt ? (a.returnGap ? "gap return" : "return") : at == a.holdAt ? "held beyond" : at == a.crossAt ? (a.crossGap ? "gap across" : "closed across") : (a.touchUncertain ? "observed test" : "first test")
                        string who = at == a.sweepAt ? a.sweepWho : at == a.returnAt ? a.returnWho : at == a.holdAt ? a.holdWho : at == a.crossAt ? a.crossWho : a.touchWho
                        result := str.format_time(at, "HH:mm", displayZone) + " " + who + " -> " + f_line_id(origin.sid, a.kind) + " " + str.format_time(origin.start, "dd/MM", f_zone(origin.sid)) + " " + f_px(a.price) + " | " + eventName
                        detail := f_tip(origin, false) + "\n" + f_audit_tip(a)
    [result, detail]
 
f_map_cell(int col, int row, string value, color ink, string tip, bool heading = false) =>
    bool merged = row == 0 or row >= 5
    int wrapAt = merged ? deskWrap * 3 : deskWrap
    int font = row == 0 ? panelText + 1 : heading or row >= 5 ? math.max(10, panelText - 1) : panelText
    table.cell(ledger, col, row, f_desk_wrap(value, wrapAt), text_size = font,
         text_color = ink, text_halign = text.align_left, text_valign = text.align_top,
         bgcolor = heading ? uiAlt : uiBG, tooltip = tip)
    0
 
f_draw_trader(array<Session> shown, string historyText, string historyTip) =>
    color positive = uiTheme == "Dark" ? #4DC7A5 : #08785D
    color negative = uiTheme == "Dark" ? #EE757D : #AC2637
    color caution = uiTheme == "Dark" ? #F0C778 : #8E5E0A
    bool blocked = manualPause or dataStale or conflict or na(lastPrice)
    bool hasSetup = not blocked and not na(candidate)
    Level watch = hasSetup ? candidate : blocked ? na : f_decision_watch()
    MapReference above = f_map_neighbor(shown, 1)
    MapReference below = f_map_neighbor(shown, -1)
    string state = "WAIT | NO CONFIRMED SETUP"
    color statusColor = caution
    string basis = not na(watch) ? "Watch " + f_map_watch_identity(watch) : "No eligible completed H/L trigger"
    string need = "Do not turn a profile touch into a trade."
    string risk = "No setup -> no assigned stop or target"
    string planTip = "Rules use completed H/L: quick return or hold, then a separate closed-minute retest. POC/VA are mapped context, not independent entries. All geometry excludes execution costs."
    string dir = hasSetup and candidate.direction > 0 ? "LONG" : "SHORT"
    if manualPause
        state := "PAUSED | MANUAL BLOCK"
        basis := "Analysis only"
        need := "Remove the manual block after reviewing conditions."
    else if na(lastPrice)
        state := "WAIT | NO CLOSED 1m DATA"
        basis := "Source minutes unavailable"
        need := "No current setup can be evaluated."
    else if dataStale
        state := "WAIT | SOURCE DATA IS STALE"
        basis := "Snapshot only; check timestamp below"
        need := "No current-entry status until fresh source minutes arrive."
    else if conflict
        state := "WAIT | OPPOSITE SETUPS"
        basis := "Both LONG and SHORT setups remain active"
        need := "Wait until the conflict clears; do not choose a side from this card."
    else if hasSetup
        basis := dir + " | " + f_map_watch_identity(candidate)
        basis += "\n" + (candidate.kind == "RETURN" ? "Failed break; returned inside" : "Held outside session range")
        basis += "\n" + f_actor(candidate.setupAt) + " " + str.format_time(candidate.setupAt + 60000, "HH:mm", displayZone)
        float boundary = candidate.price + candidate.direction * candidate.eps
        int minutesLeft = math.max(0, int(math.ceil((candidate.setupAt + scenarioLife * 60000 - lastMinute) / 60000.0)))
        float riskNow = math.abs(lastPrice - candidate.invalid)
        // Never hide an earlier objective behind a farther mapped obstacle.
        float first = objective
        string firstName = objectiveName
        if not na(firstLevel) and (na(first) or (firstLevel - lastPrice) * candidate.direction < (first - lastPrice) * candidate.direction)
            first := firstLevel
            firstName := firstLevelTag
        float firstR = not na(first) and riskNow >= syminfo.mintick ? math.abs(first - lastPrice) / riskNow : na
        risk := "INVALID " + f_px(candidate.invalid) + " | " + str.tostring(minutesLeft) + "m left"
        risk += "\nFIRST " + f_px(first) + (na(firstR) ? "" : " | " + str.tostring(firstR, "#.00") + "R from now")
        risk += "\n" + f_compact_tag(firstName)
        planTip += "\nLevel: " + candidate.tag + " " + f_px(candidate.price) + "\nConfirmation close: " + f_px(candidate.entry) + " (not a fill)."
        planTip += "\nFrozen objective: " + f_px(objective) + " / " + objectiveName
        planTip += "\nFirst mapped level: " + f_px(firstLevel) + " / " + firstLevelTag + " / " + firstLevelState
        planTip += "\nInitial objective R: " + str.tostring(initialR, "#.00") + "; current objective R: " + str.tostring(roomR, "#.00")
        if candidate.state == 2 or candidate.state == 3
            state := dir + " WATCH | WAIT FOR RETEST"
            need := "Retest " + f_px(candidate.price) + "; later 1m close " + (candidate.direction > 0 ? "> " : "< ") + f_px(boundary)
            need += "\nMinute must NOT hit invalidation."
            risk := "PREVIEW | " + risk
        else if na(roomR) or na(initialR)
            state := "PASS | NO VALID OBJECTIVE"
            need := "No valid objective ahead. An old retest is not a new entry."
        else if initialR < minRoomR
            state := "PASS | INSUFFICIENT INITIAL ROOM"
            need := "Only " + str.tostring(initialR, "#.00") + "R at retest; rule needs " + str.tostring(minRoomR, "#.0") + "R."
        else if firstLevelBlocked
            state := "WAIT | NEARBY LEVEL TOO CLOSE"
            need := "Only " + str.tostring(firstLevelR, "#.00") + "R to the first mapped level; rule needs " + str.tostring(minRoomR, "#.0") + "R."
        else if roomR < minRoomR
            state := "DO NOT CHASE | LITTLE ROOM LEFT"
            need := "Only " + str.tostring(roomR, "#.00") + "R remains to the objective."
        else if actionable
            int age = math.max(0, int((lastMinute - candidate.readyAt) / 60000))
            bool freshLive = newReady and isExecutionChart and barstate.isconfirmed and barstate.isrealtime
            state := dir + (freshLive ? " RETEST | JUST CONFIRMED" : " PLAN | RETEST " + str.tostring(age) + "m AGO")
            need := freshLive ? "New closed 1m retest. Check spread, risk and the first level." : "Existing plan, NOT a fresh entry. Watch invalidation / objective."
            statusColor := candidate.direction > 0 ? positive : negative
    else if not na(watch)
        float eps = math.max(tickBuffer * syminfo.mintick, nz(lastATR, rowStep) * atrBuffer)
        float outside = watch.price + watch.side * eps
        float inside = watch.price - watch.side * eps
        basis += "\n" + f_px(math.abs(watch.price - lastPrice)) + " price units away"
        // Explicit two-way conditional roadmap, never a claimed signal from proximity.
        need := watch.side > 0 ? "SHORT: breach > " + f_px(outside) + ", quick close < " + f_px(inside) : "LONG: breach < " + f_px(outside) + ", quick close > " + f_px(inside)
        need += "\n" + (watch.side > 0 ? "LONG: " : "SHORT: ") + str.tostring(acceptCloses) + " closes " + (watch.side > 0 ? "> " : "< ") + f_px(outside)
        need += "\nBOTH require a later retest."
        planTip += "\nThese numbers use the current 1m buffer; it freezes at a breach. Quick return must occur within " + str.tostring(reclaimWindow) + "m."
    string stamp = "As of " + f_stamp(lastMinuteEnd) + " " + displayZone
    string header = state + " | " + syminfo.ticker + " " + f_px(lastPrice)
    f_map_cell(0, 0, header, statusColor, planTip + "\n" + stamp)
    f_map_cell(0, 1, "LOCATION / CONTEXT", uiMuted, "A description, not a direction signal.", true)
    f_map_cell(1, 1, "NEAREST ABOVE", uiMuted, f_map_neighbor_tip(above), true)
    f_map_cell(2, 1, "NEAREST BELOW", uiMuted, f_map_neighbor_tip(below), true)
    string location = f_desk_regime(lastRegime)
    string locationTip = "No complete reference profile. DEV is not substituted for a fixed level."
    if not na(reference) and not na(lastPrice)
        string refId = (reference.sid == 5 ? "LN-PRE" : f_code(reference.sid)) + " " + str.format_time(reference.start, "dd/MM", f_zone(reference.sid))
        location += "\n" + refId + (lastPrice > reference.vah ? " | ABOVE VALUE" : lastPrice < reference.val ? " | BELOW VALUE" : " | INSIDE VALUE")
        float boundary = lastPrice > reference.vah ? reference.vah : lastPrice < reference.val ? reference.val : reference.poc
        string boundaryName = lastPrice > reference.vah ? "VAH " : lastPrice < reference.val ? "VAL " : "POC "
        location += "\n" + boundaryName + f_px(boundary) + " | " + (lastPrice >= boundary ? "+" : "-") + f_px(math.abs(lastPrice - boundary))
        locationTip := f_tip(reference, false) + "\nInside value is not automatically balance; being outside value is not proof of acceptance."
    f_map_cell(0, 2, location, uiFG, locationTip)
    f_map_cell(1, 2, f_map_neighbor_text(above, 1), na(above) ? uiMuted : f_acolor(above.detail.kind), f_map_neighbor_tip(above))
    f_map_cell(2, 2, f_map_neighbor_text(below, -1), na(below) ? uiMuted : f_acolor(below.detail.kind), f_map_neighbor_tip(below))
    f_map_cell(0, 3, "SETUP / BASIS", uiMuted, planTip, true)
    f_map_cell(1, 3, "NEXT CONDITION", uiMuted, planTip, true)
    f_map_cell(2, 3, "INVALID / FIRST LEVEL", uiMuted, planTip, true)
    f_map_cell(0, 4, basis, uiFG, planTip)
    f_map_cell(1, 4, need, uiFG, planTip)
    f_map_cell(2, 4, risk, hasSetup ? caution : uiMuted, planTip)
    [reaction, reactionTip] = f_map_last_reaction(shown)
    f_map_cell(0, 5, "LAST REACTION | " + reaction, uiFG, reactionTip)
    Session src = not na(current) ? current : reference
    string source = na(src) ? "NO PROFILE" : src.fpMinutes > 0 and src.proxyMinutes > 0 ? "MIX" : src.fpMinutes > 0 ? "TV FP" : src.proxyMinutes > 0 ? "PROXY" : "PRICE"
    string footer = stamp + " | " + f_actor(nz(lastMinute, time)) + " | " + source
    footer += " | 1m V " + (na(lastRV) ? "--" : str.tostring(lastRV, "#.0") + "x")
    if not isExecutionChart
        footer += " | alerts on 1m only"
    if not barstate.isrealtime
        footer += " | HISTORICAL SNAPSHOT"
    string footerTip = historyText + "\n" + historyTip
    footerTip += "\n1m volume: last CLOSED minute / previous " + str.tostring(spikeLookback) + "m mean; not time-of-day adjusted."
    if showVolumePace and not na(current)
        [pace, samples] = f_pace(current, completed)
        footerTip += "\nSame-elapsed session volume: " + (na(pace) ? "warming up" : str.tostring(pace, "#.00") + "x") + "; samples=" + str.tostring(samples)
    footerTip += "\nTable = last processed minute, not the cursor bar. Use Replay for past states. TV FP is classified volume, not direct CME aggressor tape."
    f_map_cell(0, 6, footer, dataStale ? caution : uiMuted, footerTip)
    0
 
 
f_history_enabled(int sid) =>
    sid == 0 ? historyAsia : sid == 1 ? historyLondon : sid == 2 ? historyNY : sid == 3 ? historyPM : false
 
// Titles use chart viewport coordinates ONLY for presentation. Neither profile
// calculations nor setup/alert rules depend on zoom, pan, visible range or cursor.
f_view_index(int stamp) =>
    int lo = 0
    int hi = array.size(viewTimes) - 1
    int result = 0
    while lo <= hi
        int mid = int(math.floor((lo + hi) / 2.0))
        if array.get(viewTimes, mid) <= stamp
            result := mid
            lo := mid + 1
        else
            hi := mid - 1
    result
 
f_title_name(int sid, bool shortName) =>
    shortName ? (sid == 5 ? "PRE" : f_code(sid)) : sid == 0 ? "ASIA" : sid == 1 ? "LONDON" : sid == 2 ? "NY GOLD" : sid == 3 ? "US PM" : sid == 5 ? "PRE-NY" : "DAY"
 
f_title_room(float center, float halfWidth, int lane, array<float> starts, array<float> ends, array<int> lanes) =>
    bool available = true
    if array.size(starts) > 0
        for k = 0 to array.size(starts) - 1
            if array.get(lanes, k) == lane
                if center + halfWidth > array.get(starts, k) and center - halfWidth < array.get(ends, k)
                    available := false
                    break
    available
 
f_draw_titles(array<Session> shown, array<int> ordering) =>
    // Session text is attached to each box; no viewport-floating title lanes.
    [0, 0]
 
f_line(int a, int b, float price, color cc, int width, string style) =>
    if not na(price) and b > a
        array.push(drawnLines, line.new(a, price, b, price, xloc = xloc.bar_time,
             color = cc, width = width, style = style, force_overlay = true))
    0
 
// Each band is a closed step polygon: up-contour, then reverse down-contour.
// <=4*1000 points per polygon. No hidden division of 280 boxes across all sessions.
f_band(array<float> inner, array<float> outer, int first, int last, int anchor, int sign, int width,
     float peak, int key0, int batch, int highKey, color cc) =>
    if first <= last and peak > 0
        array<chart.point> pts = array.new<chart.point>()
        bool hasArea = false
        for j = first to last
            float bot = (key0 + j * batch) * rowStep
            float top = math.min(highKey + 1, key0 + (j + 1) * batch) * rowStep
            int x = anchor + sign * int(math.round(width * array.get(outer, j) / peak))
            array.push(pts, chart.point.from_time(x, bot))
            array.push(pts, chart.point.from_time(x, top))
            hasArea := hasArea or array.get(outer, j) > array.get(inner, j)
        for j = last to first
            float bot = (key0 + j * batch) * rowStep
            float top = math.min(highKey + 1, key0 + (j + 1) * batch) * rowStep
            int x = anchor + sign * int(math.round(width * array.get(inner, j) / peak))
            array.push(pts, chart.point.from_time(x, top))
            array.push(pts, chart.point.from_time(x, bot))
        if hasArea and array.size(pts) >= 4 and array.size(drawnPolys) < 100
            array.push(drawnPolys, polyline.new(pts, curved = false, closed = true,
                 xloc = xloc.bar_time, line_color = color.new(cc, 100), fill_color = cc,
                 force_overlay = true))
    0
 
f_vp_alpha(color c) =>
    color.new(c, int(math.max(color.t(c), profileTransparency)))
 
f_render_profile(Session s, int capWidth, bool allowDelta) =>
    int count = 0
    if miniProfiles and f_available(s)
        array<int> keys = map.keys(s.bins)
        array.sort(keys, order.ascending)
        int k0 = array.first(keys)
        int k1 = array.last(keys)
        int batch = math.max(1, int(math.ceil((k1 - k0 + 1.0) / sessionRows)))
        count := int(math.ceil((k1 - k0 + 1.0) / batch))
        array<float> total = array.new<float>(count, 0.0)
        array<float> up = array.new<float>(count, 0.0)
        array<float> both = array.new<float>(count, 0.0)
        array<float> zero = array.new<float>(count, 0.0)
        array<float> dpos = array.new<float>(count, 0.0)
        array<float> dneg = array.new<float>(count, 0.0)
        for k in keys
            int j = int(math.floor((k - k0) / batch))
            float u = map.contains(s.buys, k) ? map.get(s.buys, k) : 0.0
            float d = map.contains(s.sells, k) ? map.get(s.sells, k) : 0.0
            array.set(total, j, array.get(total, j) + f_bin(s, k))
            array.set(up, j, array.get(up, j) + u)
            array.set(both, j, array.get(both, j) + u + d)
        for j = 0 to count - 1
            float v = array.get(total, j)
            float ud = array.get(both, j)
            if ud > v and ud > 0
                array.set(up, j, array.get(up, j) * v / ud)
                array.set(both, j, v)
            float diff = 2 * array.get(up, j) - array.get(both, j)
            array.set(dpos, j, math.max(diff, 0.0))
            array.set(dneg, j, math.max(-diff, 0.0))
        float peak = array.max(total)
        bool left = profileSide == "Left"
        int anchor = left ? s.start : f_endview(s)
        int direction = left ? 1 : -1
        int width = math.max(1, capWidth)
        bool deltaLane = profileStyle == "Up/Down + Delta" and allowDelta
        int deltaW = deltaLane ? int(width * 0.20) : 0
        int mainW = width - deltaW
        // <=4 base polygons per profile, regardless of how many sessions are shown.
        // Neutral total + full grey up component; VA overlays preserve the green/purple split.
        // The genuinely unclassified fraction remains grey, never invented directional volume.
        f_band(zero, total, 0, count - 1, anchor, direction, mainW, peak, k0, batch, k1, f_vp_alpha(vpDown))
        if profileStyle != "Total"
            f_band(zero, up, 0, count - 1, anchor, direction, mainW, peak, k0, batch, k1, f_vp_alpha(vpUp))
            int vaFirst = math.max(0, math.min(count - 1, int(math.floor((s.val / rowStep - k0) / batch))))
            int vaLast = math.max(vaFirst, math.min(count - 1, int(math.ceil((s.vah / rowStep - k0) / batch)) - 1))
            f_band(zero, up, vaFirst, vaLast, anchor, direction, mainW, peak, k0, batch, k1, f_vp_alpha(vaUp))
            f_band(up, both, vaFirst, vaLast, anchor, direction, mainW, peak, k0, batch, k1, f_vp_alpha(vaDown))
        if deltaLane
            int deltaX = anchor + direction * (mainW + int(deltaW / 2))
            float dpeak = math.max(array.max(dpos), array.max(dneg))
            f_band(zero, dpos, 0, count - 1, deltaX, 1, int(deltaW * 0.46), dpeak, k0, batch, k1, f_vp_alpha(vaUp))
            f_band(zero, dneg, 0, count - 1, deltaX, -1, int(deltaW * 0.46), dpeak, k0, batch, k1, f_vp_alpha(vaDown))
    count
 
f_draw(Session s, bool live, int width, bool extendThis, bool allowDelta, bool drawDetailedProfile) =>
    int endAt = f_endview(s)
    bool partial = s.partial or s.gaps > 0 or f_coverage(s) < minCoverage
    color cc = f_color(s.sid)
    bool value = (live ? showActiveVA : showSessionValue) and not na(s.poc) and (live or drawDetailedProfile or extendThis)
    string edge = live or partial ? line.style_dashed : line.style_solid
    if showRanges
        bool showCode = sessionLabelMode == "Codes top-left" or sessionLabelMode == "Codes + bottom title"
        bool bottomOnly = sessionLabelMode == "Bottom title only"
        string codeText = showCode ? f_code(s.sid) + (live ? "*" : "") : bottomOnly ? f_title_name(s.sid, false) + (live ? "*" : "") : ""
        string textVAlign = bottomOnly ? text.align_bottom : text.align_top
        array.push(drawnBoxes, box.new(s.start, s.hi, endAt, s.lo, xloc = xloc.bar_time,
             border_color = color.new(cc, 20), border_width = 1, border_style = edge,
             bgcolor = color.new(cc, rangeTransparency), text = codeText, text_size = bottomOnly ? titleFont : 10,
             text_color = cc, text_halign = text.align_left, text_valign = textVAlign, force_overlay = true))
        if sessionLabelMode == "Codes + bottom title" and array.size(drawnLabels) < 300
            string fullTitle = f_title_name(s.sid, false) + (live ? "*" : "")
            float pad = math.max(rowStep, (s.hi - s.lo) * (titlePadY / 100.0))
            int padTime = s.start + int(titlePadBars * timeframe.in_seconds() * 1000)
            array.push(drawnLabels, label.new(padTime, s.lo + pad, fullTitle, xloc = xloc.bar_time,
                 style = label.style_label_left, color = color.new(uiBG, 14), textcolor = cc,
                 size = titleFont, tooltip = f_tip(s, live), force_overlay = true))
    int renderedRows = drawDetailedProfile and sessionVPWidth > 0 ? f_render_profile(s, width, allowDelta) : 0
    if value
        for k = 0 to 2
            float price = k == 0 ? s.poc : k == 1 ? s.vah : s.val
            color lc = f_acolor(k)
            f_line(s.start, endAt, price, lc, k == 0 ? pocWidth : 1, live ? line.style_dotted : line.style_solid)
            bool enabled = k == 0 ? extendPOC : k == 1 ? extendVAH : extendVAL
            if not live and extendThis and enabled and extensionMode != "Off" and not partial and not na(s.audit)
                Audit a = array.get(s.audit, k)
                int until = extensionMode == "Until touch" and not na(a.touchAt) ? a.touchAt : lastMinuteEnd
                f_line(s.expectedEnd, until, price, color.new(lc, na(a.touchAt) ? 10 : 55), 1, line.style_dashed)
                f_queue_extension(s, a, until)
                if touchDots and not na(a.touchAt) and array.size(drawnLabels) < 350
                    array.push(drawnLabels, label.new(a.touchAt, price, "", xloc = xloc.bar_time,
                         style = label.style_circle, size = size.tiny, color = color.new(lc, 10),
                         tooltip = f_name(s.sid) + " " + f_stamp(s.start) + "\n" + f_audit_tip(a), force_overlay = true))
    renderedRows
 
f_cell(int col, int row, string txt, color cc, string tip, float width = 0.0) =>
    // AUDIT only. Auto sizing avoids forcing the raw journal across the screen.
    table.cell(ledger, col, row, f_desk_wrap(txt, row == 0 or row >= ledgerRows + 2 ? 100 : 32),
         text_size = panelText, text_color = cc, text_halign = text.align_left,
         text_valign = text.align_top, bgcolor = row % 2 == 0 ? uiBG : uiAlt, tooltip = tip)
    0
 
if barstate.islast
    array.clear(extensionNames)
    while array.size(drawnLines) > 0
        line.delete(array.pop(drawnLines))
    while array.size(drawnBoxes) > 0
        box.delete(array.pop(drawnBoxes))
    while array.size(drawnLabels) > 0
        label.delete(array.pop(drawnLabels))
    while array.size(drawnPolys) > 0
        polyline.delete(array.pop(drawnPolys))
    if not na(ledger)
        table.clear(ledger, 0, 0, traderPanel ? 2 : 6, traderPanel ? 6 : ledgerRows + 4)
    array<Session> shown = array.new<Session>()
    int historyCutoff = na(lastMinute) ? 0 : lastMinute - historyDays * 86400000
    int boxSafetyMax = 420
    bool historyClipped = false
    if array.size(completed) > 0
        int kept = 0
        for j = array.size(completed) - 1 to 0
            Session s = array.get(completed, j)
            if s.sid < 4 and f_history_enabled(s.sid) and s.expectedEnd >= historyCutoff
                if kept < boxSafetyMax
                    array.unshift(shown, s)
                    kept += 1
                else
                    historyClipped := true
        if showPreNYMap
            for j = array.size(completed) - 1 to 0
                Session s = array.get(completed, j)
                if s.sid == 5 and s.expectedEnd >= historyCutoff
                    array.push(shown, s)
                    break
    for sid = 0 to 3
        Session s = array.get(active, sid)
        if not na(s)
            f_profile(s)
            array.push(shown, s)
    array<int> ordering = array.new<int>()
    for s in shown
        array.push(ordering, s.start)
    array<int> order = array.sort_indices(ordering, order.ascending)
    int finished = 0
    int mainFinished = 0
    int liveCount = 0
    int profileCount = 0
    for s in shown
        Session alive = s.sid < 4 ? array.get(active, s.sid) : na
        if na(alive) or alive.start != s.start
            finished += 1
            if s.sid < 4
                mainFinished += 1
        else
            liveCount += 1
    array<bool> profileEnabled = array.new<bool>(array.size(shown), false)
    int profilesAllocated = 0
    if miniProfiles and detailProfiles > 0 and sessionVPWidth > 0 and array.size(order) > 0
        for q = array.size(order) - 1 to 0
            int idx = array.get(order, q)
            Session s = array.get(shown, idx)
            if f_available(s) and profilesAllocated < detailProfiles
                array.set(profileEnabled, idx, true)
                profilesAllocated += 1
    profileCount := profilesAllocated
    int baseCost = profileStyle == "Total" ? 1 : 4
    int deltaCapacity = profileStyle == "Up/Down + Delta" ? math.min(profileCount, math.max(0, int(math.floor((100 - profileCount * baseCost) / 2.0)))) : 0
    array<bool> deltaEnabled = array.new<bool>(array.size(shown), false)
    int deltaAllocated = 0
    if deltaCapacity > 0 and array.size(order) > 0
        for q = array.size(order) - 1 to 0
            int idx = array.get(order, q)
            if array.get(profileEnabled, idx) and deltaAllocated < deltaCapacity
                array.set(deltaEnabled, idx, true)
                deltaAllocated += 1
    int finishIndex = 0
    int requestedExtend = extendCountMode == "Auto from history" ? finished : extendProfilesManual
    // Three lines per profile plus intra-box value lines share Pine's 500-line budget.
    int extendProfiles = math.min(requestedExtend, 70)
    array<int> rowCounts = array.new<int>(array.size(shown), 0)
    for idx in order
        Session s = array.get(shown, idx)
        Session activeS = s.sid < 4 ? array.get(active, s.sid) : na
        bool live = not na(activeS) and activeS.start == s.start
        int width = int((f_endview(s) - s.start) * sessionVPWidth / 100.0)
        if avoidProfileOverlap
            for other in shown
                if other.sid != s.sid or other.start != s.start
                    int here = profileSide == "Left" ? s.start : f_endview(s)
                    int there = profileSide == "Left" ? other.start : f_endview(other)
                    int gap = profileSide == "Left" ? there - here : here - there
                    if gap > 0
                        width := math.min(width, int(gap * 0.85))
        if not live
            finishIndex += 1
        bool extendThis = not live and finishIndex > finished - extendProfiles
        int nr = f_draw(s, live, math.max(1, width), extendThis, array.get(deltaEnabled, idx), array.get(profileEnabled, idx))
        array.set(rowCounts, idx, nr)
    [titlesShown, titlesHidden] = f_draw_titles(shown, order)
    [lineNamesShown, lineNamesHidden] = f_draw_extension_names()
    string historyText = "History " + str.tostring(historyDays) + "d · " + str.tostring(mainFinished) + " completed + " + str.tostring(liveCount) + " DEV"
    historyText += "\nVP detail " + str.tostring(profilesAllocated) + "/" + str.tostring(detailProfiles) + " · Extend " + str.tostring(extendProfiles) + (extendCountMode == "Auto from history" ? " AUTO" : " MANUAL")
    historyText += "\nExtended names " + str.tostring(lineNamesShown) + (lineNamesHidden > 0 ? " | crowded/limited " + str.tostring(lineNamesHidden) : "")
    historyText += "\nSource 1m since " + f_stamp(firstMinute)
    if historyClipped
        historyText += " · BOX LIMIT CLIPPED"
    if profileStyle == "Up/Down + Delta"
        historyText += "\n" + "Delta lane: " + str.tostring(deltaAllocated) + "/" + str.tostring(profileCount)
        if deltaAllocated < profileCount
            historyText += " · other VPs without Delta"
    string historyTip = "History span is calendar days. Full VP detail is intentionally separate from box history because Pine caps the indicator at 500 boxes / 100 polylines / 500 lines. Old retained sessions can remain as clean boxes even when their heavy VAP maps are no longer stored. Disable unneeded session families to reach farther back before the box budget clips. Available 1m data can be shorter than requested."
    historyTip += "\n" + "Source 1m request: " + str.tostring(historyMinutes) + " bars. Polygons: " + str.tostring(array.size(drawnPolys)) + "/100."
    historyTip += "\nAll selected available VPs are retained. If extra delta lanes do not all fit, newer profiles get priority. POC/VA and calculation rules do not depend on this allocation."
    if panelMode == "TRADE MAP"
        f_draw_trader(shown, historyText, historyTip)
    else if panelMode == "AUDIT"
        string refText = na(reference) ? "no full reference" : f_code(reference.sid) + " " + str.format_time(reference.start, "dd/MM", displayZone) +
             (lastPrice > reference.vah ? " · above VAH" : lastPrice < reference.val ? " · below VAL" : " · inside VA")
        string context = "ARTIO 2.5.4 · AUDIT | " + (na(lastMinute) ? "—" : f_actor(lastMinute)) + " | " + refText + " | " + action
        f_cell(0, 0, context, uiFG, "Descriptive rules, not a profitability forecast. Developing levels are not retroactively treated as fixed.")
        array<string> names = array.from("SESSION", "POC", "VAH", "VAL", "HIGH · breach/return", "LOW · breach/return", "SOURCE")
        array<float> widths = array.from(12.0, 16.0, 16.0, 16.0, 16.0, 16.0, 8.0)
        for k = 0 to 6
            f_cell(k, 1, array.get(names, k), k >= 1 and k <= 3 ? f_acolor(k - 1) : uiMuted, "", array.get(widths, k))
        int firstRow = math.max(0, array.size(order) - ledgerRows)
        if array.size(order) > 0
            for j = firstRow to array.size(order) - 1
                int idx = array.get(order, j)
                Session s = array.get(shown, idx)
                Session activeS = s.sid < 4 ? array.get(active, s.sid) : na
                bool live = not na(activeS) and activeS.start == s.start
                bool partial = s.partial or s.gaps > 0 or f_coverage(s) < minCoverage
                int row = j - firstRow + 2
                string state = live ? "DEV" : partial ? "PARTIAL" : "closed"
                f_cell(0, row, f_code(s.sid) + " " + str.format_time(s.start, "dd/MM", f_zone(s.sid)) + "\n" + state, f_color(s.sid), f_tip(s, live))
                for k = 0 to 4
                    float price = k == 0 ? s.poc : k == 1 ? s.vah : k == 2 ? s.val : k == 3 ? s.hi : s.lo
                    string status = live ? "DEV" : partial ? "partial data" : "untested"
                    string tip = f_tip(s, live)
                    if not live and not partial and not na(s.audit)
                        Audit a = array.get(s.audit, k)
                        status := f_brief(a, k >= 3)
                        tip += "\n\n" + f_audit_tip(a)
                    f_cell(k + 1, row, f_px(price) + "\n" + status, k <= 2 ? f_acolor(k) : uiFG, tip)
                string source = s.fpMinutes > 0 and s.proxyMinutes > 0 ? "MIX" : s.fpMinutes > 0 ? "TV FP" : "PROXY"
                f_cell(6, row, (s.overflow ? "LIMIT" : source) + "\n" + str.tostring(array.get(rowCounts, idx)) + " rows", uiMuted, f_tip(s, live))
        string latest = "No new closed observations yet"
        int latestAt = 0
        if array.size(completed) > 0
            for s in completed
                if s.sid < 4 and not na(s.audit)
                    for a in s.audit
                        int at = math.max(nz(a.touchAt, 0), nz(a.crossAt, 0), nz(a.holdAt, 0), nz(a.returnAt, 0), nz(a.sweepAt, 0))
                        if at > latestAt
                            latestAt := at
                            string eventName = at == a.sweepAt ? "breach + return" : at == a.returnAt ? "return" : at == a.holdAt ? "hold" : at == a.crossAt ? (a.crossGap ? "GAP" : "close across") : "test"
                            string who = at == a.sweepAt ? a.sweepWho : at == a.returnAt ? a.returnWho : at == a.holdAt ? a.holdWho : at == a.crossAt ? a.crossWho : a.touchWho
                            latest := f_code(s.sid) + " " + str.format_time(s.start, "dd/MM", displayZone) + " " + f_levelkind(a.kind) + " " + f_px(a.price) + " → " + eventName + " · " + f_who(at, who)
        f_cell(0, ledgerRows + 2, "EVENT: " + latest, uiFG, "First test and later key stages are retained separately. Hover a level cell for its audit.")
        string volText = "1m V " + (na(lastRV) ? "—" : str.tostring(lastRV, "#.00") + "×")
        if showVolumePace and not na(current)
            [pace, samples] = f_pace(current, completed)
            volText += na(pace) ? " | RVOL —" : " | RVOL " + str.tostring(pace, "#.00") + "×"
        string plan = not na(candidate) ? " | " + "invalid " + f_px(candidate.invalid) + " | " + "objective " + f_px(objective) : ""
        f_cell(0, ledgerRows + 3, volText + plan + " | " + "As of 1m close: " + f_stamp(lastMinuteEnd) + " · " + displayZone + "\n" + historyText, uiMuted, historyTip)
        f_cell(0, ledgerRows + 4, "AS Asia · LN London · NY New York · PM US PM | * / DEV developing | PRE = clock phase | level test ≠ stop fills", uiMuted,
             "First test: a closed minute spans the level AFTER the source session ends. Colored levels inside a completed box are its final profile, not a historical signal.")

← 返回列表