本页源码来自 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/
// =============================================================================
// TURTLE BREAKOUT — Donchian Channel · Graded · 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 Donchian channel read as a breakout engine (the classic Turtle system). A confirmed
// close BEYOND the prior N-bar high is a bullish BREAK; beyond the prior N-bar low, a bearish
// one. Each break is GRADED 0–5 on how convincing the breaking bar was, drawn with a flowing
// trend ribbon, and carries an Entry · Stop · Target plan whose trailing stop is the turtle
// EXIT channel. Two things make it more than a visual:
// • REGIME GATE — a breakout is a trend trigger; it bleeds in chop. Breaks only ARM when the
// market is trending (higher-TF alignment and/or a Kaufman efficiency ratio). Out-of-regime
// breaks are shown faint as context, not traded.
// • MEASURED EDGE — every armed break is forward-resolved, past-only, under the chosen exit
// model (a trailing channel/chandelier ride that records the R captured, or a fixed ±ATR
// barrier). 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.
//
// THE "LINE" AND THE "BREAK"
// • Entry channel = highest-high / lowest-low of the last N bars (default 20 = turtle entry).
// A break = a confirmed close beyond the PRIOR bar's channel edge (+ optional ATR buffer).
// • The trend line that is drawn and ridden = the EXIT channel (default 10 = turtle exit):
// the lowest-low in an uptrend / highest-high in a downtrend. This is the trailing stop.
//
// HOW THE GRADE IS BUILT (transparent — one point each, on the breaking bar)
// (1) displacement > 0.25 ATR past the broken channel edge; (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 break's direction. 0 = limp break, 5 = decisive thrust.
//
// WHAT THE PANEL TENDS TO SHOW (in-sample — verify on YOUR market)
// On the engine's own measured-edge table, LOW-timeframe breakouts (roughly 1–5m) tend to LOSE and
// even lose to the random null — they get whipsawed, and fading pays more. The edge only appears on
// HIGHER timeframes (about 1h / 4h / 1D), where the breakout turns net-positive and beats the null,
// consistent with the original Turtle being a higher-timeframe method. The 0–5 GRADE rates how
// decisive the breaking bar looked; it does NOT reliably predict the outcome, so read it as visual
// context, not a quality score. The tool SHOWS you all of this — read the table before trusting a
// setup, and prefer higher timeframes for the with-trend breakout.
//
// 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 channel lengths, and measure.
//
// EVIDENCE & CONCEPT CREDITS (techniques operationalised here — not third-party code)
// Donchian channel — Richard Donchian. Turtle breakout system — Dennis & Eckhardt. ATR &
// Chandelier exit — J. W. Wilder / 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 and the per-grade edge measurement are this
// script's own synthesis.
//
// NON-REPAINT / DISCLAIMER
// Research & education only. NOT financial advice, NOT a recommendation, NOT a guarantee, NO
// performance promise. Breaks 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 channel; all signals run on the raw channel.
// Trading carries risk of loss.
// =============================================================================
//@version=6
indicator("Turtle Breakout — Donchian Channel, Graded & Edge-Measured", "TURTLE-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 · Auto-optimizer (visual highlight)"
autoOpt = input.bool(false, "Highlight decisive-looking breaks (visual only)", group = gAuto, tooltip = "OFF by default. When ON, draws a soft amber HALO around the higher-grade breaks (grade 5 intraday / grade 4 on 1h+). This is PURELY VISUAL and changes no signal. IMPORTANT: 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. Read the table, not the halo.")
g1 = "Donchian / Turtle channel"
donLen = input.int(20, "Entry channel length (breakout)", minval = 2, maxval = 500, group = g1, tooltip = "A break triggers when price closes beyond the highest-high / lowest-low of the prior N bars. Classic turtle entry = 20.")
exitLen = input.int(10, "Exit / trail channel length", minval = 2, maxval = 500, group = g1, tooltip = "The trailing line that is drawn and ridden: the lowest-low (uptrend) / highest-high (downtrend) of the last N bars. Classic turtle exit = 10. This is the 'trend line' of this tool.")
g2 = "Breaks"
confirmClose = input.bool(true, "Confirm breaks on bar close (non-repaint)", group = g2)
bufATR = input.float(0.0, "Break buffer beyond channel (× 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 breaks 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 break 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 = ▲ break 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 breaks when trending. HTF alignment = require N of 9 TFs to agree with the break. Efficiency ratio = Kaufman ER on the calc TF above a threshold. Set Off to trade every graded break (any asset).")
alignNeedM = input.int(2, "HTF alignment: TFs that must agree (of 9)", minval = 1, maxval = 9, group = gReg, tooltip = "A long break needs ≥ this many of the 9 TFs bullish; a short break 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 breaks 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 break, run a past-only triple-barrier test: did price reach +1R (target) before −1R (stop) within the horizon? Accumulates a win-rate per grade bucket and reports the Wilson lower bound (an honest small-sample floor). 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","External line"], group = gVal, tooltip = "Scores every break under ONE exit — switch between them and watch net R vs the NULL to find the exit that converts the entry edge into profit. Trailing tight = chandelier trail at 1R. Trailing wide = 2R trail (lets trends run). Fixed 1.5R / 2R = target in R, stop 1R. Time exit = hold to the horizon (pure directional drift). External line = ride until price closes back through the wired External SL line.")
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) expressed in R, subtracted from avg R to show the NET figure. The signal-vs-null LIFT is cost-independent (cost cancels); NET tells you if it actually pays after costs.")
gExt = "External feed (other engine's SL / bias)"
extSLsrc = input.source(close, "External SL line (wire another engine's stop)", group = gExt, tooltip = "Wire another engine's stop line here (its data-window stop output). Used three ways: (1) as the live trade stop when 'Use external SL' is on; (2) by the 'External line' exit model in the edge table; (3) as the bias when 'Trade only aligned' is on. Left as 'close' it stays inactive and the script behaves as standard Donchian.")
useExtSL = input.bool(false, "Use external SL as the trade stop (else internal channel trail)", group = gExt, tooltip = "ON = the trade's stop / exit follows the wired external SL line instead of the internal channel / chandelier trail. OFF (default) = standard Donchian behaviour.")
useExtAlign = input.bool(false, "Trade only when aligned to the external SL side", group = gExt, tooltip = "ON = a long arms only when price is ABOVE the external SL, a short only when BELOW it. Requires the SL wired. OFF (default) = no external gating.")
nullOn = input.bool(true, "Random-direction null baseline", group = gVal, tooltip = "For every break, 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, not the signal.")
fadeOn = input.bool(true, "Fade (anti-signal) baseline", group = gVal, tooltip = "For every break, also books the OPPOSITE direction (same exit model) — i.e. fading the break. 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 break)", "Ribbon colour", options = ["Trend (green/red by break)","Blue","Gold"], group = gR, tooltip = "Trend = GREEN after a bullish break, RED after a bearish break (holds until the next break). 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 — lags vs the raw channel, but signals/stop stay on the raw channel.")
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 channel", "Stop mode", options = ["Trail the channel","Fixed at entry channel","Chandelier (ATR trail)"], group = g3, tooltip = "Trail the channel = dynamic stop riding the turtle exit channel (ratchets only in your favour). Fixed = stays at the entry-bar channel. Chandelier = highest-high − ATR×.")
slBufATR = input.float(0.1, "Initial stop buffer beyond channel (× ATR)", minval = 0.0, maxval = 1.0, step = 0.05, group = g3)
chMult = input.float(3.0, "Chandelier ATR ×", minval = 0.5, maxval = 10.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-break = flipped within N bars", minval = 1, maxval = 20, group = g6, tooltip = "The Brk column lights up (✦) when that TF's channel direction flipped within this many of its own bars — a FRESH break — versus an ongoing trend. Trend = state, Brk = event.")
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"
showChan = input.bool(true, "Draw Donchian entry channel (upper/lower)", group = g4)
showLine = input.bool(false, "Draw raw trail line (channel)", group = g4)
colorBars = input.bool(false, "Colour bars by channel 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
// Wilson score interval, lower bound (95%, z=1.96) — honest small-sample floor for a win rate
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 Donchian / Turtle engine. "Line" = the exit channel ridden; breaks = close beyond the
// PRIOR entry-channel edge. Direction is a persistent state that flips on each breakout.
f_calc() =>
float atrv = ta.atr(14)
float up = ta.highest(high, donLen)
float lo = ta.lowest(low, donLen)
float upPrev = up[1]
float loPrev = lo[1]
float exLo = ta.lowest(low, exitLen)
float exHi = ta.highest(high, exitLen)
float bufv = bufATR * nz(atrv, 0.0)
bool bU = not na(upPrev) and close > upPrev + bufv
bool bD = not na(loPrev) and close < loPrev - bufv
var int d = 0
d := bU ? 1 : bD ? -1 : d
bool rawU = d == 1 and d[1] != 1
bool rawD = d == -1 and d[1] != -1
float line = d == 1 ? exLo : d == -1 ? exHi : (up + lo) / 2.0
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(upPrev)) ? 0.0 : (close - upPrev) / atrv
float dispD = (na(atrv) or atrv<=0 or na(loPrev)) ? 0.0 : (loPrev - 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, up, lo]
[sar, dir, atr, rU, rD, qU, qD, cPx, barsIn, er, dcUp, dcLo] = 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)
float up = ta.highest(high, donLen)
float lo = ta.lowest(low, donLen)
float upPrev = up[1]
float loPrev = lo[1]
float exLo = ta.lowest(low, exitLen)
float exHi = ta.highest(high, exitLen)
bool bU = not na(upPrev) and close > upPrev
bool bD = not na(loPrev) and close < loPrev
var int d = 0
d := bU ? 1 : bD ? -1 : d
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(upPrev)) ? 0.0 : (close - upPrev) / atrv
float dispD = (na(atrv) or atrv<=0 or na(loPrev)) ? 0.0 : (loPrev - 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
float line = d == 1 ? exLo : d == -1 ? exHi : (up + lo) / 2.0
[d, gh, bIn, line]
[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 regLongOK0 = regimeMode=="Off" ? true : regimeMode=="HTF alignment" ? regAlignL : regimeMode=="Efficiency ratio" ? regER : (regAlignL and regER)
bool regShortOK0 = regimeMode=="Off" ? true : regimeMode=="HTF alignment" ? regAlignS : regimeMode=="Efficiency ratio" ? regER : (regAlignS and regER)
bool extAlignL = not useExtAlign or close > extSLsrc
bool extAlignS = not useExtAlign or close < extSLsrc
bool regLongOK = regLongOK0 and extAlignL
bool regShortOK = regShortOK0 and extAlignS
// ───────────────────────────── BREAK (channel 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 = useExtSL ? extSLsrc : (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 useExtSL
pStop := extSLsrc
else if dir == 1 and stopMode != "Fixed at entry channel"
float tnew = stopMode == "Chandelier (ATR trail)" ? pHH - chMult * nz(atr, 0.0) : sar
pStop := math.max(pStop, tnew)
if low <= pStop or (not useExtSL and dir == -1)
pSide := 0
else if pSide == -1
pLL := math.min(nz(pLL, low), low)
if useExtSL
pStop := extSLsrc
else if dir == -1 and stopMode != "Fixed at entry channel"
float tnew = stopMode == "Chandelier (ATR trail)" ? pLL + chMult * nz(atr, 0.0) : sar
pStop := math.min(pStop, tnew)
if high >= pStop or (not useExtSL and dir == 1)
pSide := 0
string stopTag = useExtSL ? "ext·SL" : stopMode == "Trail the channel" ? "trail·DC" : stopMode == "Chandelier (ATR trail)" ? "trail·ATR" : "fixed·DC"
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
bool isExt = exitModel == "External line"
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 isExt
bool brokeBack = sd == 1 ? close < extSLsrc : close > extSLsrc
if brokeBack
resolved := true
rR := (close - en) / R0 * sd
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 + CHANNEL ──────────────────────
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)
// Donchian entry channel (the breakout boundaries) + optional raw trail line
plot(showChan ? dcUp : na, "Donchian upper", color = color.new(cDn, 55), linewidth = 1, style = plot.style_stepline)
plot(showChan ? dcLo : na, "Donchian lower", color = color.new(cUp, 55), linewidth = 1, style = plot.style_stepline)
plot(showLine ? sar : na, "Trail line", color = color.new(trendCol, 0), linewidth = 2, style = plot.style_stepline)
barcolor(colorBars ? color.new(trendCol, 40) : na, title = "Channel trend 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")
// ───────────────────────────── BREAK MARKERS ───────────────────────────────
if brUp
string t = markerDetail == "Arrow only" ? "▲" : markerDetail == "Short" ? "▲" + str.tostring(qU) : markerDetail == "Compact (grade+TF)" ? "▲" + str.tostring(qU) + "·" + tfTag : "▲ break " + 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 : "▼ break " + 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, 8, border_width = 1, frame_color = frameCl, frame_width = 1)
table.clear(pnl, 0, 0, 1, 7)
table.cell(pnl, 0, 0, " TB · " + 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, "Trail line", 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 break", 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 breaks)" : (regLongOK0?"TREND ↑":regShortOK0?"TREND ↓":"RANGE — hold") + " · " + str.tostring(alignUp) + "/9" + (regimeMode=="HTF alignment" ? "" : " · ER " + str.tostring(er, "#.##"))
color regCol = regimeMode=="Off" ? tVal : regLongOK0 ? cUp : regShortOK0 ? cDn : cAmb
f_row(pnl, 5, "Regime", regTxt, regCol, rowAlt)
string extTxt = not (useExtSL or useExtAlign) ? "off" : (useExtSL ? "SL" : "") + (useExtSL and useExtAlign ? "+" : "") + (useExtAlign ? "align" : "") + " · " + (close > extSLsrc ? "long side" : "short side")
color extCol = not (useExtSL or useExtAlign) ? tVal : close > extSLsrc ? cUp : cDn
f_row(pnl, 6, "Ext feed", extTxt, extCol, panelBg)
string autoTxt = autoOpt ? ("ON · halo grade ≥ " + str.tostring(effGrade) + " (visual only)") : "off"
f_row(pnl, 7, "Auto-opt", autoTxt, autoOpt ? cAmb : tLbl, rowAlt)
// ───────────────── 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_Line", 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 ? pStop : na, "EXP_Stop", 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)
plot(showEXP ? dcUp : na, "EXP_ChanUp", color = color.new(color.gray,100), display = display.data_window)
plot(showEXP ? dcLo : na, "EXP_ChanLo", color = color.new(color.gray,100), display = display.data_window)
// ───────────────────────────── ALERTS ──────────────────────────────────────
alertcondition(brUp, "Armed break UP", "TURTLE-BO: regime-armed Donchian breakout UP (bullish breakout in trend)")
alertcondition(brDn, "Armed break DOWN", "TURTLE-BO: regime-armed Donchian breakout DOWN (bearish breakout in trend)")
alertcondition(strongUp, "Strong break UP", "TURTLE-BO: strong (graded) armed breakout UP")
alertcondition(strongDn, "Strong break DOWN","TURTLE-BO: strong (graded) armed breakout DOWN")