Skip to Main Content
Back to website
Indicator Disclaimer | Report this indicator

QuantRange

QuantRange is a volatility and options-trading indicator. It projects the price range the market is expected to cover during the week, signals trades at the edges of that range, and shows option fair values.

FEATURES

  1. Weekly expected move bands: ±1σ (inner) and ±1.5σ (outer), anchored to the prior close and reset every week. The inner zone is shaded.
  2. Four volatility sources: real options IV, GARCH(1,1), Realized HV, or Legacy GARCH.
  3. BUY/SELL signals at the bands, with entry, stop and target lines on the chart.
  4. Black-Scholes fair value and Greeks for the real option contract.

KEY SETTINGS

  • Vol Source: Switch Vol Source between Options IV, GARCH, Realized HV and Legacy GARCH, and keep the one whose bands fit your ticker and timeframe best. The dashboard's Band Hit Rate (ideal about 68%) helps you compare them.
  • IV Target DTE: the expiry whose IV is used (7 suits weekly bands).
  • Band Mult / Outer Mult: width of the 1σ and 1.5σ bands.
  • Signal Mode: Strict Band Reversals (BUY at the lower band, SELL at the upper band), All Trend Flips (midline crosses), Breakouts Only, or Reversals + Breakouts.
  • Cooldown (bars): minimum candles between signals.
  • Max ADX For Fades: above this, the dashboard marks the market as trending.
  • Target Cap ATR / Stop Buffer ATR: control how far the target and stop sit from entry.
  • Risk Free % / Dividend Yield %: used for option pricing.

DASHBOARD

  • Bias: LONG or SHORT while a signal is active, otherwise WAIT, with a reason (e.g. "Near lower band – need green reversal bar").
  • Entry / Target / Stop: the trade levels drawn on the chart.
  • Vol Source / Band Vol Used: where the band volatility comes from (green = real IV) and its value.
  • 1 sigma Move: expected weekly move in dollars and percent. Upper/Lower show each band's price and distance.
  • ADX: TRENDING or RANGING.
  • Fair Call / Put, Delta, Theta: Black-Scholes values for the real at-the-money contract. Compare with broker quotes to spot cheap or expensive options.
  • Band Hit Rate: share of past weeks that closed inside the 1σ band. The ideal is about 68%.
  • Bottom banner: "Premium RICH" means IV is well above realized volatility, "Premium CHEAP" means well below.

HOW TO USE

  1. Treat the inner bands as the normal weekly range and the outer bands as extremes.
  2. In a RANGING market, take a BUY at the lower band or a SELL at the upper band after the reversal candle closes.
  3. In a TRENDING market, reversals are riskier. Skip them or use Breakouts mode.
  4. Use the stop line as invalidation and the target line as the first profit level.
  5. For options, compare Fair Call/Put with market prices. RICH premium favors selling, CHEAP favors buying.

Best on 15 minute charts, also other timeframes like 5M,30M,1H and daily.

TSBuild26

describe_indicator('QuantRange', 'upper');

//====================================================
// SECTION 1 - INPUTS
//====================================================
// Volatility source
const volSource      = input.select('Vol Source', 'Legacy GARCH', ['Options IV', 'GARCH', 'Realized HV', 'Legacy GARCH']);
const useOptionsIV   = volSource === 'Options IV';
const targetDTE      = input.number('IV Target DTE', 7, { min: 1, max: 30 });
const hvDays         = input.number('HV Window (days)', 20, { min: 5, max: 100 });
const garchAlpha     = input.number('GARCH Alpha', 0.10, { min: 0.01, max: 0.49 });
const garchBeta      = input.number('GARCH Beta', 0.85, { min: 0.10, max: 0.98 });
const rateInput      = input.number('Risk Free %', 4.5, { min: 0.0, max: 20.0 });
const divYield       = input.number('Dividend Yield %', 0.0, { min: 0.0, max: 20.0 });
const bandMult       = input.number('Band Mult (1 sigma)', 1.0, { min: 0.5, max: 3.0 });
const outerMult      = input.number('Outer Mult (1.5 sigma)', 1.5, { min: 1.0, max: 4.0 });

// Signals
const signalFilter   = input.select('Signal Mode', 'Strict Band Reversals Only', [
    'Strict Band Reversals Only',
    'All Trend Flips',
    'Breakouts Only',
    'Reversals + Breakouts'
]);
const cooldownBars   = input.number('Cooldown (bars)', 5, { min: 1, max: 50 });
const adxPeriod      = input.number('ADX Period', 14, { min: 5, max: 50 });
const brkJump        = input.number('Brk Vol Jump %', 12, { min: 1, max: 100 });
const tgtAtrCap      = input.number('Target Cap ATR', 3, { min: 1, max: 10 });
const adxMax         = input.number('Max ADX For Fades', 25, { min: 10, max: 50 });
const waitClose      = input.boolean('Ignore Live Bar', false);

// Trade plan
const stopLook       = input.number('Stop Lookback', 3, { min: 1, max: 20 });
const stopAtr        = input.number('Stop Buffer ATR', 0.5, { min: 0.1, max: 3 });
const minRiskAtr     = input.number('Min Risk ATR', 0.5, { min: 0.1, max: 3 });
const minRR          = input.number('Min R:R (0 = off)', 0, { min: 0, max: 5 });
const maxHold        = input.number('Max Hold (bars)', 40, { min: 5, max: 500 });

// Display
const showBands        = input.boolean('Show Bands', true);
const shadeZone        = input.boolean('Shade Band Zone', true);
const showTradeSignals = input.boolean('Show Signals', true);
const showTradeLines   = input.boolean('Show Trade Lines', true);
const showTable        = input.boolean('Show Dashboard', true);
const compactTable     = input.boolean('Compact Dashboard', false);
const tableOffsetX     = input.number('Table Offset X', -70, { min: -500, max: 500 });
const tableOffsetY     = input.number('Table Offset Y', 35, { min: -200, max: 500 });

//====================================================
// SECTION 2 - CONSTANTS
//====================================================
const n = close.length;
const r = rateInput / 100.0;
const q = divYield / 100.0;
const SQRT_2PI = Math.sqrt(2 * Math.PI);
const WEEK_FRAC = 5 / 252;

const GREEN = '#00e676';
const RED = '#ff5252';
const AMBER = '#ffab40';
const CYAN = '#00E5FF';
const PINK = '#FF4081';
const GREY = '#b0bec5';
const WHITE = '#e0f2f1';

function toMs(ts) {
    let t = ts;
    if (t < 1e12) t = t * 1000;
    return t;
}

//====================================================
// SECTION 3 - TIMEFRAME DETECTION (fixes annualization)
//====================================================
let minStep = 1e15;
let stepFrom = n - 300;
if (stepFrom < 1) stepFrom = 1;
for (let i = stepFrom; i < n; i++) {
    const dt = toMs(time[i]) - toMs(time[i - 1]);
    if (dt > 0 && dt < minStep) minStep = dt;
}
if (minStep === 1e15) minStep = 86400000;

const dayOf = Array(n).fill(0);
for (let i = 0; i < n; i++) dayOf[i] = Math.floor(toMs(time[i]) / 86400000);

const dayCounts = {};
for (let i = 0; i < n; i++) {
    const d = dayOf[i];
    if (!dayCounts[d]) dayCounts[d] = 0;
    dayCounts[d] = dayCounts[d] + 1;
}
const todayKey = dayOf[n - 1];
const completedCounts = [];
const dayKeys = Object.keys(dayCounts);
for (let i = 0; i < dayKeys.length; i++) {
    const d = parseInt(dayKeys[i], 10);
    if (d !== todayKey) completedCounts.push(dayCounts[d]);
}
let barsPerDay = 1;
if (minStep < 80000000) {
    if (completedCounts.length > 0) {
        completedCounts.sort((a, b) => a - b);
        barsPerDay = completedCounts[Math.floor(completedCounts.length / 2)];
    } else {
        barsPerDay = dayCounts[todayKey];
    }
    if (barsPerDay < 1) barsPerDay = 1;
}
let barsPerYear;
if (minStep < 80000000) barsPerYear = barsPerDay * 252;
else if (minStep < 4 * 86400000) barsPerYear = 252;
else if (minStep < 10 * 86400000) barsPerYear = 52;
else barsPerYear = 12;

//====================================================
// SECTION 4 - MATH HELPERS & BLACK-SCHOLES
//====================================================
function normPdf(x) {
    return Math.exp(-0.5 * x * x) / SQRT_2PI;
}
function normCdf(x) {
    const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741;
    const a4 = -1.453152027, a5 = 1.061405429, p = 0.3275911;
    const sign = x >= 0 ? 1.0 : -1.0;
    const ax = Math.abs(x);
    const t = 1.0 / (1.0 + p * ax);
    const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));
    const erf = 1.0 - poly * Math.exp(-ax * ax);
    return (1.0 + sign * erf) / 2.0;
}
function bsd1(S, K, T, sigma) {
    if (sigma <= 0 || T <= 0 || S <= 0 || K <= 0) return 0;
    return (Math.log(S / K) + (r - q + 0.5 * sigma * sigma) * T) / (sigma * Math.sqrt(T));
}
function bsCall(S, K, T, sigma) {
    if (sigma <= 0 || T <= 0) return Math.max(S - K, 0);
    const d1 = bsd1(S, K, T, sigma);
    const d2 = d1 - sigma * Math.sqrt(T);
    return S * Math.exp(-q * T) * normCdf(d1) - K * Math.exp(-r * T) * normCdf(d2);
}
function bsPut(S, K, T, sigma) {
    if (sigma <= 0 || T <= 0) return Math.max(K - S, 0);
    const d1 = bsd1(S, K, T, sigma);
    const d2 = d1 - sigma * Math.sqrt(T);
    return K * Math.exp(-r * T) * normCdf(-d2) - S * Math.exp(-q * T) * normCdf(-d1);
}
function bsDeltaCall(S, K, T, sigma) {
    if (sigma <= 0 || T <= 0) return S >= K ? 1.0 : 0.0;
    return Math.exp(-q * T) * normCdf(bsd1(S, K, T, sigma));
}
function bsThetaCall(S, K, T, sigma) {
    if (sigma <= 0 || T <= 0 || S <= 0) return 0;
    const d1 = bsd1(S, K, T, sigma);
    const d2 = d1 - sigma * Math.sqrt(T);
    const p1 = -S * Math.exp(-q * T) * normPdf(d1) * sigma / (2 * Math.sqrt(T));
    const p2 = -r * K * Math.exp(-r * T) * normCdf(d2);
    const p3 = q * S * Math.exp(-q * T) * normCdf(d1);
    return (p1 + p2 + p3) / 365.0;
}

function daysFromCivil(y, m, d) {
    let yy = y;
    if (m <= 2) yy = yy - 1;
    const era = Math.floor((yy >= 0 ? yy : yy - 399) / 400);
    const yoe = yy - era * 400;
    const doy = Math.floor((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + (d - 1);
    const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
    return era * 146097 + doe - 719468;
}
const nowStamp = (typeof current !== 'undefined' && current !== null && typeof current.now === 'number' && current.now > 0)
    ? current.now
    : time[n - 1];
const nowDays = Math.floor(toMs(nowStamp) / 86400000);
function keyToDTE(key) {
    const y = parseInt(key.slice(0, 2), 10) + 2000;
    const m = parseInt(key.slice(2, 4), 10);
    const d = parseInt(key.slice(4, 6), 10);
    return daysFromCivil(y, m, d) - nowDays;
}

//====================================================
// SECTION 5 - ATR + ADX (Wilder, self-contained)
//====================================================
const atrA = Array(n).fill(null);
const adxA = Array(n).fill(null);
(function () {
    const p = adxPeriod;
    if (n <= 2 * p + 1) return;
    let sTR = 0, sP = 0, sM = 0, dxSum = 0, adxVal = 0;
    for (let i = 1; i < n; i++) {
        const tr = Math.max(high[i] - low[i], Math.abs(high[i] - close[i - 1]), Math.abs(low[i] - close[i - 1]));
        const up = high[i] - high[i - 1];
        const dn = low[i - 1] - low[i];
        const pdm = (up > dn && up > 0) ? up : 0;
        const mdm = (dn > up && dn > 0) ? dn : 0;
        if (i <= p) {
            sTR += tr; sP += pdm; sM += mdm;
        } else {
            sTR = sTR - sTR / p + tr;
            sP = sP - sP / p + pdm;
            sM = sM - sM / p + mdm;
        }
        if (i >= p) {
            atrA[i] = sTR / p;
            const pdi = sTR > 0 ? 100 * sP / sTR : 0;
            const mdi = sTR > 0 ? 100 * sM / sTR : 0;
            const dx = (pdi + mdi) > 0 ? 100 * Math.abs(pdi - mdi) / (pdi + mdi) : 0;
            if (i < 2 * p - 1) {
                dxSum += dx;
            } else if (i === 2 * p - 1) {
                dxSum += dx;
                adxVal = dxSum / p;
                adxA[i] = adxVal;
            } else {
                adxVal = (adxVal * (p - 1) + dx) / p;
                adxA[i] = adxVal;
            }
        }
    }
})();

//====================================================
// SECTION 6 - REALIZED VOL (HV) + GARCH(1,1), per-bar correct
//====================================================
const lr = Array(n).fill(null);
for (let i = 1; i < n; i++) {
    if (close[i] > 0 && close[i - 1] > 0) lr[i] = Math.log(close[i] / close[i - 1]);
}

const cs = Array(n + 1).fill(0);
const cs2 = Array(n + 1).fill(0);
const cc = Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
    const v = lr[i];
    cs[i + 1] = cs[i] + (v !== null ? v : 0);
    cs2[i + 1] = cs2[i] + (v !== null ? v * v : 0);
    cc[i + 1] = cc[i] + (v !== null ? 1 : 0);
}
const hvWin = Math.max(10, Math.round(hvDays * barsPerDay));
const hvA = Array(n).fill(null);
for (let i = hvWin; i < n; i++) {
    const cnt = cc[i + 1] - cc[i + 1 - hvWin];
    if (cnt > 2) {
        const winSum = cs[i + 1] - cs[i + 1 - hvWin];
        const sq = cs2[i + 1] - cs2[i + 1 - hvWin];
        const v = (sq - winSum * winSum / cnt) / (cnt - 1);
        hvA[i] = Math.sqrt(Math.max(v, 0) * barsPerYear);
    }
}

// Long-run variance is calibrated causally (expanding mean) so omega is on the same per-bar scale as the data
const garchA = Array(n).fill(null);
(function () {
    let prevVar = null, sumSq = 0, cnt = 0;
    for (let i = 0; i < n; i++) {
        if (lr[i] === null) continue;
        const eps2 = lr[i] * lr[i];
        sumSq += eps2;
        cnt++;
        if (cnt < 30) { prevVar = sumSq / cnt; continue; }
        const omega = (1 - garchAlpha - garchBeta) * (sumSq / cnt);
        const nv = omega + garchAlpha * eps2 + garchBeta * prevVar;
        prevVar = nv;
        garchA[i] = Math.sqrt(nv * barsPerYear);
    }
})();

// Legacy GARCH = the exact volatility the original QuantRange used (fixed omega, sqrt(252) on every bar)
const legacyA = Array(n).fill(null);
(function () {
    const om = (1.0 - garchAlpha - garchBeta) * 0.0002;
    let pv = null;
    for (let i = 0; i < n; i++) {
        let v;
        if (i === 0 || lr[i] === null) {
            v = lr[i] !== null ? lr[i] * lr[i] : 0.0001;
        } else {
            v = om + garchAlpha * lr[i] * lr[i] + garchBeta * pv;
        }
        pv = v;
        legacyA[i] = Math.sqrt(v * 252);
    }
})();

const sigmaModel = Array(n).fill(0.25);
for (let i = 0; i < n; i++) {
    let s = null;
    if (volSource === 'Legacy GARCH') {
        s = legacyA[i];
    } else if (volSource === 'Realized HV') {
        if (hvA[i] !== null) s = hvA[i];
        else if (garchA[i] !== null) s = garchA[i];
    } else {
        if (garchA[i] !== null) s = garchA[i];
        else if (hvA[i] !== null) s = hvA[i];
    }
    if (s === null) s = 0.25;
    if (s < 0.05) s = 0.05;
    if (s > 3) s = 3;
    sigmaModel[i] = s;
}

//====================================================
// SECTION 7 - REAL OPTIONS IV (nearest expiry to target DTE)
//====================================================
const spot = close[n - 1];
let ivOK = false;
let ivSigma = 0, ivDTE = 0, ivStrike = 0, ivExp = '';

function normIV(v) {
    if (v === undefined || v === null || !(v > 0)) return 0;
    return v > 3 ? v / 100 : v;
}

if (useOptionsIV) {
    try {
        const callsData = await request.options_data_for_all_expirations(current.ticker, 30, ['iv', 'oi'], 'C');
        const putsData = await request.options_data_for_all_expirations(current.ticker, 30, ['iv', 'oi'], 'P');
        if (callsData && !callsData.error && putsData && !putsData.error) {
            let bestExp = null, bestScore = 1e9;
            for (const exp in callsData.resultByExpiration) {
                const dte = keyToDTE(exp);
                if (dte < 1) continue;
                const score = Math.abs(dte - targetDTE);
                if (score < bestScore) { bestScore = score; bestExp = exp; }
            }
            if (bestExp !== null) {
                const cE = callsData.resultByExpiration[bestExp] || {};
                const pE = (putsData.resultByExpiration && putsData.resultByExpiration[bestExp]) || {};
                let bestDist = 1e12, bestIV = 0, bestK = 0;
                for (const sStr in cE) {
                    const s = parseFloat(sStr);
                    const cl = cE[sStr] ? cE[sStr].C : null;
                    if (!cl) continue;
                    const civ = normIV(cl.iv);
                    if (civ <= 0) continue;
                    const pl = pE[sStr] ? pE[sStr].P : null;
                    const piv = pl ? normIV(pl.iv) : 0;
                    const iv = piv > 0 ? (civ + piv) / 2 : civ;
                    const dist = Math.abs(s - spot);
                    if (dist < bestDist) { bestDist = dist; bestIV = iv; bestK = s; }
                }
                if (bestIV >= 0.05 && bestIV <= 3) {
                    ivOK = true;
                    ivSigma = bestIV;
                    ivStrike = bestK;
                    ivDTE = keyToDTE(bestExp);
                    ivExp = bestExp;
                }
            }
        }
    } catch (e) {
        ivOK = false;
    }
}

//====================================================
// SECTION 8 - WEEKLY EXPECTED MOVE BANDS
//====================================================
const isNewWeek = Array(n).fill(false);
let lastWeekStart = 0;
(function () {
    let lastDow = -1, lastDay = -999;
    for (let i = 0; i < n; i++) {
        const dow = (dayOf[i] + 4) % 7;
        if (i === 0 || dow < lastDow || dayOf[i] - lastDay >= 6) {
            isNewWeek[i] = true;
            lastWeekStart = i;
        }
        lastDow = dow;
        lastDay = dayOf[i];
    }
})();

const upperBand = series_of(null);
const lowerBand = series_of(null);
const upperOuter = series_of(null);
const lowerOuter = series_of(null);
const midBand = series_of(null);

let aP = 0, aU = 0, aL = 0, aOU = 0, aOL = 0, aSigma = 0, aFromIV = false;
let curWeekStart = 0;
let calIn = 0, calTot = 0;

for (let i = 0; i < n; i++) {
    if (isNewWeek[i] || aP === 0) {
        // Calibration: did the week that just ended close inside its 1-sigma band?
        if (i > 0 && curWeekStart > 0 && !aFromIV && upperBand[i - 1] !== null) {
            calTot++;
            if (close[i - 1] <= upperBand[i - 1] && close[i - 1] >= lowerBand[i - 1]) calIn++;
        }
        curWeekStart = i;
        const base = i > 0 ? close[i - 1] : close[i];
        const useIV = ivOK && i >= lastWeekStart;
        const sig = useIV ? ivSigma : (i > 0 ? sigmaModel[i - 1] : sigmaModel[i]);
        const em = base * sig * Math.sqrt(WEEK_FRAC);
        aP = base;
        aSigma = sig;
        aFromIV = useIV;
        aU = base + em * bandMult;
        aL = base - em * bandMult;
        aOU = base + em * outerMult;
        aOL = base - em * outerMult;
    }
    upperBand[i] = aU;
    lowerBand[i] = aL;
    upperOuter[i] = aOU;
    lowerOuter[i] = aOL;
    midBand[i] = aP;
}
const bandSigmaNow = aSigma;
const bandFromIV = aFromIV;
const emNow = upperBand[n - 1] - midBand[n - 1];

//====================================================
// SECTION 9 - SIGNAL ENGINE WITH TRADE PLAN + BACKTEST
//====================================================
const buySig = series_of(null);
const sellSig = series_of(null);
const brkBuySig = series_of(null);
const brkSellSig = series_of(null);

const trades = [];

function resolveTrade(t) {
    const risk = Math.abs(t.entry - t.stop);
    const end = Math.min(t.i + maxHold, n - 1);
    for (let j = t.i + 1; j <= end; j++) {
        const hitStop = t.dir === 1 ? low[j] <= t.stop : high[j] >= t.stop;
        const hitTgt = t.dir === 1 ? high[j] >= t.target : low[j] <= t.target;
        if (hitStop) { t.res = 'LOSS'; t.R = -1; t.exit = j; return; }
        if (hitTgt) { t.res = 'WIN'; t.R = t.rr; t.exit = j; return; }
    }
    if (t.i + maxHold <= n - 1) {
        const j = t.i + maxHold;
        t.res = 'TIMEOUT';
        t.R = t.dir * (close[j] - t.entry) / risk;
        t.exit = j;
        return;
    }
    t.res = 'OPEN';
    t.R = t.dir * (close[n - 1] - t.entry) / risk;
    t.exit = n;
}

(function () {
    let lastSigIdx = -999;
    let trend = 0; // 0 neutral, 1 long, -1 short (same state machine as the original)
    const lastEval = waitClose ? n - 2 : n - 1;
    const modeRev = signalFilter === 'Strict Band Reversals Only' || signalFilter === 'Reversals + Breakouts';
    const modeFlip = signalFilter === 'All Trend Flips';
    const modeBrk = signalFilter === 'Breakouts Only' || signalFilter === 'Reversals + Breakouts';

    for (let i = 2; i <= lastEval; i++) {
        if (garchA[i] === null || garchA[i - 1] === null || atrA[i] === null) continue;
        if (i - lastSigIdx < cooldownBars) continue;

        const S = close[i], O = open[i], pC = close[i - 1];
        const H = high[i], L = low[i], pH = high[i - 1], pL = low[i - 1];
        const up = upperBand[i], lo = lowerBand[i], mid = midBand[i];
        const a = atrA[i];
        const relChange = garchA[i - 1] > 0 ? (garchA[i] - garchA[i - 1]) / garchA[i - 1] : 0;

        let cand = null;

        // BUY
        if (modeRev) {
            if ((L <= lo * 1.002 || pL <= lo * 1.002) && S > O && S > pC && trend !== 1) cand = { dir: 1, type: 'REV', target: mid };
        } else if (modeFlip) {
            if (pC <= mid && S > mid && S > O && trend !== 1) cand = { dir: 1, type: 'FLIP', target: up };
        }
        // SELL
        if (cand === null) {
            if (modeRev) {
                if ((H >= up * 0.998 || pH >= up * 0.998) && S < O && S < pC && trend !== -1) cand = { dir: -1, type: 'REV', target: mid };
            } else if (modeFlip) {
                if (pC >= mid && S < mid && S < O && trend !== -1) cand = { dir: -1, type: 'FLIP', target: lo };
            }
        }
        // Breakouts (vol jump + band break)
        if (cand === null && modeBrk && relChange > brkJump / 100 && S > up && pC <= up && S > O && trend !== 1) cand = { dir: 1, type: 'BRK', target: S + (up - mid) };
        if (cand === null && modeBrk && relChange > brkJump / 100 && S < lo && pC >= lo && S < O && trend !== -1) cand = { dir: -1, type: 'BRK', target: S - (mid - lo) };
        if (cand === null) continue;

        // Trade plan (display + stats only, does not decide whether a signal fires unless Min R:R > 0)
        const capDist = tgtAtrCap * a;
        if (cand.dir * (cand.target - S) <= 0) cand.target = S + cand.dir * capDist;
        if (cand.dir * (cand.target - S) > capDist) cand.target = S + cand.dir * capDist;

        let swing = cand.dir === 1 ? 1e12 : -1e12;
        for (let k = Math.max(0, i - stopLook + 1); k <= i; k++) {
            if (cand.dir === 1 && low[k] < swing) swing = low[k];
            if (cand.dir === -1 && high[k] > swing) swing = high[k];
        }
        let stopPx;
        if (cand.type === 'BRK') stopPx = cand.dir === 1 ? up - stopAtr * a : lo + stopAtr * a;
        else stopPx = cand.dir === 1 ? swing - stopAtr * a : swing + stopAtr * a;
        if (Math.abs(S - stopPx) < minRiskAtr * a || (cand.dir === 1 && stopPx >= S) || (cand.dir === -1 && stopPx <= S)) {
            stopPx = cand.dir === 1 ? S - minRiskAtr * a : S + minRiskAtr * a;
        }
        const risk = Math.abs(S - stopPx);
        const rr = cand.dir * (cand.target - S) / risk;
        if (minRR > 0 && rr < minRR) continue;

        const t = { i: i, dir: cand.dir, type: cand.type, entry: S, stop: stopPx, target: cand.target, rr: rr, res: '', R: 0, exit: 0 };
        resolveTrade(t);
        trades.push(t);
        lastSigIdx = i;
        trend = cand.dir;

        if (cand.type === 'BRK') {
            if (cand.dir === 1) brkBuySig[i] = 'BUY BREAKOUT';
            else brkSellSig[i] = 'SELL BREAKOUT';
        } else {
            if (cand.dir === 1) buySig[i] = 'BUY';
            else sellSig[i] = 'SELL';
        }
    }
})();

// Stats
let nWin = 0, nLoss = 0, nTimeout = 0, sumR = 0, grossWin = 0, grossLoss = 0, nResolved = 0;
let activeTrade = null;
let lastClosed = null;
for (let k = 0; k < trades.length; k++) {
    const t = trades[k];
    if (t.res === 'OPEN') { activeTrade = t; continue; }
    nResolved++;
    lastClosed = t;
    sumR += t.R;
    if (t.R > 0) grossWin += t.R; else grossLoss += Math.abs(t.R);
    if (t.res === 'WIN') nWin++;
    else if (t.res === 'LOSS') nLoss++;
    else nTimeout++;
}
const winRate = nResolved > 0 ? (nWin / nResolved) * 100 : 0;
const avgR = nResolved > 0 ? sumR / nResolved : 0;
const profitFactor = grossLoss > 0 ? grossWin / grossLoss : (grossWin > 0 ? 99 : 0);
const calPct = calTot > 0 ? (calIn / calTot) * 100 : 0;

//====================================================
// SECTION 10 - LAST-BAR READINGS
//====================================================
const lastIdx = n - 1;
const atrNow = atrA[lastIdx] !== null ? atrA[lastIdx] : 0;
const adxNow = adxA[lastIdx] !== null ? adxA[lastIdx] : null;
const hvNow = hvA[lastIdx] !== null ? hvA[lastIdx] : null;
const garchNow = garchA[lastIdx] !== null ? garchA[lastIdx] : null;

let hvPct = null;
if (hvNow !== null) {
    let below = 0, tot = 0;
    for (let i = 0; i < n; i++) {
        if (hvA[i] !== null) { tot++; if (hvA[i] <= hvNow) below++; }
    }
    if (tot > 20) hvPct = (below / tot) * 100;
}
const ivHvRatio = (ivOK && hvNow !== null && hvNow > 0) ? ivSigma / hvNow : null;

const upNow = upperBand[lastIdx];
const loNow = lowerBand[lastIdx];
const midNow = midBand[lastIdx];
const distUpPct = (upNow - spot) / spot * 100;
const distLoPct = (spot - loNow) / spot * 100;

//====================================================
// SECTION 11 - PAINT: BANDS (always painted; null series when off)
//====================================================
const outerUpperPlot = showBands ? upperOuter : series_of(null);
const upperPlot      = showBands ? upperBand  : series_of(null);
const lowerPlot      = showBands ? lowerBand  : series_of(null);
const outerLowerPlot = showBands ? lowerOuter : series_of(null);
const midPlot        = showBands ? midBand    : series_of(null);

paint(outerUpperPlot, { name: 'Outer Target Upper', color: '#00B0FF', thickness: 1, style: 'dotted' });
const uId = paint(upperPlot, { name: 'Upper Expected Move (+1 sigma)', color: CYAN, thickness: 2, style: 'dotted' });
const lId = paint(lowerPlot, { name: 'Lower Expected Move (-1 sigma)', color: PINK, thickness: 2, style: 'dotted' });
paint(outerLowerPlot, { name: 'Outer Target Lower', color: '#F50057', thickness: 1, style: 'dotted' });
paint(midPlot, { name: 'Weekly Anchor (prior close)', color: '#9E9E9E', thickness: 1, style: 'dotted' });
// fill is unconditional too: bands are null when hidden, and opacity is 0 when shading is off
fill(uId, lId, '#00B0FF', (showBands && shadeZone) ? 0.05 : 0);

//====================================================
// SECTION 12 - PAINT: SIGNALS (always painted; null series when off)
//====================================================
const buyPlot     = showTradeSignals ? buySig     : series_of(null);
const sellPlot    = showTradeSignals ? sellSig    : series_of(null);
const brkBuyPlot  = showTradeSignals ? brkBuySig  : series_of(null);
const brkSellPlot = showTradeSignals ? brkSellSig : series_of(null);

paint(buyPlot,     { style: 'labels_below', name: 'BUY SIGNAL',     color: 'white', backgroundColor: '#00C853', backgroundBorderRadius: 4 });
paint(sellPlot,    { style: 'labels_above', name: 'SELL SIGNAL',    color: 'white', backgroundColor: '#D50000', backgroundBorderRadius: 4 });
paint(brkBuyPlot,  { style: 'labels_below', name: 'BREAKOUT BUY',   color: 'black', backgroundColor: '#00E5FF', backgroundBorderRadius: 4 });
paint(brkSellPlot, { style: 'labels_above', name: 'BREAKOUT SELL',  color: 'white', backgroundColor: '#FF4081', backgroundBorderRadius: 4 });

//====================================================
// SECTION 13 - PAINT: ACTIVE TRADE LINES (always painted)
//====================================================
const entryLine  = series_of(null);
const stopLine   = series_of(null);
const targetLine = series_of(null);
const showActive = activeTrade !== null && showTradeLines;
if (showActive) {
    for (let j = activeTrade.i; j < n; j++) {
        entryLine[j]  = activeTrade.entry;
        stopLine[j]   = activeTrade.stop;
        targetLine[j] = activeTrade.target;
    }
}
paint(entryLine,  { name: 'Entry',     color: '#9E9E9E', style: 'dotted', thickness: 1 });
paint(stopLine,   { name: 'Stop Loss', color: '#e53935', style: 'dotted', thickness: 2 });
paint(targetLine, { name: 'Target',    color: '#00c853', style: 'line',   thickness: 2 });

const projBars = 20;
function projectionOf(value) {
    const arr = [];
    for (let i = 0; i < projBars; i++) arr.push(value);
    return arr;
}
const stopP = paint_projection(projectionOf(showActive ? activeTrade.stop : null), {
    name: 'Stop Ahead', color: '#e53935', style: 'dotted', thickness: 2, ignoreWhenScaling: true, hideInLegend: true
});
const tgtP = paint_projection(projectionOf(showActive ? activeTrade.target : null), {
    name: 'Target Ahead', color: '#00c853', style: 'line', thickness: 2, ignoreWhenScaling: true, hideInLegend: true
});
// Labels are also unconditional: placeholder text, transparent when no trade 
const tgtLabelTxt  = showActive ? ('Target ' + activeTrade.target.toFixed(2) + ' | ' + activeTrade.rr.toFixed(1) + 'R') : 'Target';
const stopLabelTxt = showActive ? ('Stop ' + activeTrade.stop.toFixed(2)) : 'Stop';
paint_label_at_line(tgtP, 10, tgtLabelTxt, {
    color: showActive ? '#ffffff' : 'rgba(0,0,0,0)',
    background_color: showActive ? 'rgba(0,200,83,0.85)' : 'rgba(0,0,0,0)',
    border_radius: 4, border_width: 0
});
paint_label_at_line(stopP, 10, stopLabelTxt, {
    color: showActive ? '#ffffff' : 'rgba(0,0,0,0)',
    background_color: showActive ? 'rgba(229,57,53,0.75)' : 'rgba(0,0,0,0)',
    border_radius: 4, border_width: 0
});

//====================================================
// SECTION 14 - DASHBOARD (paint_overlay always called; empty rows when off)
//====================================================
const BG = '#0a1929';
function sec(text) {
    return { cells: [{ text: text, colspan: 2, color: '#90caf9', fontWeight: 'bold', fontSize: '10px', padding: '2px 6px', background: '#0d1b2a', borderTop: '1px solid #263238', borderBottom: '1px solid #263238' }] };
}
function row(k, v, vc) {
    return { cells: [
        { text: k, color: GREY, fontSize: '11px', padding: '2px 6px', background: BG, whiteSpace: 'nowrap' },
        { text: v, color: vc || WHITE, fontSize: '11px', fontWeight: 'bold', padding: '2px 8px', background: BG, textAlign: 'right', whiteSpace: 'nowrap' }
    ] };
}
function note(text, color) {
    return { cells: [{ text: text, colspan: 2, color: color || GREY, fontSize: '10px', padding: '2px 8px', background: BG, textAlign: 'center' }] };
}
function usd(v) { return '$' + v.toFixed(2); }

const rows = [];   // stays empty when the dashboard is hidden

if (showTable) {
    let bias = 'WAIT';
    let biasColor = AMBER;
    let reason = '';
    if (activeTrade !== null) {
        bias = activeTrade.dir === 1 ? 'LONG' : 'SHORT';
        biasColor = activeTrade.dir === 1 ? GREEN : RED;
        const typeTxt = activeTrade.type === 'REV' ? 'Band reversal' : (activeTrade.type === 'FLIP' ? 'Midline flip' : 'Band breakout');
        reason = typeTxt + ' - ' + (n - 1 - activeTrade.i) + ' bars ago';
    } else if (atrA[lastIdx] === null || adxNow === null) {
        reason = 'Warming up - need more history';
    } else if (adxNow >= adxMax) {
        reason = 'Trending (ADX ' + adxNow.toFixed(0) + ') - fades riskier';
    } else if (atrNow > 0 && (spot - loNow) / atrNow < 1) {
        reason = 'Near lower band - need green reversal bar';
    } else if (atrNow > 0 && (upNow - spot) / atrNow < 1) {
        reason = 'Near upper band - need red reversal bar';
    } else {
        reason = 'Mid-range - no edge';
    }

    rows.push({ cells: [{ text: 'QuantRange', colspan: 2, background: '#0d2137', color: '#58a6ff', fontWeight: 'bold', fontSize: '12px', padding: '4px 8px', textAlign: 'center' }] });
    rows.push(sec('Trade Plan'));
    rows.push(row('Bias', bias, biasColor));
    rows.push(note(reason, biasColor === AMBER ? GREY : biasColor));
    if (activeTrade !== null) {
        rows.push(row('Entry', usd(activeTrade.entry), WHITE));
        rows.push(row('Target', usd(activeTrade.target), GREEN));
        rows.push(row('Stop', usd(activeTrade.stop), RED));
        rows.push(row('R:R / Open P&L', activeTrade.rr.toFixed(1) + ' / ' + (activeTrade.R >= 0 ? '+' : '') + activeTrade.R.toFixed(1) + 'R', activeTrade.R >= 0 ? GREEN : RED));
    } else if (lastClosed !== null) {
        const lc = lastClosed;
        rows.push(row('Last Trade', (lc.dir === 1 ? 'LONG ' : 'SHORT ') + lc.res + ' ' + (lc.R >= 0 ? '+' : '') + lc.R.toFixed(1) + 'R', lc.R > 0 ? GREEN : RED));
    }

    rows.push(sec('Expected Move (weekly)'));
    const srcLabel = bandFromIV ? 'Options IV' : (volSource === 'Options IV' ? 'GARCH (no IV data)' : volSource);
    rows.push(row('Vol Source', srcLabel, bandFromIV ? GREEN : AMBER));
    rows.push(row('Band Vol Used', (bandSigmaNow * 100).toFixed(1) + '%', WHITE));
    rows.push(row('1 sigma Move', '+/-' + usd(emNow) + ' (' + (emNow / midNow * 100).toFixed(1) + '%)', WHITE));
    rows.push(row('Upper ' + upNow.toFixed(2), '+' + distUpPct.toFixed(2) + '% away', CYAN));
    rows.push(row('Lower ' + loNow.toFixed(2), '-' + distLoPct.toFixed(2) + '% away', PINK));

    if (!compactTable) {
        rows.push(sec('Volatility & Trend'));
        if (ivOK) rows.push(row('ATM IV (' + ivDTE + 'DTE)', (ivSigma * 100).toFixed(1) + '%', WHITE));
        else if (garchNow !== null) rows.push(row('GARCH Vol', (garchNow * 100).toFixed(1) + '%', WHITE));
        if (hvNow !== null) rows.push(row('Realized Vol (' + hvDays + 'd)', (hvNow * 100).toFixed(1) + '%', WHITE));
        if (hvPct !== null) rows.push(row('RV Percentile (loaded)', hvPct.toFixed(0) + '%', WHITE));
        if (adxNow !== null) rows.push(row('ADX', adxNow.toFixed(0) + (adxNow >= adxMax ? ' TRENDING' : ' RANGING'), adxNow >= adxMax ? AMBER : GREEN));

        if (ivOK) {
            const Tc = ivDTE / 365;
            rows.push(sec('Contract: ' + ivStrike + ' strike, ' + ivDTE + 'DTE'));
            rows.push(row('Fair Call / Put', usd(bsCall(spot, ivStrike, Tc, ivSigma)) + ' / ' + usd(bsPut(spot, ivStrike, Tc, ivSigma)), WHITE));
            rows.push(row('Call Delta', (bsDeltaCall(spot, ivStrike, Tc, ivSigma) * 100).toFixed(0) + '%', WHITE));
            rows.push(row('Call Theta / day', '-' + usd(Math.abs(bsThetaCall(spot, ivStrike, Tc, ivSigma))), '#FF7043'));
        }
        if (calTot > 0) {
            rows.push(row('1 sigma Band Hit Rate', calPct.toFixed(0) + '% (' + calTot + 'w, ideal 68%)', (calPct >= 55 && calPct <= 80) ? GREEN : AMBER));
        }
        if (ivHvRatio !== null) {
            let txt = 'Premium fair vs realized';
            let col = GREY;
            if (ivHvRatio > 1.2) { txt = 'Premium RICH vs realized (IV/RV ' + ivHvRatio.toFixed(2) + ')'; col = RED; }
            else if (ivHvRatio < 0.9) { txt = 'Premium CHEAP vs realized (IV/RV ' + ivHvRatio.toFixed(2) + ')'; col = GREEN; }
            rows.push({ cells: [{ text: txt, colspan: 2, color: col, fontWeight: 'bold', fontSize: '11px', textAlign: 'center', padding: '4px 8px', background: '#0d1b2a', borderTop: '1px solid #37474f' }] });
        } else if (!ivOK) {
            rows.push({ cells: [{ text: 'No options IV - model bands', colspan: 2, color: AMBER, fontWeight: 'bold', fontSize: '10px', textAlign: 'center', padding: '4px 8px', background: '#0d1b2a', borderTop: '1px solid #37474f' }] });
        }
    }
}

paint_overlay('QuantRangeTable', {
    position: 'top_right',
    parent: 'chart',
    order: 'above_all',
    offset_x: tableOffsetX,
    offset_y: tableOffsetY
}, {
    width: '250px',
    border: showTable ? '1px solid #37474f' : 'none',
    borderRadius: '6px',
    background: showTable ? BG : 'transparent',
    overflow: 'hidden',
    rows: rows
});
   

//====================================================
// SECTION 15 - REGISTER SIGNALS
//====================================================
register_signal(buySig, 'Bullish Band Reversal / Flip (R:R filtered)');
register_signal(sellSig, 'Bearish Band Reversal / Flip (R:R filtered)');
register_signal(brkBuySig, 'Bullish Band Breakout (ADX rising)');
register_signal(brkSellSig, 'Bearish Band Breakout (ADX rising)');