Strong Pressure Signals | ProjectSyndicate

ProjectSyndicate · study · 1413 行 · 点赞 1,232 · TradingView 原页

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

Pine Script

//@version=6
indicator("Strong Pressure Signals", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 2000)
 
gB = "01 · Burst Engine (signal source)"
srcIn      = input.source(close, "Basis source", group = gB)
basisType  = input.string("EMA", "Basis type", options = ["EMA", "SMA", "HMA", "WMA", "VWMA", "RMA"], group = gB)
basisLen   = input.int(20, "Basis length", minval = 2, maxval = 400, group = gB)
atrLen     = input.int(14, "ATR length", minval = 2, maxval = 200, group = gB)
bandMult   = input.float(2.0, "Band width (ATR beyond basis = burst starts)", minval = 0.2, maxval = 10.0, step = 0.1, group = gB, tooltip = "A bar bursts when its high pokes above basis + this·ATR (or its low below basis − this·ATR).")
stepATR    = input.float(0.5, "ATR per stack step", minval = 0.1, maxval = 3.0, step = 0.05, group = gB)
maxLevels  = input.int(6, "Max stack height", minval = 1, maxval = 6, group = gB)
heatSat    = input.float(3.0, "Heat saturates at (ATR beyond band)", minval = 0.5, maxval = 12.0, step = 0.5, group = gB)
needClose  = input.bool(false, "Require closing burst (close beyond band)", group = gB)
confirmBar = input.bool(true, "Confirm on bar close (non-repaint)", group = gB, tooltip = "ON: burst peaks are only detected on closed bars, so nothing repaints.")
 
gP = "02 · Pressure Clusters (liquidation fuel)"
clSide     = input.string("Both", "Cluster side", options = ["Both", "Longs Only (below)", "Shorts Only (above)"], group = gP, tooltip = "Long-liquidation clusters sit UNDER price at swing lows (support magnets). Short-liquidation clusters sit ABOVE at swing highs (resistance magnets).")
leftBars   = input.int(12, "Pivot left", minval = 1, group = gP)
rightBars  = input.int(4,  "Pivot right", minval = 1, group = gP)
lookbackW  = input.int(3000, "Lookback (bars, 0 = all)", minval = 0, group = gP)
maxZones   = input.int(30, "Max live clusters", minval = 2, maxval = 60, group = gP)
maxLife    = input.int(400, "Max cluster age (bars)", minval = 10, group = gP)
clMinMag   = input.float(0.0, "Min magnitude to keep (0-1)", minval = 0.0, maxval = 1.0, step = 0.05, group = gP)
hideOverlap= input.bool(true, "Merge overlapping clusters", group = gP)
overlapThr = input.int(35, "Overlap threshold (%)", minval = 1, maxval = 100, group = gP)
clAtrLen   = input.int(200, "Cluster ATR length (band + sweeps)", minval = 1, maxval = 500, group = gP)
bandATR    = input.float(0.5, "Band height (ATR mult)", minval = 0.05, maxval = 6.0, step = 0.05, group = gP, tooltip = "Invisible band around each cluster used for touch / sweep detection.")
minDepth   = input.float(0.15, "Min sweep depth (ATR)", minval = 0.02, maxval = 4.0, step = 0.01, group = gP)
reclaimWin = input.int(6, "Max reclaim window (bars)", minval = 1, maxval = 40, group = gP)
breakAtr   = input.float(0.9, "Decisive break acceptance (ATR)", minval = 0.1, maxval = 8.0, step = 0.1, group = gP)
flipBroken = input.bool(true, "Flip broken clusters (breakers)", group = gP)
magWeight  = input.float(0.7, "Magnitude weight in cluster strength", minval = 0.0, maxval = 1.0, step = 0.05, group = gP)
weightLB   = input.int(1000, "Magnitude lookback (bars)", minval = 100, maxval = 5000, group = gP)
magContrast= input.float(0.6, "Magnitude contrast", minval = 0.1, maxval = 3.0, step = 0.05, group = gP)
volLen     = input.int(20, "Volume baseline length", minval = 1, group = gP)
useBinance = input.bool(true,  "BTC: aggregate Binance volume",  group = gP, tooltip = "On BTC pairs the three venues' volume is aggregated for a fuller pressure read. Every other market uses its own chart volume automatically.")
useCoinbase= input.bool(true,  "BTC: aggregate Coinbase volume", group = gP)
useBitstamp= input.bool(true,  "BTC: aggregate Bitstamp volume", group = gP)
 
gR = "03 · Session Ranges (timed range context)"
useRange   = input.bool(true, "Enable session ranges", group = gR, tooltip = "Intraday charts only — on Daily and above this module switches itself off and the Range pillar reads neutral.")
tzInput    = input.string("America/New_York", "Timezone", options = ["Exchange", "UTC", "America/New_York", "America/Chicago", "Europe/London", "Europe/Berlin", "Asia/Karachi", "Asia/Kolkata", "Asia/Dubai", "Asia/Tokyo", "Asia/Singapore", "Australia/Sydney"], group = gR)
w1On       = input.bool(true, "Window 1", group = gR, inline = "w1")
w1Name     = input.string("NY", "Name", group = gR, inline = "w1")
w1Range    = input.session("0930-0945", "Range", group = gR, inline = "w1s")
w1Full     = input.session("0930-1600", "Session", group = gR, inline = "w1s")
w2On       = input.bool(true, "Window 2", group = gR, inline = "w2")
w2Name     = input.string("LON", "Name", group = gR, inline = "w2")
w2Range    = input.session("0300-0315", "Range", group = gR, inline = "w2s")
w2Full     = input.session("0300-1100", "Session", group = gR, inline = "w2s")
w3On       = input.bool(false, "Window 3", group = gR, inline = "w3")
w3Name     = input.string("ASIA", "Name", group = gR, inline = "w3")
w3Range    = input.session("2000-2015", "Range", group = gR, inline = "w3s")
w3Full     = input.session("2000-0400", "Session", group = gR, inline = "w3s")
rangeSat   = input.float(1.0, "Range pillar saturates at (x range beyond Cap / Floor)", minval = 0.25, maxval = 5.0, step = 0.25, group = gR, tooltip = "A burst this many range-widths beyond the Pressure Cap (range high) or Pressure Floor (range low) scores a full Range pillar (STRB T2 by default).")
showRangeBox = input.bool(true, "Draw range box + Cap / Floor / Equilibrium", group = gR, tooltip = "Pressure Cap = range high, Pressure Floor = range low, Equilibrium = midpoint. Each level carries a window-prefixed name tag on the chart.")
showRangeTags = input.bool(true, "Show level name tags", group = gR)
keepDays   = input.int(4, "Ranges kept on chart (per window)", minval = 1, maxval = 20, group = gR)
w1Col      = input.color(#2962FF, "W1", group = gR, inline = "wc")
w2Col      = input.color(#AB47BC, "W2", group = gR, inline = "wc")
w3Col      = input.color(#00ACC1, "W3", group = gR, inline = "wc")
 
gF = "04 · Signal Filter & Pressure Gates"
fadeMin    = input.int(3, "Min stack height to signal", minval = 1, maxval = 6, group = gF)
minMag     = input.float(0.0, "Min burst magnitude (ATR beyond band)", minval = 0, maxval = 12, step = 0.1, group = gF)
needRej    = input.bool(false, "Require rejection wick on the peak bar", group = gF)
rejMin     = input.float(0.30, "Min rejection wick (share of peak-bar range)", minval = 0, maxval = 0.95, step = 0.05, group = gF)
useRsiGate = input.bool(false, "Require RSI exhaustion", group = gF)
rsiLen     = input.int(14, "RSI length", minval = 2, maxval = 100, group = gF)
rsiOB      = input.float(65, "RSI overbought (SHORT above)", minval = 51, maxval = 99, group = gF)
rsiOS      = input.float(35, "RSI oversold (LONG below)", minval = 1, maxval = 49, group = gF)
needCluster= input.bool(false, "GATE · burst must hit / sweep an opposing cluster", group = gF, tooltip = "A SHORT needs the up-burst to reach into a short-liquidation cluster above; a LONG needs the down-burst to reach into a long-liquidation cluster below. A reclaim on the signal bar also satisfies it.")
clProx     = input.float(1.0, "Cluster proximity for partial credit (ATR)", minval = 0.1, maxval = 10, step = 0.1, group = gF, tooltip = "If the burst stops short of a cluster, the Pressure pillar still earns partial credit when the cluster is within this many ATR of the peak extreme.")
needRange  = input.bool(false, "GATE · burst must extend beyond the session range", group = gF)
sessionOnly= input.bool(false, "GATE · only trade inside an enabled trading session", group = gF)
allowShort = input.bool(true, "Allow SHORTS (up bursts)", group = gF)
allowLong  = input.bool(true, "Allow LONGS (down bursts)", group = gF)
cooldown   = input.int(20, "Minimum spacing between signals (bars)", minval = 0, maxval = 500, group = gF)
 
gT = "05 · Trade Levels & Universal Zones"
stopMode   = input.string("Burst Extreme", "Stop basis", options = ["Burst Extreme", "ATR Multiple", "Swing Extreme"], group = gT)
swingLook  = input.int(10, "Swing lookback (bars)", minval = 2, maxval = 200, group = gT)
stopAtr    = input.float(1.2, "Stop distance (ATR)", minval = 0.1, maxval = 10, step = 0.1, group = gT)
slBuf      = input.float(0.30, "Stop buffer beyond extreme (ATR)", minval = 0.0, maxval = 3, step = 0.05, group = gT)
maxRisk    = input.float(3.0, "Max risk (ATR) — stop cap", minval = 0.3, maxval = 10, step = 0.1, group = gT)
minRisk    = input.float(0.5, "Min risk (ATR) — stop floor", minval = 0.1, maxval = 5, step = 0.1, group = gT)
targetMode = input.string("Pressure Ladder", "Target ladder", options = ["R Multiples", "Mean Reversion (band → basis)", "Pressure Ladder"], group = gT, tooltip = "Pressure Ladder: TP1/2/3 snap to the nearest opposing liquidation clusters in the trade direction (price magnets); any missing rung falls back to its R multiple.\nMean Reversion: TP1 halfway to the basis, TP2 at the basis, TP3 half a band beyond.")
ladderMinR = input.float(0.6, "Pressure Ladder · min rung distance (R)", minval = 0.1, maxval = 5, step = 0.1, group = gT)
tp1R       = input.float(1.0, "TP1 (R)", minval = 0.25, maxval = 50, step = 0.25, group = gT)
tp2R       = input.float(2.0, "TP2 (R)", minval = 0.25, maxval = 50, step = 0.25, group = gT)
tp3R       = input.float(3.0, "TP3 (R)", minval = 0.25, maxval = 50, step = 0.25, group = gT)
maxHunt    = input.int(200, "Max bars in trade (time stop)", minval = 5, maxval = 5000, group = gT)
zoneW      = input.int(18, "UNIVERSAL zone width (bars)", minval = 3, maxval = 150, group = gT)
showBoxes  = input.bool(true, "Show SL / TP zones", group = gT)
showLines  = input.bool(true, "Show SL / TP lines", group = gT)
showLevelLbl = input.bool(true, "Label level prices", group = gT)
showExitLbl  = input.bool(true, "Show trade result labels", group = gT)
showBasisMark= input.bool(true, "Show basis marker on entry", group = gT)
maxHist    = input.int(16, "Max historical tickets drawn", minval = 1, maxval = 30, group = gT, tooltip = "Visual cap only. Statistics stay cumulative over every closed trade.")
 
gS = "06 · Strength Ranking (0-10)"
minStars   = input.int(0, "Minimum stars to take", minval = 0, maxval = 4, group = gS)
alertStars = input.int(0, "Alert minimum stars", minval = 0, maxval = 4, group = gS)
wExt   = input.float(0.16, "Weight · Burst Extension",     minval = 0, maxval = 1, step = 0.01, group = gS)
wStack = input.float(0.12, "Weight · Stack Height",        minval = 0, maxval = 1, step = 0.01, group = gS)
wExh   = input.float(0.12, "Weight · Momentum Exhaustion", minval = 0, maxval = 1, step = 0.01, group = gS)
wRej   = input.float(0.10, "Weight · Rejection Wick",      minval = 0, maxval = 1, step = 0.01, group = gS)
wTrend = input.float(0.08, "Weight · Trend Fit",           minval = 0, maxval = 1, step = 0.01, group = gS)
wCalm  = input.float(0.06, "Weight · Volatility Regime",   minval = 0, maxval = 1, step = 0.01, group = gS)
wRoom  = input.float(0.06, "Weight · Reversion Room",      minval = 0, maxval = 1, step = 0.01, group = gS)
wPress = input.float(0.20, "Weight · PRESSURE Cluster",    minval = 0, maxval = 1, step = 0.01, group = gS, tooltip = "Peak into / sweep of an opposing liquidation cluster, weighted by that cluster's 0-10 strength. A reclaim on the signal bar scores 0.9.")
wRange = input.float(0.10, "Weight · Session RANGE",       minval = 0, maxval = 1, step = 0.01, group = gS, tooltip = "Burst over-extension beyond the timed session range. A failed breakout back inside on the signal bar scores 0.9. Neutral (0.5) when no range is live.")
 
gD = "07 · Dashboard"
showDash    = input.bool(true, "Show dashboard", group = gD)
dashPosOpt  = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right", "Middle Left"], group = gD)
dashSizeOpt = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = gD)
gaugeLen    = input.int(10, "Gauge width (blocks)", minval = 4, maxval = 20, group = gD)
showGauges  = input.bool(true, "Show live quality sliders", group = gD)
showPressRows = input.bool(true, "Show pressure context", group = gD)
showRangeRows = input.bool(true, "Show session range context", group = gD)
showHeatRow = input.bool(true, "Show TP1/2/3 · SL breakdown", group = gD)
showTiers   = input.bool(true, "Show win rate by strength", group = gD)
showRecent  = input.bool(true, "Show last trades", group = gD)
showMtf     = input.bool(true, "Show MTF burst strip", group = gD)
mtfTf2      = input.timeframe("15", "MTF · TF 2", group = gD)
mtfTf3      = input.timeframe("60", "MTF · TF 3", group = gD)
 
gV = "08 · Visuals & Theme"
theme      = input.string("Aurora", "Color theme", options = ["Aurora", "Gold Noir", "Bloomberg Amber", "Ice Blue", "Aqua Violet", "Neon Magenta", "Institutional"], group = gV)
showSignal = input.bool(true, "Show signal labels", group = gV)
showStars  = input.bool(true, "Show ★ ranking on labels", group = gV)
lblSizeOpt = input.string("Small", "Signal label size", options = ["Tiny", "Small", "Normal", "Large"], group = gV)
showBg     = input.bool(false, "Tint background on extreme bursts", group = gV)
showReclaimMarks = input.bool(false, "Show cluster reclaim diamonds", group = gV, tooltip = "Diamonds mark a sweep-and-reclaim of a cluster (support tone below, resistance tone above). Off by default to keep the chart clean — the reclaim still feeds the Pressure pillar, the dashboard event log and the alerts.")
showFailMarks    = input.bool(true, "Show failed range-breakout crosses", group = gV)
showBubbles= input.bool(true, "Show cluster bubbles", group = gV)
showGlow   = input.bool(true, "Bubble glow halo", group = gV)
showScore  = input.bool(true, "Show strength inside bubble", group = gV)
bubbleBoost= input.int(1, "Bubble size boost", minval = 0, maxval = 2, group = gV)
showLevels = input.bool(true, "Show cluster level lines", group = gV)
levelWidth = input.int(5, "Cluster level width", minval = 1, maxval = 10, group = gV)
levelTransp= input.int(70, "Cluster level transparency", minval = 0, maxval = 100, group = gV)
levelProj  = input.int(3, "Project levels past current bar", minval = 0, maxval = 200, group = gV)
colorMode  = input.string("By Side", "Cluster color mode", options = ["Spectrum (vertical)", "By Side"], group = gV)
topCol     = input.color(#21c997, "Top / Support tone",    group = gV, inline = "cc")
midCol     = input.color(#5b6cff, "Mid",                   group = gV, inline = "cc")
botCol     = input.color(#cc24e2, "Bottom / Resist tone",  group = gV, inline = "cc")
cCold      = input.color(#26c6da, "Mild",    group = gV, inline = "heat")
cWarm      = input.color(#ffd54a, "Warm",    group = gV, inline = "heat")
cHot       = input.color(#ff7a1a, "Hot",     group = gV, inline = "heat")
cExtreme   = input.color(#ff2b4e, "Extreme", group = gV, inline = "heat")
 
longCol  = theme == "Gold Noir" ? color.rgb(230, 184, 75) : theme == "Bloomberg Amber" ? color.rgb(255, 176, 46) : theme == "Ice Blue" ? color.rgb(38, 198, 255) : theme == "Aqua Violet" ? color.rgb(0, 225, 200) : theme == "Neon Magenta" ? color.rgb(0, 230, 200) : theme == "Institutional" ? color.rgb(31, 176, 118) : color.rgb(20, 214, 122)
shortCol = theme == "Gold Noir" ? color.rgb(203, 68, 56) : theme == "Bloomberg Amber" ? color.rgb(233, 84, 72) : theme == "Ice Blue" ? color.rgb(255, 112, 92) : theme == "Aqua Violet" ? color.rgb(184, 122, 255) : theme == "Neon Magenta" ? color.rgb(255, 62, 190) : theme == "Institutional" ? color.rgb(176, 62, 74) : color.rgb(243, 62, 110)
tpFill   = theme == "Gold Noir" ? color.rgb(120, 92, 20) : theme == "Bloomberg Amber" ? color.rgb(126, 86, 14) : theme == "Ice Blue" ? color.rgb(0, 92, 132) : theme == "Aqua Violet" ? color.rgb(0, 96, 88) : theme == "Neon Magenta" ? color.rgb(0, 98, 86) : theme == "Institutional" ? color.rgb(18, 96, 66) : color.rgb(12, 104, 64)
slFill   = theme == "Gold Noir" ? color.rgb(120, 40, 30) : theme == "Bloomberg Amber" ? color.rgb(122, 44, 34) : theme == "Ice Blue" ? color.rgb(140, 44, 66) : theme == "Aqua Violet" ? color.rgb(96, 40, 120) : theme == "Neon Magenta" ? color.rgb(128, 26, 90) : theme == "Institutional" ? color.rgb(110, 34, 42) : color.rgb(140, 30, 62)
 
color panelBg     = #0a0c12
color panelBgAlt  = #0f131c
color panelHdr    = #161b27
color panelBorder = #2c3342
color txtHi       = #ebeef5
color txtLo       = #8791a2
color neutralCol  = #69748a
color goodCol     = #21c87a
color badCol      = #e6435a
color warnCol     = color.rgb(214, 176, 74)
color midGray     = #9598A1
 
f_clamp(float v) => math.min(math.max(v, 0.0), 1.0)
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
f_pos(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Top Right"    => position.top_right
        "Bottom Left"  => position.bottom_left
        "Bottom Right" => position.bottom_right
        "Middle Right" => position.middle_right
        "Middle Left"  => position.middle_left
        => position.top_right
 
f_stars(float sc) => sc >= 7.5 ? "★★★★" : sc >= 6.5 ? "★★★" : sc >= 5.5 ? "★★" : sc >= 4.5 ? "★" : "·"
f_tier(float sc)  => sc >= 7.5 ? 4 : sc >= 6.5 ? 3 : sc >= 5.5 ? 2 : sc >= 4.5 ? 1 : 0
f_tname(float sc) => sc >= 7.5 ? "ELITE" : sc >= 6.5 ? "STRONG" : sc >= 5.5 ? "MODERATE" : sc >= 4.5 ? "WEAK" : "MINIMAL"
f_signedR(float v) => (v >= 0 ? "+" : "") + str.tostring(v, "#.##") + "R"
f_px(float v) => na(v) ? "—" : str.tostring(v, format.mintick)
 
f_gauge(float v01, int n) =>
    int filled = math.max(0, math.min(n, int(math.round(f_clamp(v01) * n))))
    string s = ""
    for i = 1 to n
        s := s + (i <= filled ? "█" : "░")
    s
 
f_gcol(float v01) =>
    float t = f_clamp(v01)
    t < 0.5 ? color.from_gradient(t, 0.0, 0.5, badCol, warnCol) : color.from_gradient(t, 0.5, 1.0, warnCol, goodCol)
 
f_heat(float t) =>
    float tt = f_clamp(t)
    tt < 0.40 ? color.from_gradient(tt, 0.0, 0.40, cCold, cWarm) : tt < 0.75 ? color.from_gradient(tt, 0.40, 0.75, cWarm, cHot) : color.from_gradient(tt, 0.75, 1.0, cHot, cExtreme)
 
f_spectrum(float t) =>
    float x = f_clamp(t)
    x < 0.5 ? color.from_gradient(x / 0.5, 0.0, 1.0, botCol, midCol) : color.from_gradient((x - 0.5) / 0.5, 0.0, 1.0, midCol, topCol)
 
basis = switch basisType
    "SMA"  => ta.sma(srcIn, basisLen)
    "HMA"  => ta.hma(srcIn, basisLen)
    "WMA"  => ta.wma(srcIn, basisLen)
    "VWMA" => ta.vwma(srcIn, basisLen)
    "RMA"  => ta.rma(srcIn, basisLen)
    => ta.ema(srcIn, basisLen)
 
atr        = ta.atr(atrLen)
rsi        = ta.rsi(close, rsiLen)
atrPct     = ta.percentrank(atr, 100)
basisSlope = ta.change(basis, 3)
swingLo    = ta.lowest(low, swingLook)
swingHi    = ta.highest(high, swingLook)
 
float aSafe = nz(atr) > 0 ? atr : syminfo.mintick
float bSafe = nz(basis, close)
float upper = basis + bandMult * atr
float lower = basis - bandMult * atr
 
float upExtP = high - upper
float dnExtP = lower - low
float upMag  = na(upExtP) ? 0.0 : upExtP / aSafe
float dnMag  = na(dnExtP) ? 0.0 : dnExtP / aSafe
 
bool upSpike = not na(upper) and upExtP > 0 and (not needClose or close > upper)
bool dnSpike = not na(lower) and dnExtP > 0 and (not needClose or close < lower)
bool okBar   = confirmBar ? barstate.isconfirmed : true
 
float upM0 = upSpike ? math.max(0.0, upMag) : 0.0
float dnM0 = dnSpike ? math.max(0.0, dnMag) : 0.0
 
bool upPeak = okBar and nz(upM0[1]) > 0 and nz(upM0[1]) >= nz(upM0[2]) and nz(upM0[1]) > upM0
bool dnPeak = okBar and nz(dnM0[1]) > 0 and nz(dnM0[1]) >= nz(dnM0[2]) and nz(dnM0[1]) > dnM0
 
float upPk = nz(upM0[1])
float dnPk = nz(dnM0[1])
int   upLvlPk = math.min(maxLevels, 1 + int(upPk / stepATR))
int   dnLvlPk = math.min(maxLevels, 1 + int(dnPk / stepATR))
 
float pkHi    = nz(high[1], high)
float pkLo    = nz(low[1], low)
float pkOpen  = nz(open[1], open)
float pkClose = nz(close[1], close)
float pkRange = math.max(pkHi - pkLo, syminfo.mintick)
float upRej   = (pkHi - math.max(pkOpen, pkClose)) / pkRange
float dnRej   = (math.min(pkOpen, pkClose) - pkLo) / pkRange
float rsiPk   = nz(rsi[1], 50.0)
 
int   liveDir = upSpike ? -1 : dnSpike ? 1 : (close > bSafe ? -1 : 1)
float liveMag = upSpike ? upMag : dnSpike ? dnMag : 0.0
int   liveLvl = upSpike or dnSpike ? math.min(maxLevels, 1 + int(math.max(0.0, liveMag) / stepATR)) : 0
float barRng  = math.max(high - low, syminfo.mintick)
float liveRej = liveDir == -1 ? (high - math.max(open, close)) / barRng : (math.min(open, close) - low) / barRng
 
int   n      = bar_index
float atrRaw = math.max(nz(ta.atr(clAtrLen), ta.cum(high - low) / (n + 1)), syminfo.mintick)
 
bool  isBTC = syminfo.basecurrency == "BTC"
float binV  = useBinance  and isBTC ? request.security("BINANCE:BTCUSD",  timeframe.period, volume, gaps = barmerge.gaps_off) : 0.0
float cbV   = useCoinbase and isBTC ? request.security("COINBASE:BTCUSD", timeframe.period, volume, gaps = barmerge.gaps_off) : 0.0
float bsV   = useBitstamp and isBTC ? request.security("BITSTAMP:BTCUSD", timeframe.period, volume, gaps = barmerge.gaps_off) : 0.0
float cumV   = binV + cbV + bsV
float volVal = cumV > 0 ? cumV : volume
float volBase= ta.sma(volVal, volLen)
 
float liqWeight = volVal * (high - low) * 100.0
float weightMax = math.min(ta.highest(liqWeight, weightLB), 1e10)
float weightMinR= ta.lowest(liqWeight, weightLB)
float weightMin = weightMinR == weightMax ? weightMax * 0.85 : weightMinR
float specHi    = ta.highest(high, weightLB)
float specLo    = ta.lowest(low,  weightLB)
 
float ph    = ta.pivothigh(leftBars, rightBars)
float pl    = ta.pivotlow(leftBars, rightBars)
bool  inWin = lookbackW <= 0 or (last_bar_index - n) <= lookbackW
float bandH = atrRaw * bandATR
bool  supOn = clSide == "Both" or clSide == "Longs Only (below)"
bool  resOn = clSide == "Both" or clSide == "Shorts Only (above)"
 
f_zoneCol(float mid, int side) =>
    color c = na
    if colorMode == "By Side"
        c := side == 1 ? topCol : botCol
    else
        float vr = specHi - specLo
        float nv = vr > 0 ? f_clamp((mid - specLo) / vr) : 0.5
        c := f_spectrum(nv)
    c
 
f_wnorm(float w) =>
    float den = weightMax - weightMin
    float nw  = den > 0 ? f_clamp((w - weightMin) / den) : 0.5
    math.pow(nw, magContrast)
 
f_tierOf(float wn) => wn < 0.25 ? 0 : wn < 0.5 ? 1 : wn < 0.75 ? 2 : 3
f_coreSize(int t)  => t <= 0 ? size.small : t == 1 ? size.normal : t == 2 ? size.large : size.huge
f_glowSize(int t)  => f_coreSize(t + 1)
f_rangeOverlap(float t1, float b1, float t2, float b2) =>
    float ov   = math.min(t1, t2) - math.max(b1, b2)
    float minH = math.min(t1 - b1, t2 - b2)
    ov > 0 and minH > 0 and ov / minH >= overlapThr / 100.0
 
type zone
    int   dir     = 1
    float top     = na
    float bot     = na
    float mid     = na
    int   bornBar = na
    int   lastBar = na
    int   touches = 0
    float volSum  = 0.0
    int   volN    = 0
    float wickSum = 0.0
    int   wickN   = 0
    int   sweeps  = 0
    int   phase   = 0
    int   swBar   = na
    float score   = 0.0
    float weight  = 0.0
    int   tier    = 0
    line  ln      = na
    label glow    = na
    label core    = na
    label num     = na
    bool  dead    = false
 
var array<zone> zones = array.new<zone>()
 
f_defense(zone z) =>
    float tF = math.min(z.touches / 4.0, 1.0)
    float vF = volBase > 0 and z.volN > 0 ? math.min((z.volSum / z.volN) / volBase, 1.0) : 0.0
    float wF = z.wickN > 0 ? math.min((z.wickSum / z.wickN) / atrRaw, 1.0) : 0.0
    float sF = math.min(z.sweeps / 2.0, 1.0)
    tF * 0.30 + vF * 0.20 + wF * 0.20 + sF * 0.30
 
f_ageF(int age) => math.max(1.0 - 0.35 * math.min(age / 400.0, 1.0), 0.65)
 
method buildBubble(zone self) =>
    if not na(self.glow)
        label.delete(self.glow)
    if not na(self.core)
        label.delete(self.core)
    if not na(self.num)
        label.delete(self.num)
    self.glow := na
    self.core := na
    self.num  := na
    if showBubbles
        color base = f_zoneCol(self.mid, self.dir)
        int   t    = math.min(self.tier + bubbleBoost, 3)
        if showGlow
            self.glow := label.new(self.bornBar, self.mid, "", xloc = xloc.bar_index, style = label.style_circle, color = color.new(base, 88), size = f_glowSize(t))
        self.core := label.new(self.bornBar, self.mid, "", xloc = xloc.bar_index, style = label.style_circle, color = color.new(base, 66), size = f_coreSize(t))
        if showScore
            self.num := label.new(self.bornBar, self.mid, "", xloc = xloc.bar_index, style = label.style_label_center, color = color.new(color.black, 100), textcolor = color.white, size = size.small)
    if not na(self.core)
        label.set_xy(self.core, self.bornBar, self.mid)
 
method refresh(zone self, float sc) =>
    color base = f_zoneCol(self.mid, self.dir)
    int   ct   = int(math.round(66.0 - 46.0 * f_clamp(sc / 10.0)))
    if showLevels
        int lx2 = n + levelProj
        if na(self.ln)
            self.ln := line.new(self.bornBar, self.mid, lx2, self.mid, xloc = xloc.bar_index, color = color.new(base, levelTransp), width = levelWidth, style = line.style_solid)
        else
            line.set_xy1(self.ln, self.bornBar, self.mid)
            line.set_xy2(self.ln, lx2, self.mid)
        if not na(self.ln)
            line.set_color(self.ln, color.new(base, self.phase == 1 ? math.min(levelTransp + 15, 100) : levelTransp))
    else if not na(self.ln)
        line.delete(self.ln)
        self.ln := na
    int et = math.min(self.tier + bubbleBoost, 3)
    if not na(self.core)
        label.set_color(self.core, color.new(base, ct))
        label.set_size(self.core, f_coreSize(et))
    if not na(self.glow)
        label.set_color(self.glow, color.new(base, math.min(ct + 22, 100)))
        label.set_size(self.glow, f_glowSize(et))
    if not na(self.num)
        label.set_text(self.num, str.tostring(int(math.round(sc))))
    if not na(self.core)
        label.set_xy(self.core, self.bornBar, self.mid)
 
method kill(zone self) =>
    if not na(self.ln)
        line.delete(self.ln)
    if not na(self.glow)
        label.delete(self.glow)
    if not na(self.core)
        label.delete(self.core)
    if not na(self.num)
        label.delete(self.num)
    self.dead := true
 
f_overlapsActive(float t, float b) =>
    bool hit = false
    if array.size(zones) > 0
        for z in zones
            if not z.dead and z.phase != 1 and f_rangeOverlap(t, b, z.top, z.bot)
                hit := true
                break
    hit
 
f_spawn(int side, float lvl, float w) =>
    float wn = f_wnorm(nz(w))
    float t  = lvl + bandH / 2.0
    float b  = lvl - bandH / 2.0
    if wn >= clMinMag and not (hideOverlap and f_overlapsActive(t, b))
        zone z = zone.new()
        z.dir     := side
        z.top     := t
        z.bot     := b
        z.mid     := lvl
        z.bornBar := n - rightBars
        z.lastBar := n - rightBars
        z.volSum  := nz(volVal)
        z.volN    := 1
        z.weight  := nz(w)
        z.tier    := f_tierOf(wn)
        z.buildBubble()
        array.push(zones, z)
 
if supOn and not na(pl) and inWin
    f_spawn(1, pl, liqWeight[rightBars])
if resOn and not na(ph) and inWin
    f_spawn(-1, ph, liqWeight[rightBars])
 
while array.size(zones) > maxZones
    array.shift(zones).kill()
 
bool  evTouch  = false
bool  evSweep  = false
bool  evBreak  = false
bool  recBull  = false
bool  recBear  = false
bool  hitRes   = false
bool  hitSup   = false
float hitResSc = 0.0
float hitSupSc = 0.0
 
float liveMaxW = 0.0
float liveMinW = 1e18
if array.size(zones) > 0
    for z in zones
        if not z.dead
            liveMaxW := math.max(liveMaxW, z.weight)
            liveMinW := math.min(liveMinW, z.weight)
if liveMaxW <= 0.0
    liveMaxW := 1.0
if liveMinW > liveMaxW
    liveMinW := 0.0
 
if array.size(zones) > 0
    for i = 0 to array.size(zones) - 1
        zone z = array.get(zones, i)
        if not z.dead
            z.volSum += nz(volVal)
            z.volN   += 1
            if n - z.bornBar >= maxLife
                z.kill()
            else
                if z.dir == 1
                    if low <= z.top
                        hitSup   := true
                        hitSupSc := math.max(hitSupSc, z.score)
                    if z.phase == 0
                        if low <= z.top and low >= z.bot and close > z.bot
                            z.touches += 1
                            z.wickSum += math.max(z.top - low, 0)
                            z.wickN   += 1
                            z.lastBar := n
                            evTouch   := true
                        else if low < z.bot - minDepth * atrRaw
                            z.phase := 1
                            z.swBar := n
                            evSweep := true
                    else if z.phase == 1
                        bool accepted = close < z.bot - breakAtr * atrRaw or (n - z.swBar >= reclaimWin and close < z.bot)
                        if close > z.bot
                            recBull   := true
                            z.sweeps  += 1
                            z.lastBar := n
                            z.phase   := 0
                        else if accepted
                            evBreak := true
                            if flipBroken
                                z.dir     := -1
                                z.touches := 0
                                z.wickSum := 0.0
                                z.wickN   := 0
                                z.phase   := 0
                                z.lastBar := n
                            else
                                z.kill()
                else
                    if high >= z.bot
                        hitRes   := true
                        hitResSc := math.max(hitResSc, z.score)
                    if z.phase == 0
                        if high >= z.bot and high <= z.top and close < z.top
                            z.touches += 1
                            z.wickSum += math.max(high - z.bot, 0)
                            z.wickN   += 1
                            z.lastBar := n
                            evTouch   := true
                        else if high > z.top + minDepth * atrRaw
                            z.phase := 1
                            z.swBar := n
                            evSweep := true
                    else if z.phase == 1
                        bool accepted = close > z.top + breakAtr * atrRaw or (n - z.swBar >= reclaimWin and close > z.top)
                        if close < z.top
                            recBear   := true
                            z.sweeps  += 1
                            z.lastBar := n
                            z.phase   := 0
                        else if accepted
                            evBreak := true
                            if flipBroken
                                z.dir     := 1
                                z.touches := 0
                                z.wickSum := 0.0
                                z.wickN   := 0
                                z.phase   := 0
                                z.lastBar := n
                            else
                                z.kill()
                if not z.dead
                    float magN = liveMaxW > liveMinW ? f_clamp((z.weight - liveMinW) / (liveMaxW - liveMinW)) : 0.5
                    magN := math.pow(magN, magContrast)
                    float sc = math.min(math.max((magWeight * magN + (1.0 - magWeight) * f_defense(z) * f_ageF(n - z.lastBar)) * 10.0, 1.0), 10.0)
                    z.score := sc
                    z.tier  := f_tierOf(magN)
                    z.refresh(sc)
 
if array.size(zones) > 0
    for i = array.size(zones) - 1 to 0
        if array.get(zones, i).dead
            array.remove(zones, i)
 
float nearResPx = na
float nearResD  = na
float nearResSc = na
float nearSupPx = na
float nearSupD  = na
float nearSupSc = na
int   liveSup   = 0
int   liveRes   = 0
int   sweptCnt  = 0
if array.size(zones) > 0
    for z in zones
        if not z.dead
            if z.phase == 1
                sweptCnt += 1
            if z.dir == -1
                liveRes += 1
                if z.mid > close
                    float d = (z.mid - close) / aSafe
                    if na(nearResD) or d < nearResD
                        nearResD  := d
                        nearResPx := z.mid
                        nearResSc := z.score
            else
                liveSup += 1
                if z.mid < close
                    float d = (close - z.mid) / aSafe
                    if na(nearSupD) or d < nearSupD
                        nearSupD  := d
                        nearSupPx := z.mid
                        nearSupSc := z.score
 
var string lastEvt    = "—"
var int    lastEvtBar = na
var int    cSweeps    = 0
var int    cReclaims  = 0
var int    cBreaks    = 0
if recBull or recBear
    lastEvt    := recBull ? "RECLAIM ▲" : "RECLAIM ▼"
    lastEvtBar := n
    cReclaims  += 1
else if evBreak
    lastEvt    := "BREAK"
    lastEvtBar := n
    cBreaks    += 1
else if evSweep
    lastEvt    := "SWEEP"
    lastEvtBar := n
    cSweeps    += 1
else if evTouch
    lastEvt    := "TOUCH"
    lastEvtBar := n
 
bool   rangeOk = useRange and timeframe.isintraday
string tz      = tzInput == "Exchange" ? syminfo.timezone : tzInput
 
type Win
    string name
    color  col
    bool   wasInside = false
    bool   wasFull   = false
    float  hi        = na
    float  lo        = na
    int    startBar  = na
    bool   done      = false
    bool   armed     = false
    bool   extending = false
    int    brk       = 0
    bool   failed    = false
    int    sessions  = 0
    int    nBrk      = 0
    int    nFail     = 0
    array<line>  lns
    array<box>   bxs
    array<label> lbls
 
f_runWin(Win w, bool enabled, bool inR, bool inF) =>
    bool brkUp = false
    bool brkDn = false
    bool failU = false
    bool failD = false
    bool rDone = false
    if enabled and barstate.isconfirmed
        bool rStart = inR and not w.wasInside
        bool rEnd   = not inR and w.wasInside
        if not inF and w.wasFull
            w.armed := false
        if rStart
            w.hi        := high
            w.lo        := low
            w.startBar  := bar_index
            w.done      := false
            w.armed     := false
            w.extending := false
            w.brk       := 0
            w.failed    := false
            w.sessions  += 1
            if showRangeBox
                while array.size(w.bxs) >= keepDays
                    box.delete(array.shift(w.bxs))
                while array.size(w.lns) > (keepDays - 1) * 3
                    line.delete(array.shift(w.lns))
                while array.size(w.lbls) > (keepDays - 1) * 3
                    label.delete(array.shift(w.lbls))
                array.push(w.bxs, box.new(bar_index, high, bar_index, low, bgcolor = color.new(w.col, 88), border_color = w.col, border_width = 1))
        else if inR and not na(w.hi)
            w.hi := math.max(w.hi, high)
            w.lo := math.min(w.lo, low)
        if inR and showRangeBox and array.size(w.bxs) > 0
            box bx = array.get(w.bxs, array.size(w.bxs) - 1)
            box.set_top(bx, w.hi)
            box.set_bottom(bx, w.lo)
            box.set_right(bx, bar_index)
        if rEnd and not na(w.hi) and not w.done
            w.done  := true
            w.armed := true
            rDone   := true
            if showRangeBox
                array.push(w.lns, line.new(w.startBar, w.hi, bar_index, w.hi, color = longCol,  width = 2))
                array.push(w.lns, line.new(w.startBar, w.lo, bar_index, w.lo, color = shortCol, width = 2))
                array.push(w.lns, line.new(w.startBar, (w.hi + w.lo) / 2, bar_index, (w.hi + w.lo) / 2, color = color.new(midGray, 30), width = 1, style = line.style_dashed))
                if showRangeTags
                    array.push(w.lbls, label.new(bar_index, w.hi, w.name + " Pressure Cap", style = label.style_label_left, color = color.new(longCol, 100), textcolor = longCol, size = size.small))
                    array.push(w.lbls, label.new(bar_index, w.lo, w.name + " Pressure Floor", style = label.style_label_left, color = color.new(shortCol, 100), textcolor = shortCol, size = size.small))
                    array.push(w.lbls, label.new(bar_index, (w.hi + w.lo) / 2, w.name + " Equilibrium", style = label.style_label_left, color = color.new(midGray, 100), textcolor = midGray, size = size.small))
            w.extending := inF
        if w.extending and not inF
            w.extending := false
        if w.extending and array.size(w.lns) >= 3
            int sz = array.size(w.lns)
            for i = sz - 3 to sz - 1
                line.set_x2(array.get(w.lns, i), bar_index)
        if w.extending and array.size(w.lbls) >= 3
            int lz = array.size(w.lbls)
            for i = lz - 3 to lz - 1
                label.set_x(array.get(w.lbls, i), bar_index)
        if w.armed and w.done and inF and not inR and not na(w.hi)
            if w.brk == 0
                if close > w.hi
                    brkUp := true
                    w.brk := 1
                    w.nBrk += 1
                else if close < w.lo
                    brkDn := true
                    w.brk := -1
                    w.nBrk += 1
            else if not w.failed
                if w.brk == 1 and close < w.hi
                    failU    := true
                    w.failed := true
                    w.nFail  += 1
                else if w.brk == -1 and close > w.lo
                    failD    := true
                    w.failed := true
                    w.nFail  += 1
        w.wasInside := inR
        w.wasFull   := inF
    [brkUp, brkDn, failU, failD, rDone]
 
var Win w1 = Win.new(name = w1Name, col = w1Col, lns = array.new<line>(), bxs = array.new<box>(), lbls = array.new<label>())
var Win w2 = Win.new(name = w2Name, col = w2Col, lns = array.new<line>(), bxs = array.new<box>(), lbls = array.new<label>())
var Win w3 = Win.new(name = w3Name, col = w3Col, lns = array.new<line>(), bxs = array.new<box>(), lbls = array.new<label>())
 
bool en1 = rangeOk and w1On
bool en2 = rangeOk and w2On
bool en3 = rangeOk and w3On
 
bool inR1 = en1 and not na(time(timeframe.period, w1Range, tz))
bool inF1 = en1 and not na(time(timeframe.period, w1Full,  tz))
bool inR2 = en2 and not na(time(timeframe.period, w2Range, tz))
bool inF2 = en2 and not na(time(timeframe.period, w2Full,  tz))
bool inR3 = en3 and not na(time(timeframe.period, w3Range, tz))
bool inF3 = en3 and not na(time(timeframe.period, w3Full,  tz))
 
[bu1, bd1, fu1, fd1, rd1] = f_runWin(w1, en1, inR1, inF1)
[bu2, bd2, fu2, fd2, rd2] = f_runWin(w2, en2, inR2, inF2)
[bu3, bd3, fu3, fd3, rd3] = f_runWin(w3, en3, inR3, inF3)
 
bool brkUpAny  = bu1 or bu2 or bu3
bool brkDnAny  = bd1 or bd2 or bd3
bool failUpAny = fu1 or fu2 or fu3
bool failDnAny = fd1 or fd2 or fd3
bool rangeDone = rd1 or rd2 or rd3
bool inSession = inF1 or inF2 or inF3
 
Win ctx = w1
bool ctxLive = false
if inF1 and w1.done
    ctx     := w1
    ctxLive := true
else if inF2 and w2.done
    ctx     := w2
    ctxLive := true
else if inF3 and w3.done
    ctx     := w3
    ctxLive := true
else
    int best = -1
    if w1.done and not na(w1.startBar) and w1.startBar > best
        best := w1.startBar
        ctx  := w1
    if w2.done and not na(w2.startBar) and w2.startBar > best
        best := w2.startBar
        ctx  := w2
    if w3.done and not na(w3.startBar) and w3.startBar > best
        best := w3.startBar
        ctx  := w3
bool  haveRange = rangeOk and ctx.done and not na(ctx.hi) and not na(ctx.lo)
float ctxHi  = haveRange ? ctx.hi : na
float ctxLo  = haveRange ? ctx.lo : na
float ctxRng = haveRange ? math.max(ctx.hi - ctx.lo, syminfo.mintick) : na
 
f_pressN(int dir, bool hitNow, float hitSc, bool hitPrev, float hitScPrev, float ext, float nearPx, float nearSc, bool reclaimed) =>
    float v = 0.0
    if hitNow or hitPrev
        v := math.max(0.5, math.max(hitNow ? hitSc : 0.0, hitPrev ? hitScPrev : 0.0) / 10.0)
    else if not na(nearPx)
        float d = dir == -1 ? (nearPx - ext) / aSafe : (ext - nearPx) / aSafe
        if d >= 0 and d <= clProx
            v := (1.0 - d / clProx) * math.max(nz(nearSc), 1.0) / 10.0 * 0.7
    if reclaimed
        v := math.max(v, 0.9)
    f_clamp(v)
 
f_rangeN(int dir, float ext, bool failedNow) =>
    float v = 0.5
    if haveRange
        float beyond = dir == -1 ? (ext - ctxHi) / ctxRng : (ctxLo - ext) / ctxRng
        v := beyond > 0 ? f_clamp(beyond / rangeSat) : 0.0
        if failedNow
            v := math.max(v, 0.9)
    v
 
bool  pkHitRes   = hitRes[1]
bool  pkHitSup   = hitSup[1]
float pkHitResSc = nz(hitResSc[1])
float pkHitSupSc = nz(hitSupSc[1])
float pressShort = f_pressN(-1, hitRes, hitResSc, pkHitRes, pkHitResSc, pkHi, nearResPx, nearResSc, recBear)
float pressLong  = f_pressN( 1, hitSup, hitSupSc, pkHitSup, pkHitSupSc, pkLo, nearSupPx, nearSupSc, recBull)
float rangeShort = f_rangeN(-1, pkHi, failUpAny)
float rangeLong  = f_rangeN( 1, pkLo, failDnAny)
bool  beyondUp   = haveRange and pkHi > ctxHi
bool  beyondDn   = haveRange and pkLo < ctxLo
bool  clusterUp  = hitRes or pkHitRes or recBear
bool  clusterDn  = hitSup or pkHitSup or recBull
 
float livePress = liveDir == -1 ? f_pressN(-1, hitRes, hitResSc, false, 0.0, high, nearResPx, nearResSc, recBear) : f_pressN(1, hitSup, hitSupSc, false, 0.0, low, nearSupPx, nearSupSc, recBull)
float liveRange = liveDir == -1 ? f_rangeN(-1, high, failUpAny) : f_rangeN(1, low, failDnAny)
 
f_score(int dir, float mag, int lvl, float rsiVal, float rejRaw, float entry, float pressN, float rangeN) =>
    float extN   = f_clamp(mag / math.max(heatSat, 0.1))
    float stackN = f_clamp(lvl * 1.0 / math.max(maxLevels, 1))
    float exhN   = dir == 1 ? f_clamp((50.0 - rsiVal) / 30.0) : f_clamp((rsiVal - 50.0) / 30.0)
    float rejN   = f_clamp(rejRaw / 0.6)
    float slopeN = nz(basisSlope) / aSafe
    float trendN = f_clamp((dir * slopeN + 1.0) / 2.0)
    float calmN  = f_clamp(1.0 - nz(atrPct, 50.0) / 100.0)
    float roomN  = f_clamp(math.abs(entry - bSafe) / (math.max(bandMult, 0.1) * aSafe * 1.5))
    float wsum   = wExt + wStack + wExh + wRej + wTrend + wCalm + wRoom + wPress + wRange
    float raw    = wsum > 0 ? (extN * wExt + stackN * wStack + exhN * wExh + rejN * wRej + trendN * wTrend + calmN * wCalm + roomN * wRoom + pressN * wPress + rangeN * wRange) / wsum : 0.0
    [extN, stackN, exhN, rejN, trendN, calmN, roomN, pressN, rangeN, math.min(math.max(raw * 10.0, 0.0), 10.0)]
 
bool gateUp = (not needCluster or clusterUp) and (not needRange or beyondUp) and (not sessionOnly or inSession)
bool gateDn = (not needCluster or clusterDn) and (not needRange or beyondDn) and (not sessionOnly or inSession)
bool upQual = upPeak and allowShort and upLvlPk >= fadeMin and upPk >= minMag and (not needRej or upRej >= rejMin) and (not useRsiGate or rsiPk >= rsiOB) and gateUp
bool dnQual = dnPeak and allowLong  and dnLvlPk >= fadeMin and dnPk >= minMag and (not needRej or dnRej >= rejMin) and (not useRsiGate or rsiPk <= rsiOS) and gateDn
 
int   fireDir = upQual and dnQual ? (upPk >= dnPk ? -1 : 1) : upQual ? -1 : dnQual ? 1 : 0
float sigMag  = fireDir == -1 ? upPk : fireDir == 1 ? dnPk : 0.0
int   sigLvl  = fireDir == -1 ? upLvlPk : fireDir == 1 ? dnLvlPk : 0
float sigRej  = fireDir == -1 ? upRej : fireDir == 1 ? dnRej : 0.0
int   scDir   = fireDir != 0 ? fireDir : liveDir
float sigPress= scDir == -1 ? pressShort : pressLong
float sigRange= scDir == -1 ? rangeShort : rangeLong
 
[lvExt, lvStk, lvExh, lvRej, lvTrd, lvCal, lvRoom, lvPrs, lvRng, lvScore] = f_score(liveDir, liveMag, liveLvl, rsi, liveRej, close, livePress, liveRange)
[sgExt, sgStk, sgExh, sgRej, sgTrd, sgCal, sgRoom, sgPrs, sgRng, sgScore] = f_score(scDir, sigMag, sigLvl, rsiPk, sigRej, close, sigPress, sigRange)
 
f_tooltip(int dir, float sc, float mag, int lvl, float prsN, float rngN) =>
    string tt = "Setup quality: " + str.tostring(math.round(sc * 10) / 10) + "/10  " + f_stars(sc) + "  " + f_tname(sc)
    tt += "\nDirection: " + (dir == 1 ? "LONG (down burst)" : "SHORT (up burst)")
    tt += "\nBurst magnitude: " + str.tostring(mag, "#.##") + " ATR beyond band"
    tt += "\nStack height: " + str.tostring(lvl) + "/" + str.tostring(maxLevels)
    tt += "\nExhaustion (RSI): " + str.tostring(rsiPk, "#.#")
    tt += "\nRejection wick: " + str.tostring((dir == 1 ? dnRej : upRej) * 100, "#") + "% of peak bar"
    tt += "\nPressure cluster: " + str.tostring(prsN * 100, "#") + "%" + (dir == 1 ? (clusterDn ? "  (hit / swept)" : "") : (clusterUp ? "  (hit / swept)" : ""))
    tt += "\nSession range: " + (haveRange ? str.tostring(rngN * 100, "#") + "%  (" + ctx.name + ")" : "n/a")
    tt += "\nVolatility pctile: " + str.tostring(nz(atrPct), "#") + "  (calmer = better)"
    tt += "\nNote: a confluence read, not a win-rate guarantee."
    tt
 
var int lastSigBar  = na
var int lastSigSide = 0
bool cooldownOk = na(lastSigBar) or (bar_index - lastSigBar >= cooldown)
 
var bool  tradeActive = false
var int   tradeSide   = 0
var int   tradeBar    = na
var float tEntry      = na
var float tStop       = na
var float tTp1        = na
var float tTp2        = na
var float tTp3        = na
var float tR1         = na
var float tR2         = na
var float tR3         = na
var int   bestStage   = 0
var float tradeScore  = na
var int   tradeTier   = 0
var bool  tradePress  = false
var bool  tradeRange  = false
 
var line  aEntry = na
var line  aSl    = na
var line  aT1    = na
var line  aT2    = na
var line  aT3    = na
var line  aBm    = na
var box   aB1    = na
var box   aB2    = na
var box   aB3    = na
var box   aSlBox = na
var label aSig   = na
var label aLEntry= na
var label aLSl   = na
var label aLT1   = na
var label aLT2   = na
var label aLT3   = na
var label aExit  = na
 
type tradeViz
    line  e  = na
    line  s  = na
    line  t1 = na
    line  t2 = na
    line  t3 = na
    line  bm = na
    box   b1 = na
    box   b2 = na
    box   b3 = na
    box   sb = na
    label sg = na
    label le = na
    label ls = na
    label l1 = na
    label l2 = na
    label l3 = na
    label ex = na
 
var array<tradeViz> history = array.new<tradeViz>()
 
var int   sClosed   = 0
var int   sTp1      = 0
var int   sTp2      = 0
var int   sTp3      = 0
var int   sSl       = 0
var int   sExp      = 0
var int   sWins     = 0
var float sR        = 0.0
var float sGrossWin = 0.0
var float sGrossLos = 0.0
var int   sMaxWin   = 0
var int   sMaxLos   = 0
var int   sCurWin   = 0
var int   sCurLos   = 0
var int   sStreak   = 0
var int   sLong     = 0
var int   sLongWin  = 0
var int   sShort    = 0
var int   sShortWin = 0
var int   sPress    = 0
var int   sPressWin = 0
var int   sRange    = 0
var int   sRangeWin = 0
var array<int>    tierWin  = array.new_int(5, 0)
var array<int>    tierLoss = array.new_int(5, 0)
var array<string> recentOut = array.new<string>()
var array<float>  recentR   = array.new<float>()
 
f_logRecent(string s, float r) =>
    array.unshift(recentOut, s)
    array.unshift(recentR, r)
    if array.size(recentOut) > 10
        array.pop(recentOut)
    if array.size(recentR) > 10
        array.pop(recentR)
 
bool closedTp3 = false
bool closedSl  = false
bool closedTp  = false
bool closedExp = false
 
if tradeActive
    bool tp1Hit = tradeSide == 1 ? high >= tTp1 : low <= tTp1
    bool tp2Hit = tradeSide == 1 ? high >= tTp2 : low <= tTp2
    bool tp3Hit = tradeSide == 1 ? high >= tTp3 : low <= tTp3
    bool slHit  = tradeSide == 1 ? low <= tStop : high >= tStop
 
    int  stage     = tp3Hit ? 3 : tp2Hit ? 2 : tp1Hit ? 1 : 0
    bool sameBarSl = slHit and stage > 0
    if stage > bestStage and not sameBarSl
        bestStage := stage
 
    int  barsIn    = not na(tradeBar) ? bar_index - tradeBar : 0
    bool finalTp3  = not sameBarSl and bestStage == 3
    bool finalSl   = slHit and (bestStage == 0 or sameBarSl)
    bool finalTp   = slHit and not sameBarSl and bestStage > 0 and bestStage < 3
    bool expireNow = not finalTp3 and not finalSl and not finalTp and barsIn >= maxHunt
 
    if finalTp3 or finalSl or finalTp or expireNow
        float mtmR = math.abs(tEntry - tStop) > 0 ? (tradeSide == 1 ? (close - tEntry) : (tEntry - close)) / math.abs(tEntry - tStop) : 0.0
        float resR = finalTp3 ? tR3 : finalTp and bestStage == 2 ? tR2 : finalTp and bestStage == 1 ? tR1 : expireNow ? mtmR : -1.0
 
        closedTp3 := finalTp3
        closedSl  := finalSl
        closedTp  := finalTp
        closedExp := expireNow
 
        bool isWin = resR > 0
        sClosed += 1
        sR      += resR
        if isWin
            sWins     += 1
            sGrossWin += resR
            sCurWin   += 1
            sCurLos   := 0
            sMaxWin   := math.max(sMaxWin, sCurWin)
            sStreak   := sCurWin
            array.set(tierWin, tradeTier, array.get(tierWin, tradeTier) + 1)
        else
            sGrossLos += math.abs(resR)
            sCurLos   += 1
            sCurWin   := 0
            sMaxLos   := math.max(sMaxLos, sCurLos)
            sStreak   := -sCurLos
            array.set(tierLoss, tradeTier, array.get(tierLoss, tradeTier) + 1)
        if tradeSide == 1
            sLong    += 1
            sLongWin += isWin ? 1 : 0
        else
            sShort    += 1
            sShortWin += isWin ? 1 : 0
        if tradePress
            sPress    += 1
            sPressWin += isWin ? 1 : 0
        if tradeRange
            sRange    += 1
            sRangeWin += isWin ? 1 : 0
        if finalTp3
            sTp3 += 1
            f_logRecent("TP3", resR)
        else if finalTp and bestStage == 2
            sTp2 += 1
            f_logRecent("TP2", resR)
        else if finalTp and bestStage == 1
            sTp1 += 1
            f_logRecent("TP1", resR)
        else if expireNow
            sExp += 1
            f_logRecent("TIME", resR)
        else
            sSl += 1
            f_logRecent("SL", resR)
 
        float resPrice = finalTp3 ? tTp3 : finalTp and bestStage == 2 ? tTp2 : finalTp and bestStage == 1 ? tTp1 : expireNow ? close : tStop
        string resTxt  = finalTp3 ? "TP3 ✔ " + f_signedR(resR) : finalTp ? "TP" + str.tostring(bestStage) + " ✔ " + f_signedR(resR) : expireNow ? (isWin ? "TIME ✔ " : "TIME ✘ ") + f_signedR(resR) : "SL ✘ " + f_signedR(resR)
        color resCol   = resR >= 0 ? longCol : shortCol
        string resStyle = tradeSide == 1 ? (resR >= 0 ? label.style_label_down : label.style_label_up) : (resR >= 0 ? label.style_label_up : label.style_label_down)
 
        if showExitLbl
            aExit := label.new(bar_index, resPrice, resTxt, style = resStyle, color = color.new(resCol, 0), textcolor = color.white, size = size.small)
 
        tradeViz tv = tradeViz.new(aEntry, aSl, aT1, aT2, aT3, aBm, aB1, aB2, aB3, aSlBox, aSig, aLEntry, aLSl, aLT1, aLT2, aLT3, aExit)
        array.push(history, tv)
        while array.size(history) > maxHist
            tradeViz old = array.shift(history)
            line.delete(old.e)
            line.delete(old.s)
            line.delete(old.t1)
            line.delete(old.t2)
            line.delete(old.t3)
            line.delete(old.bm)
            box.delete(old.b1)
            box.delete(old.b2)
            box.delete(old.b3)
            box.delete(old.sb)
            label.delete(old.sg)
            label.delete(old.le)
            label.delete(old.ls)
            label.delete(old.l1)
            label.delete(old.l2)
            label.delete(old.l3)
            label.delete(old.ex)
 
        aEntry  := na
        aSl     := na
        aT1     := na
        aT2     := na
        aT3     := na
        aBm     := na
        aB1     := na
        aB2     := na
        aB3     := na
        aSlBox  := na
        aSig    := na
        aLEntry := na
        aLSl    := na
        aLT1    := na
        aLT2    := na
        aLT3    := na
        aExit   := na
 
        tradeActive := false
        tradeSide   := 0
        tradeBar    := na
        tEntry      := na
        tStop       := na
        tTp1        := na
        tTp2        := na
        tTp3        := na
        bestStage   := 0
 
bool canOpen = not tradeActive and not closedTp3 and not closedSl and not closedTp and not closedExp and not na(atr) and cooldownOk
bool rawSig  = fireDir != 0 and canOpen
bool takeSig = rawSig and f_tier(sgScore) >= minStars
 
bool strongLong  = takeSig and fireDir == 1
bool strongShort = takeSig and fireDir == -1
 
if takeSig
    lastSigBar  := bar_index
    lastSigSide := fireDir
 
if takeSig
    bool  isLong  = fireDir == 1
    float entv    = close
    float burstHi = math.max(high, pkHi)
    float burstLo = math.min(low, pkLo)
    float rawStop = stopMode == "ATR Multiple" ? (isLong ? entv - atr * stopAtr : entv + atr * stopAtr) : stopMode == "Swing Extreme" ? (isLong ? swingLo - atr * slBuf : swingHi + atr * slBuf) : (isLong ? burstLo - atr * slBuf : burstHi + atr * slBuf)
    float risk0   = math.abs(entv - rawStop)
    float risk    = math.min(math.max(risk0, atr * minRisk), atr * maxRisk)
    float stopv   = isLong ? entv - risk : entv + risk
 
    float r1 = isLong ? entv + risk * tp1R : entv - risk * tp1R
    float r2 = isLong ? entv + risk * tp2R : entv - risk * tp2R
    float r3 = isLong ? entv + risk * tp3R : entv - risk * tp3R
 
    bool  revOk = targetMode == "Mean Reversion (band → basis)" and (isLong ? bSafe > entv : bSafe < entv)
    float half  = math.abs(bSafe - entv) * 0.5
    float band  = math.max(bandMult, 0.1) * aSafe * 0.5
 
    float l1 = na
    float l2 = na
    float l3 = na
    if targetMode == "Pressure Ladder" and array.size(zones) > 0
        array<float> cands = array.new<float>()
        for z in zones
            if not z.dead and z.dir == (isLong ? -1 : 1)
                float d = isLong ? z.mid - entv : entv - z.mid
                if d >= risk * ladderMinR
                    array.push(cands, d)
        array.sort(cands, order.ascending)
        int nc = array.size(cands)
        if nc >= 1
            l1 := isLong ? entv + array.get(cands, 0) : entv - array.get(cands, 0)
        if nc >= 2
            l2 := isLong ? entv + array.get(cands, 1) : entv - array.get(cands, 1)
        if nc >= 3
            l3 := isLong ? entv + array.get(cands, 2) : entv - array.get(cands, 2)
    float t1 = revOk ? (isLong ? entv + half : entv - half) : not na(l1) ? l1 : r1
    float t2 = revOk ? bSafe : not na(l2) ? l2 : (isLong ? math.max(r2, t1 + risk * 0.5) : math.min(r2, t1 - risk * 0.5))
    float t3 = revOk ? (isLong ? bSafe + band : bSafe - band) : not na(l3) ? l3 : (isLong ? math.max(r3, t2 + risk * 0.5) : math.min(r3, t2 - risk * 0.5))
 
    tradeActive := true
    tradeSide   := isLong ? 1 : -1
    tradeBar    := bar_index
    tEntry      := entv
    tStop       := stopv
    tTp1        := t1
    tTp2        := t2
    tTp3        := t3
    tR1         := risk > 0 ? math.abs(t1 - entv) / risk : 0.0
    tR2         := risk > 0 ? math.abs(t2 - entv) / risk : 0.0
    tR3         := risk > 0 ? math.abs(t3 - entv) / risk : 0.0
    bestStage   := 0
    tradeScore  := sgScore
    tradeTier   := f_tier(sgScore)
    tradePress  := isLong ? clusterDn : clusterUp
    tradeRange  := isLong ? beyondDn  : beyondUp
 
    color c  = isLong ? longCol : shortCol
    int   xr = bar_index + zoneW
 
    if showSignal
        string head = isLong ? "LONG" : "SHORT"
        string tags = (tradePress ? " ⚡PRESSURE" : "") + (tradeRange ? " ⧉RANGE" : "")
        string txt  = showStars ? head + "  " + str.tostring(sigLvl) + "/" + str.tostring(maxLevels) + tags + "\n" + f_stars(sgScore) + "  " + str.tostring(math.round(sgScore * 10) / 10) + "/10  " + f_tname(sgScore) : head + tags
        aSig := label.new(bar_index, isLong ? low : high, txt, style = isLong ? label.style_label_up : label.style_label_down, color = color.new(c, 6), textcolor = color.white, size = f_size(lblSizeOpt), tooltip = f_tooltip(tradeSide, sgScore, sigMag, sigLvl, sigPress, sigRange))
 
    if showBasisMark
        aBm := line.new(bar_index, bSafe, xr, bSafe, xloc = xloc.bar_index, color = color.new(neutralCol, 25), width = 1, style = line.style_dotted)
 
    if showBoxes
        aSlBox := box.new(bar_index, isLong ? entv : stopv, xr, isLong ? stopv : entv, xloc = xloc.bar_index, bgcolor = color.new(slFill, 80), border_color = color.new(shortCol, 45), border_width = 1)
        aB1    := box.new(bar_index, isLong ? t1 : entv, xr, isLong ? entv : t1, xloc = xloc.bar_index, bgcolor = color.new(tpFill, 78), border_color = color.new(c, 40), border_width = 1)
        aB2    := box.new(bar_index, isLong ? t2 : t1, xr, isLong ? t1 : t2, xloc = xloc.bar_index, bgcolor = color.new(tpFill, 85), border_color = color.new(c, 55), border_width = 1)
        aB3    := box.new(bar_index, isLong ? t3 : t2, xr, isLong ? t2 : t3, xloc = xloc.bar_index, bgcolor = color.new(tpFill, 91), border_color = color.new(c, 70), border_width = 1)
 
    if showLines
        aEntry := line.new(bar_index, entv, xr, entv, xloc = xloc.bar_index, color = color.new(c, 0), width = 2, style = line.style_solid)
        aSl    := line.new(bar_index, stopv, xr, stopv, xloc = xloc.bar_index, color = color.new(shortCol, 10), width = 1, style = line.style_dashed)
        aT1    := line.new(bar_index, t1, xr, t1, xloc = xloc.bar_index, color = color.new(c, 12), width = 1, style = line.style_solid)
        aT2    := line.new(bar_index, t2, xr, t2, xloc = xloc.bar_index, color = color.new(c, 30), width = 1, style = line.style_solid)
        aT3    := line.new(bar_index, t3, xr, t3, xloc = xloc.bar_index, color = color.new(c, 48), width = 1, style = line.style_solid)
        if showLevelLbl
            string dw = isLong ? "LONG" : "SHORT"
            string lm = targetMode == "Pressure Ladder" ? " ⚡" : ""
            aLEntry := label.new(xr, entv, dw + " @ " + str.tostring(entv, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(c, 0), textcolor = color.white, size = f_size(lblSizeOpt))
            aLSl    := label.new(xr, stopv, "SL @ " + str.tostring(stopv, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(shortCol, 10), textcolor = color.white, size = f_size(lblSizeOpt))
            aLT1    := label.new(xr, t1, "TP1 " + str.tostring(tR1, "#.#") + "R" + (not na(l1) ? lm : "") + " @ " + str.tostring(t1, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(c, 10), textcolor = color.white, size = f_size(lblSizeOpt))
            aLT2    := label.new(xr, t2, "TP2 " + str.tostring(tR2, "#.#") + "R" + (not na(l2) ? lm : "") + " @ " + str.tostring(t2, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(c, 26), textcolor = color.white, size = f_size(lblSizeOpt))
            aLT3    := label.new(xr, t3, "TP3 " + str.tostring(tR3, "#.#") + "R" + (not na(l3) ? lm : "") + " @ " + str.tostring(t3, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(c, 42), textcolor = color.white, size = f_size(lblSizeOpt))
 
color upColPk = f_heat(upPk / math.max(heatSat, 0.1))
color dnColPk = f_heat(dnPk / math.max(heatSat, 0.1))
color bgCol   = showBg and upPeak and upLvlPk >= maxLevels ? color.new(upColPk, 84) : showBg and dnPeak and dnLvlPk >= maxLevels ? color.new(dnColPk, 84) : na
bgcolor(bgCol, offset = -1, title = "Extreme-burst tint")
 
plotshape(showReclaimMarks and recBull, "Cluster reclaim ▲", shape.diamond, location.belowbar, color.new(topCol, 20), size = size.tiny)
plotshape(showReclaimMarks and recBear, "Cluster reclaim ▼", shape.diamond, location.abovebar, color.new(botCol, 20), size = size.tiny)
plotshape(showFailMarks and failUpAny, "Failed range breakout ▲", shape.xcross, location.abovebar, color.new(warnCol, 10), size = size.tiny)
plotshape(showFailMarks and failDnAny, "Failed range breakout ▼", shape.xcross, location.belowbar, color.new(warnCol, 10), size = size.tiny)
 
int mtfBias = upSpike ? -1 : dnSpike ? 1 : 0
int mtfLvl  = upSpike or dnSpike ? math.min(maxLevels, 1 + int(math.max(0.0, upSpike ? upMag : dnMag) / stepATR)) : 0
 
[b2, l2v] = request.security(syminfo.tickerid, mtfTf2, [mtfBias[1], mtfLvl[1]], lookahead = barmerge.lookahead_on)
[b3, l3v] = request.security(syminfo.tickerid, mtfTf3, [mtfBias[1], mtfLvl[1]], lookahead = barmerge.lookahead_on)
 
float winRate = sClosed > 0 ? sWins / sClosed * 100.0 : 0.0
float avgR    = sClosed > 0 ? sR / sClosed : 0.0
float pf      = sGrossLos > 0 ? sGrossWin / sGrossLos : sGrossWin > 0 ? 999.0 : 0.0
float longWR  = sLong > 0 ? sLongWin / sLong * 100.0 : 0.0
float shortWR = sShort > 0 ? sShortWin / sShort * 100.0 : 0.0
float pressWR = sPress > 0 ? sPressWin / sPress * 100.0 : 0.0
float rangeWR = sRange > 0 ? sRangeWin / sRange * 100.0 : 0.0
float tp1Rate = sClosed > 0 ? sTp1 / sClosed * 100.0 : 0.0
float tp2Rate = sClosed > 0 ? sTp2 / sClosed * 100.0 : 0.0
float tp3Rate = sClosed > 0 ? sTp3 / sClosed * 100.0 : 0.0
float slRate  = sClosed > 0 ? sSl / sClosed * 100.0 : 0.0
 
string bestDir   = sLong == 0 and sShort == 0 ? "—" : sLong > 0 and sShort == 0 ? "LONG" : sShort > 0 and sLong == 0 ? "SHORT" : longWR > shortWR ? "LONG" : shortWR > longWR ? "SHORT" : "EVEN"
string streakTxt = sStreak > 0 ? "W" + str.tostring(sStreak) : sStreak < 0 ? "L" + str.tostring(math.abs(sStreak)) : "—"
string pfTxt     = pf >= 999.0 ? "INF" : str.tostring(pf, "#.##")
 
string statusTxt = tradeActive ? "IN TRADE" : (upSpike or dnSpike) and liveLvl >= fadeMin ? "ARMED" : upSpike or dnSpike ? "BURSTING" : "SCANNING"
color  statusC   = tradeActive ? longCol : (upSpike or dnSpike) and liveLvl >= fadeMin ? warnCol : upSpike or dnSpike ? cWarm : neutralCol
string activeTxt = tradeActive ? (tradeSide == 1 ? "LONG" : "SHORT") : "—"
string lastTxt   = lastSigSide == 1 ? "LONG" : lastSigSide == -1 ? "SHORT" : "—"
string lastScoreTxt = na(tradeScore) ? "—" : f_stars(tradeScore) + " " + str.tostring(math.round(tradeScore * 10) / 10)
string burstTxt  = upSpike ? "UP " + str.tostring(liveLvl) + "/" + str.tostring(maxLevels) : dnSpike ? "DN " + str.tostring(liveLvl) + "/" + str.tostring(maxLevels) : "INSIDE"
string biasTxt   = upSpike ? "SHORT" : dnSpike ? "LONG" : "—"
color  pfC       = pf >= 1.5 ? goodCol : pf >= 1.0 ? warnCol : badCol
 
string resTxt  = na(nearResPx) ? "—" : f_px(nearResPx) + "  " + f_stars(nearResSc)
string resDTxt = na(nearResD)  ? "—" : str.tostring(nearResD, "#.#") + " ATR"
string supTxt  = na(nearSupPx) ? "—" : f_px(nearSupPx) + "  " + f_stars(nearSupSc)
string supDTxt = na(nearSupD)  ? "—" : str.tostring(nearSupD, "#.#") + " ATR"
color  resC    = na(nearResD) ? txtLo : nearResD <= 1.0 ? botCol : txtHi
color  supC    = na(nearSupD) ? txtLo : nearSupD <= 1.0 ? topCol : txtHi
string evtTxt  = na(lastEvtBar) ? "—" : lastEvt + "  " + str.tostring(n - lastEvtBar) + "b"
color  evtC    = lastEvt == "RECLAIM ▲" ? topCol : lastEvt == "RECLAIM ▼" ? botCol : lastEvt == "BREAK" ? badCol : lastEvt == "SWEEP" ? warnCol : txtHi
string pressStateTxt = hitRes and hitSup ? "BOTH SIDES" : hitRes ? "AT RESIST ▲" : hitSup ? "AT SUPPORT ▼" : sweptCnt > 0 ? str.tostring(sweptCnt) + " SWEPT" : "CLEAR"
color  pressStateC   = hitRes ? botCol : hitSup ? topCol : sweptCnt > 0 ? warnCol : txtLo
 
string rngStateTxt = not rangeOk ? (useRange ? "INTRADAY ONLY" : "OFF") : not haveRange ? "NO RANGE YET" : not ctxLive ? "LAST (" + ctx.name + ")" : ctx.brk == 0 ? "SET · " + ctx.name : ctx.failed ? "FAILED " + (ctx.brk == 1 ? "▲" : "▼") : ctx.brk == 1 ? "BROKE ▲" : "BROKE ▼"
color  rngStateC   = not haveRange ? txtLo : ctx.failed ? warnCol : ctx.brk == 1 ? longCol : ctx.brk == -1 ? shortCol : ctx.col
string rngLvlTxt   = haveRange ? f_px(ctxHi) + " / " + f_px(ctxLo) : "—"
string rngSizeTxt  = haveRange ? str.tostring(ctxRng / aSafe, "#.#") + " ATR" : "—"
string rngPosTxt   = not haveRange ? "—" : close > ctxHi ? "+" + str.tostring((close - ctxHi) / ctxRng, "#.##") + "x above" : close < ctxLo ? "-" + str.tostring((ctxLo - close) / ctxRng, "#.##") + "x below" : "inside"
color  rngPosC     = not haveRange ? txtLo : close > ctxHi ? shortCol : close < ctxLo ? longCol : txtHi
int    totSess     = w1.sessions + w2.sessions + w3.sessions
int    totBrk      = w1.nBrk + w2.nBrk + w3.nBrk
int    totFail     = w1.nFail + w2.nFail + w3.nFail
string rngStatTxt  = str.tostring(totSess) + " rng · " + str.tostring(totBrk) + " brk"
string rngFailTxt  = totBrk > 0 ? str.tostring(totFail * 100.0 / totBrk, "#") + "% fail" : "—"
 
f_biasTxt(int d) => d == 1 ? "▲ LONG" : d == -1 ? "▼ SHORT" : "—"
f_biasCol(int d) => d == 1 ? longCol : d == -1 ? shortCol : neutralCol
 
f_tierWR(int k) =>
    int w  = array.get(tierWin, k)
    int l  = array.get(tierLoss, k)
    int nn = w + l
    [nn > 0 ? w * 100.0 / nn : 0.0, nn]
 
string ps = f_size(dashSizeOpt)
var int dashRows = 56
var table dash = table.new(f_pos(dashPosOpt), 3, dashRows, frame_color = color.new(panelBorder, 0), frame_width = 1, border_width = 1, border_color = color.new(panelBorder, 30))
 
f_hdr(table t, int row, string a, string b, string c) =>
    table.cell(t, 0, row, a, text_color = txtHi, text_size = ps, text_halign = text.align_left, bgcolor = panelHdr)
    table.cell(t, 1, row, b, text_color = txtLo, text_size = ps, text_halign = text.align_center, bgcolor = panelHdr)
    table.cell(t, 2, row, c, text_color = txtLo, text_size = ps, text_halign = text.align_right, bgcolor = panelHdr)
 
f_row(table t, int row, string a, string b, color bc, string c, color cc, bool alt) =>
    color bg = alt ? panelBgAlt : panelBg
    table.cell(t, 0, row, a, text_color = txtLo, text_size = ps, text_halign = text.align_left, bgcolor = bg)
    table.cell(t, 1, row, b, text_color = bc, text_size = ps, text_halign = text.align_center, bgcolor = bg)
    table.cell(t, 2, row, c, text_color = cc, text_size = ps, text_halign = text.align_right, bgcolor = bg)
 
f_gRow(table t, int row, string a, float v01, string val, bool alt) =>
    color bg = alt ? panelBgAlt : panelBg
    table.cell(t, 0, row, a, text_color = txtLo, text_size = ps, text_halign = text.align_left, bgcolor = bg)
    table.cell(t, 1, row, f_gauge(v01, gaugeLen), text_color = f_gcol(v01), text_size = ps, text_halign = text.align_center, bgcolor = bg)
    table.cell(t, 2, row, val, text_color = txtHi, text_size = ps, text_halign = text.align_right, bgcolor = bg)
 
if barstate.islast and showDash
    table.clear(dash, 0, 0, 2, dashRows - 1)
    int r = 0
 
    f_hdr(dash, r, "STRONG PRESSURE", syminfo.ticker, timeframe.period)
    r += 1
    f_row(dash, r, "Status", statusTxt, statusC, activeTxt, tradeSide == 1 ? longCol : tradeSide == -1 ? shortCol : neutralCol, false)
    r += 1
    f_row(dash, r, "Burst State", burstTxt, upSpike ? shortCol : dnSpike ? longCol : neutralCol, biasTxt, upSpike ? shortCol : dnSpike ? longCol : neutralCol, true)
    r += 1
    f_row(dash, r, "Last Signal", lastTxt, lastSigSide == 1 ? longCol : lastSigSide == -1 ? shortCol : neutralCol, lastScoreTxt, txtHi, false)
    r += 1
 
    if showPressRows
        f_hdr(dash, r, "PRESSURE CLUSTERS", pressStateTxt, str.tostring(liveRes) + "▲ " + str.tostring(liveSup) + "▼")
        r += 1
        f_row(dash, r, "Resist ▲ (short-liq)", resTxt, resC, resDTxt, resC, false)
        r += 1
        f_row(dash, r, "Support ▼ (long-liq)", supTxt, supC, supDTxt, supC, true)
        r += 1
        f_row(dash, r, "Last Event", evtTxt, evtC, str.tostring(cSweeps) + "sw " + str.tostring(cReclaims) + "rc " + str.tostring(cBreaks) + "bk", txtLo, false)
        r += 1
        f_row(dash, r, "Pressure WR", sPress > 0 ? str.tostring(pressWR, "#") + "%" : "—", sPress > 0 ? (pressWR >= 50 ? goodCol : pressWR >= 38 ? warnCol : badCol) : txtLo, str.tostring(sPress) + " trd", txtLo, true)
        r += 1
 
    if showRangeRows
        f_hdr(dash, r, "SESSION RANGE", rngStateTxt, haveRange ? ctx.name : "")
        r += 1
        f_row(dash, r, "Cap / Floor", rngLvlTxt, rngStateC, rngSizeTxt, txtHi, false)
        r += 1
        f_row(dash, r, "Price vs Range", rngPosTxt, rngPosC, rngStatTxt, txtLo, true)
        r += 1
        f_row(dash, r, "Range WR", sRange > 0 ? str.tostring(rangeWR, "#") + "%" : "—", sRange > 0 ? (rangeWR >= 50 ? goodCol : rangeWR >= 38 ? warnCol : badCol) : txtLo, str.tostring(sRange) + " trd · " + rngFailTxt, txtLo, false)
        r += 1
 
    if showGauges
        f_hdr(dash, r, "LIVE SETUP QUALITY", f_biasTxt(liveDir), "VALUE")
        r += 1
        f_gRow(dash, r, "Extension", lvExt, str.tostring(liveMag, "#.##") + " ATR", false)
        r += 1
        f_gRow(dash, r, "Stack", lvStk, str.tostring(liveLvl) + "/" + str.tostring(maxLevels), true)
        r += 1
        f_gRow(dash, r, "Exhaustion", lvExh, str.tostring(rsi, "#.#") + " RSI", false)
        r += 1
        f_gRow(dash, r, "Rejection", lvRej, str.tostring(liveRej * 100, "#") + "%", true)
        r += 1
        f_gRow(dash, r, "Trend Fit", lvTrd, str.tostring(nz(basisSlope) / aSafe, "#.##"), false)
        r += 1
        f_gRow(dash, r, "Calm Regime", lvCal, str.tostring(nz(atrPct), "#") + " pct", true)
        r += 1
        f_gRow(dash, r, "Rev Room", lvRoom, str.tostring(math.abs(close - bSafe) / aSafe, "#.#") + " ATR", false)
        r += 1
        f_gRow(dash, r, "⚡ Pressure", lvPrs, liveDir == -1 ? (hitRes ? "IN CLUSTER" : resDTxt) : (hitSup ? "IN CLUSTER" : supDTxt), true)
        r += 1
        f_gRow(dash, r, "⧉ Range", lvRng, haveRange ? rngPosTxt : "n/a", false)
        r += 1
        table.cell(dash, 0, r, "SCORE", text_color = txtHi, text_size = ps, text_halign = text.align_left, bgcolor = panelHdr)
        table.cell(dash, 1, r, f_gauge(lvScore / 10.0, gaugeLen), text_color = f_gcol(lvScore / 10.0), text_size = ps, text_halign = text.align_center, bgcolor = panelHdr)
        table.cell(dash, 2, r, str.tostring(math.round(lvScore * 10) / 10) + "  " + f_stars(lvScore), text_color = txtHi, text_size = ps, text_halign = text.align_right, bgcolor = panelHdr)
        r += 1
 
    f_hdr(dash, r, "PERFORMANCE", "VALUE", "DETAIL")
    r += 1
    f_row(dash, r, "Win Rate", str.tostring(winRate, "#.#") + "%", txtHi, str.tostring(sClosed) + " trd", txtHi, false)
    r += 1
    f_row(dash, r, "Profit Factor", pfTxt, pfC, f_signedR(avgR) + "/t", avgR >= 0 ? goodCol : badCol, true)
    r += 1
    f_row(dash, r, "Total R", f_signedR(sR), sR >= 0 ? goodCol : badCol, bestDir, bestDir == "LONG" ? longCol : bestDir == "SHORT" ? shortCol : neutralCol, false)
    r += 1
    f_row(dash, r, "Long / Short WR", str.tostring(longWR, "#") + "% / " + str.tostring(shortWR, "#") + "%", txtHi, str.tostring(sLong) + "L " + str.tostring(sShort) + "S", txtLo, true)
    r += 1
    f_row(dash, r, "Streak", streakTxt, sStreak >= 0 ? goodCol : badCol, "W" + str.tostring(sMaxWin) + "/L" + str.tostring(sMaxLos), txtHi, false)
    r += 1
 
    if showHeatRow
        f_row(dash, r, "TP1/2/3 · SL", str.tostring(tp1Rate, "#") + "/" + str.tostring(tp2Rate, "#") + "/" + str.tostring(tp3Rate, "#"), txtHi, str.tostring(slRate, "#") + "%", badCol, true)
        r += 1
 
    if showMtf
        f_hdr(dash, r, "MTF BURST BIAS", timeframe.period, mtfTf2 + " · " + mtfTf3)
        r += 1
        f_row(dash, r, "Bias", f_biasTxt(mtfBias), f_biasCol(mtfBias), f_biasTxt(b2) + " " + f_biasTxt(b3), b2 + b3 > 0 ? longCol : b2 + b3 < 0 ? shortCol : neutralCol, false)
        r += 1
 
    if showTiers
        f_hdr(dash, r, "WIN RATE BY STRENGTH", "WR", "n")
        r += 1
        for k = 4 to 1
            [twr, tn] = f_tierWR(k)
            string star = k == 4 ? "★★★★" : k == 3 ? "★★★" : k == 2 ? "★★" : "★"
            color tc = tn == 0 ? txtLo : twr >= 45 ? goodCol : twr >= 33 ? warnCol : badCol
            bool alt = k % 2 == 0
            color bg = alt ? panelBg : panelBgAlt
            table.cell(dash, 0, r, star, text_color = warnCol, text_size = ps, text_halign = text.align_left, bgcolor = bg)
            table.cell(dash, 1, r, tn > 0 ? str.tostring(twr, "#.#") + "%" : "—", text_color = tc, text_size = ps, text_halign = text.align_center, bgcolor = bg)
            table.cell(dash, 2, r, str.tostring(tn), text_color = txtHi, text_size = ps, text_halign = text.align_right, bgcolor = bg)
            r += 1
 
    if showRecent
        f_hdr(dash, r, "LAST TRADES", "EXIT", "R")
        r += 1
        int hn = array.size(recentOut)
        if hn > 0
            int shown = math.min(hn, 6)
            for i = 0 to shown - 1
                string o  = array.get(recentOut, i)
                float rv  = array.size(recentR) > i ? array.get(recentR, i) : 0.0
                color oc  = rv > 0 ? goodCol : badCol
                bool alt2 = i % 2 == 1
                color bg2 = alt2 ? panelBgAlt : panelBg
                table.cell(dash, 0, r, "#" + str.tostring(i + 1), text_color = txtLo, text_size = ps, text_halign = text.align_left, bgcolor = bg2)
                table.cell(dash, 1, r, o, text_color = oc, text_size = ps, text_halign = text.align_center, bgcolor = bg2)
                table.cell(dash, 2, r, f_signedR(rv), text_color = oc, text_size = ps, text_halign = text.align_right, bgcolor = bg2)
                r += 1
 
bool alertOk  = f_tier(sgScore) >= alertStars
bool upXtreme = upPeak and upLvlPk >= maxLevels
bool dnXtreme = dnPeak and dnLvlPk >= maxLevels
bool nearStrongRes = not na(nearResD) and nearResD <= 0.5 and nz(nearResSc) >= 7.0
bool nearStrongSup = not na(nearSupD) and nearSupD <= 0.5 and nz(nearSupSc) >= 7.0
 
alertcondition(strongLong and alertOk,  "Long",  "Strong Pressure Signals: LONG (down-burst exhaustion) on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(strongShort and alertOk, "Short", "Strong Pressure Signals: SHORT (up-burst exhaustion) on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(takeSig, "Any Signal", "Strong Pressure Signals: new entry on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(strongLong and alertOk and clusterDn,  "Long + Cluster",  "Strong Pressure Signals: LONG into a long-liquidation cluster on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(strongShort and alertOk and clusterUp, "Short + Cluster", "Strong Pressure Signals: SHORT into a short-liquidation cluster on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(closedTp3, "TP3 Hit", "Strong Pressure Signals: TP3 hit on {{ticker}} {{interval}}.")
alertcondition(closedTp,  "Partial TP Exit", "Strong Pressure Signals: protected TP exit on {{ticker}} {{interval}}.")
alertcondition(closedSl,  "SL Hit", "Strong Pressure Signals: SL hit on {{ticker}} {{interval}}.")
alertcondition(upXtreme,  "Extreme Up Burst", "Strong Pressure Signals: extreme up burst — maximum over-extension on {{ticker}} {{interval}}.")
alertcondition(dnXtreme,  "Extreme Down Burst", "Strong Pressure Signals: extreme down burst — maximum over-extension on {{ticker}} {{interval}}.")
alertcondition(evSweep,   "Cluster Sweep", "Strong Pressure Signals: a liquidation cluster was swept on {{ticker}} {{interval}} — watch for a reclaim.")
alertcondition(recBull,   "Bullish Cluster Reclaim", "Strong Pressure Signals: sweep below a support cluster reclaimed on {{ticker}} {{interval}}.")
alertcondition(recBear,   "Bearish Cluster Reclaim", "Strong Pressure Signals: sweep above a resistance cluster reclaimed on {{ticker}} {{interval}}.")
alertcondition(evBreak,   "Cluster Break", "Strong Pressure Signals: a liquidation cluster was decisively broken on {{ticker}} {{interval}}.")
alertcondition(nearStrongRes or nearStrongSup, "Near Strong Cluster", "Strong Pressure Signals: price within 0.5 ATR of a STRONG liquidation cluster on {{ticker}} {{interval}}.")
alertcondition(rangeDone, "Session Range Set", "Strong Pressure Signals: session range set on {{ticker}} {{interval}}.")
alertcondition(brkUpAny or brkDnAny, "Range Breakout", "Strong Pressure Signals: session range breakout on {{ticker}} {{interval}} @ {{close}}.")
alertcondition(failUpAny or failDnAny, "Failed Range Breakout", "Strong Pressure Signals: range breakout FAILED back inside on {{ticker}} {{interval}} @ {{close}} — fade pressure.")

← 返回列表