本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// =============================================================================
// SUPERTREND BREAKOUT — Graded Flips · Regime-Gated · Edge-Measured (MTF)
// © Market_Logic_India MPL-2.0 · v1.0
// -----------------------------------------------------------------------------
// OPEN-SOURCE publication — free to use, study and build on. If you reuse the code,
// please keep this licence notice and a credit, per the Mozilla Public License 2.0.
// -----------------------------------------------------------------------------
// WHAT IT IS (plain language)
// The Supertrend read as a flip engine. The ATR band sits below price in an uptrend, above it in
// a downtrend, and flips when price closes through it. A confirmed flip is the BREAK. Each flip is
// GRADED 0–5 on how decisive the breaking bar was, drawn with a trend ribbon, and carries an
// Entry · Stop · Target plan whose trailing stop is the Supertrend line itself. Two things make it
// more than a visual:
// • REGIME GATE — a flip is a trend trigger; it bleeds in chop. Flips only ARM when the market
// is trending (higher-TF alignment and/or a Kaufman efficiency ratio). Out-of-regime flips are
// shown faint as context, not traded.
// • MEASURED EDGE — every armed flip is forward-resolved, past-only, under the chosen exit model.
// Results show per grade as WIN-RATE (Wilson lower bound) and AVG R per trade, against a
// RANDOM-DIRECTION NULL and a FADE baseline — so a grade earns its weight on THIS instrument,
// and only beats the null if the edge is real. Read the table before you trust a setup.
//
// MULTI-TIMEFRAME ON ONE CHART
// Beyond the 9-TF alignment table, the "Extra timeframe supertrends" group has six tick-boxes:
// tick any of them and that timeframe's Supertrend line is drawn on your current chart, coloured by
// its own trend and tagged with its timeframe. Stack several at once to see where each timeframe's
// trend flips — all from one instance, no external indicators needed.
//
// HOW THE GRADE IS BUILT (transparent — one point each, on the flip bar)
// (1) displacement > 0.25 ATR past the broken line; (2) close in the top/bottom 40% of the bar;
// (3) volume > 1.3× its 20-bar average; (4) bar range > 1.5× ATR; (5) candle closed in the flip's
// direction. 0 = limp flip, 5 = decisive thrust. NOTE: read the measured-edge table before trusting
// grade as quality — a decisive-looking bar does not guarantee a better outcome.
//
// WHAT THE PANEL SHOWS (in-sample — verify on YOUR market)
// Of the trailing-stop-flip family, the Supertrend flip measured the STRONGEST here. Intraday
// (roughly 1–5m) it loses and is beaten by the random null — it gets whipsawed, fading pays more.
// But from about 30m up it consistently beats the null, and it turns NET-POSITIVE on 1h, 4h and the
// daily, the daily being the strongest. In short, the Supertrend breakout is a HIGHER-TIMEFRAME,
// with-trend read — not an intraday scalp. The 0–5 grade rates how decisive the flip bar looked; it
// does NOT reliably predict the outcome, so read it as context, not a quality score. Prefer higher
// timeframes, and read the measured-edge table before trusting a setup.
//
// EVERY INPUT IS ADJUSTABLE, so the same engine works on any asset class / timeframe. Turn the
// regime gate off or switch to the efficiency ratio, retune the factor / ATR length, and measure.
//
// EVIDENCE & CONCEPT CREDITS (techniques operationalised here — not third-party code)
// Supertrend (ATR bands) & ATR — Olivier Seban / J. W. Wilder. Chandelier exit — Chuck LeBeau.
// Efficiency ratio — Perry Kaufman. Triple-barrier labelling — in the spirit of M. López de Prado.
// Wilson score interval — E. B. Wilson. The grading, ribbon, alignment tally, regime gate, the
// per-grade edge measurement and the multi-TF overlay are this script's own synthesis.
//
// NON-REPAINT / DISCLAIMER
// Research & education only. NOT financial advice, NOT a recommendation, NOT a guarantee, NO
// performance promise. Flips confirm on bar CLOSE; the live bar is provisional. HTF values come
// only from CLOSED bars (no look-ahead); sub-chart TFs are informational. The measured edge is
// built ONLY from past, resolved events and accumulates over time — guidance, not proof. The
// smoothed ribbon is cosmetic and lags the raw Supertrend; all signals run on the raw Supertrend.
// Trading carries risk of loss.
// =============================================================================
//@version=6
indicator("Supertrend Breakout — Graded, Regime-Gated, Edge-Measured (MTF)", "ST-BO", overlay = true, max_labels_count = 300, max_lines_count = 10)
// ───────────────────────────── INPUTS ──────────────────────────────────────
g0 = "Calculation timeframe"
tfOpt = input.string("Chart", "Compute on (markers/stop)", options = ["Chart","1","2","3","5","15","30","60","120","240","D","W"], group = g0, tooltip = "Timeframe the markers, stop, targets and ribbon compute on. Default 'Chart' = follow whatever TF you're viewing; pick a fixed TF (e.g. 5, 240) to lock it. The alignment table always reads all 9 TFs regardless.")
gAuto = "0 · Visual highlight"
autoOpt = input.bool(true, "Highlight decisive-looking flips (visual only)", group = gAuto, tooltip = "ON by default. Draws a soft amber HALO around the higher-grade flips (grade 5 intraday / grade 4 on 1h+). Purely visual, changes no signal. The measured-edge table shows the grade does NOT reliably predict the outcome, so the halo marks a decisive-LOOKING bar, not a better bet.")
g1 = "Supertrend"
stFactor = input.float(3.0, "ATR factor (multiplier)", minval = 0.5, maxval = 15.0, step = 0.1, group = g1, tooltip = "The ATR band width. Classic Supertrend = 3.0. Larger = wider band, fewer flips.")
stAtrLen = input.int(10, "ATR length", minval = 1, maxval = 100, group = g1, tooltip = "ATR period for the Supertrend band. Classic = 10.")
g2 = "Flips (breaks)"
confirmClose = input.bool(true, "Confirm flips on bar close (non-repaint)", group = g2)
bufATR = input.float(0.0, "Flip buffer beyond line (× ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = g2)
strFilter = input.string("≥ 4", "Signal strength filter", options = ["Show all","≥ 1","≥ 2","≥ 3","≥ 4","only 5"], group = g2, tooltip = "Show only flips at or above the chosen grade (0–5). ≥ 3 = grades 3/4/5. 'only 5' = the strongest only. Gates markers, trade plan and ribbon colour.")
int minQualM = strFilter == "≥ 1" ? 1 : strFilter == "≥ 2" ? 2 : strFilter == "≥ 3" ? 3 : strFilter == "≥ 4" ? 4 : strFilter == "only 5" ? 5 : 0
ringQual = input.int(3, "Ring a flip at grade ≥", minval = 1, maxval = 5, group = g2)
arrowSize= input.string("Small", "Marker size", options = ["Tiny","Small","Normal","Large"], group = g2)
markerDetail = input.string("Compact (grade+TF)", "Marker detail", options = ["Compact (grade+TF)","Full","Short","Arrow only"], group = g2, tooltip = "Compact = ▲5·5m. Full = ▲ flip 5/5 · 5m. Short = ▲5. Arrow only = ▲.")
gReg = "Regime filter (trade only in-regime)"
regimeModeM = input.string("Off", "Regime gate", options = ["Off","HTF alignment","Efficiency ratio","Both"], group = gReg, tooltip = "Only ARM flips when trending. HTF alignment = require N of 9 TFs to agree with the flip. Efficiency ratio = Kaufman ER on the calc TF above a threshold. Set Off to trade every graded flip (any asset).")
alignNeedM = input.int(2, "HTF alignment: TFs that must agree (of 9)", minval = 1, maxval = 9, group = gReg, tooltip = "A long flip needs ≥ this many of the 9 TFs bullish; a short flip needs ≥ this many bearish. Lower = more trades, higher = stricter trend.")
erLen = input.int(10, "Efficiency ratio length", minval = 2, maxval = 100, group = gReg)
erThresh = input.float(0.35, "Efficiency ratio threshold", minval = 0.0, maxval = 1.0, step = 0.05, group = gReg, tooltip = "Kaufman ER above this = trending. ~0.3–0.4 suits intraday; raise for stricter.")
showFiltered = input.bool(true, "Show out-of-regime flips faintly (else hide)", group = gReg)
gVal = "Measured edge (past-only validation)"
valOn = input.bool(true, "Measure each grade's realised edge", group = gVal, tooltip = "For every armed flip, run a past-only triple-barrier test: did price reach +1R before −1R within the horizon? Accumulates a win-rate per grade bucket and reports the Wilson lower bound. Non-repaint — evaluates only resolved past events.")
valHorizon = input.int(24, "Validation horizon (calc-TF bars)", minval = 4, maxval = 500, group = gVal)
exitModel = input.string("Trailing tight", "Exit model (A/B these)", options = ["Trailing tight","Trailing wide","Fixed 1.5R","Fixed 2R","Time exit"], group = gVal, tooltip = "Scores every flip under ONE exit — switch between them and watch net R vs the NULL. Trailing tight = chandelier trail at 1R. Trailing wide = 2R trail. Fixed 1.5R / 2R = target in R, stop 1R. Time exit = hold to the horizon.")
valATRk = input.float(1.5, "Risk unit 1R (× ATR)", minval = 0.2, maxval = 5.0, step = 0.1, group = gVal, tooltip = "1R in ATR = the initial stop / barrier / trail-unit. Every R value in the table is measured against this.")
costR = input.float(0.05, "Cost per trade (R) — for NET", minval = 0.0, maxval = 1.0, step = 0.01, group = gVal, tooltip = "Round-trip cost (brokerage + taxes + slippage + realistic fill) in R, subtracted from avg R for the NET figure. The signal-vs-null LIFT is cost-independent; NET tells you if it pays after costs.")
nullOn = input.bool(true, "Random-direction null baseline", group = gVal, tooltip = "For every flip, also books a coin-flip-direction trade with the SAME exit model. If the signal's net R doesn't beat the null's, the 'edge' is just drift / payoff geometry.")
fadeOn = input.bool(true, "Fade (anti-signal) baseline", group = gVal, tooltip = "For every flip, also books the OPPOSITE direction (same exit). If fading earns more than taking, the signal is better used inverted. FADE row in the table.")
showEdge = input.bool(false, "Show measured-edge table (research)", group = gVal)
valPos = input.string("Middle Right", "Edge table position", options = ["Top Right","Top Left","Bottom Right","Bottom Left","Middle Right"], group = gVal)
gR = "Trend ribbon"
ribbonOn = input.bool(true, "Paintbrush ribbon", group = gR)
ribColor = input.string("Trend (green/red by flip)", "Ribbon colour", options = ["Trend (green/red by flip)","Blue","Gold"], group = gR, tooltip = "Trend = GREEN after a bullish flip, RED after a bearish flip. Blue / Gold = fixed stylish look.")
ribBaseATR = input.float(0.07, "Base thickness (× ATR)", minval = 0.02, maxval = 1.0, step = 0.01, group = gR)
ribGloss = input.bool(true, "Glossy sheen (two-tone)", group = gR)
ribGlow = input.bool(true, "Soft outer glow (brush edge)", group = gR)
ribSmooth = input.int(5, "Base smoothing (bars)", minval = 1, maxval = 50, group = gR)
autoSmooth = input.bool(true, "Auto-smooth HTF steps into a curve", group = gR, tooltip = "Scales smoothing to the HTF/chart ratio so a higher-TF ribbon looks smooth on a lower-TF chart. Display only — signals/stop stay on the raw Supertrend.")
smoothStrength = input.float(1.0, "HTF smooth strength", minval = 0.2, maxval = 3.0, step = 0.1, group = gR)
ribWidthMult = input.float(1.0, "Width × (manual tweak)", minval = 0.1, maxval = 5.0, step = 0.1, group = gR)
coreWidth = input.int(1, "Core line width (px)", minval = 1, maxval = 7, group = gR)
ribLabel = input.bool(true, "Tag ribbon with its TF", group = gR)
g3 = "Trade plan — dynamic risk"
showPlan = input.bool(true, "Show entry / stop / target plan", group = g3)
stopModeM = input.string("Trail the Supertrend", "Stop mode", options = ["Trail the Supertrend","Fixed at entry line","Wider chandelier (× below)"], group = g3, tooltip = "Trail the Supertrend = ride the Supertrend line (ratchets only in your favour). Fixed = stays at the entry-bar line. Wider chandelier = a looser highest-high − (plan ×) ATR trail.")
slBufATR = input.float(0.1, "Initial stop buffer beyond line (× ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = g3)
planMult = input.float(4.0, "Wider-chandelier ATR × (plan)", minval = 0.5, maxval = 12.0, step = 0.5, group = g3)
targetBasisM = input.string("R-multiple (risk-based)", "Target basis", options = ["R-multiple (risk-based)","ATR-multiple"], group = g3)
tM1M = input.float(1.0, "Target 1 (R or ATR×)", minval = 0.1, step = 0.1, group = g3)
tM2 = input.float(2.0, "Target 2 (R or ATR×)", minval = 0.1, step = 0.1, group = g3)
tM3 = input.float(3.0, "Target 3 (R or ATR×)", minval = 0.1, step = 0.1, group = g3)
g6 = "MTF alignment table"
showAlign = input.bool(true, "Show MTF alignment table", group = g6)
alignPos = input.string("Bottom Right", "Alignment table position", options = ["Top Right","Top Left","Bottom Right","Bottom Left","Middle Right"], group = g6)
alignSize = input.string("Small", "Alignment text size", options = ["Tiny","Small","Normal"], group = g6)
freshBars = input.int(2, "Fresh-flip = flipped within N bars", minval = 1, maxval = 20, group = g6, tooltip = "The Brk column lights up (✦) when that TF's Supertrend flipped within this many of its own bars — a FRESH flip — versus an ongoing trend.")
gM = "Extra timeframe supertrends — tick to overlay on this chart"
showMTF = input.bool(true, "Enable extra-TF lines", group = gM, tooltip = "Master switch for the tick-boxes below. Each ticked row draws that timeframe's Supertrend line on the current chart, coloured by its own trend (green up / red down) and tagged with its timeframe. Reference overlay only — not measured or traded by the primary engine above.")
enM1 = input.bool(false, "", inline = "m1", group = gM), tfM1 = input.timeframe("3", "TF", inline = "m1", group = gM)
enM2 = input.bool(false, "", inline = "m2", group = gM), tfM2 = input.timeframe("5", "TF", inline = "m2", group = gM)
enM3 = input.bool(false, "", inline = "m3", group = gM), tfM3 = input.timeframe("15", "TF", inline = "m3", group = gM)
enM4 = input.bool(false, "", inline = "m4", group = gM), tfM4 = input.timeframe("30", "TF", inline = "m4", group = gM)
enM5 = input.bool(false, "", inline = "m5", group = gM), tfM5 = input.timeframe("60", "TF", inline = "m5", group = gM)
enM6 = input.bool(false, "", inline = "m6", group = gM), tfM6 = input.timeframe("240", "TF", inline = "m6", group = gM)
g5 = "ATR envelope (optional — off by default)"
showEnv = input.bool(false, "Show ATR envelope (replaces dotted targets when on)", group = g5)
envLen = input.int(20, "Envelope smoothing (centre)", minval = 1, group = g5)
envM1 = input.float(1.5, "Inner band × ATR", minval = 0.1, step = 0.1, group = g5)
envM2 = input.float(3.0, "Outer band × ATR", minval = 0.1, step = 0.1, group = g5)
g4 = "Display"
showLine = input.bool(true, "Draw raw Supertrend line", group = g4)
colorBars = input.bool(false, "Colour bars by Supertrend trend", group = g4)
showPanel = input.bool(true, "Stats panel", group = g4)
panelPos = input.string("Top Right", "Stats panel position", options = ["Top Right","Top Left","Bottom Right","Bottom Left","Middle Right"], group = g4)
showEXP = input.bool(true, "Publish EXP_* outputs", group = g4)
themeOpt = input.string("Auto (match chart)", "Theme", options = ["Auto (match chart)","Dark","Light"], group = g4)
// ───────────────────────────── THEME / HELPERS ─────────────────────────────
f_lumaDark(color c) => na(c) ? true : (0.299*color.r(c)+0.587*color.g(c)+0.114*color.b(c)) < 140
bool isDark = themeOpt == "Dark" ? true : themeOpt == "Light" ? false : f_lumaDark(chart.bg_color)
color cUp = isDark ? #2dd4bf : #0e9e76
color cDn = isDark ? #ff6b78 : #c0392b
color cFlat = isDark ? #9aa3b2 : #8a93a0
color cAmb = isDark ? #e0a81f : #b7860b
color cUpDk = #0a4027
color cDnDk = #7a0d12
color tVal = isDark ? #f2f4f8 : #10151d
color tLbl = isDark ? #9aa3b2 : #515a67
color frameCl= isDark ? #3a4250 : #c2c8d0
color panelBg= isDark ? color.new(#0e131d,0) : color.new(#f4f6fa,0)
color rowAlt = isDark ? color.new(#141a26,0) : color.new(#e9edf3,0)
f_pos(string s) =>
switch s
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
"Middle Right" => position.middle_right
=> position.top_right
f_sz(string s) => s=="Tiny"?size.tiny : s=="Small"?size.small : s=="Normal"?size.normal : size.large
f_tfLabel(string t) => t=="D"?"D" : t=="W"?"W" : t=="60"?"1h" : t=="120"?"2h" : t=="240"?"4h" : t+"m"
f_tfThick(string t) =>
switch t
"1" => 0.5
"2" => 0.7
"3" => 0.9
"5" => 1.2
"15" => 1.8
"30" => 2.5
"60" => 3.4
"120" => 4.5
"240" => 6.0
"D" => 8.0
"W" => 10.0
=> 1.2
f_wilson(int w, int n) =>
float out = 0.0
if n > 0
float p = float(w) / float(n)
float z = 1.96
float denom = 1.0 + z*z/n
float centre = p + z*z/(2*n)
float margin = z * math.sqrt((p*(1.0-p) + z*z/(4*n)) / n)
out := (centre - margin) / denom
out
// ───────────────────────────── CALC TF (markers / stop) ────────────────────
string tf = tfOpt == "Chart" ? timeframe.period : tfOpt
string tfTag = f_tfLabel(tfOpt == "Chart" ? timeframe.period : tfOpt)
float tfF = f_tfThick(tfOpt == "Chart" ? timeframe.period : tfOpt)
int chartSec = timeframe.in_seconds(timeframe.period)
int calcSec = timeframe.in_seconds(tf)
float stepRatio = chartSec > 0 ? math.max(1.0, float(calcSec) / float(chartSec)) : 1.0
int effGrade = calcSec <= 1800 ? 5 : 4
int minQual = minQualM
int alignNeed = alignNeedM
string regimeMode = regimeModeM
string targetBasis = targetBasisM
float tM1 = tM1M
string stopMode = stopModeM
// The Supertrend engine. "Line" = the active Supertrend band ridden; a FLIP is a close through it.
f_calc() =>
float atrv = ta.atr(14)
[stL, stD] = ta.supertrend(stFactor, stAtrLen)
int d = stD < 0 ? 1 : -1
float prevL = stL[1]
float bufv = bufATR * nz(atrv, 0.0)
bool rawU = d == 1 and d[1] != 1 and (na(prevL) or close > prevL + bufv)
bool rawD = d == -1 and d[1] != -1 and (na(prevL) or close < prevL - bufv)
float line = stL
float volAvg = ta.sma(volume, 20)
bool hasVol = not na(volAvg) and volAvg > 0
float rngBar = math.max(high - low, syminfo.mintick)
bool volSurge = hasVol and volume > volAvg * 1.3
bool rangeExp = not na(atrv) and (high - low) > atrv * 1.5
float dispU = (na(atrv) or atrv<=0 or na(prevL)) ? 0.0 : (close - prevL) / atrv
float dispD = (na(atrv) or atrv<=0 or na(prevL)) ? 0.0 : (prevL - close) / atrv
int qU = (dispU > 0.25 ? 1:0) + ((close - low)/rngBar > 0.6 ? 1:0) + (volSurge?1:0) + (rangeExp?1:0) + (close > open ? 1:0)
int qD = (dispD > 0.25 ? 1:0) + ((high - close)/rngBar > 0.6 ? 1:0) + (volSurge?1:0) + (rangeExp?1:0) + (close < open ? 1:0)
var int bIn = 0
bIn := d == d[1] ? bIn + 1 : 0
float erCh = math.abs(close - close[erLen])
float erSum = math.sum(math.abs(close - close[1]), erLen)
float erv = erSum > 0 ? erCh / erSum : 0.0
[line, d, atrv, rawU ? 1 : 0, rawD ? 1 : 0, qU, qD, close, bIn, erv]
[sar, dir, atr, rU, rD, qU, qD, cPx, barsIn, er] = request.security(syminfo.tickerid, tf, f_calc(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
color trendCol = dir == 1 ? cUp : cDn
// ───────────────────────────── PER-TF STATE (alignment) ────────────────────
f_tf() =>
float atrv = ta.atr(14)
[stL, stD] = ta.supertrend(stFactor, stAtrLen)
int d = stD < 0 ? 1 : -1
float prevL = stL[1]
float volAvg = ta.sma(volume, 20)
bool hasVol = not na(volAvg) and volAvg > 0
float rngBar = math.max(high - low, syminfo.mintick)
bool volSurge = hasVol and volume > volAvg * 1.3
bool rangeExp = not na(atrv) and (high - low) > atrv * 1.5
float dispU = (na(atrv) or atrv<=0 or na(prevL)) ? 0.0 : (close - prevL) / atrv
float dispD = (na(atrv) or atrv<=0 or na(prevL)) ? 0.0 : (prevL - close) / atrv
int qU = (dispU > 0.25 ? 1:0) + ((close - low)/rngBar > 0.6 ? 1:0) + (volSurge?1:0) + (rangeExp?1:0) + (close > open ? 1:0)
int qD = (dispD > 0.25 ? 1:0) + ((high - close)/rngBar > 0.6 ? 1:0) + (volSurge?1:0) + (rangeExp?1:0) + (close < open ? 1:0)
bool flip = d != d[1]
var int gh = 0
if flip
gh := d == 1 ? qU : qD
var int bIn = 0
bIn := d == d[1] ? bIn + 1 : 0
[d, gh, bIn, stL]
// a tiny version for the extra-TF overlay lines (line + direction only)
f_st() =>
[stL, stD] = ta.supertrend(stFactor, stAtrLen)
int d = stD < 0 ? 1 : -1
[stL, d]
[ad1,ag1,ab1,as1] = request.security(syminfo.tickerid, "1", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad3,ag3,ab3,as3] = request.security(syminfo.tickerid, "3", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad5,ag5,ab5,as5] = request.security(syminfo.tickerid, "5", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad15,ag15,ab15,as15] = request.security(syminfo.tickerid, "15", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad30,ag30,ab30,as30] = request.security(syminfo.tickerid, "30", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad60,ag60,ab60,as60] = request.security(syminfo.tickerid, "60", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad120,ag120,ab120,as120] = request.security(syminfo.tickerid, "120", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[ad240,ag240,ab240,as240] = request.security(syminfo.tickerid, "240", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
[adD,agD,abD,asD] = request.security(syminfo.tickerid, "D", f_tf(), lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
// ───────────────────────────── REGIME ──────────────────────────────────────
int alignUp = (ad1==1?1:0)+(ad3==1?1:0)+(ad5==1?1:0)+(ad15==1?1:0)+(ad30==1?1:0)+(ad60==1?1:0)+(ad120==1?1:0)+(ad240==1?1:0)+(adD==1?1:0)
int alignDn = 9 - alignUp
bool regAlignL = alignUp >= alignNeed
bool regAlignS = alignDn >= alignNeed
bool regER = er >= erThresh
bool regLongOK = regimeMode=="Off" ? true : regimeMode=="HTF alignment" ? regAlignL : regimeMode=="Efficiency ratio" ? regER : (regAlignL and regER)
bool regShortOK = regimeMode=="Off" ? true : regimeMode=="HTF alignment" ? regAlignS : regimeMode=="Efficiency ratio" ? regER : (regAlignS and regER)
// ───────────────────────────── FLIP + GATES ────────────────────────────────
bool okBar = not confirmClose or barstate.isconfirmed
bool edgeUp = rU == 1 and (na(rU[1]) or rU[1] == 0)
bool edgeDn = rD == 1 and (na(rD[1]) or rD[1] == 0)
bool rawBrUp = okBar and edgeUp and qU >= minQual
bool rawBrDn = okBar and edgeDn and qD >= minQual
bool brUp = rawBrUp and regLongOK
bool brDn = rawBrDn and regShortOK
bool filteredUp = rawBrUp and not regLongOK
bool filteredDn = rawBrDn and not regShortOK
bool strongUp = brUp and qU >= ringQual
bool strongDn = brDn and qD >= ringQual
var int lastSide = 0
var int lastQual = 0
var int lastBar = na
if brUp
lastSide := 1
lastQual := qU
lastBar := bar_index
if brDn
lastSide := -1
lastQual := qD
lastBar := bar_index
// ───────────────────────────── TRADE PLAN (dynamic risk) ───────────────────
var int pSide = 0
var float pEntry = na
var float pStop = na
var float pT1 = na
var float pT2 = na
var float pT3 = na
var float pHH = na
var float pLL = na
bool newSig = brUp or brDn
if newSig
float sbuf = slBufATR * nz(atr, 0.0)
float initStop = brUp ? sar - sbuf : sar + sbuf
float r = math.abs(cPx - initStop)
float a = nz(atr, 0.0)
float u1 = targetBasis == "ATR-multiple" ? tM1 * a : tM1 * r
float u2 = targetBasis == "ATR-multiple" ? tM2 * a : tM2 * r
float u3 = targetBasis == "ATR-multiple" ? tM3 * a : tM3 * r
pSide := brUp ? 1 : -1
pEntry := cPx
pStop := initStop
pHH := high
pLL := low
pT1 := brUp ? cPx + u1 : cPx - u1
pT2 := brUp ? cPx + u2 : cPx - u2
pT3 := brUp ? cPx + u3 : cPx - u3
else
if pSide == 1
pHH := math.max(nz(pHH, high), high)
if dir == 1 and stopMode != "Fixed at entry line"
float tnew = stopMode == "Wider chandelier (× below)" ? pHH - planMult * nz(atr, 0.0) : sar
pStop := math.max(pStop, tnew)
if low <= pStop or dir == -1
pSide := 0
else if pSide == -1
pLL := math.min(nz(pLL, low), low)
if dir == -1 and stopMode != "Fixed at entry line"
float tnew = stopMode == "Wider chandelier (× below)" ? pLL + planMult * nz(atr, 0.0) : sar
pStop := math.min(pStop, tnew)
if high >= pStop or dir == 1
pSide := 0
string stopTag = stopMode == "Trail the Supertrend" ? "trail·ST" : stopMode == "Wider chandelier (× below)" ? "trail·wide" : "fixed·ST"
string tU = targetBasis == "ATR-multiple" ? "×ATR" : "R"
// ───────────────────────────── MEASURED-EDGE VALIDATION ────────────────────
var array<int> oStart = array.new<int>()
var array<int> oSide = array.new<int>()
var array<float> oEntry = array.new<float>()
var array<float> oR = array.new<float>()
var array<int> oGrade = array.new<int>()
var array<int> oNull = array.new<int>()
var array<float> oExt = array.new<float>()
var array<float> oTrl = array.new<float>()
var array<int> winCnt = array.new<int>(6, 0)
var array<int> totCnt = array.new<int>(6, 0)
var array<float> sumR = array.new<float>(6, 0.0)
var int nullTot = 0
var int nullWin = 0
var float nullSum = 0.0
var int fadeTot = 0
var int fadeWin = 0
var float fadeSum = 0.0
int valH = math.max(1, int(math.round(valHorizon * stepRatio)))
bool isTrail = exitModel == "Trailing tight" or exitModel == "Trailing wide"
float trailK = exitModel == "Trailing wide" ? 2.0 : 1.0
bool isFixed = exitModel == "Fixed 1.5R" or exitModel == "Fixed 2R"
float fixTgt = exitModel == "Fixed 2R" ? 2.0 : 1.5
if valOn and barstate.isconfirmed
if brUp or brDn
float atrE = nz(atr, 0.0)
float R0 = math.max(valATRk * atrE, syminfo.mintick)
if R0 > 0
int sSig = brUp ? 1 : -1
int gSig = brUp ? qU : qD
array.push(oStart, bar_index)
array.push(oSide, sSig)
array.push(oEntry, cPx)
array.push(oR, R0)
array.push(oGrade, gSig)
array.push(oNull, 0)
array.push(oExt, cPx)
array.push(oTrl, cPx - sSig * R0)
if nullOn
float xr = bar_index * 0.6180339887
int sNull = (xr - math.floor(xr)) < 0.5 ? 1 : -1
array.push(oStart, bar_index)
array.push(oSide, sNull)
array.push(oEntry, cPx)
array.push(oR, R0)
array.push(oGrade, gSig)
array.push(oNull, 1)
array.push(oExt, cPx)
array.push(oTrl, cPx - sNull * R0)
if fadeOn
int sFade = -sSig
array.push(oStart, bar_index)
array.push(oSide, sFade)
array.push(oEntry, cPx)
array.push(oR, R0)
array.push(oGrade, gSig)
array.push(oNull, 2)
array.push(oExt, cPx)
array.push(oTrl, cPx - sFade * R0)
int k = array.size(oStart) - 1
while k >= 0
int st = array.get(oStart, k)
int sd = array.get(oSide, k)
float en = array.get(oEntry, k)
float R0 = array.get(oR, k)
int gr = array.get(oGrade, k)
int isN = array.get(oNull, k)
float ext = array.get(oExt, k)
float trl = array.get(oTrl, k)
int elapsed = bar_index - st
bool resolved = false
bool counted = true
float rR = 0.0
if elapsed >= 1
if isTrail
ext := sd == 1 ? math.max(ext, high) : math.min(ext, low)
float newTrl = sd == 1 ? ext - trailK * R0 : ext + trailK * R0
trl := sd == 1 ? math.max(trl, newTrl) : math.min(trl, newTrl)
array.set(oExt, k, ext)
array.set(oTrl, k, trl)
bool hit = sd == 1 ? low <= trl : high >= trl
if hit
resolved := true
rR := (trl - en) / R0 * sd
else if elapsed >= valH
resolved := true
rR := (close - en) / R0 * sd
else if isFixed
float tgt = sd == 1 ? en + fixTgt * R0 : en - fixTgt * R0
float stp = sd == 1 ? en - R0 : en + R0
bool hitT = sd == 1 ? high >= tgt : low <= tgt
bool hitS = sd == 1 ? low <= stp : high >= stp
if hitT and hitS
resolved := true
counted := false
else if hitT
resolved := true
rR := fixTgt
else if hitS
resolved := true
rR := -1.0
else if elapsed >= valH
resolved := true
rR := (close - en) / R0 * sd
else
if elapsed >= valH
resolved := true
rR := (close - en) / R0 * sd
if resolved
if counted
if isN == 1
nullTot := nullTot + 1
nullSum := nullSum + rR
nullWin := nullWin + (rR > 0 ? 1 : 0)
else if isN == 2
fadeTot := fadeTot + 1
fadeSum := fadeSum + rR
fadeWin := fadeWin + (rR > 0 ? 1 : 0)
else
int gi = math.min(5, math.max(0, gr))
array.set(totCnt, gi, array.get(totCnt, gi) + 1)
array.set(sumR, gi, array.get(sumR, gi) + rR)
if rR > 0
array.set(winCnt, gi, array.get(winCnt, gi) + 1)
array.remove(oStart, k)
array.remove(oSide, k)
array.remove(oEntry, k)
array.remove(oR, k)
array.remove(oGrade, k)
array.remove(oNull, k)
array.remove(oExt, k)
array.remove(oTrl, k)
k := k - 1
// ───────────────────────────── TREND RIBBON + LINE ─────────────────────────
float atrLoc = ta.atr(14)
int smoothLen = autoSmooth ? math.min(2000, math.max(ribSmooth, int(math.round(stepRatio * smoothStrength)))) : ribSmooth
float sarRib = ta.ema(ta.ema(sar, smoothLen), math.max(2, int(smoothLen / 2)))
float hw = ribBaseATR * nz(atrLoc, 0.0) * tfF * ribWidthMult
int ribDir = lastSide != 0 ? lastSide : dir
bool up = ribDir == 1
color cHi = ribColor == "Gold" ? #f6d55c : ribColor == "Blue" ? #7cc0f5 : (up ? #7ff0e0 : #ffb3ba)
color cBody = ribColor == "Gold" ? #d4a017 : ribColor == "Blue" ? #2a7fd4 : (up ? #2dd4bf : #ff6b78)
color cDk = ribColor == "Gold" ? #9c7314 : ribColor == "Blue" ? #154e94 : (up ? #0c8f7f : #a62f24)
color cSheen = ribGloss ? cHi : cBody
color cBase = ribGloss ? cDk : cBody
p_g0 = plot(ribbonOn ? sarRib + hw * 1.3 : na, "rib glow+", color = na)
p_t = plot(ribbonOn ? sarRib + hw : na, "rib top", color = na)
p_u = plot(ribbonOn ? sarRib + hw * 0.5 : na, "rib upper", color = na)
p_m = plot(ribbonOn ? sarRib : na, "rib mid", color = na)
p_d = plot(ribbonOn ? sarRib - hw * 0.5 : na, "rib lower", color = na)
p_b = plot(ribbonOn ? sarRib - hw : na, "rib bot", color = na)
p_g1 = plot(ribbonOn ? sarRib - hw * 1.5 : na, "rib shadow",color = na)
fill(p_g0, p_t, color = (ribbonOn and ribGlow) ? color.new(cHi, 86) : na, title = "Glow top")
fill(p_t, p_u, color = ribbonOn ? color.new(cSheen, 40) : na, title = "Sheen")
fill(p_u, p_m, color = ribbonOn ? color.new(cBody, 26) : na, title = "Body upper")
fill(p_m, p_d, color = ribbonOn ? color.new(cBody, 15) : na, title = "Body lower")
fill(p_d, p_b, color = ribbonOn ? color.new(cBase, 20) : na, title = "Base")
fill(p_b, p_g1, color = (ribbonOn and ribGlow) ? color.new(cDk, 82) : na, title = "Drop shadow")
plot(ribbonOn ? sarRib : na, "rib core", color = ribbonOn ? color.new(cBody, 0) : na, linewidth = coreWidth, style = plot.style_line)
var label rLab = na
if ribbonOn and ribLabel and barstate.islast
if na(rLab)
rLab := label.new(bar_index, sarRib, "", xloc = xloc.bar_index, style = label.style_label_left, size = size.small)
label.set_xy(rLab, bar_index + 2, sarRib)
label.set_text(rLab, tfTag)
label.set_color(rLab, color.new(cBody, 10))
label.set_textcolor(rLab, color.white)
plot(showLine ? sar : na, "Supertrend", color = color.new(trendCol, 0), linewidth = 2, style = plot.style_stepline)
barcolor(colorBars ? color.new(trendCol, 40) : na, title = "Supertrend bars")
float envC = ta.ema(close, envLen)
p_u2 = plot(showEnv ? envC + envM2 * atrLoc : na, "Env +outer", color = color.new(cDn, 55), linewidth = 1)
p_u1 = plot(showEnv ? envC + envM1 * atrLoc : na, "Env +inner", color = color.new(cDn, 70), linewidth = 1)
p_l1 = plot(showEnv ? envC - envM1 * atrLoc : na, "Env -inner", color = color.new(cUp, 70), linewidth = 1)
p_l2 = plot(showEnv ? envC - envM2 * atrLoc : na, "Env -outer", color = color.new(cUp, 55), linewidth = 1)
fill(p_u1, p_u2, color = showEnv ? color.new(cDn, 90) : na, title = "Upper zone")
fill(p_l1, p_l2, color = showEnv ? color.new(cUp, 90) : na, title = "Lower zone")
// ── EXTRA TIMEFRAME SUPERTRENDS (tick-boxes) — each ticked TF's line, coloured by its trend ──
[mL1,mD1] = request.security(syminfo.tickerid, tfM1, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
[mL2,mD2] = request.security(syminfo.tickerid, tfM2, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
[mL3,mD3] = request.security(syminfo.tickerid, tfM3, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
[mL4,mD4] = request.security(syminfo.tickerid, tfM4, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
[mL5,mD5] = request.security(syminfo.tickerid, tfM5, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
[mL6,mD6] = request.security(syminfo.tickerid, tfM6, f_st(), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
bool M1 = showMTF and enM1
bool M2 = showMTF and enM2
bool M3 = showMTF and enM3
bool M4 = showMTF and enM4
bool M5 = showMTF and enM5
bool M6 = showMTF and enM6
plot(M1?mL1:na, "MTF1 ST", color = M1?(mD1>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=1, style=plot.style_stepline)
plot(M2?mL2:na, "MTF2 ST", color = M2?(mD2>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=1, style=plot.style_stepline)
plot(M3?mL3:na, "MTF3 ST", color = M3?(mD3>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=1, style=plot.style_stepline)
plot(M4?mL4:na, "MTF4 ST", color = M4?(mD4>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=1, style=plot.style_stepline)
plot(M5?mL5:na, "MTF5 ST", color = M5?(mD5>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=2, style=plot.style_stepline)
plot(M6?mL6:na, "MTF6 ST", color = M6?(mD6>0?color.new(cUp,20):color.new(cDn,20)):na, linewidth=2, style=plot.style_stepline)
var label lM1=na, var label lM2=na, var label lM3=na, var label lM4=na, var label lM5=na, var label lM6=na
if barstate.islast
label.delete(lM1), label.delete(lM2), label.delete(lM3), label.delete(lM4), label.delete(lM5), label.delete(lM6)
lM1 := M1 ? label.new(bar_index, mL1, tfM1, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD1>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
lM2 := M2 ? label.new(bar_index, mL2, tfM2, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD2>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
lM3 := M3 ? label.new(bar_index, mL3, tfM3, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD3>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
lM4 := M4 ? label.new(bar_index, mL4, tfM4, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD4>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
lM5 := M5 ? label.new(bar_index, mL5, tfM5, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD5>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
lM6 := M6 ? label.new(bar_index, mL6, tfM6, xloc=xloc.bar_index, style=label.style_label_left, color=color.new(mD6>0?cUp:cDn,20), textcolor=color.white, size=size.small) : na
// ───────────────────────────── FLIP MARKERS ────────────────────────────────
if brUp
string t = markerDetail == "Arrow only" ? "▲" : markerDetail == "Short" ? "▲" + str.tostring(qU) : markerDetail == "Compact (grade+TF)" ? "▲" + str.tostring(qU) + "·" + tfTag : "▲ flip " + str.tostring(qU) + "/5 · " + tfTag
bool hiU = autoOpt and qU >= effGrade
label.new(bar_index, low, (strongUp ? "◉ " : "") + t, yloc = yloc.belowbar, style = label.style_label_up, color = hiU ? color.new(cAmb, 0) : color.new(cUp, 0), textcolor = cUpDk, size = f_sz(arrowSize))
if brDn
string t = markerDetail == "Arrow only" ? "▼" : markerDetail == "Short" ? "▼" + str.tostring(qD) : markerDetail == "Compact (grade+TF)" ? "▼" + str.tostring(qD) + "·" + tfTag : "▼ flip " + str.tostring(qD) + "/5 · " + tfTag
bool hiD = autoOpt and qD >= effGrade
label.new(bar_index, high, (strongDn ? "◉ " : "") + t, yloc = yloc.abovebar, style = label.style_label_down, color = hiD ? color.new(cAmb, 0) : color.new(cDn, 0), textcolor = cDnDk, size = f_sz(arrowSize))
if showFiltered and filteredUp
label.new(bar_index, low, "ctx ▲" + str.tostring(qU), yloc = yloc.belowbar, style = label.style_label_up, color = color.new(cFlat, 60), textcolor = color.new(color.white, 20), size = size.tiny)
if showFiltered and filteredDn
label.new(bar_index, high, "ctx ▼" + str.tostring(qD), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(cFlat, 60), textcolor = color.new(color.white, 20), size = size.tiny)
// ───────────────────────────── PLAN LINES (entry / stop / targets) ─────────
var line plE = na
var line plS = na
var line plT1 = na
var line plT2 = na
var line plT3 = na
var label plEl = na
var label plSl = na
var label plT1l = na
var label plT2l = na
var label plT3l = na
f_pl(line ln, label lb, float y, string txt, color c, bool on) =>
line.set_xy1(ln, bar_index, y)
line.set_xy2(ln, bar_index + 8, y)
line.set_color(ln, (on and not na(y)) ? color.new(c, 10) : color.new(c, 100))
label.set_xy(lb, bar_index + 8, y)
label.set_text(lb, (on and not na(y)) ? txt : "")
label.set_textcolor(lb, c)
bool showTgtLines = showPlan and not showEnv
if showPlan and barstate.islast
if na(plE)
plE := line.new(bar_index, close, bar_index+8, close, xloc=xloc.bar_index, width=2)
plS := line.new(bar_index, close, bar_index+8, close, xloc=xloc.bar_index, style=line.style_dashed)
plT1 := line.new(bar_index, close, bar_index+8, close, xloc=xloc.bar_index, style=line.style_dotted)
plT2 := line.new(bar_index, close, bar_index+8, close, xloc=xloc.bar_index, style=line.style_dotted)
plT3 := line.new(bar_index, close, bar_index+8, close, xloc=xloc.bar_index, style=line.style_dotted)
plEl := label.new(bar_index+8, close, "", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.gray,100), size=size.small)
plSl := label.new(bar_index+8, close, "", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.gray,100), size=size.small)
plT1l := label.new(bar_index+8, close, "", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.gray,100), size=size.small)
plT2l := label.new(bar_index+8, close, "", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.gray,100), size=size.small)
plT3l := label.new(bar_index+8, close, "", xloc=xloc.bar_index, style=label.style_label_left, color=color.new(color.gray,100), size=size.small)
bool on = pSide != 0
color ec = pSide==1 ? cUp : pSide==-1 ? cDn : cFlat
f_pl(plE, plEl, on?pEntry:na, "ENTRY " + str.tostring(pEntry, format.mintick), ec, on)
f_pl(plS, plSl, on?pStop:na, "STOP " + str.tostring(pStop, format.mintick) + " (" + stopTag + ")", cDn, on)
f_pl(plT1, plT1l, (on and showTgtLines)?pT1:na, "T1 " + str.tostring(pT1, format.mintick) + " (" + str.tostring(tM1, "#.#") + tU + ")", cUp, on and showTgtLines)
f_pl(plT2, plT2l, (on and showTgtLines)?pT2:na, "T2 " + str.tostring(pT2, format.mintick) + " (" + str.tostring(tM2, "#.#") + tU + ")", cUp, on and showTgtLines)
f_pl(plT3, plT3l, (on and showTgtLines)?pT3:na, "T3 " + str.tostring(pT3, format.mintick) + " (" + str.tostring(tM3, "#.#") + tU + ")", cUp, on and showTgtLines)
// ───────────────────────────── STATS PANEL ─────────────────────────────────
f_row(table t, int r, string k, string v, color vc, color bg) =>
table.cell(t, 0, r, k, text_color = tLbl, text_size = size.tiny, text_halign = text.align_left, bgcolor = bg)
table.cell(t, 1, r, v, text_color = vc, text_size = size.tiny, text_halign = text.align_right, bgcolor = bg)
var table pnl = na
if showPanel and barstate.islast
if na(pnl)
pnl := table.new(f_pos(panelPos), 2, 7, border_width = 1, frame_color = frameCl, frame_width = 1)
table.clear(pnl, 0, 0, 1, 6)
table.cell(pnl, 0, 0, " ST · " + tfTag, text_color = color.white, text_size = size.small, text_halign = text.align_left, bgcolor = color.new(trendCol,0))
table.cell(pnl, 1, 0, dir==1?"UPTREND":"DOWNTREND", text_color = color.white, text_size = size.small, text_halign = text.align_right, bgcolor = color.new(trendCol,0))
f_row(pnl, 1, "Supertrend", str.tostring(sar, format.mintick), trendCol, rowAlt)
f_row(pnl, 2, "Bars in trend", str.tostring(barsIn), tVal, panelBg)
string lastTxt = lastSide==0 ? "—" : (lastSide==1?"▲ up":"▼ down") + " · g" + str.tostring(lastQual) + "/5" + (na(lastBar)?"":" · "+str.tostring(bar_index-lastBar)+"b")
f_row(pnl, 3, "Last flip", lastTxt, lastSide==1?cUp:lastSide==-1?cDn:tVal, rowAlt)
string planTxt = pSide==0 ? "—" : (pSide==1?"LONG":"SHORT") + " · " + str.tostring(pStop, format.mintick) + " · " + stopTag
f_row(pnl, 4, "Active plan", planTxt, pSide>0?cUp:pSide<0?cDn:tVal, panelBg)
string regTxt = regimeMode=="Off" ? "off (all flips)" : (regLongOK?"TREND ↑":regShortOK?"TREND ↓":"RANGE — hold") + " · " + str.tostring(alignUp) + "/9" + (regimeMode=="HTF alignment" ? "" : " · ER " + str.tostring(er, "#.##"))
color regCol = regimeMode=="Off" ? tVal : regLongOK ? cUp : regShortOK ? cDn : cAmb
f_row(pnl, 5, "Regime", regTxt, regCol, rowAlt)
string autoTxt = autoOpt ? ("ON · halo grade ≥ " + str.tostring(effGrade) + " (visual)") : "off"
f_row(pnl, 6, "Highlight", autoTxt, autoOpt ? cAmb : tLbl, panelBg)
// ───────────────── MTF TABLE (bottom-right, 9 TF): STATE + EVENT ────────────
var table atbl = na
if showAlign and barstate.islast
if na(atbl)
atbl := table.new(f_pos(alignPos), 6, 11, border_width = 1, frame_color = frameCl, frame_width = 1)
array<int> dirs = array.from(ad1, ad3, ad5, ad15, ad30, ad60, ad120, ad240, adD)
array<int> grs = array.from(ag1, ag3, ag5, ag15, ag30, ag60, ag120, ag240, agD)
array<int> brs = array.from(ab1, ab3, ab5, ab15, ab30, ab60, ab120, ab240, abD)
array<float> sars = array.from(as1, as3, as5, as15, as30, as60, as120, as240, asD)
array<string> nms = array.from("1m","3m","5m","15m","30m","1h","2h","4h","1D")
color biasCol = alignUp >= 7 ? cUp : alignUp <= 2 ? cDn : cFlat
string biasTxt = alignUp >= 7 ? "ALIGNED ↑" : alignUp <= 2 ? "ALIGNED ↓" : "MIXED"
table.cell(atbl, 0, 0, "TF", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(atbl, 1, 0, "Trend", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(atbl, 2, 0, "Grd", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(atbl, 3, 0, "Brk", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(atbl, 4, 0, "Bars", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(atbl, 5, 0, "Line", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
for i = 0 to 8
int dd = array.get(dirs, i)
int gg = array.get(grs, i)
int bb = array.get(brs, i)
float sv = array.get(sars, i)
string nm = array.get(nms, i)
color dc = dd == 1 ? cUp : cDn
color bg = i % 2 == 0 ? panelBg : rowAlt
bool fresh = bb <= freshBars
table.cell(atbl, 0, i+1, nm, text_color = tVal, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = bg)
table.cell(atbl, 1, i+1, dd == 1 ? "▲" : "▼", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(dc, 0))
table.cell(atbl, 2, i+1, str.tostring(gg), text_color = tVal, text_size = f_sz(alignSize), bgcolor = bg)
table.cell(atbl, 3, i+1, fresh ? "✦" + str.tostring(gg) : "•", text_color = fresh ? color.white : color.new(dc, 0), text_size = f_sz(alignSize), bgcolor = fresh ? color.new(dc, 0) : bg)
table.cell(atbl, 4, i+1, str.tostring(bb), text_color = tLbl, text_size = f_sz(alignSize), bgcolor = bg)
table.cell(atbl, 5, i+1, na(sv) ? "—" : str.tostring(sv, format.mintick), text_color = dc, text_size = f_sz(alignSize), text_halign = text.align_right, bgcolor = bg)
table.cell(atbl, 0, 10, biasTxt, text_color = color.white, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = color.new(biasCol, 0))
table.cell(atbl, 1, 10, "", bgcolor = color.new(biasCol, 0))
table.cell(atbl, 2, 10, "", bgcolor = color.new(biasCol, 0))
table.cell(atbl, 3, 10, "↑" + str.tostring(alignUp), text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(cUp, 0))
table.cell(atbl, 4, 10, "↓" + str.tostring(alignDn), text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(cDn, 0))
table.cell(atbl, 5, 10, "", bgcolor = color.new(biasCol, 0))
// ───────────────────────────── MEASURED-EDGE TABLE ─────────────────────────
f_rCol(float r, int n) => n < 5 ? cFlat : r > 0.05 ? cUp : r < -0.05 ? cDn : cAmb
var table vtbl = na
if valOn and showEdge and barstate.islast
if na(vtbl)
vtbl := table.new(f_pos(valPos), 4, 10, border_width = 1, frame_color = frameCl, frame_width = 1)
table.cell(vtbl, 0, 0, "Grade", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(vtbl, 1, 0, "Win%", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(vtbl, 2, 0, "net R", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(vtbl, 3, 0, "n", text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
int totW = 0
int totN = 0
float totR = 0.0
for g = 5 to 1
int w = array.get(winCnt, g)
int n = array.get(totCnt, g)
float sr = array.get(sumR, g)
totW := totW + w
totN := totN + n
totR := totR + sr
float lb = f_wilson(w, n) * 100.0
float ar = n > 0 ? sr / n : 0.0
color lc = n < 5 ? cFlat : lb >= 50 ? cUp : lb >= 40 ? cAmb : cDn
int rr = 6 - g
color bg = g % 2 == 0 ? panelBg : rowAlt
table.cell(vtbl, 0, rr, "g" + str.tostring(g), text_color = tVal, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = bg)
table.cell(vtbl, 1, rr, n > 0 ? str.tostring(lb, "#") + "%" : "—", text_color = lc, text_size = f_sz(alignSize), bgcolor = bg)
float netg = ar - costR
table.cell(vtbl, 2, rr, n > 0 ? (netg >= 0 ? "+" : "") + str.tostring(netg, "0.00") : "—", text_color = f_rCol(netg, n), text_size = f_sz(alignSize), bgcolor = bg)
table.cell(vtbl, 3, rr, str.tostring(n), text_color = tLbl, text_size = f_sz(alignSize), bgcolor = bg)
float lbAll = f_wilson(totW, totN) * 100.0
float arAll = totN > 0 ? totR / totN : 0.0
color lcAll = totN < 5 ? cFlat : lbAll >= 50 ? cUp : lbAll >= 40 ? cAmb : cDn
table.cell(vtbl, 0, 6, "ALL", text_color = color.white, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = color.new(#2a3340,0))
table.cell(vtbl, 1, 6, totN > 0 ? str.tostring(lbAll, "#") + "%" : "—", text_color = lcAll, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
float netAll = arAll - costR
table.cell(vtbl, 2, 6, totN > 0 ? (netAll >= 0 ? "+" : "") + str.tostring(netAll, "0.00") : "—", text_color = f_rCol(netAll, totN), text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
table.cell(vtbl, 3, 6, str.tostring(totN), text_color = color.white, text_size = f_sz(alignSize), bgcolor = color.new(#2a3340,0))
float arNull = nullTot > 0 ? nullSum / nullTot : 0.0
float lbNull = f_wilson(nullWin, nullTot) * 100.0
table.cell(vtbl, 0, 7, "NULL", text_color = tLbl, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = rowAlt)
table.cell(vtbl, 1, 7, nullTot > 0 ? str.tostring(lbNull, "#") + "%" : "—", text_color = tLbl, text_size = f_sz(alignSize), bgcolor = rowAlt)
float netNull = arNull - costR
table.cell(vtbl, 2, 7, nullTot > 0 ? (netNull >= 0 ? "+" : "") + str.tostring(netNull, "0.00") : "—", text_color = f_rCol(netNull, nullTot), text_size = f_sz(alignSize), bgcolor = rowAlt)
table.cell(vtbl, 3, 7, str.tostring(nullTot), text_color = tLbl, text_size = f_sz(alignSize), bgcolor = rowAlt)
float arFade = fadeTot > 0 ? fadeSum / fadeTot : 0.0
float lbFade = f_wilson(fadeWin, fadeTot) * 100.0
table.cell(vtbl, 0, 8, "FADE", text_color = tLbl, text_size = f_sz(alignSize), text_halign = text.align_left, bgcolor = panelBg)
table.cell(vtbl, 1, 8, fadeTot > 0 ? str.tostring(lbFade, "#") + "%" : "—", text_color = tLbl, text_size = f_sz(alignSize), bgcolor = panelBg)
float netFade = arFade - costR
table.cell(vtbl, 2, 8, fadeTot > 0 ? (netFade >= 0 ? "+" : "") + str.tostring(netFade, "0.00") : "—", text_color = f_rCol(netFade, fadeTot), text_size = f_sz(alignSize), bgcolor = panelBg)
table.cell(vtbl, 3, 8, str.tostring(fadeTot), text_color = tLbl, text_size = f_sz(alignSize), bgcolor = panelBg)
string mdlTxt = exitModel + " · " + str.tostring(valHorizon) + "b · cost " + str.tostring(costR, "0.00") + "R"
table.cell(vtbl, 0, 9, mdlTxt, text_color = tLbl, text_size = size.tiny, text_halign = text.align_left, bgcolor = rowAlt)
table.cell(vtbl, 1, 9, "", bgcolor = rowAlt)
table.cell(vtbl, 2, 9, "", bgcolor = rowAlt)
table.cell(vtbl, 3, 9, "", bgcolor = rowAlt)
// ───────────────────────────── EXPORTS ─────────────────────────────────────
plot(showEXP ? sar : na, "EXP_Stop", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? dir : na, "EXP_Dir", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? (brUp?qU:brDn?-qD:0) : na, "EXP_Break", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? (pSide!=0 ? pStop : na) : na, "EXP_TradeStop", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? alignUp : na, "EXP_AlignUp", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? er : na, "EXP_ER", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? (brUp ? 1 : brDn ? -1 : 0) : na, "EXP_BreakDir", color = color.new(color.gray,100), display = display.data_window)
// ───────────────────────────── ALERTS ──────────────────────────────────────
alertcondition(brUp, "Armed flip UP", "ST-BO: regime-armed Supertrend flip UP (bullish)")
alertcondition(brDn, "Armed flip DOWN", "ST-BO: regime-armed Supertrend flip DOWN (bearish)")
alertcondition(strongUp, "Strong flip UP", "ST-BO: strong (graded) armed flip UP")
alertcondition(strongDn, "Strong flip DOWN","ST-BO: strong (graded) armed flip DOWN")