Breadth Suite Pro

chardogg74 · study · 1327 行 · 点赞 8 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © chardogg74
 
//@version=6
// ═══════════════════════════════════════════════════════════════════════════════
//  Market Breadth Pro — everything in ONE indicator (one subpanel + price-chart signals + table)
//  SUBPANEL, stacked top to bottom:
//    • 0-100 breadth area: % of stocks above moving averages (MMTW…R2FD) plus
//      % advancing, % up volume and new-highs share (NYSE / Nasdaq), on their true 0-100 scale
//    • Lane 1 and Lane 2 (optional): any own-scale internal — McClellan Oscillator,
//      McClellan Summation, A/D Line, Net New Highs (NYSE / Nasdaq), CBOE Put/Call
//      (total / equity). Each lane auto-fits its own data; labels show the real values.
//      (The subpanel's right-hand axis numbers apply to the 0-100 area only.)
//  TABLE: its own row choices, independent of the subpanel.
//  McClellan Oscillator / Summation Index: ratio-adjusted by default (as StockCharts $NYMO/$NAMO/$NYSI/$NASI).
//  Swing-trading layer (⑦b): breadth regime, Zweig Breadth Thrust, washout / overheat, price-breadth
//  divergence and 90% volume days, each shown in the table, marked on price and sent through alert().
//  Price-chart default: RED arrow above bar / GREEN arrow below bar when a level is crossed.
// ═══════════════════════════════════════════════════════════════════════════════
indicator("Breadth Suite Pro", shorttitle = "Breadth Suite Pro", overlay = false, precision = 2, max_labels_count = 500, max_lines_count = 500, max_polylines_count = 40, max_bars_back = 500)
 
// ───────────────────────────── GROUP NAMES ─────────────────────────────
string GD  = "① Data & layout"
string GT  = "② % above-MA tickers  —  show · color · high · low"
string GT5 = "②b Short-term 5-day tickers  —  show · color · high · low"
string GN  = "②c 0-100 internals  —  show · color · high · low"
string GO  = "②d Internal lanes (below the 0-100 area)"
string GTH = "③ Thresholds & signal logic"
string GS  = "④ Plot style"
string GLV = "⑤ Last-value labels (subpanel)"
string GTB = "⑥ Table"
string GTR = "⑥b Table rows (independent of the subpanel)"
string GP  = "⑦ Subpanel signals"
string GC  = "⑧ Price-chart signals"
string GE  = "⑦b Swing-trading signals"
string GA  = "⑨ Alerts"
 
// ───────────────────────────── ① DATA & LAYOUT ─────────────────────────────
showPct = input.bool(true, "Show 0-100 breadth area", group = GD, tooltip = "Turn off to use the subpanel only for the internal lanes (section ②d).")
tfIn   = input.timeframe("", "Timeframe: % above-MA tickers (blank = chart)", group = GD)
srcIn  = input.string("Close", "Source: % above-MA tickers", options = ["Close", "Open", "High", "Low", "HL2", "HLC3", "OHLC4"], group = GD)
tfI    = input.timeframe("D", "Timeframe: internals", group = GD, tooltip = "Used for advances/declines, up/down volume, new highs/lows and put/call. McClellan, Summation, A/D Line and smoothing are calculated on this timeframe. Daily is the standard.")
 
// ───────────────────────────── ② / ②b % ABOVE-MA TICKERS ─────────────────────────────
s1 = input.bool(false, "MMTW · All US > 20D", inline = "r1", group = GT)
c1 = input.color(#6E61C7, "", inline = "r1", group = GT)
h1 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r1", group = GT)
l1 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r1", group = GT)
s2 = input.bool(true, "MMFI · All US > 50D", inline = "r2", group = GT)
c2 = input.color(#5E9C76, "", inline = "r2", group = GT)
h2 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r2", group = GT)
l2 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r2", group = GT)
s3 = input.bool(false, "MMOH · All US > 100D", inline = "r3", group = GT)
c3 = input.color(#5A9C96, "", inline = "r3", group = GT)
h3 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r3", group = GT)
l3 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r3", group = GT)
s4 = input.bool(false, "MMOF · All US > 150D", inline = "r4", group = GT)
c4 = input.color(#C9A55A, "", inline = "r4", group = GT)
h4 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r4", group = GT)
l4 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r4", group = GT)
s5 = input.bool(true, "MMTH · All US > 200D", inline = "r5", group = GT)
c5 = input.color(#C98B55, "", inline = "r5", group = GT)
h5 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r5", group = GT)
l5 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r5", group = GT)
s6 = input.bool(false, "S5TW · S&P 500 > 20D", inline = "r6", group = GT)
c6 = input.color(#8A80C9, "", inline = "r6", group = GT)
h6 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r6", group = GT)
l6 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r6", group = GT)
s7 = input.bool(false, "S5FI · S&P 500 > 50D", inline = "r7", group = GT)
c7 = input.color(#4F7D5A, "", inline = "r7", group = GT)
h7 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r7", group = GT)
l7 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r7", group = GT)
s8 = input.bool(false, "S5OH · S&P 500 > 100D", inline = "r8", group = GT)
c8 = input.color(#4F8A84, "", inline = "r8", group = GT)
h8 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r8", group = GT)
l8 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r8", group = GT)
s9 = input.bool(true, "S5TH · S&P 500 > 200D", inline = "r9", group = GT)
c9 = input.color(#C4844F, "", inline = "r9", group = GT)
h9 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r9", group = GT)
l9 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r9", group = GT)
s10 = input.bool(false, "NDTW · Nasdaq-100 > 20D", inline = "r10", group = GT)
c10 = input.color(#5B7BC9, "", inline = "r10", group = GT)
h10 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r10", group = GT)
l10 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r10", group = GT)
s11 = input.bool(false, "NDFI · Nasdaq-100 > 50D", inline = "r11", group = GT)
c11 = input.color(#8FB596, "", inline = "r11", group = GT)
h11 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r11", group = GT)
l11 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r11", group = GT)
s12 = input.bool(false, "NDTH · Nasdaq-100 > 200D", inline = "r12", group = GT)
c12 = input.color(#D2B07A, "", inline = "r12", group = GT)
h12 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r12", group = GT)
l12 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r12", group = GT)
 
// ───────────────────────────── ②b SHORT-TERM (5-DAY) TICKERS ─────────────────────────────
s13 = input.bool(false, "MMFD · All US > 5D", inline = "r13", group = GT5)
c13 = input.color(#A65466, "", inline = "r13", group = GT5)
h13 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r13", group = GT5)
l13 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r13", group = GT5)
s14 = input.bool(false, "S5FD · S&P 500 > 5D", inline = "r14", group = GT5)
c14 = input.color(#C9727A, "", inline = "r14", group = GT5)
h14 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r14", group = GT5)
l14 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r14", group = GT5)
s15 = input.bool(false, "NDFD · Nasdaq-100 > 5D", inline = "r15", group = GT5)
c15 = input.color(#B9657F, "", inline = "r15", group = GT5)
h15 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r15", group = GT5)
l15 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r15", group = GT5)
s16 = input.bool(true, "NCFD · Nasdaq Comp > 5D", inline = "r16", group = GT5)
c16 = input.color(#C2565F, "", inline = "r16", group = GT5)
h16 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r16", group = GT5)
l16 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r16", group = GT5)
s17 = input.bool(false, "DIFD · Dow 30 > 5D", inline = "r17", group = GT5)
c17 = input.color(#D48A92, "", inline = "r17", group = GT5)
h17 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r17", group = GT5)
l17 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r17", group = GT5)
s18 = input.bool(false, "R2FD · Russell 2000 > 5D", inline = "r18", group = GT5)
c18 = input.color(#9E5873, "", inline = "r18", group = GT5)
h18 = input.float(85.0, "H", minval = 0, maxval = 100, inline = "r18", group = GT5)
l18 = input.float(15.0, "L", minval = 0, maxval = 100, inline = "r18", group = GT5)
 
// ───────────────────────────── ②c 0-100 INTERNALS ─────────────────────────────
s19 = input.bool(false, "% advancing · NYSE", inline = "r19", group = GN)
c19 = input.color(#6874B3, "", inline = "r19", group = GN)
h19 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r19", group = GN)
l19 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r19", group = GN)
s20 = input.bool(false, "% advancing · Nasdaq", inline = "r20", group = GN)
c20 = input.color(#8E98C4, "", inline = "r20", group = GN)
h20 = input.float(80.0, "H", minval = 0, maxval = 100, inline = "r20", group = GN)
l20 = input.float(20.0, "L", minval = 0, maxval = 100, inline = "r20", group = GN)
s21 = input.bool(false, "% up volume · NYSE", inline = "r21", group = GN)
c21 = input.color(#4F8F96, "", inline = "r21", group = GN)
h21 = input.float(90.0, "H", minval = 0, maxval = 100, inline = "r21", group = GN)
l21 = input.float(10.0, "L", minval = 0, maxval = 100, inline = "r21", group = GN)
s22 = input.bool(false, "% up volume · Nasdaq", inline = "r22", group = GN)
c22 = input.color(#7FB8C0, "", inline = "r22", group = GN)
h22 = input.float(90.0, "H", minval = 0, maxval = 100, inline = "r22", group = GN)
l22 = input.float(10.0, "L", minval = 0, maxval = 100, inline = "r22", group = GN)
s23 = input.bool(false, "Highs share · NYSE", inline = "r23", group = GN)
c23 = input.color(#8A7368, "", inline = "r23", group = GN)
h23 = input.float(70.0, "H", minval = 0, maxval = 100, inline = "r23", group = GN)
l23 = input.float(30.0, "L", minval = 0, maxval = 100, inline = "r23", group = GN)
s24 = input.bool(false, "Highs share · Nasdaq", inline = "r24", group = GN)
c24 = input.color(#ABA095, "", inline = "r24", group = GN)
h24 = input.float(70.0, "H", minval = 0, maxval = 100, inline = "r24", group = GN)
l24 = input.float(30.0, "L", minval = 0, maxval = 100, inline = "r24", group = GN)
hlLen = input.int(10, "Highs share smoothing (days)", minval = 1, maxval = 50, group = GN, tooltip = "Highs share = new highs ÷ (new highs + new lows) × 100, using totals over this many days. 1 = that day only.")
 
// ───────────────────────────── ②d INTERNAL LANES ─────────────────────────────
lane1In    = input.string("McClellan Osc - Nasdaq", "Lane 1", options = ["None", "McClellan Osc - NYSE", "McClellan Osc - Nasdaq", "McClellan Summation - NYSE", "McClellan Summation - Nasdaq", "A/D Line - NYSE", "A/D Line - Nasdaq", "Net New Highs - NYSE", "Net New Highs - Nasdaq", "Put/Call - Total (CBOE)", "Put/Call - Equity (CBOE)", "New Highs vs Lows - NYSE", "New Highs vs Lows - Nasdaq"], inline = "ln1", group = GO)
lane1Col   = input.color(#787B86, "", inline = "ln1", group = GO)
lane2In    = input.string("McClellan Summation - Nasdaq", "Lane 2", options = ["None", "McClellan Osc - NYSE", "McClellan Osc - Nasdaq", "McClellan Summation - NYSE", "McClellan Summation - Nasdaq", "A/D Line - NYSE", "A/D Line - Nasdaq", "Net New Highs - NYSE", "Net New Highs - Nasdaq", "Put/Call - Total (CBOE)", "Put/Call - Equity (CBOE)", "New Highs vs Lows - NYSE", "New Highs vs Lows - Nasdaq"], inline = "ln2", group = GO)
lane2Col   = input.color(#787B86, "", inline = "ln2", group = GO)
lane3In    = input.string("Net New Highs - NYSE", "Lane 3", options = ["None", "McClellan Osc - NYSE", "McClellan Osc - Nasdaq", "McClellan Summation - NYSE", "McClellan Summation - Nasdaq", "A/D Line - NYSE", "A/D Line - Nasdaq", "Net New Highs - NYSE", "Net New Highs - Nasdaq", "Put/Call - Total (CBOE)", "Put/Call - Equity (CBOE)", "New Highs vs Lows - NYSE", "New Highs vs Lows - Nasdaq"], inline = "ln3", group = GO)
lane3Col   = input.color(#8A8E99, "", inline = "ln3", group = GO)
laneStyleIn = input.string("Auto", "Lane plot type", options = ["Auto", "Line"], group = GO, tooltip = "Auto draws each internal the way it is usually charted: McClellan Oscillator, Summation Index, A/D Line and Put/Call as lines; Net New Highs as columns; New Highs vs Lows as new-high columns above zero and new-low columns below zero with the net as a line.\nLine: everything as a line.")
lanePosCol = input.color(#4CAF50, "Columns ≥ 0", inline = "lc", group = GO)
laneNegCol = input.color(#EF5350, "< 0", inline = "lc", group = GO)
lnMa1On    = input.bool(true, "Lane MA 1", inline = "lm1", group = GO)
lnMa1Type  = input.string("EMA", "", options = ["EMA", "SMA"], inline = "lm1", group = GO)
lnMa1Len   = input.int(20, "", minval = 1, maxval = 300, inline = "lm1", group = GO)
lnMa1Col   = input.color(color.new(#5E9C76, 15), "", inline = "lm1", group = GO, tooltip = "Moving averages drawn on each lane's line (not on New Highs vs Lows). Defaults match the StockCharts NAMO / NASI layout: EMA 20 (green), SMA 50 (blue), SMA 200 (red).")
lnMa2On    = input.bool(true, "Lane MA 2", inline = "lm2", group = GO)
lnMa2Type  = input.string("SMA", "", options = ["EMA", "SMA"], inline = "lm2", group = GO)
lnMa2Len   = input.int(50, "", minval = 1, maxval = 300, inline = "lm2", group = GO)
lnMa2Col   = input.color(color.new(#5B7BC9, 15), "", inline = "lm2", group = GO)
lnMa3On    = input.bool(true, "Lane MA 3", inline = "lm3", group = GO)
lnMa3Type  = input.string("SMA", "", options = ["EMA", "SMA"], inline = "lm3", group = GO)
lnMa3Len   = input.int(200, "", minval = 1, maxval = 300, inline = "lm3", group = GO)
lnMa3Col   = input.color(color.new(#C2565F, 15), "", inline = "lm3", group = GO)
colW       = input.int(4, "Column width (px)", minval = 1, maxval = 20, group = GO, tooltip = "Width of the Net New Highs columns. Up to the most recent 240 bars are drawn as full columns; older bars as thin lines.")
laneBars   = input.int(250, "Bars drawn in lanes", minval = 20, maxval = 2000, group = GO, tooltip = "Lanes are redrawn on the latest bar and auto-fit to this many bars of history.")
laneH      = input.int(50, "Lane height", minval = 40, maxval = 300, group = GO, tooltip = "Relative to the 0-100 breadth area (100 = same height).")
mcMode     = input.string("Ratio-adjusted", "McClellan method", options = ["Ratio-adjusted", "Traditional"], group = GO, tooltip = "Ratio-adjusted (default) matches StockCharts $NYMO / $NAMO / $NYSI / $NASI: each day's (advances − declines) ÷ (advances + declines) × 1000, then the 19-day EMA minus the 39-day EMA. The Summation Index is the running total of the oscillator.\nTraditional uses raw advances − declines (StockCharts $NYMOT / $NAMOT / $NYSIT / $NASIT).")
nysiOff    = input.float(0.0, "NYSI offset", inline = "cal", group = GO)
nasiOff    = input.float(0.0, "NASI offset", inline = "cal", group = GO, tooltip = "The Summation Index is a running total, so its level here depends on how much history is loaded. To match StockCharts, enter (StockCharts value − this indicator's value) for the same day. Applies to the Summation lanes and table rows.")
mcoHi      = input.float(60.0, "McClellan Osc   H", inline = "o1", group = GO)
mcoLo      = input.float(-60.0, "L", inline = "o1", group = GO)
mcoFlip    = input.bool(false, "Flip", inline = "o1", group = GO)
nnhHi      = input.float(0.0, "Net New Highs   H", inline = "o2", group = GO)
nnhLo      = input.float(0.0, "L", inline = "o2", group = GO)
nnhFlip    = input.bool(true, "Flip", inline = "o2", group = GO)
pctHi      = input.float(1.20, "Put/Call Total   H", step = 0.05, inline = "o3", group = GO)
pctLo      = input.float(0.70, "L", step = 0.05, inline = "o3", group = GO)
pcFlip     = input.bool(true, "Flip", inline = "o3", group = GO)
pceHi      = input.float(1.00, "Put/Call Equity  H", step = 0.05, inline = "o4", group = GO)
pceLo      = input.float(0.50, "L", step = 0.05, inline = "o4", group = GO)
pcLen      = input.int(1, "Put/Call smoothing (SMA days, 1 = raw)", minval = 1, maxval = 50, group = GO)
adMaLen    = input.int(20, "A/D Line signal EMA", minval = 1, maxval = 200, inline = "o5", group = GO)
sumMaLen   = input.int(20, "Summation signal EMA", minval = 1, maxval = 200, inline = "o5", group = GO, tooltip = "The A/D Line and Summation Index give signals when they cross this EMA (also used by the table and the regime score). Keep it equal to Lane MA 1 to see the same line on the chart.")
trendFlip  = input.bool(true, "Flip (A/D Line & Summation MA crosses)", group = GO, tooltip = "Flip OFF: crossing above the high level (or above the MA) = RED signal; crossing below the low level (or below the MA) = GREEN signal.\nFlip ON: reversed.\nDefaults: Put/Call ON (high readings = heavy put buying relative to calls), Net New Highs ON (crossing above 0 = more new highs than new lows), A/D Line & Summation ON (crossing above the MA = rising).\nAll levels are starting points — adjust to your own history.")
 
// ───────────────────────────── ③ THRESHOLDS (0-100 SUBPANEL) ─────────────────────────────
thrMode     = input.string("Global", "Threshold mode", options = ["Global", "Per-ticker"], group = GTH, tooltip = "Global: every % above-MA ticker (② / ②b) uses the Global High/Low below.\nPer-ticker: each ticker uses its own H/L.\nThe 0-100 internals in ②c always use their own H/L.\nZone shading is drawn in Global mode only.")
gHi         = input.float(85.0, "Global high", minval = 0, maxval = 100, step = 1, group = GTH)
gLo         = input.float(15.0, "Global low", minval = 0, maxval = 100, step = 1, group = GTH)
trigIn      = input.string("Cross into zone", "Signal when", options = ["Cross into zone", "Every bar in zone"], group = GTH, tooltip = "Applies to the 0-100 area and the lanes.\nCross into zone: fires once when a value crosses a level.\nEvery bar in zone: fires on every bar the value stays beyond it.")
confirmOnly = input.bool(true, "Signal on bar close only (no repaint)", group = GTH)
showThr     = input.bool(true, "Threshold lines", inline = "tl", group = GTH)
thrHiCol    = input.color(color.new(#C2565F, 65), "", inline = "tl", group = GTH)
thrLoCol    = input.color(color.new(#4F9F86, 65), "", inline = "tl", group = GTH)
thrStyleIn  = input.string("Dashed", "Style", options = ["Solid", "Dashed", "Dotted"], inline = "tl2", group = GTH)
thrWidth    = input.int(1, "Width", minval = 1, maxval = 4, inline = "tl2", group = GTH)
showMid     = input.bool(true, "Midline (50 / zero)", inline = "mid", group = GTH)
midCol      = input.color(color.new(#9E9E9E, 75), "", inline = "mid", group = GTH)
showZone    = input.bool(true, "Shade zones beyond thresholds", inline = "zn", group = GTH)
zoneHiCol   = input.color(color.new(#C2565F, 96), "", inline = "zn", group = GTH)
zoneLoCol   = input.color(color.new(#4F9F86, 95), "", inline = "zn", group = GTH)
 
// ───────────────────────────── ④ PLOT STYLE ─────────────────────────────
styleIn     = input.string("Line", "Plot type (0-100 subpanel)", options = ["Line", "Line (breaks)", "Step Line", "Step Line + Diamonds", "Area", "Area (breaks)", "Columns", "Histogram", "Circles", "Cross"], group = GS)
ncStyleIn   = input.string("Line", "NCFD style", options = ["Line", "FOMO style"], inline = "nc", group = GS, tooltip = "Line: NCFD drawn like the other 5-day tickers (plot type below).\nFOMO style: NCFD drawn as daily open-high-low-close bars, green when it closed up and red when it closed down, as on the FOMO chart.")
ncUpCol     = input.color(#4CAF50, "", inline = "nc", group = GS)
ncDnCol     = input.color(#EF5350, "", inline = "nc", group = GS)
styleIn5    = input.string("Line", "Plot type (5-day tickers)", options = ["Line", "Line (breaks)", "Step Line", "Step Line + Diamonds", "Area", "Area (breaks)", "Columns", "Histogram", "Circles", "Cross"], group = GS, tooltip = "Plot type for NCFD and the other 5-day series (section ②b). Line matches how the FOMO-style 5-day breadth charts are usually drawn.")
lwIn        = input.int(1, "Line width", minval = 1, maxval = 4, group = GS)
baseIn      = input.float(0.0, "Base level (Columns / Histogram / Area)", group = GS)
 
// ───────────────────────────── ⑤ LAST-VALUE LABELS ─────────────────────────────
showLv    = input.bool(true, "Show last-value labels", group = GLV)
lvStyleIn = input.string("Text only", "Style", options = ["Text only", "Label"], group = GLV, tooltip = "Label: filled with the series color and uses the Custom text color.\nText only: uses the Text color source below.")
lvSizeIn  = input.string("Tiny", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], group = GLV)
lvTxtMode = input.string("Series color", "Text color source", options = ["Series color", "Custom"], inline = "lvc", group = GLV)
lvTxtCol  = input.color(#787B86, "Custom", inline = "lvc", group = GLV)
lvShowVal = input.bool(true, "Include value", group = GLV)
lvOffset  = input.int(3, "Offset (bars right of last bar)", minval = 0, maxval = 100, group = GLV)
decIn     = input.int(1, "Decimals for % values", minval = 0, maxval = 4, group = GLV)
lvSpace   = input.float(6.0, "Minimum label spacing (% of subpanel height)", minval = 0, maxval = 20, step = 0.5, group = GLV, tooltip = "Labels for the 0-100 lines are nudged apart so they never sit on top of each other. Raise this if they still touch on a small screen.")
 
// ───────────────────────────── ⑥ TABLE ─────────────────────────────
showTbl    = input.bool(true, "Show table", group = GTB)
tblOnPrice = input.bool(true, "Place table on price chart", group = GTB)
tblPosIn   = input.string("Bottom Center", "Position", options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group = GTB)
tblSizeIn  = input.string("Tiny", "Text size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], group = GTB)
tblTxtCol  = input.color(#8A8E99, "Text", inline = "tc", group = GTB)
tblBgCol   = input.color(color.new(#787B86, 92), "Background", inline = "tc", group = GTB)
tblNameCol = input.bool(true, "Color % above-MA ticker names by series color", group = GTB)
tblLayIn   = input.string("Horizontal", "Layout", options = ["Horizontal", "Vertical"], group = GTB, tooltip = "Horizontal: one column per metric (name, value, status). Vertical: one row per metric.")
showChg    = input.bool(true, "Show direction ▲ / ▼", inline = "chg", group = GTB)
chgLen     = input.int(5, "vs bars ago", minval = 1, maxval = 50, inline = "chg", group = GTB, tooltip = "Compares each value with its value this many bars ago. Hover a value to see the exact change.")
showPctl   = input.bool(false, "Show percentile", inline = "pct", group = GTB)
pctLen     = input.int(252, "Lookback bars", minval = 20, maxval = 480, inline = "pct", group = GTB, tooltip = "Where today's reading ranks within its own last N bars (252 daily bars ≈ 1 year). 90th = higher than 90% of readings.")
 
// ───────────────────────────── ⑥b TABLE ROWS ─────────────────────────────
tMA   = input.bool(true, "% above-MA tickers switched on in ② / ②b", group = GTR)
tAdv1 = input.bool(true, "% advancing · NYSE", inline = "t1", group = GTR)
tAdv2 = input.bool(false, "Nasdaq", inline = "t1", group = GTR)
tUpv1 = input.bool(false, "% up volume · NYSE", inline = "t2", group = GTR)
tUpv2 = input.bool(false, "Nasdaq", inline = "t2", group = GTR)
tHl1  = input.bool(true, "Highs share · NYSE", inline = "t3", group = GTR)
tHl2  = input.bool(false, "Nasdaq", inline = "t3", group = GTR)
tNnh1 = input.bool(false, "Net new highs · NYSE", inline = "t4", group = GTR)
tNnh2 = input.bool(false, "Nasdaq", inline = "t4", group = GTR)
tMco1 = input.bool(false, "McClellan Osc · NYSE", inline = "t5", group = GTR)
tMco2 = input.bool(true, "Nasdaq", inline = "t5", group = GTR)
tSum1 = input.bool(false, "Summation Index · NYSE", inline = "t6", group = GTR)
tSum2 = input.bool(true, "Nasdaq", inline = "t6", group = GTR)
tAdl1 = input.bool(false, "A/D Line vs MA · NYSE", inline = "t7", group = GTR)
tAdl2 = input.bool(false, "Nasdaq", inline = "t7", group = GTR)
tPc1  = input.bool(false, "Put/Call · Total", inline = "t8", group = GTR)
tPc2  = input.bool(true, "Equity", inline = "t8", group = GTR)
tReg  = input.bool(true, "Regime", inline = "t9", group = GTR)
tZbt  = input.bool(true, "Zweig thrust", inline = "t9", group = GTR)
tWs   = input.bool(true, "Washout / overheat", inline = "t9", group = GTR)
tDiv  = input.bool(true, "Divergence", inline = "t10", group = GTR)
t90   = input.bool(true, "90% days", inline = "t10", group = GTR)
 
// ───────────────────────────── ⑦ SUBPANEL SIGNALS ─────────────────────────────
bgMode    = input.string("Off", "Subpanel background", options = ["Off", "While in zone", "On signal bars"], group = GP, tooltip = "For lanes, 'While in zone' only shades for metrics with separate high and low levels (not for MA-cross metrics or when H = L).")
bgHiCol   = input.color(color.new(#C2565F, 94), "Red", inline = "bg", group = GP)
bgLoCol   = input.color(color.new(#4F9F86, 94), "Green", inline = "bg", group = GP)
paneMk    = input.bool(false, "Markers on series at signal", group = GP, tooltip = "Circle markers in the subpanel where a series crosses its level. Off by default; the price-chart arrows and table already show crossings.")
mkHiShape = input.string("Circle", "Red marker", options = ["Triangle Up", "Triangle Down", "Arrow Up", "Arrow Down", "Circle", "Square", "Diamond", "Cross", "X-Cross", "Flag", "Label Up", "Label Down", "Text Only"], inline = "mh", group = GP)
mkHiCol   = input.color(color.new(#C2565F, 35), "", inline = "mh", group = GP)
mkLoShape = input.string("Circle", "Green marker", options = ["Triangle Up", "Triangle Down", "Arrow Up", "Arrow Down", "Circle", "Square", "Diamond", "Cross", "X-Cross", "Flag", "Label Up", "Label Down", "Text Only"], inline = "ml", group = GP)
mkLoCol   = input.color(color.new(#4F9F86, 35), "", inline = "ml", group = GP)
mkSizeIn  = input.string("Tiny", "Marker size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], group = GP)
mkText    = input.bool(false, "Show name on marker", group = GP)
 
// ───────────────────────────── ⑧ PRICE-CHART SIGNALS ─────────────────────────────
showPx     = input.bool(false, "Show signals on price chart", group = GC, tooltip = "Red / green arrows on the price chart when a breadth series crosses its level. Off by default; alerts and the table still track every crossing.")
pxNames    = input.bool(false, "Append triggering names to text", group = GC)
pxHiOn     = input.bool(true, "RED", inline = "ph1", group = GC)
pxHiShape  = input.string("Arrow Down", "", options = ["Triangle Up", "Triangle Down", "Arrow Up", "Arrow Down", "Circle", "Square", "Diamond", "Cross", "X-Cross", "Flag", "Label Up", "Label Down", "Text Only"], inline = "ph1", group = GC)
pxHiCol    = input.color(color.new(#C2565F, 35), "", inline = "ph1", group = GC)
pxHiSizeIn = input.string("Tiny", "", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "ph1", group = GC)
pxHiText   = input.string("", "Text", inline = "ph2", group = GC)
pxHiTxtCol = input.color(#787B86, "", inline = "ph2", group = GC)
pxHiLoc    = input.string("Above bar", "", options = ["Above bar", "Below bar"], inline = "ph2", group = GC)
pxLoOn     = input.bool(true, "GREEN", inline = "pl1", group = GC)
pxLoShape  = input.string("Arrow Up", "", options = ["Triangle Up", "Triangle Down", "Arrow Up", "Arrow Down", "Circle", "Square", "Diamond", "Cross", "X-Cross", "Flag", "Label Up", "Label Down", "Text Only"], inline = "pl1", group = GC)
pxLoCol    = input.color(color.new(#4F9F86, 35), "", inline = "pl1", group = GC)
pxLoSizeIn = input.string("Tiny", "", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "pl1", group = GC)
pxLoText   = input.string("", "Text", inline = "pl2", group = GC)
pxLoTxtCol = input.color(#787B86, "", inline = "pl2", group = GC)
pxLoLoc    = input.string("Below bar", "", options = ["Above bar", "Below bar"], inline = "pl2", group = GC)
 
// ───────────────────────────── ⑦b SWING-TRADING SIGNALS ─────────────────────────────
regOn      = input.bool(true, "Breadth regime", group = GE, tooltip = "One point each: S5TH above 50, MMFI above 50, NASI above its MA, NYSE new highs above new lows. 3-4 = Risk-on, 2 = Mixed, 0-1 = Risk-off. Shown in the table; regime changes are marked and alerted.")
zbtOn      = input.bool(true, "Zweig Breadth Thrust (NYSE)", group = GE, tooltip = "10-day EMA of advances ÷ (advances + declines) rises from below 40% to above 61.5% within 10 days. Rare; calculated on daily data.")
wsOn       = input.bool(true, "Washout / overheat confluence", group = GE, tooltip = "Washout: short-term gauge below its Low AND intermediate gauge below its Low. Overheat: both above their Highs.")
wsShortIn  = input.string("NCFD", "Short-term", options = ["NCFD", "MMFD", "S5FD", "NDFD"], inline = "ws1", group = GE)
wsShortLo  = input.float(15.0, "Low", minval = 0, maxval = 100, inline = "ws1", group = GE)
wsShortHi  = input.float(85.0, "High", minval = 0, maxval = 100, inline = "ws1", group = GE)
wsMidIn    = input.string("MMFI", "Intermediate", options = ["MMFI", "S5FI", "NDFI", "MMTW", "S5TW"], inline = "ws2", group = GE)
wsMidLo    = input.float(20.0, "Low", minval = 0, maxval = 100, inline = "ws2", group = GE)
wsMidHi    = input.float(80.0, "High", minval = 0, maxval = 100, inline = "ws2", group = GE)
divOn      = input.bool(true, "Price / breadth divergence", group = GE, tooltip = "Bearish: the chart makes a new N-bar high while the breadth gauge sits at least Gap points below its own N-bar high. Bullish: a new N-bar low while the gauge sits at least Gap points above its own N-bar low.")
divGaugeIn = input.string("MMFI", "Gauge", options = ["MMFI", "S5FI", "NDFI", "MMTH", "S5TH", "MMTW", "S5TW"], inline = "dv1", group = GE)
divLen     = input.int(20, "Bars", minval = 5, maxval = 200, inline = "dv1", group = GE)
divTol     = input.float(5.0, "Gap", minval = 0, maxval = 50, inline = "dv1", group = GE)
v90On      = input.bool(true, "90% up / down volume days (NYSE)", group = GE, tooltip = "A 90% up day: up volume is at least 90% of up + down volume (90% down day: at most 10%). Counted over the window in the table.")
v90Len     = input.int(20, "Window (days)", minval = 5, maxval = 100, inline = "v9", group = GE)
v90Mk      = input.bool(false, "Mark each on price", inline = "v9", group = GE)
evMk       = input.bool(true, "Event markers on price chart", group = GE)
evBullCol  = input.color(color.new(#4F9F86, 30), "Bullish", inline = "ev", group = GE)
evBearCol  = input.color(color.new(#C2565F, 30), "Bearish", inline = "ev", group = GE)
evTxtCol   = input.color(#FFFFFF, "Text", inline = "ev", group = GE)
evSizeIn   = input.string("Tiny", "Size", options = ["Tiny", "Small", "Normal", "Large", "Huge", "Auto"], inline = "ev", group = GE)
 
// ───────────────────────────── ⑨ ALERTS ─────────────────────────────
alertFnOn = input.bool(true, "Detailed alert() messages (lists what triggered)", group = GA, tooltip = "To use: Create Alert → Condition: this indicator → 'Any alert() function call'. Includes threshold crosses and the swing-trading events in ⑦b.\nThe fixed conditions (RED / GREEN) cover threshold crosses only.")
 
// ───────────────────────────── HELPERS ─────────────────────────────
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
        => size.auto
 
f_lstyle(string s) =>
    switch s
        "Triangle Up"   => label.style_triangleup
        "Triangle Down" => label.style_triangledown
        "Arrow Up"      => label.style_arrowup
        "Arrow Down"    => label.style_arrowdown
        "Circle"        => label.style_circle
        "Square"        => label.style_square
        "Diamond"       => label.style_diamond
        "Cross"         => label.style_cross
        "X-Cross"       => label.style_xcross
        "Flag"          => label.style_flag
        "Label Up"      => label.style_label_up
        "Label Down"    => label.style_label_down
        => label.style_none
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
f_src() =>
    switch srcIn
        "Open"  => open
        "High"  => high
        "Low"   => low
        "HL2"   => hl2
        "HLC3"  => hlc3
        "OHLC4" => ohlc4
        => close
 
f_add(string acc, bool cond, string name) =>
    cond ? (acc == "" ? name : acc + ", " + name) : acc
 
// a ÷ (a + b) × 100, or na when there is no data
f_share(float a, float b) =>
    float tot = a + b
    tot > 0 ? a / tot * 100 : na
 
// Per-symbol pieces for advancers / decliners. McClellan, Summation and A/D Line are all linear,
// so (advancers piece) − (decliners piece) gives the exact net value.
f_advdec() =>
    float o = ta.ema(close, 19) - ta.ema(close, 39)
    float s = ta.cum(nz(o))
    float c = ta.cum(nz(close))
    [close, o, s, c, ta.ema(s, sumMaLen), ta.ema(c, adMaLen)]
 
f_hl() =>
    [close, math.sum(close, hlLen)]
 
f_pc() =>
    ta.sma(close, pcLen)
 
// Ratio-adjusted McClellan, evaluated in the advancers' context. The decliners are fetched with a nested
// request (Pine v6 dynamic requests), so both counts line up day by day before the ratio and EMAs are taken.
f_ra(string decSym) =>
    float d = request.security(decSym, "", close, ignore_invalid_symbol = true)
    float a = close
    float r = (a + d) > 0 ? (a - d) / (a + d) * 1000 : na
    float o = ta.ema(nz(r), 19) - ta.ema(nz(r), 39)
    float s = ta.cum(nz(o))
    float sh = (a + d) > 0 ? a / (a + d) : na
    float z  = ta.ema(nz(sh, 0.5), 10)
    float zl = ta.lowest(z, 10)
    bool  zf = z > 0.615 and nz(z[1], 1.0) <= 0.615 and zl < 0.40
    [o, s, ta.ema(s, sumMaLen), z, zf]
 
// 90% up / down volume days, evaluated in the up-volume context with a nested request for down volume
f_v90(string dvSym) =>
    float dv = request.security(dvSym, "", close, ignore_invalid_symbol = true)
    float u  = close
    float r  = (u + dv) > 0 ? u / (u + dv) : na
    bool  up = not na(r) and r >= 0.9
    bool  dn = not na(r) and r <= 0.1
    [math.sum(up ? 1.0 : 0.0, v90Len), math.sum(dn ? 1.0 : 0.0, v90Len), up, dn]
 
// Percentile rank of the current value within its last pctLen bars (computed on the last bar only)
f_pctl(float src) =>
    float res = na
    if showPctl and barstate.islast and not na(src)
        int below = 0
        int total = 0
        for i = 1 to pctLen
            float x = src[i]
            if not na(x)
                total += 1
                if x < src
                    below += 1
        res := total > 0 ? 100.0 * below / total : na
    res
 
// ───────────────────────────── DERIVED SETTINGS ─────────────────────────────
crossMode = trigIn == "Cross into zone"
fmt       = decIn == 0 ? "0" : "0." + str.repeat("0", decIn)
mkHiStyle = f_lstyle(mkHiShape)
mkLoStyle = f_lstyle(mkLoShape)
mkSizeV   = f_size(mkSizeIn)
lvSizeV   = f_size(lvSizeIn)
tblSizeV  = f_size(tblSizeIn)
tblPosV   = f_pos(tblPosIn)
pxHiStyle = f_lstyle(pxHiShape)
pxLoStyle = f_lstyle(pxLoShape)
pxHiSizeV = f_size(pxHiSizeIn)
pxLoSizeV = f_size(pxLoSizeIn)
pxHiYloc  = pxHiLoc == "Above bar" ? yloc.abovebar : yloc.belowbar
pxLoYloc  = pxLoLoc == "Above bar" ? yloc.abovebar : yloc.belowbar
 
// These must stay as plain ternaries on inputs (plot/hline/alert need "input" qualified values)
plotStyle = styleIn == "Line" ? plot.style_line : styleIn == "Line (breaks)" ? plot.style_linebr : styleIn == "Step Line" ? plot.style_stepline : styleIn == "Step Line + Diamonds" ? plot.style_stepline_diamond : styleIn == "Area" ? plot.style_area : styleIn == "Area (breaks)" ? plot.style_areabr : styleIn == "Columns" ? plot.style_columns : styleIn == "Histogram" ? plot.style_histogram : styleIn == "Circles" ? plot.style_circles : plot.style_cross
plotStyle5 = styleIn5 == "Line" ? plot.style_line : styleIn5 == "Line (breaks)" ? plot.style_linebr : styleIn5 == "Step Line" ? plot.style_stepline : styleIn5 == "Step Line + Diamonds" ? plot.style_stepline_diamond : styleIn5 == "Area" ? plot.style_area : styleIn5 == "Area (breaks)" ? plot.style_areabr : styleIn5 == "Columns" ? plot.style_columns : styleIn5 == "Histogram" ? plot.style_histogram : styleIn5 == "Circles" ? plot.style_circles : plot.style_cross
thrStyle  = thrStyleIn == "Solid" ? hline.style_solid : thrStyleIn == "Dotted" ? hline.style_dotted : hline.style_dashed
alertFreq = confirmOnly ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
thrLnStyle = thrStyleIn == "Solid" ? line.style_solid : thrStyleIn == "Dotted" ? line.style_dotted : line.style_dashed
laneGap   = 15.0
 
// ───────────────────────────── PER-SERIES ENGINE ─────────────────────────────
// Returns [crossedHigh, crossedLow, aboveHigh, belowLow]. When draw = true it also draws subpanel markers
// and the last-value label at the true value (0-100 area). Lanes pass draw = false and draw their own.
// flip = true sends high-side events to the GREEN marker and low-side events to the RED marker.
f_series(bool show, float v, float hiT, float loT, color col, string name, string fs, bool flip, bool draw) =>
    bool inHi  = show and not na(v) and v > hiT
    bool inLo  = show and not na(v) and v < loT
    bool xHi   = ta.crossover(v, hiT)
    bool xLo   = ta.crossunder(v, loT)
    bool okBar = not confirmOnly or barstate.isconfirmed
    bool sigHi = show and okBar and (crossMode ? xHi : inHi)
    bool sigLo = show and okBar and (crossMode ? xLo : inLo)
    if draw and paneMk and sigHi
        label.new(bar_index, v, mkText ? name : "", xloc = xloc.bar_index, yloc = yloc.price, color = flip ? mkLoCol : mkHiCol, style = flip ? mkLoStyle : mkHiStyle, textcolor = flip ? mkLoCol : mkHiCol, size = mkSizeV, tooltip = name + " ▲ " + str.tostring(v, fs) + " > " + str.tostring(hiT, fs))
    if draw and paneMk and sigLo
        label.new(bar_index, v, mkText ? name : "", xloc = xloc.bar_index, yloc = yloc.price, color = flip ? mkHiCol : mkLoCol, style = flip ? mkHiStyle : mkLoStyle, textcolor = flip ? mkHiCol : mkLoCol, size = mkSizeV, tooltip = name + " ▼ " + str.tostring(v, fs) + " < " + str.tostring(loT, fs))
    [sigHi, sigLo, inHi, inLo]
 
// ───────────────────────────── DATA REQUESTS ─────────────────────────────
v1 = request.security("INDEX:MMTW", tfIn, f_src(), ignore_invalid_symbol = true)
v2 = request.security("INDEX:MMFI", tfIn, f_src(), ignore_invalid_symbol = true)
v3 = request.security("INDEX:MMOH", tfIn, f_src(), ignore_invalid_symbol = true)
v4 = request.security("INDEX:MMOF", tfIn, f_src(), ignore_invalid_symbol = true)
v5 = request.security("INDEX:MMTH", tfIn, f_src(), ignore_invalid_symbol = true)
v6 = request.security("INDEX:S5TW", tfIn, f_src(), ignore_invalid_symbol = true)
v7 = request.security("INDEX:S5FI", tfIn, f_src(), ignore_invalid_symbol = true)
v8 = request.security("INDEX:S5OH", tfIn, f_src(), ignore_invalid_symbol = true)
v9 = request.security("INDEX:S5TH", tfIn, f_src(), ignore_invalid_symbol = true)
v10 = request.security("INDEX:NDTW", tfIn, f_src(), ignore_invalid_symbol = true)
v11 = request.security("INDEX:NDFI", tfIn, f_src(), ignore_invalid_symbol = true)
v12 = request.security("INDEX:NDTH", tfIn, f_src(), ignore_invalid_symbol = true)
v13 = request.security("INDEX:MMFD", tfIn, f_src(), ignore_invalid_symbol = true)
v14 = request.security("INDEX:S5FD", tfIn, f_src(), ignore_invalid_symbol = true)
v15 = request.security("INDEX:NDFD", tfIn, f_src(), ignore_invalid_symbol = true)
[ncO, ncH, ncL, ncC, v16] = request.security("INDEX:NCFD", tfIn, [open, high, low, close, f_src()], ignore_invalid_symbol = true)
v17 = request.security("INDEX:DIFD", tfIn, f_src(), ignore_invalid_symbol = true)
v18 = request.security("INDEX:R2FD", tfIn, f_src(), ignore_invalid_symbol = true)
 
// Advances / declines (NYSE, Nasdaq)
[advNY, aOscNY, aSumNY, aCumNY, aSumMaNY, aCumMaNY] = request.security("USI:ADVN.NY", tfI, f_advdec(), ignore_invalid_symbol = true)
[decNY, dOscNY, dSumNY, dCumNY, dSumMaNY, dCumMaNY] = request.security("USI:DECL.NY", tfI, f_advdec(), ignore_invalid_symbol = true)
[advNQ, aOscNQ, aSumNQ, aCumNQ, aSumMaNQ, aCumMaNQ] = request.security("USI:ADVN.NQ", tfI, f_advdec(), ignore_invalid_symbol = true)
[decNQ, dOscNQ, dSumNQ, dCumNQ, dSumMaNQ, dCumMaNQ] = request.security("USI:DECL.NQ", tfI, f_advdec(), ignore_invalid_symbol = true)
// Up / down volume
uvNY = request.security("USI:UVOL", tfI, close, ignore_invalid_symbol = true)
dvNY = request.security("USI:DVOL", tfI, close, ignore_invalid_symbol = true)
uvNQ = request.security("USI:UVOLQ", tfI, close, ignore_invalid_symbol = true)
dvNQ = request.security("USI:DVOLQ", tfI, close, ignore_invalid_symbol = true)
// New 52-week highs / lows
[hiNY, hiSumNY] = request.security("INDEX:HIGN", tfI, f_hl(), ignore_invalid_symbol = true)
[loNY, loSumNY] = request.security("INDEX:LOWN", tfI, f_hl(), ignore_invalid_symbol = true)
[hiNQ, hiSumNQ] = request.security("INDEX:HIGQ", tfI, f_hl(), ignore_invalid_symbol = true)
[loNQ, loSumNQ] = request.security("INDEX:LOWQ", tfI, f_hl(), ignore_invalid_symbol = true)
// CBOE put/call ratios
pcTot = request.security("USI:PCC", tfI, f_pc(), ignore_invalid_symbol = true)
pcEq  = request.security("USI:PCCE", tfI, f_pc(), ignore_invalid_symbol = true)
// Ratio-adjusted McClellan Oscillator / Summation Index (NYSE, Nasdaq)
[raOscNY, raSumNY, raSumMaNY, zbtEmaNY, zbtNY] = request.security("USI:ADVN.NY", tfI, f_ra("USI:DECL.NY"), ignore_invalid_symbol = true)
[raOscNQ, raSumNQ, raSumMaNQ, zbtEmaNQ, zbtNQ] = request.security("USI:ADVN.NQ", tfI, f_ra("USI:DECL.NQ"), ignore_invalid_symbol = true)
// 90% up / down volume days (NYSE)
[v90Up, v90Dn, v90TodayUp, v90TodayDn] = request.security("USI:UVOL", tfI, f_v90("USI:DVOL"), ignore_invalid_symbol = true)
 
// ───────────────────────────── INTERNALS MATH ─────────────────────────────
useRA   = mcMode == "Ratio-adjusted"
mcoNY   = useRA ? raOscNY : aOscNY - dOscNY
mcoNQ   = useRA ? raOscNQ : aOscNQ - dOscNQ
sumNY   = (useRA ? raSumNY : aSumNY - dSumNY) + nysiOff
sumNQ   = (useRA ? raSumNQ : aSumNQ - dSumNQ) + nasiOff
sumMaNY = (useRA ? raSumMaNY : aSumMaNY - dSumMaNY) + nysiOff
sumMaNQ = (useRA ? raSumMaNQ : aSumMaNQ - dSumMaNQ) + nasiOff
adlNY   = aCumNY - dCumNY
adlNQ   = aCumNQ - dCumNQ
adlMaNY = aCumMaNY - dCumMaNY
adlMaNQ = aCumMaNQ - dCumMaNQ
nnhNY   = hiNY - loNY
nnhNQ   = hiNQ - loNQ
v19 = f_share(advNY, decNY)
v20 = f_share(advNQ, decNQ)
v21 = f_share(uvNY, dvNY)
v22 = f_share(uvNQ, dvNQ)
v23 = f_share(hiSumNY, loSumNY)
v24 = f_share(hiSumNQ, loSumNQ)
 
// ───────────────────────────── EFFECTIVE THRESHOLDS (0-100) ─────────────────────────────
useGlobal = thrMode == "Global"
hi1 = useGlobal ? gHi : h1
lo1 = useGlobal ? gLo : l1
hi2 = useGlobal ? gHi : h2
lo2 = useGlobal ? gLo : l2
hi3 = useGlobal ? gHi : h3
lo3 = useGlobal ? gLo : l3
hi4 = useGlobal ? gHi : h4
lo4 = useGlobal ? gLo : l4
hi5 = useGlobal ? gHi : h5
lo5 = useGlobal ? gLo : l5
hi6 = useGlobal ? gHi : h6
lo6 = useGlobal ? gLo : l6
hi7 = useGlobal ? gHi : h7
lo7 = useGlobal ? gLo : l7
hi8 = useGlobal ? gHi : h8
lo8 = useGlobal ? gLo : l8
hi9 = useGlobal ? gHi : h9
lo9 = useGlobal ? gLo : l9
hi10 = useGlobal ? gHi : h10
lo10 = useGlobal ? gLo : l10
hi11 = useGlobal ? gHi : h11
lo11 = useGlobal ? gLo : l11
hi12 = useGlobal ? gHi : h12
lo12 = useGlobal ? gLo : l12
hi13 = useGlobal ? gHi : h13
lo13 = useGlobal ? gLo : l13
hi14 = useGlobal ? gHi : h14
lo14 = useGlobal ? gLo : l14
hi15 = useGlobal ? gHi : h15
lo15 = useGlobal ? gLo : l15
hi16 = useGlobal ? gHi : h16
lo16 = useGlobal ? gLo : l16
hi17 = useGlobal ? gHi : h17
lo17 = useGlobal ? gLo : l17
hi18 = useGlobal ? gHi : h18
lo18 = useGlobal ? gLo : l18
hi19 = h19  // 0-100 internals always use their own levels
lo19 = l19
hi20 = h20  // 0-100 internals always use their own levels
lo20 = l20
hi21 = h21  // 0-100 internals always use their own levels
lo21 = l21
hi22 = h22  // 0-100 internals always use their own levels
lo22 = l22
hi23 = h23  // 0-100 internals always use their own levels
lo23 = l23
hi24 = h24  // 0-100 internals always use their own levels
lo24 = l24
 
// ───────────────────────────── EVALUATE: 0-100 SUBPANEL ─────────────────────────────
[sH1, sL1, iH1, iL1] = f_series(showPct and s1, v1, hi1, lo1, c1, "MMTW", fmt, false, true)
[sH2, sL2, iH2, iL2] = f_series(showPct and s2, v2, hi2, lo2, c2, "MMFI", fmt, false, true)
[sH3, sL3, iH3, iL3] = f_series(showPct and s3, v3, hi3, lo3, c3, "MMOH", fmt, false, true)
[sH4, sL4, iH4, iL4] = f_series(showPct and s4, v4, hi4, lo4, c4, "MMOF", fmt, false, true)
[sH5, sL5, iH5, iL5] = f_series(showPct and s5, v5, hi5, lo5, c5, "MMTH", fmt, false, true)
[sH6, sL6, iH6, iL6] = f_series(showPct and s6, v6, hi6, lo6, c6, "S5TW", fmt, false, true)
[sH7, sL7, iH7, iL7] = f_series(showPct and s7, v7, hi7, lo7, c7, "S5FI", fmt, false, true)
[sH8, sL8, iH8, iL8] = f_series(showPct and s8, v8, hi8, lo8, c8, "S5OH", fmt, false, true)
[sH9, sL9, iH9, iL9] = f_series(showPct and s9, v9, hi9, lo9, c9, "S5TH", fmt, false, true)
[sH10, sL10, iH10, iL10] = f_series(showPct and s10, v10, hi10, lo10, c10, "NDTW", fmt, false, true)
[sH11, sL11, iH11, iL11] = f_series(showPct and s11, v11, hi11, lo11, c11, "NDFI", fmt, false, true)
[sH12, sL12, iH12, iL12] = f_series(showPct and s12, v12, hi12, lo12, c12, "NDTH", fmt, false, true)
[sH13, sL13, iH13, iL13] = f_series(showPct and s13, v13, hi13, lo13, c13, "MMFD", fmt, false, true)
[sH14, sL14, iH14, iL14] = f_series(showPct and s14, v14, hi14, lo14, c14, "S5FD", fmt, false, true)
[sH15, sL15, iH15, iL15] = f_series(showPct and s15, v15, hi15, lo15, c15, "NDFD", fmt, false, true)
[sH16, sL16, iH16, iL16] = f_series(showPct and s16, v16, hi16, lo16, c16, "NCFD", fmt, false, true)
[sH17, sL17, iH17, iL17] = f_series(showPct and s17, v17, hi17, lo17, c17, "DIFD", fmt, false, true)
[sH18, sL18, iH18, iL18] = f_series(showPct and s18, v18, hi18, lo18, c18, "R2FD", fmt, false, true)
[sH19, sL19, iH19, iL19] = f_series(showPct and s19, v19, hi19, lo19, c19, "ADV% NY", fmt, false, true)
[sH20, sL20, iH20, iL20] = f_series(showPct and s20, v20, hi20, lo20, c20, "ADV% NQ", fmt, false, true)
[sH21, sL21, iH21, iL21] = f_series(showPct and s21, v21, hi21, lo21, c21, "UPV% NY", fmt, false, true)
[sH22, sL22, iH22, iL22] = f_series(showPct and s22, v22, hi22, lo22, c22, "UPV% NQ", fmt, false, true)
[sH23, sL23, iH23, iL23] = f_series(showPct and s23, v23, hi23, lo23, c23, "HL% NY", fmt, false, true)
[sH24, sL24, iH24, iL24] = f_series(showPct and s24, v24, hi24, lo24, c24, "HL% NQ", fmt, false, true)
 
// ───────────────────────────── INTERNAL LANES: METRIC PICKER ─────────────────────────────
// Returns [value, MA, isMaCross, isBipolar, highLevel, lowLevel, flip, name, format, newHighs, newLows, isHighsVsLows, isColumns]
f_pick(string m) =>
    bool k1  = m == "McClellan Osc - NYSE"
    bool k2  = m == "McClellan Osc - Nasdaq"
    bool k3  = m == "McClellan Summation - NYSE"
    bool k4  = m == "McClellan Summation - Nasdaq"
    bool k5  = m == "A/D Line - NYSE"
    bool k6  = m == "A/D Line - Nasdaq"
    bool k7  = m == "Net New Highs - NYSE"
    bool k8  = m == "Net New Highs - Nasdaq"
    bool k9  = m == "Put/Call - Total (CBOE)"
    bool k10 = m == "Put/Call - Equity (CBOE)"
    bool k11 = m == "New Highs vs Lows - NYSE"
    bool k12 = m == "New Highs vs Lows - Nasdaq"
    bool isSplit = k11 or k12
    bool isCols  = k7 or k8
    bool isMco = k1 or k2
    bool isTr  = k3 or k4 or k5 or k6
    bool isNnh = k7 or k8 or k11 or k12
    bool isPc  = k9 or k10
    float pv  = k1 ? mcoNY : k2 ? mcoNQ : k3 ? sumNY : k4 ? sumNQ : k5 ? adlNY : k6 ? adlNQ : k7 ? nnhNY : k8 ? nnhNQ : k9 ? pcTot : k10 ? pcEq : k11 ? nnhNY : k12 ? nnhNQ : na
    float pH  = k11 ? hiNY : k12 ? hiNQ : na
    float pL  = k11 ? loNY : k12 ? loNQ : na
    float pma = k3 ? sumMaNY : k4 ? sumMaNQ : k5 ? adlMaNY : k6 ? adlMaNQ : na
    float pHi = isMco ? mcoHi : isNnh ? nnhHi : k9 ? pctHi : k10 ? pceHi : na
    float pLo = isMco ? mcoLo : isNnh ? nnhLo : k9 ? pctLo : k10 ? pceLo : na
    bool  pFl = isMco ? mcoFlip : isNnh ? nnhFlip : isPc ? pcFlip : trendFlip
    string pNm = k1 ? (useRA ? "NYMO" : "MCO NYSE") : k2 ? (useRA ? "NAMO" : "MCO Nasdaq") : k3 ? (useRA ? "NYSI" : "Summation NYSE") : k4 ? (useRA ? "NASI" : "Summation Nasdaq") : k5 ? "A/D NYSE" : k6 ? "A/D Nasdaq" : k7 ? "Net Highs/Lows NYSE" : k8 ? "Net Highs/Lows Nasdaq" : k9 ? "Put/Call Total" : k10 ? "Put/Call Equity" : k11 ? "NH/NL NYSE" : k12 ? "NH/NL Nasdaq" : ""
    string pFs = isMco ? "0.0" : isNnh ? "0" : isPc ? "0.00" : format.volume
    [pv, pma, isTr, isMco or isNnh, pHi, pLo, pFl, pNm, pFs, pH, pL, isSplit, isCols]
 
// Map a raw value into a lane's y-band
f_map(float x, bool bip, float yMid, float rBip, float yBot, float rLo, float rHi, float hgt) =>
    bip ? yMid + x / rBip * (hgt / 2) : yBot + (x - rLo) / (rHi - rLo) * hgt
 
// Builds a polyline from a stored series (skips missing values). Returns na when there is nothing to draw.
f_polyFrom(array<float> arr, int x0, bool bip, float yMid, float rBip, float yBot, float rLo, float rHi, color c, int w) =>
    array<chart.point> pts = array.new<chart.point>()
    int cnt = array.size(arr)
    if cnt > 0
        for i = 0 to cnt - 1
            float x = array.get(arr, i)
            if not na(x)
                array.push(pts, chart.point.from_index(x0 + i, f_map(x, bip, yMid, rBip, yBot, rLo, rHi, laneH)))
    polyline pl = na
    if array.size(pts) > 1
        pl := polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = c, line_width = w)
    pl
 
// Widen a running min / max with one more value
f_lo(float cur, float x) =>
    na(x) ? cur : na(cur) ? x : math.min(cur, x)
 
f_hi(float cur, float x) =>
    na(x) ? cur : na(cur) ? x : math.max(cur, x)
 
// Keeps the last laneBars values and redraws the lane on the latest bar (auto-fit scale, real-value labels).
// Display moving averages (MA 1-3) are computed here on every bar so their history is complete.
f_lane(bool on, int k, float v, bool trend, bool bip, float hL, float lL, bool sigR, bool sigG, bool flip, string name, string fs, color col, float hv, float lw, bool split, bool cols) =>
    float ema1 = ta.ema(v, lnMa1Len)
    float sma1 = ta.sma(v, lnMa1Len)
    float ema2 = ta.ema(v, lnMa2Len)
    float sma2 = ta.sma(v, lnMa2Len)
    float ema3 = ta.ema(v, lnMa3Len)
    float sma3 = ta.sma(v, lnMa3Len)
    float m1 = lnMa1Type == "EMA" ? ema1 : sma1
    float m2 = lnMa2Type == "EMA" ? ema2 : sma2
    float m3 = lnMa3Type == "EMA" ? ema3 : sma3
    bool showMa = not split and not cols
    var array<float> av = array.new<float>()
    var array<float> a1 = array.new<float>()
    var array<float> a2 = array.new<float>()
    var array<float> a3 = array.new<float>()
    var array<float> ah = array.new<float>()
    var array<float> al = array.new<float>()
    var array<bool>  ar = array.new<bool>()
    var array<bool>  ag = array.new<bool>()
    var array<polyline> polys = array.new<polyline>()
    var array<line>     lns   = array.new<line>()
    var array<label>    lbs   = array.new<label>()
    array.push(av, v)
    array.push(a1, m1)
    array.push(a2, m2)
    array.push(a3, m3)
    array.push(ah, hv)
    array.push(al, lw)
    array.push(ar, sigR)
    array.push(ag, sigG)
    if array.size(av) > laneBars
        array.shift(av)
        array.shift(a1)
        array.shift(a2)
        array.shift(a3)
        array.shift(ah)
        array.shift(al)
        array.shift(ar)
        array.shift(ag)
    if barstate.islast
        for pl in polys
            if not na(pl)
                polyline.delete(pl)
        array.clear(polys)
        for ln in lns
            line.delete(ln)
        array.clear(lns)
        for lb in lbs
            label.delete(lb)
        array.clear(lbs)
        int n = array.size(av)
        float yTop = -laneGap - (k - 1) * (laneH + laneGap)
        float yBot = yTop - laneH
        float yMid = (yTop + yBot) / 2
        if on and n > 1
            float mn = na
            float mx = na
            for i = 0 to n - 1
                float xv = array.get(av, i)
                mn := f_lo(mn, xv)
                mx := f_hi(mx, xv)
                if showMa and lnMa1On
                    mn := f_lo(mn, array.get(a1, i))
                    mx := f_hi(mx, array.get(a1, i))
                if showMa and lnMa2On
                    mn := f_lo(mn, array.get(a2, i))
                    mx := f_hi(mx, array.get(a2, i))
                if showMa and lnMa3On
                    mn := f_lo(mn, array.get(a3, i))
                    mx := f_hi(mx, array.get(a3, i))
                if split
                    float xh = array.get(ah, i)
                    float xl = array.get(al, i)
                    mx := f_hi(mx, xh)
                    mn := f_lo(mn, -xl)
            if not trend and not na(hL) and not na(lL)
                mn := f_lo(mn, lL)
                mx := f_hi(mx, hL)
            if not na(mn) and not na(mx)
                float rBip = math.max(math.abs(mn), math.abs(mx)) * 1.05
                rBip := rBip > 0 ? rBip : 1.0
                float span = mx - mn
                span := span > 0 ? span : math.max(math.abs(mx), 1.0)
                float rLo = mn - span * 0.05
                float rHi = mx + span * 0.05
                int x0 = bar_index - (n - 1)
                color frameCol = color.new(#9E9E9E, 85)
                // frame: top and bottom edges of the lane
                array.push(lns, line.new(x0, yTop, bar_index, yTop, xloc = xloc.bar_index, color = frameCol, style = line.style_solid, width = 1))
                array.push(lns, line.new(x0, yBot, bar_index, yBot, xloc = xloc.bar_index, color = frameCol, style = line.style_solid, width = 1))
                // zero line for oscillators
                if bip and showMid
                    array.push(lns, line.new(x0, yMid, bar_index, yMid, xloc = xloc.bar_index, color = midCol, style = line.style_dotted, width = 1))
                // high / low levels with their real values
                if not trend and showThr and not na(hL) and not na(lL)
                    float yH = f_map(hL, bip, yMid, rBip, yBot, rLo, rHi, laneH)
                    float yL = f_map(lL, bip, yMid, rBip, yBot, rLo, rHi, laneH)
                    color cH = flip ? thrLoCol : thrHiCol
                    color cL = flip ? thrHiCol : thrLoCol
                    array.push(lns, line.new(x0, yH, bar_index, yH, xloc = xloc.bar_index, color = cH, style = thrLnStyle, width = thrWidth))
                    array.push(lbs, label.new(x0, yH, str.tostring(hL, fs), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_right, textcolor = cH, size = size.tiny))
                    if hL != lL
                        array.push(lns, line.new(x0, yL, bar_index, yL, xloc = xloc.bar_index, color = cL, style = thrLnStyle, width = thrWidth))
                        array.push(lbs, label.new(x0, yL, str.tostring(lL, fs), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_right, textcolor = cL, size = size.tiny))
                // series: new highs / new lows columns with net line, columns from zero, or a line
                if split and laneStyleIn == "Auto"
                    array<chart.point> pHi = array.new<chart.point>()
                    array<chart.point> pLo = array.new<chart.point>()
                    for i = 0 to n - 1
                        int bx = x0 + i
                        float xh = array.get(ah, i)
                        float xl = array.get(al, i)
                        if not na(xh)
                            array.push(pHi, chart.point.from_index(bx, yMid))
                            array.push(pHi, chart.point.from_index(bx, f_map(xh, bip, yMid, rBip, yBot, rLo, rHi, laneH)))
                            array.push(pHi, chart.point.from_index(bx, yMid))
                        if not na(xl)
                            array.push(pLo, chart.point.from_index(bx, yMid))
                            array.push(pLo, chart.point.from_index(bx, f_map(-xl, bip, yMid, rBip, yBot, rLo, rHi, laneH)))
                            array.push(pLo, chart.point.from_index(bx, yMid))
                    if array.size(pHi) > 1
                        array.push(polys, polyline.new(pHi, curved = false, closed = false, xloc = xloc.bar_index, line_color = lanePosCol, line_width = 1))
                    if array.size(pLo) > 1
                        array.push(polys, polyline.new(pLo, curved = false, closed = false, xloc = xloc.bar_index, line_color = laneNegCol, line_width = 1))
                    array.push(polys, f_polyFrom(av, x0, bip, yMid, rBip, yBot, rLo, rHi, col, lwIn))
                else if cols and laneStyleIn == "Auto"
                    // the most recent 240 bars as solid columns (vertical lines with width colW), older bars as thin spikes
                    int colStart = math.max(0, n - 240)
                    array<chart.point> pPos = array.new<chart.point>()
                    array<chart.point> pNeg = array.new<chart.point>()
                    for i = 0 to n - 1
                        float xv = array.get(av, i)
                        if not na(xv)
                            int bx = x0 + i
                            float yv = f_map(xv, bip, yMid, rBip, yBot, rLo, rHi, laneH)
                            if i >= colStart
                                array.push(lns, line.new(bx, yMid, bx, yv, xloc = xloc.bar_index, color = xv >= 0 ? lanePosCol : laneNegCol, style = line.style_solid, width = colW))
                            else if xv >= 0
                                array.push(pPos, chart.point.from_index(bx, yMid))
                                array.push(pPos, chart.point.from_index(bx, yv))
                                array.push(pPos, chart.point.from_index(bx, yMid))
                            else
                                array.push(pNeg, chart.point.from_index(bx, yMid))
                                array.push(pNeg, chart.point.from_index(bx, yv))
                                array.push(pNeg, chart.point.from_index(bx, yMid))
                    if array.size(pPos) > 1
                        array.push(polys, polyline.new(pPos, curved = false, closed = false, xloc = xloc.bar_index, line_color = lanePosCol, line_width = 1))
                    if array.size(pNeg) > 1
                        array.push(polys, polyline.new(pNeg, curved = false, closed = false, xloc = xloc.bar_index, line_color = laneNegCol, line_width = 1))
                else
                    array.push(polys, f_polyFrom(av, x0, bip, yMid, rBip, yBot, rLo, rHi, col, lwIn))
                // display moving averages
                if showMa and lnMa1On
                    array.push(polys, f_polyFrom(a1, x0, bip, yMid, rBip, yBot, rLo, rHi, lnMa1Col, 1))
                if showMa and lnMa2On
                    array.push(polys, f_polyFrom(a2, x0, bip, yMid, rBip, yBot, rLo, rHi, lnMa2Col, 1))
                if showMa and lnMa3On
                    array.push(polys, f_polyFrom(a3, x0, bip, yMid, rBip, yBot, rLo, rHi, lnMa3Col, 1))
                // signal markers (already resolved to RED / GREEN)
                if paneMk
                    for i = 0 to n - 1
                        float xv = array.get(av, i)
                        if not na(xv)
                            float ym = f_map(xv, bip, yMid, rBip, yBot, rLo, rHi, laneH)
                            if array.get(ar, i)
                                array.push(lbs, label.new(x0 + i, ym, mkText ? name : "", xloc = xloc.bar_index, yloc = yloc.price, color = mkHiCol, style = mkHiStyle, textcolor = mkHiCol, size = mkSizeV, tooltip = name + " " + str.tostring(xv, fs)))
                            if array.get(ag, i)
                                array.push(lbs, label.new(x0 + i, ym, mkText ? name : "", xloc = xloc.bar_index, yloc = yloc.price, color = mkLoCol, style = mkLoStyle, textcolor = mkLoCol, size = mkSizeV, tooltip = name + " " + str.tostring(xv, fs)))
                // lane name and last value, placed to the right of the last bar (moving averages listed in the tooltip)
                string maTxt = ""
                if showMa and lnMa1On
                    maTxt := maTxt + "  " + lnMa1Type + " " + str.tostring(lnMa1Len)
                if showMa and lnMa2On
                    maTxt := maTxt + "  " + lnMa2Type + " " + str.tostring(lnMa2Len)
                if showMa and lnMa3On
                    maTxt := maTxt + "  " + lnMa3Type + " " + str.tostring(lnMa3Len)
                float lastV = array.get(av, n - 1)
                string txt = lvShowVal and not na(lastV) ? name + "  " + str.tostring(lastV, fs) : name
                float yLbl = na(lastV) ? yMid : f_map(lastV, bip, yMid, rBip, yBot, rLo, rHi, laneH)
                array.push(lbs, label.new(bar_index + lvOffset, yLbl, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_left, textcolor = lvTxtMode == "Series color" ? col : lvTxtCol, size = lvSizeV, tooltip = maTxt == "" ? name : name + " with" + maTxt))
    true
 
// ───────────────────────────── INTERNAL LANES: EVALUATE & DRAW ─────────────────────────────
l1on = lane1In != "None"
l2on = lane2In != "None"
l3on = lane3In != "None"
[l1v, l1ma, l1tr, l1bip, l1hL, l1lL, l1fl, l1nm, l1fs, l1nh, l1nl, l1sp, l1co] = f_pick(lane1In)
[l2v, l2ma, l2tr, l2bip, l2hL, l2lL, l2fl, l2nm, l2fs, l2nh, l2nl, l2sp, l2co] = f_pick(lane2In)
[l3v, l3ma, l3tr, l3bip, l3hL, l3lL, l3fl, l3nm, l3fs, l3nh, l3nl, l3sp, l3co] = f_pick(lane3In)
[a1H, a1L, a1iH, a1iL] = f_series(l1on, l1v, l1tr ? l1ma : l1hL, l1tr ? l1ma : l1lL, lane1Col, l1nm, l1fs, l1fl, false)
[a2H, a2L, a2iH, a2iL] = f_series(l2on, l2v, l2tr ? l2ma : l2hL, l2tr ? l2ma : l2lL, lane2Col, l2nm, l2fs, l2fl, false)
[a3H, a3L, a3iH, a3iL] = f_series(l3on, l3v, l3tr ? l3ma : l3hL, l3tr ? l3ma : l3lL, lane3Col, l3nm, l3fs, l3fl, false)
l1R = l1fl ? a1L : a1H
l1G = l1fl ? a1H : a1L
l2R = l2fl ? a2L : a2H
l2G = l2fl ? a2H : a2L
l3R = l3fl ? a3L : a3H
l3G = l3fl ? a3H : a3L
l1Zone = not l1tr and l1hL != l1lL
l2Zone = not l2tr and l2hL != l2lL
l3Zone = not l3tr and l3hL != l3lL
l1RIn = l1Zone and (l1fl ? a1iL : a1iH)
l1GIn = l1Zone and (l1fl ? a1iH : a1iL)
l2RIn = l2Zone and (l2fl ? a2iL : a2iH)
l2GIn = l2Zone and (l2fl ? a2iH : a2iL)
l3RIn = l3Zone and (l3fl ? a3iL : a3iH)
l3GIn = l3Zone and (l3fl ? a3iH : a3iL)
int laneK2 = l1on ? 2 : 1
int laneK3 = (l1on ? 1 : 0) + (l2on ? 1 : 0) + 1
f_lane(l1on, 1, l1v, l1tr, l1bip, l1hL, l1lL, l1R, l1G, l1fl, l1nm, l1fs, lane1Col, l1nh, l1nl, l1sp, l1co)
f_lane(l2on, laneK2, l2v, l2tr, l2bip, l2hL, l2lL, l2R, l2G, l2fl, l2nm, l2fs, lane2Col, l2nh, l2nl, l2sp, l2co)
f_lane(l3on, laneK3, l3v, l3tr, l3bip, l3hL, l3lL, l3R, l3G, l3fl, l3nm, l3fs, lane3Col, l3nh, l3nl, l3sp, l3co)
nLanes = (l1on ? 1 : 0) + (l2on ? 1 : 0) + (l3on ? 1 : 0)
 
 
 
// ───────────────────────────── COMBINE SIGNALS ─────────────────────────────
string redNames = ""
string grnNames = ""
redNames := f_add(redNames, sH1, "MMTW")
redNames := f_add(redNames, sH2, "MMFI")
redNames := f_add(redNames, sH3, "MMOH")
redNames := f_add(redNames, sH4, "MMOF")
redNames := f_add(redNames, sH5, "MMTH")
redNames := f_add(redNames, sH6, "S5TW")
redNames := f_add(redNames, sH7, "S5FI")
redNames := f_add(redNames, sH8, "S5OH")
redNames := f_add(redNames, sH9, "S5TH")
redNames := f_add(redNames, sH10, "NDTW")
redNames := f_add(redNames, sH11, "NDFI")
redNames := f_add(redNames, sH12, "NDTH")
redNames := f_add(redNames, sH13, "MMFD")
redNames := f_add(redNames, sH14, "S5FD")
redNames := f_add(redNames, sH15, "NDFD")
redNames := f_add(redNames, sH16, "NCFD")
redNames := f_add(redNames, sH17, "DIFD")
redNames := f_add(redNames, sH18, "R2FD")
redNames := f_add(redNames, sH19, "ADV% NY")
redNames := f_add(redNames, sH20, "ADV% NQ")
redNames := f_add(redNames, sH21, "UPV% NY")
redNames := f_add(redNames, sH22, "UPV% NQ")
redNames := f_add(redNames, sH23, "HL% NY")
redNames := f_add(redNames, sH24, "HL% NQ")
redNames := f_add(redNames, l1R, l1nm)
redNames := f_add(redNames, l2R, l2nm)
redNames := f_add(redNames, l3R, l3nm)
grnNames := f_add(grnNames, sL1, "MMTW")
grnNames := f_add(grnNames, sL2, "MMFI")
grnNames := f_add(grnNames, sL3, "MMOH")
grnNames := f_add(grnNames, sL4, "MMOF")
grnNames := f_add(grnNames, sL5, "MMTH")
grnNames := f_add(grnNames, sL6, "S5TW")
grnNames := f_add(grnNames, sL7, "S5FI")
grnNames := f_add(grnNames, sL8, "S5OH")
grnNames := f_add(grnNames, sL9, "S5TH")
grnNames := f_add(grnNames, sL10, "NDTW")
grnNames := f_add(grnNames, sL11, "NDFI")
grnNames := f_add(grnNames, sL12, "NDTH")
grnNames := f_add(grnNames, sL13, "MMFD")
grnNames := f_add(grnNames, sL14, "S5FD")
grnNames := f_add(grnNames, sL15, "NDFD")
grnNames := f_add(grnNames, sL16, "NCFD")
grnNames := f_add(grnNames, sL17, "DIFD")
grnNames := f_add(grnNames, sL18, "R2FD")
grnNames := f_add(grnNames, sL19, "ADV% NY")
grnNames := f_add(grnNames, sL20, "ADV% NQ")
grnNames := f_add(grnNames, sL21, "UPV% NY")
grnNames := f_add(grnNames, sL22, "UPV% NQ")
grnNames := f_add(grnNames, sL23, "HL% NY")
grnNames := f_add(grnNames, sL24, "HL% NQ")
grnNames := f_add(grnNames, l1G, l1nm)
grnNames := f_add(grnNames, l2G, l2nm)
grnNames := f_add(grnNames, l3G, l3nm)
 
bool anyRed   = redNames != ""
bool anyGrn   = grnNames != ""
bool anyRedIn = iH1 or iH2 or iH3 or iH4 or iH5 or iH6 or iH7 or iH8 or iH9 or iH10 or iH11 or iH12 or iH13 or iH14 or iH15 or iH16 or iH17 or iH18 or iH19 or iH20 or iH21 or iH22 or iH23 or iH24 or l1RIn or l2RIn or l3RIn
bool anyGrnIn = iL1 or iL2 or iL3 or iL4 or iL5 or iL6 or iL7 or iL8 or iL9 or iL10 or iL11 or iL12 or iL13 or iL14 or iL15 or iL16 or iL17 or iL18 or iL19 or iL20 or iL21 or iL22 or iL23 or iL24 or l1GIn or l2GIn or l3GIn
 
// ───────────────────────────── SWING-TRADING SIGNALS ─────────────────────────────
bool okBarG = not confirmOnly or barstate.isconfirmed
bool tfNew  = nz(ta.change(time(tfI))) != 0  // first chart bar of a new internals period (daily by default)
evSizeV = f_size(evSizeIn)
 
// Regime score
int regScore = (v9 > 50 ? 1 : 0) + (v2 > 50 ? 1 : 0) + (sumNQ > sumMaNQ ? 1 : 0) + (nnhNY > 0 ? 1 : 0)
string regTxt = regScore >= 3 ? "Risk-on" : regScore == 2 ? "Mixed" : "Risk-off"
bool regChange = regOn and okBarG and bar_index > 0 and regTxt != regTxt[1]
 
// Zweig Breadth Thrust
bool zbtEv = zbtOn and okBarG and zbtNY and (not zbtNY[1] or tfNew)
int  zbtAgo = ta.barssince(zbtNY and (not zbtNY[1] or tfNew))
 
// Washout / overheat
float wsS = wsShortIn == "NCFD" ? v16 : wsShortIn == "MMFD" ? v13 : wsShortIn == "S5FD" ? v14 : v15
float wsM = wsMidIn == "MMFI" ? v2 : wsMidIn == "S5FI" ? v7 : wsMidIn == "NDFI" ? v11 : wsMidIn == "MMTW" ? v1 : v6
bool washNow = not na(wsS) and not na(wsM) and wsS < wsShortLo and wsM < wsMidLo
bool heatNow = not na(wsS) and not na(wsM) and wsS > wsShortHi and wsM > wsMidHi
bool washEv  = wsOn and okBarG and washNow and not washNow[1]
bool heatEv  = wsOn and okBarG and heatNow and not heatNow[1]
 
// Price / breadth divergence
float divG  = divGaugeIn == "MMFI" ? v2 : divGaugeIn == "S5FI" ? v7 : divGaugeIn == "NDFI" ? v11 : divGaugeIn == "MMTH" ? v5 : divGaugeIn == "S5TH" ? v9 : divGaugeIn == "MMTW" ? v1 : v6
float divGH = ta.highest(divG, divLen)
float divGL = ta.lowest(divG, divLen)
bool priceNewHi = high >= ta.highest(high, divLen)
bool priceNewLo = low <= ta.lowest(low, divLen)
bool bearDivNow = not na(divG) and priceNewHi and divG <= divGH - divTol
bool bullDivNow = not na(divG) and priceNewLo and divG >= divGL + divTol
bool bearDivEv  = divOn and okBarG and bearDivNow and not bearDivNow[1]
bool bullDivEv  = divOn and okBarG and bullDivNow and not bullDivNow[1]
int  bearDivAgo = ta.barssince(bearDivNow)
int  bullDivAgo = ta.barssince(bullDivNow)
 
// 90% volume days
bool up90Ev = v90On and okBarG and v90TodayUp and (not v90TodayUp[1] or tfNew)
bool dn90Ev = v90On and okBarG and v90TodayDn and (not v90TodayDn[1] or tfNew)
 
// Event markers on the price chart
f_ev(bool cond, bool bull, string txt, string tip) =>
    if evMk and cond
        label.new(bar_index, bull ? low : high, txt, xloc = xloc.bar_index, yloc = bull ? yloc.belowbar : yloc.abovebar, color = bull ? evBullCol : evBearCol, style = bull ? label.style_label_up : label.style_label_down, textcolor = evTxtCol, size = evSizeV, tooltip = tip, force_overlay = true)
 
f_ev(zbtEv, true, "ZBT", "Zweig Breadth Thrust (NYSE)")
f_ev(washEv, true, "WASH", "Washout: " + wsShortIn + " < " + str.tostring(wsShortLo) + " and " + wsMidIn + " < " + str.tostring(wsMidLo))
f_ev(heatEv, false, "HEAT", "Overheat: " + wsShortIn + " > " + str.tostring(wsShortHi) + " and " + wsMidIn + " > " + str.tostring(wsMidHi))
f_ev(bearDivEv, false, "DIV", "Bearish divergence: new " + str.tostring(divLen) + "-bar high, " + divGaugeIn + " below its high")
f_ev(bullDivEv, true, "DIV", "Bullish divergence: new " + str.tostring(divLen) + "-bar low, " + divGaugeIn + " above its low")
f_ev(v90Mk and up90Ev, true, "90", "90% up-volume day (NYSE)")
f_ev(v90Mk and dn90Ev, false, "90", "90% down-volume day (NYSE)")
f_ev(regChange and regTxt == "Risk-on", true, "ON", "Breadth regime changed to Risk-on")
f_ev(regChange and regTxt == "Risk-off", false, "OFF", "Breadth regime changed to Risk-off")
 
string evNames = ""
evNames := f_add(evNames, zbtEv, "Zweig Breadth Thrust")
evNames := f_add(evNames, washEv, "Washout")
evNames := f_add(evNames, heatEv, "Overheat")
evNames := f_add(evNames, bearDivEv, "Bearish divergence (" + divGaugeIn + ")")
evNames := f_add(evNames, bullDivEv, "Bullish divergence (" + divGaugeIn + ")")
evNames := f_add(evNames, up90Ev, "90% up-volume day")
evNames := f_add(evNames, dn90Ev, "90% down-volume day")
evNames := f_add(evNames, regChange, "Regime now " + regTxt)
 
// ───────────────────────────── LAST-VALUE LABELS (0-100 area) ─────────────────────────────
// Drawn together and nudged apart so labels never overlap; placed to the right of the last bar so they never cover lines.
f_lvAdd(array<float> ys, array<string> ts, array<color> cs, bool show, float v, string name, color c) =>
    if show and not na(v)
        array.push(ys, v)
        array.push(ts, lvShowVal ? name + "  " + str.tostring(v, fmt) : name)
        array.push(cs, c)
 
var array<label> lvLbls = array.new<label>()
if barstate.islast
    for lb in lvLbls
        label.delete(lb)
    array.clear(lvLbls)
    if showLv and showPct
        array<float>  lvYs = array.new<float>()
        array<string> lvTs = array.new<string>()
        array<color>  lvCs = array.new<color>()
        f_lvAdd(lvYs, lvTs, lvCs, s1, v1, "MMTW", c1)
        f_lvAdd(lvYs, lvTs, lvCs, s2, v2, "MMFI", c2)
        f_lvAdd(lvYs, lvTs, lvCs, s3, v3, "MMOH", c3)
        f_lvAdd(lvYs, lvTs, lvCs, s4, v4, "MMOF", c4)
        f_lvAdd(lvYs, lvTs, lvCs, s5, v5, "MMTH", c5)
        f_lvAdd(lvYs, lvTs, lvCs, s6, v6, "S5TW", c6)
        f_lvAdd(lvYs, lvTs, lvCs, s7, v7, "S5FI", c7)
        f_lvAdd(lvYs, lvTs, lvCs, s8, v8, "S5OH", c8)
        f_lvAdd(lvYs, lvTs, lvCs, s9, v9, "S5TH", c9)
        f_lvAdd(lvYs, lvTs, lvCs, s10, v10, "NDTW", c10)
        f_lvAdd(lvYs, lvTs, lvCs, s11, v11, "NDFI", c11)
        f_lvAdd(lvYs, lvTs, lvCs, s12, v12, "NDTH", c12)
        f_lvAdd(lvYs, lvTs, lvCs, s13, v13, "MMFD", c13)
        f_lvAdd(lvYs, lvTs, lvCs, s14, v14, "S5FD", c14)
        f_lvAdd(lvYs, lvTs, lvCs, s15, v15, "NDFD", c15)
        f_lvAdd(lvYs, lvTs, lvCs, s16, v16, "NCFD", c16)
        f_lvAdd(lvYs, lvTs, lvCs, s17, v17, "DIFD", c17)
        f_lvAdd(lvYs, lvTs, lvCs, s18, v18, "R2FD", c18)
        f_lvAdd(lvYs, lvTs, lvCs, s19, v19, "ADV% NY", c19)
        f_lvAdd(lvYs, lvTs, lvCs, s20, v20, "ADV% NQ", c20)
        f_lvAdd(lvYs, lvTs, lvCs, s21, v21, "UPV% NY", c21)
        f_lvAdd(lvYs, lvTs, lvCs, s22, v22, "UPV% NQ", c22)
        f_lvAdd(lvYs, lvTs, lvCs, s23, v23, "HL% NY", c23)
        f_lvAdd(lvYs, lvTs, lvCs, s24, v24, "HL% NQ", c24)
        int lvN = array.size(lvYs)
        if lvN > 0
            float panelSpan = 100.0 + nLanes * (laneH + laneGap)
            float lvGap = panelSpan * lvSpace / 100.0
            array<int> lvOrder = array.sort_indices(lvYs, order.descending)
            float prevY = na
            for j = 0 to lvN - 1
                int ii = array.get(lvOrder, j)
                float y = array.get(lvYs, ii)
                y := na(prevY) ? y : math.min(y, prevY - lvGap)
                prevY := y
                color cc = array.get(lvCs, ii)
                array.push(lvLbls, label.new(bar_index + lvOffset, y, array.get(lvTs, ii), xloc = xloc.bar_index, yloc = yloc.price, color = lvStyleIn == "Label" ? cc : color(na), style = label.style_label_left, textcolor = lvStyleIn == "Label" ? lvTxtCol : lvTxtMode == "Series color" ? cc : lvTxtCol, size = lvSizeV))
 
// ───────────────────────────── PLOTS: 0-100 SUBPANEL ─────────────────────────────
 
plot(showPct and s1 ? v1 : na, "MMTW", color = c1, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s1 ? display.all - display.price_scale : display.none)
plot(showPct and s2 ? v2 : na, "MMFI", color = c2, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s2 ? display.all - display.price_scale : display.none)
plot(showPct and s3 ? v3 : na, "MMOH", color = c3, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s3 ? display.all - display.price_scale : display.none)
plot(showPct and s4 ? v4 : na, "MMOF", color = c4, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s4 ? display.all - display.price_scale : display.none)
plot(showPct and s5 ? v5 : na, "MMTH", color = c5, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s5 ? display.all - display.price_scale : display.none)
plot(showPct and s6 ? v6 : na, "S5TW", color = c6, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s6 ? display.all - display.price_scale : display.none)
plot(showPct and s7 ? v7 : na, "S5FI", color = c7, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s7 ? display.all - display.price_scale : display.none)
plot(showPct and s8 ? v8 : na, "S5OH", color = c8, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s8 ? display.all - display.price_scale : display.none)
plot(showPct and s9 ? v9 : na, "S5TH", color = c9, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s9 ? display.all - display.price_scale : display.none)
plot(showPct and s10 ? v10 : na, "NDTW", color = c10, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s10 ? display.all - display.price_scale : display.none)
plot(showPct and s11 ? v11 : na, "NDFI", color = c11, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s11 ? display.all - display.price_scale : display.none)
plot(showPct and s12 ? v12 : na, "NDTH", color = c12, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s12 ? display.all - display.price_scale : display.none)
plot(showPct and s13 ? v13 : na, "MMFD", color = c13, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s13 ? display.all - display.price_scale : display.none)
plot(showPct and s14 ? v14 : na, "S5FD", color = c14, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s14 ? display.all - display.price_scale : display.none)
plot(showPct and s15 ? v15 : na, "NDFD", color = c15, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s15 ? display.all - display.price_scale : display.none)
plot(showPct and s16 and ncStyleIn != "FOMO style" ? v16 : na, "NCFD", color = c16, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s16 and ncStyleIn != "FOMO style" ? display.all - display.price_scale : display.none)
plotbar(ncO, ncH, ncL, ncC, "NCFD bars", color = ncC >= ncO ? ncUpCol : ncDnCol, display = showPct and s16 and ncStyleIn == "FOMO style" ? display.all - display.price_scale : display.none)
plot(showPct and s17 ? v17 : na, "DIFD", color = c17, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s17 ? display.all - display.price_scale : display.none)
plot(showPct and s18 ? v18 : na, "R2FD", color = c18, linewidth = lwIn, style = plotStyle5, histbase = baseIn, display = showPct and s18 ? display.all - display.price_scale : display.none)
plot(showPct and s19 ? v19 : na, "ADV% NY", color = c19, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s19 ? display.all - display.price_scale : display.none)
plot(showPct and s20 ? v20 : na, "ADV% NQ", color = c20, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s20 ? display.all - display.price_scale : display.none)
plot(showPct and s21 ? v21 : na, "UPV% NY", color = c21, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s21 ? display.all - display.price_scale : display.none)
plot(showPct and s22 ? v22 : na, "UPV% NQ", color = c22, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s22 ? display.all - display.price_scale : display.none)
plot(showPct and s23 ? v23 : na, "HL% NY", color = c23, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s23 ? display.all - display.price_scale : display.none)
plot(showPct and s24 ? v24 : na, "HL% NQ", color = c24, linewidth = lwIn, style = plotStyle, histbase = baseIn, display = showPct and s24 ? display.all - display.price_scale : display.none)
 
// ───────────────────────────── DATA WINDOW VALUES (for checking against source data) ─────────────────────────────
// These draw nothing; hover any bar and open the Data Window to read the exact values.
// Plot budget (TradingView max 64): 25 plots + 24 input colors + NCFD plotbar 5 + 2 alertconditions + 1 bgcolor + 2 fills = 59, plus these 3 = 62.
plot(mcoNQ, "DW NAMO / MCO Nasdaq", display = display.data_window)
plot(sumNY, "DW NYSI / Summation NYSE", display = display.data_window)
plot(sumNQ, "DW NASI / Summation Nasdaq", display = display.data_window)
 
// ───────────────────────────── LANE SCALE ANCHOR ─────────────────────────────
// Invisible line at the bottom of the last lane so the subpanel always has room for the lanes.
plot(nLanes > 0 ? -nLanes * (laneH + laneGap) : na, "Lane scale anchor", color = color.new(color.gray, 100), editable = false, display = display.pane)
 
// ───────────────────────────── LEVELS & ZONES ─────────────────────────────
// 0-100 area (invisible 0/100 lines lock the scale)
hTop = hline(100, "Scale top (0-100 lock)", color = color.new(color.gray, 100), editable = false, display = showPct ? display.all : display.none)
hBot = hline(0, "Scale bottom (0-100 lock)", color = color.new(color.gray, 100), editable = false, display = showPct ? display.all : display.none)
hZHi = hline(gHi, "Zone edge high", color = color.new(color.gray, 100), editable = false, display = showPct ? display.all : display.none)
hZLo = hline(gLo, "Zone edge low", color = color.new(color.gray, 100), editable = false, display = showPct ? display.all : display.none)
fill(hTop, hZHi, color = zoneHiCol, title = "High zone", display = showPct and showZone and useGlobal ? display.all : display.none)
fill(hZLo, hBot, color = zoneLoCol, title = "Low zone", display = showPct and showZone and useGlobal ? display.all : display.none)
hline(gHi, "High threshold", color = thrHiCol, linestyle = thrStyle, linewidth = thrWidth, display = showPct and showThr and useGlobal ? display.all : display.none)
hline(gLo, "Low threshold", color = thrLoCol, linestyle = thrStyle, linewidth = thrWidth, display = showPct and showThr and useGlobal ? display.all : display.none)
hline(50, "Midline", color = midCol, linestyle = hline.style_dotted, linewidth = 1, display = showPct and showMid ? display.all : display.none)
 
// ───────────────────────────── SUBPANEL BACKGROUND ─────────────────────────────
color bgCol = na
if bgMode == "While in zone"
    bgCol := anyRedIn ? bgHiCol : anyGrnIn ? bgLoCol : na
else if bgMode == "On signal bars"
    bgCol := anyRed ? bgHiCol : anyGrn ? bgLoCol : na
bgcolor(bgCol, title = "Subpanel highlight")
 
// ───────────────────────────── PRICE-CHART SIGNALS ─────────────────────────────
if showPx and pxHiOn and anyRed
    string tHi = pxNames ? (pxHiText == "" ? redNames : pxHiText + "\n" + redNames) : pxHiText
    label.new(bar_index, high, tHi, xloc = xloc.bar_index, yloc = pxHiYloc, color = pxHiCol, style = pxHiStyle, textcolor = pxHiTxtCol, size = pxHiSizeV, tooltip = "Breadth RED signal: " + redNames, force_overlay = true)
if showPx and pxLoOn and anyGrn
    string tLo = pxNames ? (pxLoText == "" ? grnNames : pxLoText + "\n" + grnNames) : pxLoText
    label.new(bar_index, low, tLo, xloc = xloc.bar_index, yloc = pxLoYloc, color = pxLoCol, style = pxLoStyle, textcolor = pxLoTxtCol, size = pxLoSizeV, tooltip = "Breadth GREEN signal: " + grnNames, force_overlay = true)
 
// ───────────────────────────── TABLE ─────────────────────────────
// Direction and percentile series (computed every bar so their history exists)
adlDNY = adlNY - adlMaNY
adlDNQ = adlNQ - adlMaNQ
ch_v1 = v1 - v1[chgLen]
ch_v2 = v2 - v2[chgLen]
ch_v3 = v3 - v3[chgLen]
ch_v4 = v4 - v4[chgLen]
ch_v5 = v5 - v5[chgLen]
ch_v6 = v6 - v6[chgLen]
ch_v7 = v7 - v7[chgLen]
ch_v8 = v8 - v8[chgLen]
ch_v9 = v9 - v9[chgLen]
ch_v10 = v10 - v10[chgLen]
ch_v11 = v11 - v11[chgLen]
ch_v12 = v12 - v12[chgLen]
ch_v13 = v13 - v13[chgLen]
ch_v14 = v14 - v14[chgLen]
ch_v15 = v15 - v15[chgLen]
ch_v16 = v16 - v16[chgLen]
ch_v17 = v17 - v17[chgLen]
ch_v18 = v18 - v18[chgLen]
ch_v19 = v19 - v19[chgLen]
ch_v20 = v20 - v20[chgLen]
ch_v21 = v21 - v21[chgLen]
ch_v22 = v22 - v22[chgLen]
ch_v23 = v23 - v23[chgLen]
ch_v24 = v24 - v24[chgLen]
ch_nnhNY = nnhNY - nnhNY[chgLen]
ch_nnhNQ = nnhNQ - nnhNQ[chgLen]
ch_mcoNY = mcoNY - mcoNY[chgLen]
ch_mcoNQ = mcoNQ - mcoNQ[chgLen]
ch_sumNY = sumNY - sumNY[chgLen]
ch_sumNQ = sumNQ - sumNQ[chgLen]
ch_adlDNY = adlDNY - adlDNY[chgLen]
ch_adlDNQ = adlDNQ - adlDNQ[chgLen]
ch_pcTot = pcTot - pcTot[chgLen]
ch_pcEq = pcEq - pcEq[chgLen]
pr_v1 = f_pctl(v1)
pr_v2 = f_pctl(v2)
pr_v3 = f_pctl(v3)
pr_v4 = f_pctl(v4)
pr_v5 = f_pctl(v5)
pr_v6 = f_pctl(v6)
pr_v7 = f_pctl(v7)
pr_v8 = f_pctl(v8)
pr_v9 = f_pctl(v9)
pr_v10 = f_pctl(v10)
pr_v11 = f_pctl(v11)
pr_v12 = f_pctl(v12)
pr_v13 = f_pctl(v13)
pr_v14 = f_pctl(v14)
pr_v15 = f_pctl(v15)
pr_v16 = f_pctl(v16)
pr_v17 = f_pctl(v17)
pr_v18 = f_pctl(v18)
pr_v19 = f_pctl(v19)
pr_v20 = f_pctl(v20)
pr_v21 = f_pctl(v21)
pr_v22 = f_pctl(v22)
pr_v23 = f_pctl(v23)
pr_v24 = f_pctl(v24)
pr_nnhNY = f_pctl(nnhNY)
pr_nnhNQ = f_pctl(nnhNQ)
pr_mcoNY = f_pctl(mcoNY)
pr_mcoNQ = f_pctl(mcoNQ)
pr_sumNY = f_pctl(sumNY)
pr_sumNQ = f_pctl(sumNQ)
pr_adlDNY = f_pctl(adlDNY)
pr_adlDNQ = f_pctl(adlDNQ)
pr_pcTot = f_pctl(pcTot)
pr_pcEq = f_pctl(pcEq)
 
tblHorizB = tblLayIn == "Horizontal"
 
f_gt(float x, string fs) =>
    "▲ > " + str.tostring(x, fs)
 
f_lt(float x, string fs) =>
    "▼ < " + str.tostring(x, fs)
 
// Writes one cell; part 0 = name, 1 = value, 2 = status, 3 = percentile
f_put(table tb, int idx, int part, string txt, color tc, color bg, string tip) =>
    int col = tblHorizB ? idx : part
    int row = tblHorizB ? part : idx
    table.cell(tb, col, row, txt, text_color = tc, text_size = tblSizeV, bgcolor = bg, tooltip = tip, text_halign = text.align_center)
 
// Numeric metric column/row. Returns the next free index.
f_cell(table tb, int idx, bool show, string name, color nameCol, float v, string vf, bool up, bool dn, string upTxt, string dnTxt, bool flip, float chg, float pctl) =>
    int nx = idx
    if show
        color redBg = color.new(#C2565F, 85)
        color grnBg = color.new(#4F9F86, 85)
        string st   = up ? upTxt : dn ? dnTxt : "—"
        color  stBg = up ? (flip ? grnBg : redBg) : dn ? (flip ? redBg : grnBg) : color(na)
        string arw  = showChg and not na(chg) ? (chg > 0 ? " ▲" : chg < 0 ? " ▼" : " ▸") : ""
        string vTxt = na(v) ? "n/a" : str.tostring(v, vf) + arw
        string tip  = showChg and not na(chg) ? "Change vs " + str.tostring(chgLen) + " bars ago: " + str.tostring(chg, vf) : ""
        f_put(tb, idx, 0, name, nameCol, color(na), "")
        f_put(tb, idx, 1, vTxt, tblTxtCol, color(na), tip)
        f_put(tb, idx, 2, st, tblTxtCol, stBg, "")
        if showPctl
            f_put(tb, idx, 3, na(pctl) ? "—" : str.tostring(pctl, "0") + "%ile", tblTxtCol, color(na), "Percentile within the last " + str.tostring(pctLen) + " bars")
        nx := idx + 1
    nx
 
// Text column/row for signals. Returns the next free index.
f_tcell(table tb, int idx, bool show, string name, string vTxt, string st, color stBg, string tip) =>
    int nx = idx
    if show
        f_put(tb, idx, 0, name, tblTxtCol, color(na), "")
        f_put(tb, idx, 1, vTxt, tblTxtCol, color(na), tip)
        f_put(tb, idx, 2, st, tblTxtCol, stBg, "")
        if showPctl
            f_put(tb, idx, 3, "", tblTxtCol, color(na), "")
        nx := idx + 1
    nx
 
f_ago(int n) =>
    na(n) ? "—" : n == 0 ? "today" : str.tostring(n) + " bars ago"
 
var table tbl = na
if barstate.isfirst and showTbl
    if tblOnPrice
        tbl := table.new(tblPosV, 50, 50, bgcolor = tblBgCol, border_color = color.new(#787B86, 80), border_width = 1, force_overlay = true)
    else
        tbl := table.new(tblPosV, 50, 50, bgcolor = tblBgCol, border_color = color.new(#787B86, 80), border_width = 1)
 
if showTbl and barstate.islast
    color redBgT = color.new(#C2565F, 85)
    color grnBgT = color.new(#4F9F86, 85)
    string pcSfx = pcLen > 1 ? " (" + str.tostring(pcLen) + "d)" : ""
    string hlSfx = hlLen > 1 ? " (" + str.tostring(hlLen) + "d)" : ""
    // header labels
    f_put(tbl, 0, 0, "Breadth", tblTxtCol, color(na), "")
    f_put(tbl, 0, 1, "Value", tblTxtCol, color(na), "")
    f_put(tbl, 0, 2, "Status", tblTxtCol, color(na), "")
    if showPctl
        f_put(tbl, 0, 3, "Pctl", tblTxtCol, color(na), "")
    int r = 1
    // swing-trading signals
    r := f_tcell(tbl, r, regOn and tReg, "Regime", str.tostring(regScore) + " / 4", regTxt, regTxt == "Risk-on" ? grnBgT : regTxt == "Risk-off" ? redBgT : color(na), "S5TH > 50, MMFI > 50, NASI > MA, NYSE NH > NL")
    r := f_tcell(tbl, r, zbtOn and tZbt, "Zweig thrust", na(zbtEmaNY) ? "n/a" : str.tostring(zbtEmaNY * 100, "0.0") + "%", na(zbtAgo) ? "—" : "Fired " + f_ago(zbtAgo), not na(zbtAgo) and zbtAgo <= 20 ? grnBgT : color(na), "10-day EMA of NYSE advances share; thrust = from < 40% to > 61.5% within 10 days")
    r := f_tcell(tbl, r, wsOn and tWs, wsShortIn + " / " + wsMidIn, (na(wsS) ? "n/a" : str.tostring(wsS, "0")) + " / " + (na(wsM) ? "n/a" : str.tostring(wsM, "0")), washNow ? "Washout" : heatNow ? "Overheat" : "—", washNow ? grnBgT : heatNow ? redBgT : color(na), "Washout: both below their Lows. Overheat: both above their Highs.")
    r := f_tcell(tbl, r, divOn and tDiv, "Divergence · " + divGaugeIn, na(divG) ? "n/a" : str.tostring(divG, "0.0"), bearDivNow ? "Bearish" : bullDivNow ? "Bullish" : (nz(bearDivAgo, 9999) < nz(bullDivAgo, 9999) ? "Bear " + f_ago(bearDivAgo) : not na(bullDivAgo) ? "Bull " + f_ago(bullDivAgo) : "—"), bearDivNow ? redBgT : bullDivNow ? grnBgT : color(na), "Latest price / breadth divergence over " + str.tostring(divLen) + " bars")
    r := f_tcell(tbl, r, v90On and t90, "90% days (" + str.tostring(v90Len) + "d)", na(v90Up) ? "n/a" : "▲" + str.tostring(v90Up, "0") + " ▼" + str.tostring(v90Dn, "0"), v90TodayUp ? "Up day" : v90TodayDn ? "Down day" : "—", v90TodayUp ? grnBgT : v90TodayDn ? redBgT : color(na), "Count of 90% up- and down-volume days (NYSE)")
    r := f_cell(tbl, r, tMA and s1, "MMTW", tblNameCol ? c1 : tblTxtCol, v1, fmt, v1 > hi1, v1 < lo1, f_gt(hi1, fmt), f_lt(lo1, fmt), false, ch_v1, pr_v1)
    r := f_cell(tbl, r, tMA and s2, "MMFI", tblNameCol ? c2 : tblTxtCol, v2, fmt, v2 > hi2, v2 < lo2, f_gt(hi2, fmt), f_lt(lo2, fmt), false, ch_v2, pr_v2)
    r := f_cell(tbl, r, tMA and s3, "MMOH", tblNameCol ? c3 : tblTxtCol, v3, fmt, v3 > hi3, v3 < lo3, f_gt(hi3, fmt), f_lt(lo3, fmt), false, ch_v3, pr_v3)
    r := f_cell(tbl, r, tMA and s4, "MMOF", tblNameCol ? c4 : tblTxtCol, v4, fmt, v4 > hi4, v4 < lo4, f_gt(hi4, fmt), f_lt(lo4, fmt), false, ch_v4, pr_v4)
    r := f_cell(tbl, r, tMA and s5, "MMTH", tblNameCol ? c5 : tblTxtCol, v5, fmt, v5 > hi5, v5 < lo5, f_gt(hi5, fmt), f_lt(lo5, fmt), false, ch_v5, pr_v5)
    r := f_cell(tbl, r, tMA and s6, "S5TW", tblNameCol ? c6 : tblTxtCol, v6, fmt, v6 > hi6, v6 < lo6, f_gt(hi6, fmt), f_lt(lo6, fmt), false, ch_v6, pr_v6)
    r := f_cell(tbl, r, tMA and s7, "S5FI", tblNameCol ? c7 : tblTxtCol, v7, fmt, v7 > hi7, v7 < lo7, f_gt(hi7, fmt), f_lt(lo7, fmt), false, ch_v7, pr_v7)
    r := f_cell(tbl, r, tMA and s8, "S5OH", tblNameCol ? c8 : tblTxtCol, v8, fmt, v8 > hi8, v8 < lo8, f_gt(hi8, fmt), f_lt(lo8, fmt), false, ch_v8, pr_v8)
    r := f_cell(tbl, r, tMA and s9, "S5TH", tblNameCol ? c9 : tblTxtCol, v9, fmt, v9 > hi9, v9 < lo9, f_gt(hi9, fmt), f_lt(lo9, fmt), false, ch_v9, pr_v9)
    r := f_cell(tbl, r, tMA and s10, "NDTW", tblNameCol ? c10 : tblTxtCol, v10, fmt, v10 > hi10, v10 < lo10, f_gt(hi10, fmt), f_lt(lo10, fmt), false, ch_v10, pr_v10)
    r := f_cell(tbl, r, tMA and s11, "NDFI", tblNameCol ? c11 : tblTxtCol, v11, fmt, v11 > hi11, v11 < lo11, f_gt(hi11, fmt), f_lt(lo11, fmt), false, ch_v11, pr_v11)
    r := f_cell(tbl, r, tMA and s12, "NDTH", tblNameCol ? c12 : tblTxtCol, v12, fmt, v12 > hi12, v12 < lo12, f_gt(hi12, fmt), f_lt(lo12, fmt), false, ch_v12, pr_v12)
    r := f_cell(tbl, r, tMA and s13, "MMFD", tblNameCol ? c13 : tblTxtCol, v13, fmt, v13 > hi13, v13 < lo13, f_gt(hi13, fmt), f_lt(lo13, fmt), false, ch_v13, pr_v13)
    r := f_cell(tbl, r, tMA and s14, "S5FD", tblNameCol ? c14 : tblTxtCol, v14, fmt, v14 > hi14, v14 < lo14, f_gt(hi14, fmt), f_lt(lo14, fmt), false, ch_v14, pr_v14)
    r := f_cell(tbl, r, tMA and s15, "NDFD", tblNameCol ? c15 : tblTxtCol, v15, fmt, v15 > hi15, v15 < lo15, f_gt(hi15, fmt), f_lt(lo15, fmt), false, ch_v15, pr_v15)
    r := f_cell(tbl, r, tMA and s16, "NCFD", tblNameCol ? c16 : tblTxtCol, v16, fmt, v16 > hi16, v16 < lo16, f_gt(hi16, fmt), f_lt(lo16, fmt), false, ch_v16, pr_v16)
    r := f_cell(tbl, r, tMA and s17, "DIFD", tblNameCol ? c17 : tblTxtCol, v17, fmt, v17 > hi17, v17 < lo17, f_gt(hi17, fmt), f_lt(lo17, fmt), false, ch_v17, pr_v17)
    r := f_cell(tbl, r, tMA and s18, "R2FD", tblNameCol ? c18 : tblTxtCol, v18, fmt, v18 > hi18, v18 < lo18, f_gt(hi18, fmt), f_lt(lo18, fmt), false, ch_v18, pr_v18)
    r := f_cell(tbl, r, tAdv1, "% adv · NYSE", tblTxtCol, v19, fmt, v19 > hi19, v19 < lo19, f_gt(hi19, fmt), f_lt(lo19, fmt), false, ch_v19, pr_v19)
    r := f_cell(tbl, r, tAdv2, "% adv · Nasdaq", tblTxtCol, v20, fmt, v20 > hi20, v20 < lo20, f_gt(hi20, fmt), f_lt(lo20, fmt), false, ch_v20, pr_v20)
    r := f_cell(tbl, r, tUpv1, "% up vol · NYSE", tblTxtCol, v21, fmt, v21 > hi21, v21 < lo21, f_gt(hi21, fmt), f_lt(lo21, fmt), false, ch_v21, pr_v21)
    r := f_cell(tbl, r, tUpv2, "% up vol · Nasdaq", tblTxtCol, v22, fmt, v22 > hi22, v22 < lo22, f_gt(hi22, fmt), f_lt(lo22, fmt), false, ch_v22, pr_v22)
    r := f_cell(tbl, r, tHl1, "Highs share" + hlSfx + " · NYSE", tblTxtCol, v23, fmt, v23 > hi23, v23 < lo23, f_gt(hi23, fmt), f_lt(lo23, fmt), false, ch_v23, pr_v23)
    r := f_cell(tbl, r, tHl2, "Highs share" + hlSfx + " · Nasdaq", tblTxtCol, v24, fmt, v24 > hi24, v24 < lo24, f_gt(hi24, fmt), f_lt(lo24, fmt), false, ch_v24, pr_v24)
    r := f_cell(tbl, r, tNnh1, "Net new highs · NYSE", tblTxtCol, nnhNY, "0", nnhNY > nnhHi, nnhNY < nnhLo, f_gt(nnhHi, "0"), f_lt(nnhLo, "0"), nnhFlip, ch_nnhNY, pr_nnhNY)
    r := f_cell(tbl, r, tNnh2, "Net new highs · Nasdaq", tblTxtCol, nnhNQ, "0", nnhNQ > nnhHi, nnhNQ < nnhLo, f_gt(nnhHi, "0"), f_lt(nnhLo, "0"), nnhFlip, ch_nnhNQ, pr_nnhNQ)
    r := f_cell(tbl, r, tMco1, useRA ? "NYMO" : "McClellan Osc · NYSE", tblTxtCol, mcoNY, "0.0", mcoNY > mcoHi, mcoNY < mcoLo, f_gt(mcoHi, "0"), f_lt(mcoLo, "0"), mcoFlip, ch_mcoNY, pr_mcoNY)
    r := f_cell(tbl, r, tMco2, useRA ? "NAMO" : "McClellan Osc · Nasdaq", tblTxtCol, mcoNQ, "0.0", mcoNQ > mcoHi, mcoNQ < mcoLo, f_gt(mcoHi, "0"), f_lt(mcoLo, "0"), mcoFlip, ch_mcoNQ, pr_mcoNQ)
    r := f_cell(tbl, r, tSum1, (useRA ? "NYSI" : "Summation NYSE") + " vs EMA" + str.tostring(sumMaLen), tblTxtCol, sumNY, "0", sumNY > sumMaNY, sumNY < sumMaNY, "▲ above MA", "▼ below MA", trendFlip, ch_sumNY, pr_sumNY)
    r := f_cell(tbl, r, tSum2, (useRA ? "NASI" : "Summation Nasdaq") + " vs EMA" + str.tostring(sumMaLen), tblTxtCol, sumNQ, "0", sumNQ > sumMaNQ, sumNQ < sumMaNQ, "▲ above MA", "▼ below MA", trendFlip, ch_sumNQ, pr_sumNQ)
    r := f_cell(tbl, r, tAdl1, "A/D Line vs EMA" + str.tostring(adMaLen) + " · NYSE", tblTxtCol, adlDNY, "0", adlDNY > 0, adlDNY < 0, "▲ above MA", "▼ below MA", trendFlip, ch_adlDNY, pr_adlDNY)
    r := f_cell(tbl, r, tAdl2, "A/D Line vs EMA" + str.tostring(adMaLen) + " · Nasdaq", tblTxtCol, adlDNQ, "0", adlDNQ > 0, adlDNQ < 0, "▲ above MA", "▼ below MA", trendFlip, ch_adlDNQ, pr_adlDNQ)
    r := f_cell(tbl, r, tPc1, "Put/Call total" + pcSfx, tblTxtCol, pcTot, "0.00", pcTot > pctHi, pcTot < pctLo, f_gt(pctHi, "0.00"), f_lt(pctLo, "0.00"), pcFlip, ch_pcTot, pr_pcTot)
    r := f_cell(tbl, r, tPc2, "Put/Call equity" + pcSfx, tblTxtCol, pcEq, "0.00", pcEq > pceHi, pcEq < pceLo, f_gt(pceHi, "0.00"), f_lt(pceLo, "0.00"), pcFlip, ch_pcEq, pr_pcEq)
 
// ───────────────────────────── ALERTS ─────────────────────────────
alertcondition(anyRed, "Breadth RED signal", "Breadth RED signal on {{ticker}} ({{interval}})")
alertcondition(anyGrn, "Breadth GREEN signal", "Breadth GREEN signal on {{ticker}} ({{interval}})")
 
if alertFnOn and anyRed
    alert("Breadth RED signal: " + redNames + " | Chart: " + syminfo.ticker + " " + timeframe.period, alertFreq)
if alertFnOn and anyGrn
    alert("Breadth GREEN signal: " + grnNames + " | Chart: " + syminfo.ticker + " " + timeframe.period, alertFreq)
if alertFnOn and evNames != ""
    alert("Breadth event: " + evNames + " | Chart: " + syminfo.ticker + " " + timeframe.period, alertFreq)

← 返回列表