Volume Profile Levels - POC / Breakthrough Zone / Reversal Zone

RUpward · study · 561 行 · 点赞 35 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ⓒ RUpward
//@version=6
// ═══════════════════════════════════════════════════════════════════════════
// VP Levels · Anchored — Breakthrough Zone (TZ) / Reversal Zone (RZ) / Path Gauge
//
// Anchored volume profile from the most recent confirmed swing pivot.
// Thin bins = Reversal Zones (RZ), thick bins = Breakthrough Zones (TZ).
// The Path Gauge measures the average profile thickness between the current
// price and a bracket above / below, and labels each direction Clear / Neutral / Hold.
//
// Notes
//  · Calculated on the last bar only. Levels are not kept on historical bars.
//  · Alerts use alert(). Create the alert with "Any alert() function call".
//  · Multi-timeframe POC / VA lines are display only. They are not used by the
//    Path Gauge or alerts.
// ═══════════════════════════════════════════════════════════════════════════
 
// max_bars_back is required: the binning loop references high[b] / low[b] / volume[b]
// with a variable offset, so Pine cannot infer the history depth on its own.
indicator("VP Levels · Anchored - Breakthrough Zone / Reversal Zone", "VPLV-Anc·B/RZ", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500,
     max_bars_back = 2100)
 
// ── Inputs ─────────────────────────────────────────────────────────────────
gA = "Anchor"
anchorMode = input.string("pivot", "Anchor Mode", options = ["pivot", "rolling"], group = gA,
     tooltip = "pivot = anchored to the most recent confirmed swing pivot (recommended). rolling = fixed lookback window.")
pivW       = input.int(12,  "Pivot Half-Width",     minval = 3,  maxval = 200, group = gA,
     tooltip = "Bars on each side required to confirm a swing pivot. The pivot is confirmed this many bars later, so it never looks ahead.")
anchorMin  = input.int(24,  "Min Anchor Distance",  minval = 10, maxval = 500, group = gA,
     tooltip = "In bars. Pivots closer to the current bar than this are skipped.")
anchorMax  = input.int(480, "Max Anchor Distance",  minval = 50, maxval = 2000, group = gA,
     tooltip = "In bars. An anchor further back than this is capped here.")
lookbackIn = input.int(72,  "Fallback Lookback",    minval = 20, maxval = 2000, group = gA,
     tooltip = "In bars. Used in rolling mode, or in pivot mode when no valid pivot exists.")
nBins      = input.int(60,  "Price Bins",           minval = 20, maxval = 200, group = gA)
vaPct      = input.float(70.0, "Value Area %", minval = 10, maxval = 95, step = 5, group = gA)
 
gM = "Multi-Timeframe"
mtfSel = input.string("Off", "Timeframe",
     options = ["Off", "15m", "30m", "1H", "2H", "4H", "12H", "1D", "1W", "1M"], group = gM,
     tooltip = "Adds the POC and Value Area high / low lines of the selected timeframe. Anchor, binning and VA use the same logic run on that timeframe's bars, and bar-count settings refer to that timeframe's bars.")
cMPOC = input.color(#ffa726, "POC Color",  group = gM)
wMPOC = input.int(1, "POC Width", minval = 1, maxval = 5, group = gM)
sMPOC = input.string("solid", "POC Style", options = ["solid", "dashed", "dotted"], group = gM)
cMVA  = input.color(#7e57c2, "VA Color",   group = gM)
wMVA  = input.int(1, "VA Width",  minval = 1, maxval = 5, group = gM)
sMVA  = input.string("dotted", "VA Style", options = ["solid", "dashed", "dotted"], group = gM)
 
gB = "Baseline · Detection"
baseStat  = input.string("median", "Thickness Baseline", options = ["median", "mean"], group = gB,
     tooltip = "median = robust to a few dominant bins (recommended). mean = total volume / bins.")
thinM     = input.float(0.80, "RZ Threshold", minval = 0.1, maxval = 1.0, step = 0.05, group = gB,
     tooltip = "A local low bin thinner than baseline × this value is a Reversal Zone.")
thickM    = input.float(1.20, "TZ Threshold", minval = 1.0, maxval = 3.0, step = 0.05, group = gB,
     tooltip = "A local peak bin thicker than baseline × this value is a Breakthrough Zone.")
maxLevels = input.int(6, "Max Levels Each", minval = 1, maxval = 12, group = gB)
 
gC = "Path Gauge"
pathPct   = input.float(1.5,  "Bracket Width %", minval = 0.2, maxval = 10.0, step = 0.1, group = gC,
     tooltip = "Distance above and below the current price that is measured. Match it to your SL / TP distance.")
gateThin  = input.float(0.80, "Clear Threshold", minval = 0.1, maxval = 1.5, step = 0.05, group = gC,
     tooltip = "Path thickness at or below this multiple of the baseline = Clear.")
gateThick = input.float(1.20, "Hold Threshold",  minval = 0.8, maxval = 3.0, step = 0.05, group = gC,
     tooltip = "Path thickness at or above this multiple of the baseline = Hold.")
showPath  = input.bool(true, "Path Boxes", group = gC)
 
gD = "Display"
profSide = input.string("right", "Profile Side", options = ["right", "left"], group = gD)
showProf = input.bool(true,  "Histogram",            group = gD)
profW    = input.int(80, "Profile Width", minval = 20, maxval = 300, group = gD, tooltip = "In bars.")
showPOC  = input.bool(true,  "POC",                  group = gD)
showVAf  = input.bool(true,  "VA Fill",              group = gD)
showVAl  = input.bool(true,  "VA Lines",             group = gD)
showRZ   = input.bool(true,  "RZ Reversal Zone",     group = gD)
showTZ   = input.bool(true,  "TZ Breakthrough Zone", group = gD)
// The anchor line and the ⚓ label are independent of each other.
showAncLn  = input.bool(false, "Anchor Line",    group = gD)
showAncLbl = input.bool(false, "Anchor Label ⚓", group = gD)
showLbl  = input.bool(true,  "Labels",               group = gD)
showTbl  = input.bool(false, "Verdict Table",        group = gD)
 
gE = "Colors"
cRZ  = input.color(#ff006f, "RZ Reversal",     group = gE)
cTZ  = input.color(#8d6e63, "TZ Breakthrough", group = gE)
cMid = input.color(#546e7a, "Mid Thickness",   group = gE)
cPOC = input.color(#ffa726, "POC",             group = gE)
cVA  = input.color(#7e57c2, "VA",              group = gE)
cAnc = input.color(#b0bec5, "Anchor",          group = gE)
cOK  = input.color(#26a69a, "Path Clear",      group = gE)
cNO  = input.color(#ef5350, "Path Hold",       group = gE)
 
// Up to 6 + 6 + 3 levels can be drawn, so all widths default to 1 to keep candles readable.
gF = "Line Width · Style"
wPOC = input.int(1, "POC Width",         minval = 1, maxval = 5, group = gF)
sPOC = input.string("solid",  "POC Style",         options = ["solid", "dashed", "dotted"], group = gF)
wVA  = input.int(1, "VA Line Width",     minval = 1, maxval = 5, group = gF)
sVA  = input.string("dotted", "VA Line Style",     options = ["solid", "dashed", "dotted"], group = gF)
wRZ  = input.int(1, "RZ Width",          minval = 1, maxval = 5, group = gF)
sRZ  = input.string("solid",  "RZ Style",          options = ["solid", "dashed", "dotted"], group = gF)
wTZ  = input.int(1, "TZ Width",          minval = 1, maxval = 5, group = gF)
sTZ  = input.string("dashed", "TZ Style",          options = ["solid", "dashed", "dotted"], group = gF)
wAnc = input.int(1, "Anchor Line Width", minval = 1, maxval = 5, group = gF)
sAnc = input.string("dashed", "Anchor Line Style", options = ["solid", "dashed", "dotted"], group = gF)
 
// ── Helpers ────────────────────────────────────────────────────────────────
// Average thickness (multiple of baseline) of a price range, plus coverage.
// Coverage = share of the requested range actually covered by the profile.
// An anchored range is often narrower than the bracket, so a partial reading
// is returned together with its coverage instead of being presented as complete.
f_zone(float[] bins, float bot, float bs, int n, float baseV, float loPx, float hiPx) =>
    float acc = 0.0
    int   cnt = 0
    for k = 0 to n - 1
        float px = bot + (k + 0.5) * bs
        if px >= loPx and px <= hiPx
            acc += array.get(bins, k) / baseV
            cnt += 1
    float want = hiPx - loPx
    float cov  = want > 0 ? math.min(1.0, cnt * bs / want) : 0.0
    float rat  = cnt >= 3 ? acc / cnt : na
    [rat, cov]
 
f_verdict(float x, float thin, float thick) =>
    na(x) ? "N/A" : x <= thin ? "Clear" : x >= thick ? "Hold" : "Neutral"
 
f_grade(float x, float thin, float thick) =>
    na(x) ? "N/A" : x <= thin ? "Thin" : x >= thick ? "Thick" : "Normal"
 
f_vcol(float x, float thin, float thick) =>
    na(x) ? color.gray : x <= thin ? cOK : x >= thick ? cNO : color.silver
 
f_ls(string st) =>
    st == "dashed" ? line.style_dashed : st == "dotted" ? line.style_dotted : line.style_solid
 
f_fmt(float x) =>
    str.tostring(x, math.abs(x) >= 1000 ? "#,###" : "#.##")
 
// ── Multi-Timeframe ────────────────────────────────────────────────────────
f_tfCode(string s) =>
    switch s
        "15m" => "15"
        "30m" => "30"
        "1H"  => "60"
        "2H"  => "120"
        "4H"  => "240"
        "12H" => "720"
        "1D"  => "D"
        "1W"  => "W"
        "1M"  => "M"
        => timeframe.period
 
// Runs inside request.security on the selected timeframe's bars.
// Binning runs on the last 3 bars only: the value the chart receives may come from
// a closed or a still-forming bar, so filtering by barstate.islast alone can return na.
f_mtfVP() =>
    var int[] mPB = array.new_int()
    float mPh = ta.pivothigh(high, pivW, pivW)
    float mPl = ta.pivotlow(low,  pivW, pivW)
    if not na(mPh) or not na(mPl)
        array.push(mPB, bar_index - pivW)
        if array.size(mPB) > 64
            array.shift(mPB)
 
    float rPoc  = na
    float rVaH  = na
    float rVaL  = na
    int   rTime = na
 
    if mtfSel != "Off" and bar_index > last_bar_index - 3
        int mA = na
        if anchorMode == "pivot" and array.size(mPB) > 0
            for i = 0 to array.size(mPB) - 1
                int pb = array.get(mPB, i)
                if bar_index - pb >= anchorMin
                    mA := pb
        if na(mA)
            mA := math.max(0, bar_index - lookbackIn + 1)
        if bar_index - mA > anchorMax
            mA := bar_index - anchorMax
 
        int   mSpan = math.min(bar_index - mA, bar_index)
        float mTop  = high
        float mBot  = low
        for b = 0 to mSpan
            mTop := math.max(mTop, high[b])
            mBot := math.min(mBot, low[b])
        float mBs = (mTop - mBot) / nBins
 
        if mBs > 0 and mSpan >= 2
            float[] mBins = array.new_float(nBins, 0.0)
            for b = 0 to mSpan
                float v = nz(volume[b])
                if v > 0
                    int loB = math.max(0, math.min(nBins - 1, int(math.floor((low[b]  - mBot) / mBs))))
                    int hiB = math.max(0, math.min(nBins - 1, int(math.floor((high[b] - mBot) / mBs))))
                    float per = v / (hiB - loB + 1)
                    for k = loB to hiB
                        array.set(mBins, k, array.get(mBins, k) + per)
 
            float mTotal = array.sum(mBins)
            if mTotal > 0
                int   mPocI = array.indexof(mBins, array.max(mBins))
                float tgt   = mTotal * vaPct / 100.0
                float acc   = array.get(mBins, mPocI)
                int   up    = mPocI
                int   dn    = mPocI
                while acc < tgt and (up < nBins - 1 or dn > 0)
                    float uv = up < nBins - 1 ? array.get(mBins, up + 1) : -1.0
                    float dv = dn > 0 ? array.get(mBins, dn - 1) : -1.0
                    if uv >= dv
                        up  += 1
                        acc += uv
                    else
                        dn  -= 1
                        acc += dv
                rPoc  := mBot + (mPocI + 0.5) * mBs
                rVaH  := mBot + (up + 1) * mBs
                rVaL  := mBot + dn * mBs
                rTime := time[mSpan]
    [rPoc, rVaH, rVaL, rTime]
 
[mPoc, mVaH, mVaL, mTime] = request.security(syminfo.tickerid, f_tfCode(mtfSel), f_mtfVP(),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
 
// ── Pivot collection ───────────────────────────────────────────────────────
// ta.pivothigh/low(w, w) confirms the pivot at bar_index - w only after seeing
// w bars on both sides. This delay is what guarantees no look-ahead.
ph = ta.pivothigh(high, pivW, pivW)
pl = ta.pivotlow(low,  pivW, pivW)
 
var int[]    PB = array.new_int()
var float[]  PP = array.new_float()
var string[] PK = array.new_string()
 
if not na(ph) or not na(pl)
    array.push(PB, bar_index - pivW)
    array.push(PP, not na(ph) ? high[pivW] : low[pivW])
    array.push(PK, not na(ph) ? "High" : "Low")
    if array.size(PB) > 64
        array.shift(PB)
        array.shift(PP)
        array.shift(PK)
 
// ── Drawing storage ────────────────────────────────────────────────────────
var line[]  LNS = array.new_line()
var box[]   BXS = array.new_box()
var label[] LBS = array.new_label()
var table   TBL = table.new(position.top_right, 2, 13, border_width = 1,
     bgcolor = color.new(color.black, 20), frame_color = color.new(color.gray, 50),
     frame_width = 1)
 
var string prevGate = ""
 
// ═══════════════════════════════════════════════════════════════════════════
// Main — last bar only
// ═══════════════════════════════════════════════════════════════════════════
if barstate.islast
    while array.size(LNS) > 0
        line.delete(array.pop(LNS))
    while array.size(BXS) > 0
        box.delete(array.pop(BXS))
    while array.size(LBS) > 0
        label.delete(array.pop(LBS))
 
    // ── Multi-timeframe lines ──────────────────────────────────────────────
    if mtfSel != "Off" and not na(mPoc) and not na(mTime)
        int mEnd = time + (profSide == "right" ? 5 + profW : 5) * timeframe.in_seconds() * 1000
        array.push(LNS, line.new(mTime, mPoc, mEnd, mPoc, xloc = xloc.bar_time,
             color = cMPOC, width = wMPOC, style = f_ls(sMPOC)))
        array.push(LNS, line.new(mTime, mVaH, mEnd, mVaH, xloc = xloc.bar_time,
             color = cMVA, width = wMVA, style = f_ls(sMVA)))
        array.push(LNS, line.new(mTime, mVaL, mEnd, mVaL, xloc = xloc.bar_time,
             color = cMVA, width = wMVA, style = f_ls(sMVA)))
        if showLbl
            array.push(LBS, label.new(mEnd, mPoc, mtfSel + " POC " + f_fmt(mPoc), xloc = xloc.bar_time,
                 style = label.style_label_left, color = color.new(cMPOC, 85),
                 textcolor = cMPOC, size = size.small))
            array.push(LBS, label.new(mEnd, mVaH, mtfSel + " VAH " + f_fmt(mVaH), xloc = xloc.bar_time,
                 style = label.style_label_left, color = color.new(cMVA, 85),
                 textcolor = cMVA, size = size.tiny))
            array.push(LBS, label.new(mEnd, mVaL, mtfSel + " VAL " + f_fmt(mVaL), xloc = xloc.bar_time,
                 style = label.style_label_left, color = color.new(cMVA, 85),
                 textcolor = cMVA, size = size.tiny))
 
    // ── Anchor ─────────────────────────────────────────────────────────────
    int    aBar = na
    float  aPx  = na
    string aKnd = ""
    if anchorMode == "pivot" and array.size(PB) > 0
        for i = 0 to array.size(PB) - 1
            int b = array.get(PB, i)
            if bar_index - b >= anchorMin
                aBar := b
                aPx  := array.get(PP, i)
                aKnd := array.get(PK, i)
    if na(aBar)
        aBar := math.max(0, bar_index - lookbackIn + 1)
        aPx  := close[math.max(0, bar_index - aBar)]
        aKnd := anchorMode == "pivot" ? "Fallback Lookback" : "Rolling"
    if bar_index - aBar > anchorMax
        aBar := bar_index - anchorMax
        aKnd := aKnd + " · Capped"
 
    int span = math.min(bar_index - aBar, bar_index)
 
    // ── Range top / bottom ─────────────────────────────────────────────────
    float top = high
    float bot = low
    for b = 0 to span
        top := math.max(top, high[b])
        bot := math.min(bot, low[b])
    float bs = (top - bot) / nBins
 
    if bs > 0 and span >= 2
        // ── Binning ────────────────────────────────────────────────────────
        float[] bins = array.new_float(nBins, 0.0)
        for b = 0 to span
            float v = nz(volume[b])
            if v > 0
                int loB = math.max(0, math.min(nBins - 1, int(math.floor((low[b]  - bot) / bs))))
                int hiB = math.max(0, math.min(nBins - 1, int(math.floor((high[b] - bot) / bs))))
                float per = v / (hiB - loB + 1)
                for k = loB to hiB
                    array.set(bins, k, array.get(bins, k) + per)
 
        float totalV = array.sum(bins)
        float meanV  = totalV / nBins
        // Median baseline: not dragged by a few dominant bins.
        float baseV  = baseStat == "median" ? array.median(bins) : meanV
        baseV := baseV <= 0 or na(baseV) ? meanV : baseV
 
        float maxV = array.max(bins)
        int   pocI = array.indexof(bins, maxV)
        float poc  = bot + (pocI + 0.5) * bs
 
        // ── Value Area — expand from POC toward the thicker neighbor ───────
        float target = totalV * vaPct / 100.0
        float acc    = array.get(bins, pocI)
        int   up     = pocI
        int   dn     = pocI
        while acc < target and (up < nBins - 1 or dn > 0)
            float uv = up < nBins - 1 ? array.get(bins, up + 1) : -1.0
            float dv = dn > 0 ? array.get(bins, dn - 1) : -1.0
            if uv >= dv
                up  += 1
                acc += uv
            else
                dn  -= 1
                acc += dv
        float vaH = bot + (up + 1) * bs
        float vaL = bot + dn * bs
 
        // ── TZ (Breakthrough) / RZ (Reversal) ──────────────────────────────
        float[] tzP = array.new_float()
        float[] tzV = array.new_float()
        float[] rzP = array.new_float()
        float[] rzV = array.new_float()
        for i = 1 to nBins - 2
            float pv = array.get(bins, i - 1)
            float cv = array.get(bins, i)
            float nv = array.get(bins, i + 1)
            float px = bot + (i + 0.5) * bs
            if cv > pv and cv >= nv and cv > baseV * thickM
                array.push(tzP, px)
                array.push(tzV, cv)
            if cv < pv and cv <= nv and cv < baseV * thinM
                array.push(rzP, px)
                array.push(rzV, cv)
 
        // ── Path Gauge ─────────────────────────────────────────────────────
        float pp = pathPct / 100.0
        [upTh, upCov] = f_zone(bins, bot, bs, nBins, baseV, close, close * (1.0 + pp))
        [dnTh, dnCov] = f_zone(bins, bot, bs, nBins, baseV, close * (1.0 - pp), close)
        string longV  = f_verdict(upTh, gateThin, gateThick)
        string shortV = f_verdict(dnTh, gateThin, gateThick)
 
        // ── Coordinates ────────────────────────────────────────────────────
        bool  isR       = profSide == "right"
        int   profStart = isR ? bar_index + 5 : aBar
        int   profEnd   = profStart + profW
        int   linesEnd  = bar_index + 5
        int   lvlEnd    = isR ? profStart : linesEnd
        int   rMain     = isR ? profEnd : linesEnd
 
        // ① Histogram — thin bins use the highlight color
        if showProf and maxV > 0
            for i = 0 to nBins - 1
                float cv = array.get(bins, i)
                if cv > 0
                    int   w   = math.max(1, int(math.round(cv / maxV * profW)))
                    float r   = cv / baseV
                    color col = r < thinM ? cRZ : r > thickM ? cTZ : cMid
                    array.push(BXS, box.new(profStart, bot + (i + 1) * bs,
                         profStart + w, bot + i * bs,
                         border_color = color.new(col, 100),
                         bgcolor = color.new(col, 58)))
 
        // ② Anchor — shows where the profile starts
        if showAncLn
            array.push(LNS, line.new(aBar, top, aBar, bot,
                 color = color.new(cAnc, 30), width = wAnc, style = f_ls(sAnc)))
        if showAncLbl
            array.push(LBS, label.new(aBar, aPx, "⚓ " + aKnd,
                 style = label.style_label_down, color = color.new(cAnc, 80),
                 textcolor = cAnc, size = size.tiny))
 
        // ③ Path boxes — the range an entry now would travel through
        if showPath
            color lc = longV  == "Clear" ? cOK : longV  == "Hold" ? cNO : color.gray
            color sc = shortV == "Clear" ? cOK : shortV == "Hold" ? cNO : color.gray
            array.push(BXS, box.new(bar_index, close * (1.0 + pp), linesEnd, close,
                 border_color = color.new(lc, 70), bgcolor = color.new(lc, 87)))
            array.push(BXS, box.new(bar_index, close, linesEnd, close * (1.0 - pp),
                 border_color = color.new(sc, 70), bgcolor = color.new(sc, 87)))
 
        // ④ POC / VA
        if showPOC
            array.push(LNS, line.new(aBar, poc, rMain, poc, color = cPOC,
                 width = wPOC, style = f_ls(sPOC)))
            if showLbl
                array.push(LBS, label.new(aBar, poc, "POC " + f_fmt(poc),
                     style = label.style_label_right, color = color.new(cPOC, 85),
                     textcolor = cPOC, size = size.small))
        if showVAf
            array.push(BXS, box.new(aBar, vaH, rMain, vaL,
                 border_color = color.new(cVA, 100), bgcolor = color.new(cVA, 90)))
        if showVAl
            array.push(LNS, line.new(aBar, vaH, rMain, vaH, color = cVA, width = wVA, style = f_ls(sVA)))
            array.push(LNS, line.new(aBar, vaL, rMain, vaL, color = cVA, width = wVA, style = f_ls(sVA)))
            if showLbl
                array.push(LBS, label.new(aBar, vaH, "VAH " + f_fmt(vaH),
                     style = label.style_label_right, color = color.new(cVA, 85),
                     textcolor = cVA, size = size.tiny))
                array.push(LBS, label.new(aBar, vaL, "VAL " + f_fmt(vaL),
                     style = label.style_label_right, color = color.new(cVA, 85),
                     textcolor = cVA, size = size.tiny))
 
        // ⑤ RZ (Reversal Zone) — drawn bright
        if showRZ and array.size(rzP) > 0
            int[] oR = array.sort_indices(rzV, order.ascending)
            int   nR = math.min(maxLevels, array.size(oR))
            for j = 0 to nR - 1
                float px = array.get(rzP, array.get(oR, j))
                array.push(LNS, line.new(aBar, px, lvlEnd, px, color = color.new(cRZ, 15),
                     width = wRZ, style = f_ls(sRZ)))
                if showLbl
                    array.push(LBS, label.new(lvlEnd, px, "RZ Reversal " + f_fmt(px),
                         style = label.style_label_left, color = color.new(cRZ, 85),
                         textcolor = cRZ, size = size.tiny))
 
        // ⑥ TZ (Breakthrough Zone) — drawn faint: do not expect price to stall here
        if showTZ and array.size(tzP) > 0
            int[] oT = array.sort_indices(tzV, order.descending)
            int   nT = math.min(maxLevels, array.size(oT))
            for j = 0 to nT - 1
                float px = array.get(tzP, array.get(oT, j))
                array.push(LNS, line.new(aBar, px, lvlEnd, px, color = color.new(cTZ, 35),
                     width = wTZ, style = f_ls(sTZ)))
                if showLbl
                    array.push(LBS, label.new(lvlEnd, px, "TZ Breakthrough " + f_fmt(px),
                         style = label.style_label_left, color = color.new(cTZ, 85),
                         textcolor = cTZ, size = size.tiny))
 
        // ── Verdict table ──────────────────────────────────────────────────
        // The 0.80 / 1.20 gate thresholds were set for the default configuration.
        // Changing any of the settings below shifts the thickness distribution,
        // so the table flags it.
        string off = ""
        off := off + (anchorMode != "pivot"  ? "anchor=" + anchorMode + " " : "")
        off := off + (pivW      != 12        ? "pivW="   + str.tostring(pivW) + " " : "")
        off := off + (baseStat  != "median"  ? "base="   + baseStat + " " : "")
        off := off + (nBins     != 60        ? "bins="   + str.tostring(nBins) + " " : "")
        off := off + (pathPct   != 1.5       ? "path="   + str.tostring(pathPct) + " " : "")
 
        if showTbl
            table.clear(TBL, 0, 0, 1, 12)
            float posPct = top > bot ? (close - bot) / (top - bot) * 100.0 : na
            table.cell(TBL, 0, 0, "VP · Path Gauge", text_color = color.white,
                 text_size = size.small, bgcolor = color.new(color.gray, 60))
            table.cell(TBL, 1, 0, "Long " + longV + " / Short " + shortV,
                 text_color = longV == "Clear" or shortV == "Clear" ? cOK :
                              longV == "Hold" and shortV == "Hold" ? cNO : color.silver,
                 text_size = size.small, bgcolor = color.new(color.gray, 60))
 
            table.cell(TBL, 0, 1, "Anchor",            text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 1, aKnd + " · " + str.tostring(bar_index - aBar) + " bars ago @ " + f_fmt(aPx),
                 text_color = color.white, text_size = size.tiny)
            table.cell(TBL, 0, 2, "Range",             text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 2, f_fmt(bot) + " ~ " + f_fmt(top), text_color = color.white, text_size = size.tiny)
            table.cell(TBL, 0, 3, "Position in Range", text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 3, na(posPct) ? "—" : str.tostring(posPct, "#") + "%",
                 text_color = color.white, text_size = size.tiny)
            table.cell(TBL, 0, 4, "Baseline",          text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 4, (baseStat == "median" ? "Median" : "Mean") +
                 " · Mean/Median " + str.tostring(meanV / baseV, "#.##") + "x",
                 text_color = color.white, text_size = size.tiny)
            table.cell(TBL, 0, 5, "POC",               text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 5, f_fmt(poc) + "  (" + str.tostring((close / poc - 1) * 100, "+#.##") + "%)",
                 text_color = cPOC, text_size = size.tiny)
            table.cell(TBL, 0, 6, "VA",                text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 6, f_fmt(vaL) + " ~ " + f_fmt(vaH), text_color = cVA, text_size = size.tiny)
 
            table.cell(TBL, 0, 7, "↑ Path 0~+" + str.tostring(pathPct) + "%",
                 text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 7, (na(upTh) ? "N/A" : str.tostring(upTh, "#.##") + "x  " +
                 f_grade(upTh, gateThin, gateThick)) + "   [Covered " + str.tostring(upCov * 100, "#") + "%]",
                 text_color = f_vcol(upTh, gateThin, gateThick), text_size = size.tiny)
            table.cell(TBL, 0, 8, "↓ Path -" + str.tostring(pathPct) + "~0%",
                 text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 8, (na(dnTh) ? "N/A" : str.tostring(dnTh, "#.##") + "x  " +
                 f_grade(dnTh, gateThin, gateThick)) + "   [Covered " + str.tostring(dnCov * 100, "#") + "%]",
                 text_color = f_vcol(dnTh, gateThin, gateThick), text_size = size.tiny)
 
            table.cell(TBL, 0, 9,  "Long Verdict",  text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 9,  longV,  text_color = f_vcol(upTh, gateThin, gateThick), text_size = size.tiny)
            table.cell(TBL, 0, 10, "Short Verdict", text_color = color.silver, text_size = size.tiny)
            table.cell(TBL, 1, 10, shortV, text_color = f_vcol(dnTh, gateThin, gateThick), text_size = size.tiny)
 
            if off != ""
                table.cell(TBL, 0, 11, "⚠ Non-default Config", text_color = cPOC, text_size = size.tiny)
                table.cell(TBL, 1, 11, off + "— 0.8 / 1.2 thresholds may not apply", text_color = cPOC, text_size = size.tiny)
            if math.min(upCov, dnCov) < 0.5
                table.cell(TBL, 0, 12, "⚠ Path Partly Outside", text_color = cPOC, text_size = size.tiny)
                table.cell(TBL, 1, 12, "Verdict uses the covered part only", text_color = cPOC, text_size = size.tiny)
 
        // ── Alerts — create with "Any alert() function call" ───────────────
        string gate = "Long " + longV + " / Short " + shortV
        if barstate.isconfirmed
            if prevGate != "" and gate != prevGate
                alert("🚦 Path verdict changed — " + gate +
                     (na(upTh) ? "" : " (↑" + str.tostring(upTh, "#.##") + "x") +
                     (na(dnTh) ? "" : " / ↓" + str.tostring(dnTh, "#.##") + "x)"),
                     alert.freq_once_per_bar_close)
            prevGate := gate
 
            // Close entered a Reversal Zone (thin bin)
            if array.size(rzP) > 0
                for j = 0 to array.size(rzP) - 1
                    float px = array.get(rzP, j)
                    if math.abs(close - px) <= bs / 2 and math.abs(close[1] - px) > bs / 2
                        alert("🟦 Entered Reversal Zone (RZ) — " + f_fmt(px) + " / price " + f_fmt(close) +
                             ". Thin area, pullbacks are common here.", alert.freq_once_per_bar_close)
 
            // Crossed a Breakthrough Zone — "passed through as expected", not "broke a wall"
            if array.size(tzP) > 0
                for j = 0 to array.size(tzP) - 1
                    float px = array.get(tzP, j)
                    if close > px and close[1] <= px
                        alert("⬆️ Crossed Breakthrough Zone (TZ) upward — " + f_fmt(px), alert.freq_once_per_bar_close)
                    if close < px and close[1] >= px
                        alert("⬇️ Crossed Breakthrough Zone (TZ) downward — " + f_fmt(px), alert.freq_once_per_bar_close)
 
            // Value Area enter / exit
            bool nowIn  = close  >= vaL and close  <= vaH
            bool prevIn = close[1] >= vaL and close[1] <= vaH
            if nowIn and not prevIn
                alert("🟣 Entered Value Area — " + f_fmt(close), alert.freq_once_per_bar_close)
            if prevIn and not nowIn
                alert("⚪ Left Value Area — " + f_fmt(close), alert.freq_once_per_bar_close)

← 返回列表