Esco Pressure Cooker

escobrypto · study · 892 行 · 点赞 6 · TradingView 原页

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

Pine Script

// This Pine Script™ source code is subject to the terms of the Mozilla Public License 2.0
// https://mozilla.org/MPL/2.0/
// © Esco Theory · Brypto
 
//@version=6
indicator("Esco Theory — Pressure Cooker", shorttitle = "ET · PC", overlay = true, max_boxes_count = 100, max_lines_count = 200, max_labels_count = 100)
 
// ════════════════════════════════════════════════════════════════════
// ESCO THEORY — PRESSURE COOKER  · v1.3
// Volatility compression → pressure → expansion → resolution.
// Descriptive instrument. It measures conditions; it does not predict.
//
// ── MEASURES ──
//
//   BASE INDEX (0–100)
//     Weighted mean of three tightness components, each relative to this
//     symbol's own history:
//       S_atr = 100 − percentrank(ATR / close, L)
//       S_bbw = 100 − percentrank(BB width / basis, L)
//       S_sq  = 100 × clamp((1 − q) / (1 − floor)),  q = BB half-width / KC half-width
//     KC half-width = mult × median(true range, N) by default (v1.2).
//
//   TIGHT RUN (bars)
//     Consecutive confirmed bars with BASE INDEX ≥ Enter. Resets on any bar
//     below Enter. Independent of the state machine.
//       S_dur = 100 × min(tight run / Full-Credit Duration, 1)
//
//   COMPOSITE INDEX (0–100)
//     Weighted mean of S_atr, S_bbw, S_sq, S_dur. Drives every state change.
//     A composite tightness index — not a probability and not an exact
//     volatility percentile. Usually crosses Enter a few bars after the
//     base index, because S_dur starts at 0.
//
//   EPISODE BARS / RANGE BARS
//     Episode bars include grace and gate BUILDING.
//     Range bars exclude grace and gate breakout arming.
//
// ── v1.2 · WHY MEDIAN TRUE RANGE FOR KELTNER ──
//   Bollinger width is built from closes; Keltner width from full bar ranges.
//   A single huge-range bar (liquidation wick) inflates a mean/RMA-based
//   Keltner width for 20+ bars while closes stay put, so the bands look
//   "inside" Keltner and squeeze depth reads high with no real coiling.
//   The median ignores isolated outliers but follows any sustained change in
//   range. Synthetic tests (300 runs per scenario, 40 bars after the event):
//     wick shock            v1.1 43% → v1.2 17% of runs could start an episode
//     impulse then coil     v1.1 100% → v1.2 100%  (genuine coils unaffected)
//     no shock (control)    v1.1 62% → v1.2 61%
//   Synthetic data, not BTC — directional evidence, not a calibration.
//   Because true range is right-skewed, median ≤ mean, so squeeze depth reads
//   somewhat lower overall than v1.1. Select "ATR (v1.1)" to compare.
//
// ── BREAKOUT QUALITY (0–100, expansion bar only) ──
//   Displacement beyond the range in ATR[1] ...... 40
//   Directional body-to-range ratio ............... 30  (0 if candle color opposes the break)
//   Relative volume vs the prior N bars ........... 30  (dropped + renormalized when unavailable)
//   Quality grades the candle. It does not predict follow-through.
//
// ── STATES ──
//   IDLE → COMPRESSION → BUILDING → EXPANSION → CONFIRMED | FAILED | EXPIRED
//   COMPRESSION / BUILDING → FIZZLED when grace runs out with no breakout
//   Grace = G: the G confirmed bars after the bar that dropped below Exit.
//   Window = W: the W confirmed bars after the expansion bar.
//     FAILED     any close back inside the frozen range within W
//     CONFIRMED  extension target and/or H consecutive closes outside (H ≤ W)
//     EXPIRED    W elapsed with neither — only reachable with Hold disabled
//
// ── RULES ──
//   • State changes, markers and alerts happen on confirmed bars only.
//   • The breakout candle is never part of its own reference range.
//   • An outcome always needs at least one candle after the expansion bar.
//   • Terminal states are shown for one bar, then the engine returns to IDLE.
// ════════════════════════════════════════════════════════════════════
 
 
// ─────────────────────────────────────────────────────────────
// CONSTANTS
// ─────────────────────────────────────────────────────────────
const int ST_IDLE      = 0
const int ST_COMP      = 1
const int ST_BUILD     = 2
const int ST_EXP       = 3
const int ST_CONFIRMED = 4
const int ST_FAILED    = 5
const int ST_FIZZLED   = 6
const int ST_EXPIRED   = 7
 
// Brypto palette
const color C_BRYPTO = #48B9F5
const color C_ACCENT = #2878D9
const color C_DEEP   = #164B9A
const color C_NAVY   = #0B1424
const color C_WHITE  = #FFFFFF
const color C_WARN   = #F87171
const color C_SLATE  = #64748B
 
const string RM_EPISODE = "Episode"
const string RM_EP_ROLL = "Episode Rolling"
const string RM_ROLL    = "Unrestricted Rolling"
 
const string KC_MEDIAN = "Median True Range"
const string KC_ATR    = "ATR (v1.1)"
 
const string G1 = "1 · Core Model"
const string G2 = "2 · Thresholds"
const string G3 = "3 · Signals"
const string G4 = "4 · Chart Layers"
const string G5 = "5 · Style"
const string G6 = "6 · Dashboard"
const string G7 = "7 · Alerts"
 
 
// ─────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────
 
// 1 · Core Model
lenRank   = input.int(200, "Percentile Lookback", minval = 50, maxval = 2000, group = G1, tooltip = "Bars used to rank ATR and Bollinger width against this symbol's own history. Longer = more stable, slower to adapt to regime change.")
atrLen    = input.int(14, "ATR Length", minval = 2, group = G1)
bbLen     = input.int(20, "Bollinger · Length × Mult", minval = 5, group = G1, inline = "bb")
bbMult    = input.float(2.0, "", minval = 0.5, step = 0.1, group = G1, inline = "bb")
kcLen     = input.int(20, "Keltner · Length × Mult", minval = 5, group = G1, inline = "kc")
kcMult    = input.float(1.5, "", minval = 0.5, step = 0.1, group = G1, inline = "kc")
kcSource  = input.string(KC_MEDIAN, "Keltner Width Source", options = [KC_MEDIAN, KC_ATR], group = G1, tooltip = "Median True Range (default): robust to single outlier bars such as liquidation wicks, which otherwise inflate Keltner width and fake a squeeze.\nATR (v1.1): Wilder ATR, the classic definition.")
sqFloor   = input.float(0.5, "Squeeze Depth Floor", minval = 0.1, maxval = 0.95, step = 0.05, group = G1, tooltip = "BB/KC half-width ratio that earns full squeeze credit. At 1.0 the bands touch (score 0).")
durFull   = input.int(20, "Full-Credit Duration", minval = 2, group = G1, tooltip = "Tight-run length (consecutive bars with base index ≥ Enter) at which the duration component reaches 100.")
wAtr      = input.float(30, "Weights · ATR / BB Width", minval = 0, step = 5, group = G1, inline = "w1")
wBbw      = input.float(30, "", minval = 0, step = 5, group = G1, inline = "w1")
wSq       = input.float(25, "Weights · Squeeze / Duration", minval = 0, step = 5, group = G1, inline = "w2")
wDur      = input.float(15, "", minval = 0, step = 5, group = G1, inline = "w2", tooltip = "Weights are relative; they do not need to sum to 100. ATR + BB Width + Squeeze must be above 0.")
smoothLen = input.int(1, "Index Smoothing (EMA)", minval = 1, maxval = 10, group = G1, tooltip = "1 = off. Any smoothing adds lag to every state change.")
 
// 2 · Thresholds
tEnterIn     = input.int(60, "Enter / Exit / Building", minval = 1, maxval = 99, group = G2, inline = "t")
tExitIn      = input.int(50, "", minval = 0, maxval = 98, group = G2, inline = "t")
tBuildIn     = input.int(75, "", minval = 1, maxval = 100, group = G2, inline = "t", tooltip = "Exit must be below Enter and Building at least Enter. Invalid values are corrected and flagged on the dashboard.")
minRangeBars = input.int(5, "Min Range Bars Before Breakout", minval = 1, group = G2, tooltip = "Breakouts are armed only after this many bars have built the reference range. Grace bars do not count.")
minBuildBars = input.int(5, "Min Episode Bars for Building", minval = 1, group = G2)
graceBars    = input.int(5, "Grace Window", minval = 0, maxval = 50, group = G2, tooltip = "Bars after the index drops below Exit during which a breakout is still accepted. The range is frozen during grace. 0 = an episode ends on the bar it drops below Exit.")
confirmBars  = input.int(3, "Confirmation Window", minval = 1, maxval = 20, group = G2, tooltip = "Bars after the expansion bar within which the breakout must resolve.")
 
// 3 · Signals
rangeMode   = input.string(RM_EPISODE, "Range Mode", options = [RM_EPISODE, RM_EP_ROLL, RM_ROLL], group = G3, tooltip = "Episode: high/low of every range bar in the episode.\nEpisode Rolling: high/low of the last N range bars, never reaching before the episode started.\nUnrestricted Rolling: high/low of the previous N bars regardless of episode start or grace — a plain Donchian reference.")
rollLen     = input.int(20, "Rolling Length", minval = 3, maxval = 500, group = G3)
useMaxWidth = input.bool(false, "Max Range Width (ATR)", group = G3, inline = "mw")
maxWidthAtr = input.float(4.0, "", minval = 0.5, step = 0.25, group = G3, inline = "mw", tooltip = "When on, breakouts are not armed while the reference range is wider than this many ATR[1].")
minDisp     = input.float(0.25, "Min Displacement (ATR)", minval = 0.0, step = 0.05, group = G3, tooltip = "How far beyond the range the expansion close must be, in previous-bar ATR.")
useExtConf  = input.bool(true, "Confirm by Extension (ATR)", group = G3, inline = "ext")
extAtr      = input.float(0.5, "", minval = 0.0, step = 0.05, group = G3, inline = "ext", tooltip = "Confirms when a later close reaches this many ATR beyond the range level. ATR is frozen at the expansion bar.")
useHoldConf = input.bool(true, "Confirm by Hold (closes)", group = G3, inline = "hold")
holdBarsIn  = input.int(3, "", minval = 1, maxval = 20, group = G3, inline = "hold", tooltip = "Confirms after this many consecutive closes outside the frozen range. Capped at the confirmation window. With Hold on, EXPIRED cannot occur.")
minQuality  = input.int(0, "Min Breakout Quality", minval = 0, maxval = 100, group = G3, tooltip = "0 = off. Expansions below this quality are ignored.")
dispFull    = input.float(1.5, "Quality · Full Displacement (ATR)", minval = 0.1, step = 0.1, group = G3)
bodyLo      = input.float(0.30, "Quality · Body Ratio (low → high)", minval = 0.0, maxval = 1.0, step = 0.05, group = G3, inline = "body")
bodyHi      = input.float(0.80, "", minval = 0.0, maxval = 1.0, step = 0.05, group = G3, inline = "body")
rvolLen     = input.int(20, "Quality · RVOL Length", minval = 2, group = G3)
rvolLo      = input.float(1.0, "Quality · RVOL (low → high)", minval = 0.0, step = 0.1, group = G3, inline = "rv")
rvolHi      = input.float(2.5, "", minval = 0.1, step = 0.1, group = G3, inline = "rv")
wDisp       = input.float(40, "Weights · Displacement / Body", minval = 0, step = 5, group = G3, inline = "q1")
wBody       = input.float(30, "", minval = 0, step = 5, group = G3, inline = "q1")
wVol        = input.float(30, "Weight · Volume", minval = 0, step = 5, group = G3)
 
// 4 · Chart Layers — what is drawn. Every layer toggles independently.
showBB      = input.bool(true, "Bollinger Bands", group = G4, tooltip = "Drawn from the exact basis and deviation the compression index uses.")
showBasis   = input.bool(false, "Basis", group = G4, tooltip = "The shared mid-line of both envelopes (SMA of close). The squeeze calculation compares widths around this one center, so Bollinger and Keltner share it.")
showKC      = input.bool(false, "Keltner Channels", group = G4, tooltip = "Drawn from the exact Keltner width the squeeze-depth score uses (source set in Core Model). Bands inside the channel on the chart ⇔ squeeze ratio q < 1 in the math.")
showFill    = input.bool(true, "Compression Fill", group = G4, tooltip = "Transparent fill between the Bollinger Bands, only while an episode is in COMPRESSION or BUILDING.")
showBoxes   = input.bool(true, "Compression Boxes · Keep", group = G4, inline = "bx")
maxBoxes    = input.int(40, "", minval = 1, maxval = 90, group = G4, inline = "bx", tooltip = "Most recent episodes kept on the chart. Older boxes and range lines are deleted first.")
showLines   = input.bool(false, "Range High / Low · Style", group = G4, inline = "ln")
lineStyleIn = input.string("Dotted", "", options = ["Dotted", "Dashed", "Solid"], group = G4, inline = "ln")
showExpMk   = input.bool(true, "Expansion Markers", group = G4)
showQLabels = input.bool(false, "Quality Labels", group = G4, tooltip = "Adds the breakout quality score next to each expansion.")
showConfMk  = input.bool(false, "Confirmation Markers", group = G4)
showFailMk  = input.bool(false, "Failure Markers", group = G4)
colorBars   = input.bool(false, "Color Compression Candles", group = G4)
showDash    = input.bool(true, "Dashboard", group = G4, tooltip = "Configuration warnings still appear in a compact panel when the dashboard is hidden.")
 
// 5 · Style — colors and transparency
cBand       = input.color(C_BRYPTO, "Bollinger · Transparency", group = G5, inline = "bnd")
bandT       = input.int(25, "", minval = 0, maxval = 95, group = G5, inline = "bnd")
cKC         = input.color(C_DEEP, "Keltner · Transparency", group = G5, inline = "kcs")
kcT         = input.int(40, "", minval = 0, maxval = 95, group = G5, inline = "kcs", tooltip = "Keltner draws more transparent than Bollinger by default so the bands stay the primary line.")
basisT      = input.int(60, "Basis Transparency", minval = 0, maxval = 95, group = G5)
cFill       = input.color(C_BRYPTO, "Compression Fill · Transparency", group = G5, inline = "cf")
fillT       = input.int(92, "", minval = 80, maxval = 99, group = G5, inline = "cf")
cBox        = input.color(C_BRYPTO, "Box Fill · Transparency", group = G5, inline = "zf")
boxFillT    = input.int(93, "", minval = 70, maxval = 99, group = G5, inline = "zf")
cBorder     = input.color(C_BRYPTO, "Box Border · Transparency", group = G5, inline = "zb")
borderT     = input.int(45, "", minval = 0, maxval = 95, group = G5, inline = "zb")
cBuild      = input.color(C_BRYPTO, "Building Border", group = G5, tooltip = "Border color once pressure is building. Drawn more opaque than the compression border.")
projBars    = input.int(10, "Project Active Levels (bars)", minval = 0, maxval = 100, group = G5, tooltip = "How far the active range lines extend past the current bar. Lines stop at the resolution bar once an episode ends.")
cBars       = input.color(C_ACCENT, "Compression Candles", group = G5)
cAccent     = input.color(C_BRYPTO, "Brand Accent", group = G5)
cBull       = input.color(C_BRYPTO, "Bullish / Bearish", group = G5, inline = "dir")
cBear       = input.color(C_WARN, "", group = G5, inline = "dir")
cNeutral    = input.color(C_SLATE, "Failed / Fizzled / Expired", group = G5)
 
// 6 · Dashboard
showDiag  = input.bool(false, "Diagnostic Mode", group = G6, tooltip = "Adds a components section: each input's raw reading and how many points it contributes to the composite. The points sum to the unsmoothed composite.")
dashPos   = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = G6)
dashTheme = input.string("Auto", "Theme", options = ["Auto", "Dark", "Light"], group = G6, tooltip = "Auto reads the chart background.")
dashSize  = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = G6)
 
// 7 · Alerts
aComp   = input.bool(false, "Compression Started", group = G7)
aBuild  = input.bool(true, "Pressure Building", group = G7)
aExp    = input.bool(true, "Bull / Bear Expansion", group = G7)
aConf   = input.bool(true, "Breakout Confirmed", group = G7)
aFail   = input.bool(true, "Breakout Failed", group = G7)
aExpire = input.bool(false, "Expansion Expired", group = G7)
aFizz   = input.bool(false, "Compression Fizzled", group = G7, tooltip = "All enabled events on a bar are combined into a single alert message, so none are dropped. Create one TradingView alert on 'Any alert() function call'.")
 
 
// ─────────────────────────────────────────────────────────────
// INPUT VALIDATION — effective values + warnings
// ─────────────────────────────────────────────────────────────
tEnter   = tEnterIn
tExit    = math.min(tExitIn, tEnterIn - 1)
tBuild   = math.max(tBuildIn, tEnterIn)
holdBars = math.min(holdBarsIn, confirmBars)
 
wBase = wAtr + wBbw + wSq
wAll  = wBase + wDur
 
bool bodyOk       = bodyLo < bodyHi
bool rvolOk       = wVol == 0 or rvolLo < rvolHi
bool qualityCfgOk = bodyOk and rvolOk and (wDisp + wBody) > 0
 
f_warn(string acc, bool cond, string msg) =>
    cond ? (acc == "" ? msg : acc + "\n" + msg) : acc
 
string cfgWarn = ""
cfgWarn := f_warn(cfgWarn, wBase == 0, "Weights ATR + BB Width + Squeeze = 0 · index unavailable")
cfgWarn := f_warn(cfgWarn, wDisp + wBody + wVol == 0, "All quality weights = 0 · quality unavailable")
cfgWarn := f_warn(cfgWarn, wDisp + wBody == 0 and wVol > 0, "Displacement + Body = 0 · quality would be volume-only · quality disabled")
cfgWarn := f_warn(cfgWarn, not bodyOk, "Body ratio range inverted · quality unavailable")
cfgWarn := f_warn(cfgWarn, not rvolOk, "RVOL range inverted · quality unavailable")
cfgWarn := f_warn(cfgWarn, not qualityCfgOk and minQuality > 0, "Min Quality is set but quality is unavailable · no expansions will fire")
cfgWarn := f_warn(cfgWarn, tExitIn >= tEnterIn, "Exit ≥ Enter · Exit set to " + str.tostring(tExit))
cfgWarn := f_warn(cfgWarn, tBuildIn < tEnterIn, "Building < Enter · Building set to " + str.tostring(tBuild))
cfgWarn := f_warn(cfgWarn, useHoldConf and holdBarsIn > confirmBars, "Hold closes > window · Hold capped at " + str.tostring(holdBars))
cfgWarn := f_warn(cfgWarn, not useExtConf and not useHoldConf, "No confirmation method · breakouts can only fail or expire")
 
 
// ─────────────────────────────────────────────────────────────
// PURE HELPERS
// ─────────────────────────────────────────────────────────────
f_safeDiv(float a, float b) =>
    na(a) or na(b) or b == 0 ? na : a / b
 
// Linear map to 0–1, clamped. na on bad input or inverted bounds.
f_map01(float x, float lo, float hi) =>
    float r = na
    if not na(x) and hi > lo
        r := math.max(0.0, math.min(1.0, (x - lo) / (hi - lo)))
    r
 
// Breakout quality. Volume drops out (weights renormalize) only when the
// symbol has no volume or the prior-N baseline is 0. Inverted thresholds
// make quality unavailable rather than silently changing its composition.
f_quality(float dispAtr, float dirBody, float rv, bool volAvailable) =>
    float q = na
    if qualityCfgOk
        bool  volIn = volAvailable and wVol > 0 and not na(rv)
        float tw    = wDisp + wBody + (volIn ? wVol : 0.0)
        float qD    = f_map01(dispAtr, 0.0, dispFull)
        float qB    = f_map01(dirBody, bodyLo, bodyHi)
        float qV    = volIn ? f_map01(rv, rvolLo, rvolHi) : 0.0
        if tw > 0 and not na(qD) and not na(qB) and not na(qV)
            q := 100.0 * (wDisp * qD + wBody * qB + (volIn ? wVol * qV : 0.0)) / tw
    q
 
f_grade(float q) =>
    na(q) ? "—" : q >= 70 ? "Strong" : q >= 40 ? "Moderate" : "Weak"
 
f_bar(float v) =>
    int n = int(math.max(0, math.min(10, math.round(v / 10.0))))
    str.repeat("▰", n) + str.repeat("▱", 10 - n)
 
f_fmt(float v, string f) =>
    na(v) ? "—" : str.tostring(v, f)
 
f_pos(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
f_sizeUp(string s) =>
    switch s
        "Tiny"   => size.small
        "Normal" => size.large
        => size.normal
 
f_lineStyle(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Solid"  => line.style_solid
        => line.style_dotted
 
f_stateName(int s) =>
    switch s
        ST_COMP      => "COMPRESSION"
        ST_BUILD     => "BUILDING"
        ST_EXP       => "EXPANSION"
        ST_CONFIRMED => "CONFIRMED"
        ST_FAILED    => "FAILED"
        ST_FIZZLED   => "FIZZLED"
        ST_EXPIRED   => "EXPIRED"
        => "IDLE"
 
f_stateColor(int s, int dir, color muted) =>
    switch s
        ST_COMP      => cBorder
        ST_BUILD     => cBuild
        ST_EXP       => dir == 1 ? cBull : cBear
        ST_CONFIRMED => dir == 1 ? cBull : cBear
        ST_FAILED    => cNeutral
        ST_FIZZLED   => cNeutral
        ST_EXPIRED   => cNeutral
        => muted
 
 
// ─────────────────────────────────────────────────────────────
// CALCULATIONS · INDEX  (all ta.* calls at global scope, every bar)
// ─────────────────────────────────────────────────────────────
atr     = ta.atr(atrLen)
atrPrev = atr[1]
 
// A · Normalized ATR percentile (ATR / close removes price-level drift)
natr    = f_safeDiv(atr, close)
atrPctl = ta.percentrank(natr, lenRank)
sAtr    = 100.0 - atrPctl
 
// B · Bollinger width percentile
basis   = ta.sma(close, bbLen)
dev     = ta.stdev(close, bbLen)
bbw     = f_safeDiv(2.0 * bbMult * dev, basis)
bbwPctl = ta.percentrank(bbw, lenRank)
sBbw    = 100.0 - bbwPctl
 
// C · Continuous squeeze depth. Keltner width from median true range (v1.2)
//     or Wilder ATR (v1.1). Both are computed every bar for series consistency.
trMedian = ta.median(ta.tr(true), kcLen)
trAtr    = ta.atr(kcLen)
kcBase   = kcSource == KC_MEDIAN ? trMedian : trAtr
sqRatio  = f_safeDiv(bbMult * dev, kcMult * kcBase)
sSq      = 100.0 * f_map01(1.0 - sqRatio, 0.0, 1.0 - sqFloor)
 
// Base index (A–C)
float baseIdx = wBase > 0 ? (wAtr * sAtr + wBbw * sBbw + wSq * sSq) / wBase : na
 
// D · Tight run → duration component. Counted from the BASE index (never the
// composite) so duration cannot feed back into its own qualification.
var int tightRun = 0
tightRun := not na(baseIdx) and baseIdx >= tEnter ? tightRun + 1 : 0
sDur = 100.0 * math.min(float(tightRun) / float(durFull), 1.0)
 
// Composite index
float rawScore = wBase > 0 and wAll > 0 ? (wAtr * sAtr + wBbw * sBbw + wSq * sSq + wDur * sDur) / wAll : na
scoreEma = ta.ema(rawScore, smoothLen)
float score = smoothLen > 1 ? scoreEma : rawScore
 
// Last-closed-bar views for the dashboard (realtime ticks show the prior close)
bool  cf          = barstate.isconfirmed
float scoreClosed = cf ? score : score[1]
float rawClosed   = cf ? rawScore : rawScore[1]
float atrPctlC    = cf ? atrPctl : atrPctl[1]
float bbwPctlC    = cf ? bbwPctl : bbwPctl[1]
float sqRatioC    = cf ? sqRatio : sqRatio[1]
float sAtrC       = cf ? sAtr : sAtr[1]
float sBbwC       = cf ? sBbw : sBbw[1]
float sSqC        = cf ? sSq : sSq[1]
float sDurC       = cf ? sDur : sDur[1]
int   tightRunC   = cf ? tightRun : tightRun[1]
 
 
// ─────────────────────────────────────────────────────────────
// CALCULATIONS · BREAKOUT INPUTS
// ─────────────────────────────────────────────────────────────
barRange  = high - low
bodyRatio = barRange > 0 ? math.abs(close - open) / barRange : 0.0
 
volAvail = ta.cum(nz(volume)) > 0
volBase  = ta.sma(nz(volume), rvolLen)[1]           // excludes the current bar
rvol     = f_safeDiv(nz(volume), volBase)
 
// Unrestricted rolling reference
rollHi     = ta.highest(high, rollLen)[1]             // prior N bars — used for breakout tests
rollLo     = ta.lowest(low, rollLen)[1]
rollHiNext = ta.highest(high, rollLen)                // includes current bar — level the NEXT bar must clear
rollLoNext = ta.lowest(low, rollLen)
 
warmBars = lenRank + math.max(math.max(bbLen, kcLen), math.max(math.max(atrLen, rollLen), rvolLen)) + 1
isReady  = bar_index >= warmBars and not na(score) and not na(atrPrev) and atrPrev > 0
 
 
// ─────────────────────────────────────────────────────────────
// STATE
// ─────────────────────────────────────────────────────────────
var int   state      = ST_IDLE
var int   epStart    = na
var float epHi       = na          // Episode-mode reference (all range bars)
var float epLo       = na
var float epPeak     = na
var int   epBars     = 0           // episode length (incl. grace, excl. expansion bar)
var int   rangeBars  = 0           // bars that built the range (excl. grace)
var bool  inGrace    = false
var int   graceLeft  = 0
var bool  buildFired = false
 
var array<float> rollHis = array.new<float>()   // Episode Rolling window (range bars only)
var array<float> rollLos = array.new<float>()
 
var int   expDir     = 0
var float expRefHi   = na
var float expRefLo   = na
var float expAtr     = na
var float expQuality = na
var int   expAge     = 0
var int   holdCount  = 0
 
var int    lastDir     = 0
var float  lastQuality = na
var int    lastOutcome = ST_IDLE
var string lastVia     = ""
 
var box          curBox    = na
var line         curHiLine = na
var line         curLoLine = na
var array<box>   boxPool   = array.new<box>()
var array<line>  linePool  = array.new<line>()
var array<label> labelPool = array.new<label>()
 
// Per-bar events (reset every bar)
bool evCompStart = false
bool evBuild     = false
bool evBullExp   = false
bool evBearExp   = false
bool evConfirm   = false
bool evFail      = false
bool evFizzle    = false
bool evExpire    = false
int  evDir       = 0
 
 
// ─────────────────────────────────────────────────────────────
// RANGE + DRAWING HELPERS
// ─────────────────────────────────────────────────────────────
 
// Reference range as of the PRIOR confirmed bar. Called before the current
// bar is added, so the current candle is never part of its own reference.
f_refHi() =>
    rangeMode == RM_ROLL ? rollHi : rangeMode == RM_EP_ROLL ? (array.size(rollHis) > 0 ? array.max(rollHis) : na) : epHi
 
f_refLo() =>
    rangeMode == RM_ROLL ? rollLo : rangeMode == RM_EP_ROLL ? (array.size(rollLos) > 0 ? array.min(rollLos) : na) : epLo
 
// Level the NEXT bar must clear — used for drawing edges after this bar is processed
f_nextHi() =>
    rangeMode == RM_ROLL ? rollHiNext : f_refHi()
 
f_nextLo() =>
    rangeMode == RM_ROLL ? rollLoNext : f_refLo()
 
f_pushRoll(float h, float l) =>
    array.push(rollHis, h)
    array.push(rollLos, l)
    if array.size(rollHis) > rollLen
        array.shift(rollHis)
        array.shift(rollLos)
 
f_pushBox(box b) =>
    array.push(boxPool, b)
    if array.size(boxPool) > maxBoxes
        box.delete(array.shift(boxPool))
 
f_pushLine(line l) =>
    array.push(linePool, l)
    if array.size(linePool) > maxBoxes * 2
        line.delete(array.shift(linePool))
 
f_pushLabel(label l) =>
    array.push(labelPool, l)
    if array.size(labelPool) > maxBoxes
        label.delete(array.shift(labelPool))
 
// Active zone: transparent Brypto fill, thin Brypto border. Building draws the
// border more opaque and the fill one step denser — same object, no extra drawing.
f_styleActive(box b, line lh, line ll, bool building) =>
    color bdr = building ? color.new(cBuild, math.max(borderT - 30, 0)) : color.new(cBorder, borderT)
    if not na(b)
        box.set_bgcolor(b, color.new(cBox, building ? math.max(boxFillT - 3, 0) : boxFillT))
        box.set_border_color(b, bdr)
        box.set_border_style(b, line.style_solid)
    if not na(lh)
        line.set_color(lh, bdr)
    if not na(ll)
        line.set_color(ll, bdr)
 
// Resolved zone: confirmed keeps a directional tint; failed / fizzled / expired
// fade to slate with a dashed border.
f_resolve(box b, line lh, line ll, int outcome, int dir) =>
    bool  ok  = outcome == ST_CONFIRMED
    color c   = ok ? (dir == 1 ? cBull : cBear) : cNeutral
    color bdr = color.new(c, ok ? 45 : 50)
    if not na(b)
        box.set_bgcolor(b, color.new(c, math.min(boxFillT + (ok ? 1 : 3), 99)))
        box.set_border_color(b, bdr)
        box.set_border_style(b, ok ? line.style_solid : line.style_dashed)
    if not na(lh)
        line.set_color(lh, bdr)
        line.set_x2(lh, bar_index)
    if not na(ll)
        line.set_color(ll, bdr)
        line.set_x2(ll, bar_index)
 
f_moveLines(line lh, line ll, float hi, float lo, int x2) =>
    if not na(lh)
        line.set_y1(lh, hi)
        line.set_y2(lh, hi)
        line.set_x2(lh, x2)
    if not na(ll)
        line.set_y1(ll, lo)
        line.set_y2(ll, lo)
        line.set_x2(ll, x2)
 
 
// ─────────────────────────────────────────────────────────────
// STATE MACHINE — confirmed bars only  (logic unchanged from v1.1)
// ─────────────────────────────────────────────────────────────
if barstate.isconfirmed and isReady
 
    // Terminal states are visible for exactly one bar
    if state >= ST_CONFIRMED
        state := ST_IDLE
 
    float refHi = f_refHi()
    float refLo = f_refLo()
 
    // ── IDLE → COMPRESSION ──
    if state == ST_IDLE
        if score >= tEnter
            state       := ST_COMP
            epStart     := bar_index
            epHi        := high
            epLo        := low
            epPeak      := score
            epBars      := 1
            rangeBars   := 1
            inGrace     := false
            graceLeft   := 0
            buildFired  := false
            evCompStart := true
            array.clear(rollHis)
            array.clear(rollLos)
            f_pushRoll(high, low)
 
            curBox    := na
            curHiLine := na
            curLoLine := na
            if showBoxes
                curBox := box.new(bar_index, f_nextHi(), bar_index, f_nextLo(), border_width = 1)
                f_pushBox(curBox)
            if showLines
                lst = f_lineStyle(lineStyleIn)
                curHiLine := line.new(bar_index, f_nextHi(), bar_index + projBars, f_nextHi(), width = 1, style = lst)
                curLoLine := line.new(bar_index, f_nextLo(), bar_index + projBars, f_nextLo(), width = 1, style = lst)
                f_pushLine(curHiLine)
                f_pushLine(curLoLine)
            f_styleActive(curBox, curHiLine, curLoLine, false)
 
    // ── COMPRESSION / BUILDING ──
    else if state == ST_COMP or state == ST_BUILD
        float rangeW  = refHi - refLo
        bool  refOk   = not na(refHi) and not na(refLo)
        bool  widthOk = not useMaxWidth or (refOk and rangeW <= maxWidthAtr * atrPrev)
        bool  armed   = refOk and rangeBars >= minRangeBars and widthOk
 
        float upDisp = refOk ? (close - refHi) / atrPrev : na
        float dnDisp = refOk ? (refLo - close) / atrPrev : na
        float qBull  = f_quality(upDisp, close > open ? bodyRatio : 0.0, rvol, volAvail)
        float qBear  = f_quality(dnDisp, close < open ? bodyRatio : 0.0, rvol, volAvail)
 
        bool bullBrk = armed and close > refHi and upDisp >= minDisp
        bool bearBrk = armed and close < refLo and dnDisp >= minDisp
        if minQuality > 0
            bullBrk := bullBrk and not na(qBull) and qBull >= minQuality
            bearBrk := bearBrk and not na(qBear) and qBear >= minQuality
 
        if bullBrk or bearBrk
            // → EXPANSION. Reference range frozen as of the prior bar.
            expDir      := bullBrk ? 1 : -1
            expRefHi    := refHi
            expRefLo    := refLo
            expAtr      := atrPrev
            expQuality  := bullBrk ? qBull : qBear
            expAge      := 0
            holdCount   := 0
            state       := ST_EXP
            lastDir     := expDir
            lastQuality := expQuality
            lastOutcome := ST_EXP
            lastVia     := ""
            evDir       := expDir
            evBullExp   := bullBrk
            evBearExp   := bearBrk
            if not na(curBox)
                box.set_right(curBox, bar_index)
                box.set_top(curBox, refHi)
                box.set_bottom(curBox, refLo)
            f_moveLines(curHiLine, curLoLine, refHi, refLo, bar_index + projBars)
            if showQLabels
                string qTxt = (bullBrk ? "▲ " : "▼ ") + f_fmt(expQuality, "#")
                f_pushLabel(label.new(bar_index, close, qTxt, yloc = bullBrk ? yloc.belowbar : yloc.abovebar, style = bullBrk ? label.style_label_up : label.style_label_down, color = color.new(C_NAVY, 100), textcolor = bullBrk ? cBull : cBear, size = size.tiny))
        else
            epBars += 1
 
            // Grace: entered on the bar the index drops below Exit; that bar and
            // every grace bar are excluded from the range. Recovering to Enter
            // ends grace and the recovery bar rejoins the range.
            if inGrace
                if score >= tEnter
                    inGrace := false
                else
                    graceLeft -= 1
            else if score < tExit
                inGrace   := true
                graceLeft := graceBars
 
            if not inGrace
                epHi      := math.max(epHi, high)
                epLo      := math.min(epLo, low)
                epPeak    := math.max(epPeak, score)
                rangeBars += 1
                f_pushRoll(high, low)
 
            if inGrace and graceLeft <= 0
                state    := ST_FIZZLED
                evFizzle := true
            else if state == ST_COMP and not inGrace and score >= tBuild and epBars >= minBuildBars
                state := ST_BUILD
                if not buildFired
                    evBuild    := true
                    buildFired := true
            else if state == ST_BUILD and (inGrace or score < tEnter)
                state := ST_COMP
 
            if not na(curBox)
                box.set_right(curBox, bar_index)
                box.set_top(curBox, f_nextHi())
                box.set_bottom(curBox, f_nextLo())
            f_moveLines(curHiLine, curLoLine, f_nextHi(), f_nextLo(), bar_index + projBars)
            if state == ST_FIZZLED
                f_resolve(curBox, curHiLine, curLoLine, ST_FIZZLED, 0)
            else
                f_styleActive(curBox, curHiLine, curLoLine, state == ST_BUILD)
 
    // ── EXPANSION → CONFIRMED / FAILED / EXPIRED ──
    else if state == ST_EXP
        expAge += 1
        bool backInside = expDir == 1 ? close <= expRefHi : close >= expRefLo
        if not backInside
            holdCount += 1
        bool extended = useExtConf and (expDir == 1 ? close >= expRefHi + extAtr * expAtr : close <= expRefLo - extAtr * expAtr)
        bool held     = useHoldConf and holdCount >= holdBars
 
        if backInside
            state  := ST_FAILED
            evFail := true
        else if extended or held
            state     := ST_CONFIRMED
            evConfirm := true
            lastVia   := extended and held ? "ext + hold" : extended ? "extension" : "hold"
        else if expAge >= confirmBars
            state    := ST_EXPIRED
            evExpire := true
 
        if not na(curBox)
            box.set_right(curBox, bar_index)
 
        if state == ST_EXP
            // Frozen levels stay projected while the breakout is being tested
            f_moveLines(curHiLine, curLoLine, expRefHi, expRefLo, bar_index + projBars)
        else
            lastOutcome := state
            evDir       := expDir
            f_resolve(curBox, curHiLine, curLoLine, state, expDir)
 
 
// ─────────────────────────────────────────────────────────────
// DEVELOPING READ — live bar only. Never plotted, never alerted.
// ─────────────────────────────────────────────────────────────
bool  liveBar  = barstate.isrealtime and not barstate.isconfirmed
bool  liveComp = state == ST_COMP or state == ST_BUILD
float liveHi   = f_refHi()
float liveLo   = f_refLo()
bool  liveArm  = liveComp and rangeBars >= minRangeBars and not na(liveHi) and not na(liveLo)
bool  devBull  = liveBar and liveArm and close > liveHi
bool  devBear  = liveBar and liveArm and close < liveLo
 
 
// ─────────────────────────────────────────────────────────────
// VISUALS
// ─────────────────────────────────────────────────────────────
 
// Envelopes — the same series the index is computed from, never a parallel
// calculation. Bollinger and Keltner share one center, so on the chart the
// bands sit inside the channel exactly when the squeeze ratio q < 1.
bbUpper = basis + bbMult * dev
bbLower = basis - bbMult * dev
kcUpper = basis + kcMult * kcBase
kcLower = basis - kcMult * kcBase
 
pBbU = plot(bbUpper, "Bollinger Upper", color = showBB ? color.new(cBand, bandT) : na, linewidth = 1, editable = false)
pBbL = plot(bbLower, "Bollinger Lower", color = showBB ? color.new(cBand, bandT) : na, linewidth = 1, editable = false)
plot(basis, "Basis", color = showBasis ? color.new(cBand, basisT) : na, linewidth = 1, editable = false)
plot(kcUpper, "Keltner Upper", color = showKC ? color.new(cKC, kcT) : na, linewidth = 1, editable = false)
plot(kcLower, "Keltner Lower", color = showKC ? color.new(cKC, kcT) : na, linewidth = 1, editable = false)
 
// Compression fill — active episodes only. Uses the state as of the last
// confirmed bar, so it never paints on an unconfirmed reading.
bool fillOn = showFill and (state == ST_COMP or state == ST_BUILD)
fill(pBbU, pBbL, color = fillOn ? color.new(cFill, state == ST_BUILD ? math.max(fillT - 2, 0) : fillT) : na, title = "Compression Fill", editable = false)
 
plotshape(showExpMk and evBullExp, "Bull Expansion", shape.triangleup, location.belowbar, cBull, size = size.tiny)
plotshape(showExpMk and evBearExp, "Bear Expansion", shape.triangledown, location.abovebar, cBear, size = size.tiny)
plotshape(showConfMk and evConfirm and evDir == 1, "Bull Confirmed", shape.circle, location.belowbar, cBull, size = size.tiny)
plotshape(showConfMk and evConfirm and evDir == -1, "Bear Confirmed", shape.circle, location.abovebar, cBear, size = size.tiny)
plotshape(showFailMk and evFail and evDir == 1, "Bull Failed", shape.xcross, location.abovebar, cNeutral, size = size.tiny)
plotshape(showFailMk and evFail and evDir == -1, "Bear Failed", shape.xcross, location.belowbar, cNeutral, size = size.tiny)
 
barcolor(colorBars and liveComp ? cBars : na, title = "Compression Candles")
 
// Data Window — every measure, bar by bar, with no chart clutter.
// Contribution plots sum to the unsmoothed composite.
plot(score, "Composite Index", color = cAccent, display = display.data_window)
plot(baseIdx, "Base Index (A–C)", display = display.data_window)
plot(tightRun, "Tight Run (bars)", display = display.data_window)
plot(atrPctl, "ATR Percentile", display = display.data_window)
plot(bbwPctl, "BB Width Percentile", display = display.data_window)
plot(sqRatio, "Squeeze Ratio q (BB/KC)", display = display.data_window)
plot(wAll > 0 ? wAtr * sAtr / wAll : na, "Pts · ATR", display = display.data_window)
plot(wAll > 0 ? wBbw * sBbw / wAll : na, "Pts · BB Width", display = display.data_window)
plot(wAll > 0 ? wSq * sSq / wAll : na, "Pts · Squeeze", display = display.data_window)
plot(wAll > 0 ? wDur * sDur / wAll : na, "Pts · Duration", display = display.data_window)
plot(liveComp ? epBars : na, "Episode Bars", display = display.data_window)
plot(liveComp ? rangeBars : na, "Range Bars", display = display.data_window)
plot(state, "Phase (0–7)", display = display.data_window)
 
 
// ─────────────────────────────────────────────────────────────
// DASHBOARD
// Three columns: label · detail · value. Hierarchy comes from weight and
// opacity only — title and Index/Phase are bold, details are regular,
// developing data is italic and muted.
// ─────────────────────────────────────────────────────────────
var table dash = table.new(f_pos(dashPos), 3, 19, border_width = 0)
 
f_row(table t, int r, string k, string d, string v, color kc, color dc, color vc, string ts, string vs, bool bold, bool ital, string tip) =>
    fmt = bold ? text.format_bold : ital ? text.format_italic : text.format_none
    table.cell(t, 0, r, k, text_color = kc, text_size = ts, text_halign = text.align_left, tooltip = tip)
    table.cell(t, 1, r, d, text_color = dc, text_size = ts, text_halign = text.align_right)
    table.cell(t, 2, r, v, text_color = vc, text_size = vs, text_halign = text.align_right, text_formatting = fmt)
 
f_gap(table t, int r) =>
    table.cell(t, 0, r, "", text_size = size.tiny)
    table.cell(t, 1, r, "", text_size = size.tiny)
    table.cell(t, 2, r, "", text_size = size.tiny)
 
if barstate.islast and (showDash or cfgWarn != "")
    float lum      = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
    bool  useLight = dashTheme == "Light" or (dashTheme == "Auto" and lum > 140)
    color bg       = useLight ? color.new(C_WHITE, 4) : color.new(C_NAVY, 6)
    color txt      = useLight ? C_NAVY : C_WHITE
    color sub      = color.new(txt, 25)
    color muted    = color.new(txt, 55)
    color accent   = useLight ? C_ACCENT : cAccent
    ts             = f_size(dashSize)
    tsUp           = f_sizeUp(dashSize)
 
    table.set_bgcolor(dash, bg)
    table.set_frame_color(dash, color.new(accent, 75))
    table.set_frame_width(dash, 1)
 
    // Title
    table.cell(dash, 0, 0, "PRESSURE COOKER", text_color = accent, text_size = ts, text_halign = text.align_left, text_formatting = text.format_bold)
    table.cell(dash, 1, 0, "", text_size = ts)
    table.cell(dash, 2, 0, "ESCO THEORY", text_color = muted, text_size = size.tiny, text_halign = text.align_right)
 
    if showDash
        // ── Primary: Index + Phase ──
        bool   idxOk = isReady and not na(scoreClosed)
        f_row(dash, 1, "Index", idxOk ? f_bar(scoreClosed) : "warming up", idxOk ? str.tostring(scoreClosed, "#") : "—", muted, color.new(accent, 35), accent, ts, tsUp, true, false, "Composite compression index on the last closed bar (0–100). Drives every state change. Not a probability.")
 
        int phaseDir = state == ST_EXP ? expDir : lastDir
        f_row(dash, 2, "Phase", "", f_stateName(state), muted, muted, f_stateColor(state, phaseDir, muted), ts, ts, true, false, "State as of the last closed bar.")
 
        f_gap(dash, 3)
 
        // ── Episode detail ──
        string epD = ""
        string epV = "—"
        if liveComp
            epD := "run " + str.tostring(tightRunC) + (inGrace ? " · grace " + str.tostring(graceLeft) : "")
            epV := str.tostring(epBars) + " bars"
        else if state == ST_EXP
            epD := useHoldConf ? "held " + str.tostring(holdCount) + "/" + str.tostring(holdBars) : ""
            epV := "bar " + str.tostring(expAge) + "/" + str.tostring(confirmBars)
        f_row(dash, 4, "Episode", epD, epV, muted, muted, sub, ts, ts, false, false, "Episode length incl. grace. Run = consecutive bars with base index ≥ Enter (feeds duration). During expansion: bars into the confirmation window and closes held outside the range.")
 
        float  dHi     = state == ST_EXP ? expRefHi : liveHi
        float  dLo     = state == ST_EXP ? expRefLo : liveLo
        float  wInAtr  = f_safeDiv(dHi - dLo, atrPrev)
        bool   showRng = (liveComp or state == ST_EXP) and not na(wInAtr)
        bool   tooWide = useMaxWidth and not na(wInAtr) and wInAtr > maxWidthAtr
        string rD      = showRng ? str.tostring(rangeBars) + " bars" + (tooWide ? " · too wide" : "") : ""
        string rV      = showRng ? str.tostring(wInAtr, "#.0") + " ATR" : "—"
        f_row(dash, 5, "Range", rD, rV, muted, tooWide ? cNeutral : muted, tooWide ? cNeutral : sub, ts, ts, false, false, "Reference range width in ATR[1], and how many bars built it (grace bars excluded). Mode: " + rangeMode + ".")
 
        string sqD = na(sqRatioC) ? "" : "q " + str.tostring(sqRatioC, "0.00")
        string sqV = na(sqRatioC) ? "—" : sqRatioC < 1 ? "ON" : "OFF"
        f_row(dash, 6, "Squeeze", sqD, sqV, muted, muted, sqRatioC < 1 ? accent : muted, ts, ts, false, false, "ON when the Bollinger Bands sit inside the Keltner Channel on the last closed bar (q < 1). q = Bollinger half-width ÷ Keltner half-width — the same relationship the chart shows when both envelopes are on.")
 
        string lD = devBull ? "▲ outside range" : devBear ? "▼ outside range" : ""
        string lV = liveBar and not na(score) ? str.tostring(score, "#") : "closed"
        f_row(dash, 7, "Live", lD, lV, muted, muted, muted, ts, ts, false, true, "Unconfirmed read of the forming bar. Changes every tick. Never drawn or alerted.")
 
        f_gap(dash, 8)
 
        // ── Last breakout ──
        string bD = lastDir == 0 ? "" : "Q " + f_fmt(lastQuality, "#") + " · " + f_grade(lastQuality)
        string bV = lastDir == 0 ? "—" : lastDir == 1 ? "▲ Bull" : "▼ Bear"
        f_row(dash, 9, "Last Break", bD, bV, muted, muted, lastDir == 1 ? cBull : lastDir == -1 ? cBear : muted, ts, ts, false, false, "Quality grades the expansion candle (displacement, body, volume). It does not predict follow-through.")
 
        string oD = lastOutcome == ST_CONFIRMED and lastVia != "" ? lastVia : ""
        string oV = lastDir == 0 ? "—" : lastOutcome == ST_EXP ? "pending" : f_stateName(lastOutcome)
        f_row(dash, 10, "Outcome", oD, oV, muted, muted, f_stateColor(lastOutcome, lastDir, muted), ts, ts, false, false, "Resolution of the most recent expansion, and which method confirmed it.")
 
        // ── Diagnostics ──
        if showDiag
            f_gap(dash, 11)
            table.cell(dash, 0, 12, "COMPONENTS", text_color = muted, text_size = size.tiny, text_halign = text.align_left)
            table.cell(dash, 1, 12, "reading", text_color = muted, text_size = size.tiny, text_halign = text.align_right)
            table.cell(dash, 2, 12, "pts", text_color = muted, text_size = size.tiny, text_halign = text.align_right)
 
            float pA = wAll > 0 ? wAtr * sAtrC / wAll : na
            float pB = wAll > 0 ? wBbw * sBbwC / wAll : na
            float pS = wAll > 0 ? wSq * sSqC / wAll : na
            float pD = wAll > 0 ? wDur * sDurC / wAll : na
            string qTxt = na(sqRatioC) ? "—" : "q " + str.tostring(sqRatioC, "0.00") + (sqRatioC >= 1 ? " · none" : "")
 
            f_row(dash, 13, "ATR", "pctl " + f_fmt(atrPctlC, "#"), f_fmt(pA, "#.0"), muted, sub, txt, ts, ts, false, false, "Normalized ATR percentile vs the last " + str.tostring(lenRank) + " bars. Low percentile = more points. If this is low while the index is high, true range is still elevated — common right after a shock bar.")
            f_row(dash, 14, "BB Width", "pctl " + f_fmt(bbwPctlC, "#"), f_fmt(pB, "#.0"), muted, sub, txt, ts, ts, false, false, "Bollinger width percentile. Drops sharply once a large move leaves the " + str.tostring(bbLen) + "-bar window.")
            f_row(dash, 15, "Squeeze", qTxt, f_fmt(pS, "#.0"), muted, sub, txt, ts, ts, false, false, "q = Bollinger half-width ÷ Keltner half-width (" + kcSource + "). Below 1 = bands inside Keltner. Full credit at q ≤ " + str.tostring(sqFloor, "0.00") + ".")
            f_row(dash, 16, "Duration", "run " + str.tostring(tightRunC) + "/" + str.tostring(durFull), f_fmt(pD, "#.0"), muted, sub, txt, ts, ts, false, false, "Consecutive bars with base index ≥ Enter, toward full credit.")
            f_row(dash, 17, "Composite", smoothLen > 1 ? "raw · EMA " + str.tostring(smoothLen) + " above" : "", f_fmt(rawClosed, "#.0"), muted, muted, accent, ts, ts, true, false, "Sum of the component points (unsmoothed).")
 
    // Configuration warnings — shown even with the dashboard hidden
    if cfgWarn != ""
        table.cell(dash, 0, 18, "Settings", text_color = cBear, text_size = ts, text_halign = text.align_left, tooltip = "Invalid or conflicting inputs. Values marked 'set to' are being corrected automatically.")
        table.cell(dash, 1, 18, "", text_size = ts)
        table.cell(dash, 2, 18, cfgWarn, text_color = cBear, text_size = ts, text_halign = text.align_right)
 
 
// ─────────────────────────────────────────────────────────────
// ALERTS — all enabled events on a bar are combined into ONE alert() call,
// so nothing is lost to once-per-bar-close frequency.
// Create one TradingView alert on "Any alert() function call".
// ─────────────────────────────────────────────────────────────
f_ev(string acc, bool cond, string msg) =>
    cond ? (acc == "" ? msg : acc + " | " + msg) : acc
 
if barstate.isconfirmed
    string side = evDir == 1 ? "Bull" : "Bear"
    string ev   = ""
    ev := f_ev(ev, aComp and evCompStart, "Compression started · index " + f_fmt(score, "#"))
    ev := f_ev(ev, aBuild and evBuild, "Pressure building · index " + f_fmt(score, "#") + " · " + str.tostring(epBars) + " bars")
    ev := f_ev(ev, aExp and (evBullExp or evBearExp), side + " expansion · Q " + f_fmt(expQuality, "#") + " " + f_grade(expQuality) + " · peak index " + f_fmt(epPeak, "#"))
    ev := f_ev(ev, aConf and evConfirm, side + " breakout confirmed (" + lastVia + ")")
    ev := f_ev(ev, aFail and evFail, side + " breakout failed · closed back inside range")
    ev := f_ev(ev, aExpire and evExpire, side + " expansion expired · no follow-through")
    ev := f_ev(ev, aFizz and evFizzle, "Compression fizzled · no breakout")
    if ev != ""
        alert(syminfo.ticker + " " + timeframe.period + " · Pressure Cooker · " + ev, alert.freq_once_per_bar_close)

← 返回列表