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

Kumo Matrix Pro is an institutional-grade trend-following signal engine designed to solve the two biggest challenges in technical trading: false breakouts in sideways markets and rapid signal whipsaws (flip-flops).

By fusing Ichimoku Kumo Structure, Heikin-Ashi Momentum, ATR Trailing Bands, and a 3-Tier Sideways Regime Detection Engine, Kumo Matrix Pro delivers high-probability BUY and SELL signals with maximum trend protection.


🌟 Key Features & Breakthroughs

  1. 🚫 3-Tier Sideways & Chop Filter (Zero False Signals in Ranges):
    • ADX Filter: Automatically detects weak trend strength (when ADX is below 20) and suppresses false signals during flat consolidation.
    • Choppiness Index Filter: Identifies choppy price action (when Choppiness Index is above 60) and pauses trade entries.
    • Kumo Flatness Detection: Identifies flat Senkou B clouds and greys out range-bound zones.
  2. 🔒 State-Machine Signal Locking (Whipsaw Elimination):
    • Eliminates back-to-back SELL then BUY flip-flop labels on adjacent candles.
    • Once a BUY signal fires, the engine locks into a Bullish State until a verified structural reversal occurs.
  3. 📊 Multi-Confluence Signal Entry Rules:
    🟢 BUY Signal Conditions (ALL must be met):
    🔴 SELL Signal Conditions (ALL must be met):

    • Price closes below the ATR Lower Band
    • Heikin-Ashi Candle is Red
    • Price closes below the Kijun-sen Line
    • Volume is greater than or equal to Volume Moving Average
    • Market is Trending (ADX is 20 or higher)
    • Price closes above the ATR Upper Band
    • Heikin-Ashi Candle is Green
    • Price closes above the Kijun-sen Line
    • Volume is greater than or equal to Volume Moving Average
    • Market is Trending (ADX is 20 or higher)
  4. 🎨 High-Contrast Visual Architecture:
    • Dynamic Bullish / Bearish Trend Clouds.
    • Neutral Grey Sideways Zone Highlighting for instant market regime recognition.
    • Fully registered signals for automated alerts, screening, and strategy backtesting.

TSBuild26

describe_indicator('Kumo matrix', 'price', {
    shortName: 'KUMO PRO',
    decimals: 'by_symbol',
    mainColorInheritFrom: 'Kumo Stop'
});

const tinycolor = library('tinycolor2');

// ═══════════════════════════════════════════════════════════════════════════════
// INPUT PARAMETERS
// ═══════════════════════════════════════════════════════════════════════════════

const gIchi = input.group('Ichimoku & Trend');
const tenkanLen  = gIchi.number('Tenkan Length', 9, { min: 1, max: 200 });
const kijunLen   = gIchi.number('Kijun Length', 26, { min: 1, max: 300 });
const senkouBLen = gIchi.number('Senkou B Length', 52, { min: 2, max: 500 });
const cloudShift = gIchi.number('Cloud Displacement', 26, { min: 0, max: 100 });
const cdLen      = gIchi.number('CD ATR Period', 20, { min: 2, max: 200 });
const atrMult    = gIchi.number('ATR Multiplier', 1.5, { min: 0.5, max: 5, step: 0.1 });
const atrLen     = gIchi.number('ATR Period', 9, { min: 1, max: 100 });

const gVol = input.group('Volume & Cooldown');
const useVolume   = gVol.boolean('Enable Volume Filter', true);
const volLookback = gVol.number('Volume MA Lookback', 20, { min: 1, max: 100 });
const volMult     = gVol.number('Volume Min x MA', 1.0, { min: 0.5, max: 3, step: 0.1 });
const minCooldown = gVol.number('Signal Cooldown (bars)', 3, { min: 1, max: 20 });

const gReg = input.group('Sideways Regime');
const adxPeriod         = gReg.number('ADX / DI Period', 14, { min: 5, max: 50 });
const useSidewaysFilter = gReg.boolean('Vote: Low ADX', true);
const adxThreshold      = gReg.number('ADX Sideways Below', 20, { min: 10, max: 50 });
const adxHysteresis     = gReg.number('ADX Hysteresis', 3, { min: 0, max: 15 });
const useChopFilter     = gReg.boolean('Vote: High CHOP', true);
const chopThreshold     = gReg.number('CHOP Sideways Above', 60, { min: 40, max: 80 });
const useERFilter       = gReg.boolean('Vote: Low ER', true);
const erLen             = gReg.number('ER Length', 20, { min: 5, max: 100 });
const erThreshold       = gReg.number('ER Sideways Below', 0.30, { min: 0.1, max: 0.6, step: 0.05 });
const useKijunFlat      = gReg.boolean('Vote: Flat Kijun', true);
const kijunFlatATR      = gReg.number('Kijun Flat (x ATR)', 0.30, { min: 0.05, max: 2, step: 0.05 });
const filterFlatCloud   = gReg.boolean('Vote: Flat Senkou B', true);
const minVotes          = gReg.number('Votes For Sideways', 2, { min: 1, max: 5 });
const useRangeGate      = gReg.boolean('Gate: Min Range vs ATR', true);
const minRangeATR       = gReg.number('Min Range (x ATR)', 4.0, { min: 2, max: 12, step: 0.5 });

const gTrig = input.group('Trigger Filters');
const useDI         = gTrig.boolean('Require DI Direction', true);
const useKijunDist  = gTrig.boolean('Require Kijun Distance', true);
const minKijunDist  = gTrig.number('Min Kijun Dist (xATR)', 0.30, { min: 0.05, max: 3, step: 0.05 });
const useCloudGate  = gTrig.boolean('Price Outside Cloud', true);
const useRSI        = gTrig.boolean('Require RSI Momentum', true);
const rsiLen        = gTrig.number('RSI Length', 14, { min: 2, max: 50 });
const rsiBull       = gTrig.number('RSI Min for BUY', 52, { min: 50, max: 70 });
const rsiBear       = gTrig.number('RSI Max for SELL', 48, { min: 30, max: 50 });
const useBreakout   = gTrig.boolean('Require Breakout', true);
const brkLen        = gTrig.number('Breakout Lookback', 10, { min: 3, max: 100 });

const gWhip = input.group('Whipsaw Guard');
const useWhipGuard  = gWhip.boolean('Enable Whipsaw Guard', true);
const whipLookback  = gWhip.number('Whipsaw Window (bars)', 30, { min: 5, max: 200 });
const maxFlips      = gWhip.number('Max Signals In Window', 2, { min: 1, max: 6 });
const strongAdx     = gWhip.number('ADX Override', 30, { min: 20, max: 60 });

const gStyle = input.group('Style');
const ribbonWidth    = gStyle.number('Ribbon Width', 1.0, { min: 0.3, max: 3, step: 0.1 });
const showRibbon     = gStyle.boolean('Show Glow Ribbon', true, { hide_in_legend: true });
const showLines      = gStyle.boolean('Show Trailing Stop', true, { hide_in_legend: true });
const showKumo       = gStyle.boolean('Show Kumo Cloud', true, { hide_in_legend: true });
const showSidewaysBg = gStyle.boolean('Highlight Sideways Zones', true, { hide_in_legend: true });
const paintCandles   = gStyle.boolean('Color Candles', true, { hide_in_legend: true });
const showPanel      = gStyle.boolean('Dashboard Panel', true, { hide_in_legend: true });
const showBlocked    = gStyle.boolean('Show Blocked Signals', false, { hide_in_legend: true });
const bullColor      = gStyle.color('Bullish Color', '#089981');
const bearColor      = gStyle.color('Bearish Color', '#F23645');
const kumoBullTint   = gStyle.color('Kumo Bull Tint', '#4C8DFF');
const kumoBearTint   = gStyle.color('Kumo Bear Tint', '#B26BFF');
const kijunColor     = gStyle.color('Kijun Color', '#F5B83D');

// ═══════════════════════════════════════════════════════════════════════════════
// STYLE CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

const RIBBON_LAYERS  = [0.35, 0.8, 1.3, 1.9, 2.6];
const RIBBON_OPACITY = [0.22, 0.16, 0.11, 0.07, 0.04];
const SHADE_STEPS = 20;
const GAUGE_SEGMENTS = 10;
const SPARKLINE_BARS = 60;

const COLOR_CORE = '#2B3140';
const COLOR_TEXT = '#D1D4DC';
const COLOR_MUTED = '#787B86';
const COLOR_PANEL = '#131722';
const COLOR_ROW_A = '#1E222D';
const COLOR_ROW_B = '#181C27';
const COLOR_HEADLINE = '#E7EAF0';
const COLOR_LABEL_ON_BULL = '#E8FFF8';
const COLOR_LABEL_ON_BEAR = '#FFE8EC';
const COLOR_BULL_SOFT = 'rgba(8, 153, 129, 0.20)';
const COLOR_BEAR_SOFT = 'rgba(242, 54, 69, 0.20)';
const COLOR_NEUTRAL_SOFT = 'rgba(120, 123, 134, 0.12)';

const hiddenLineOptions = {
    hidden: true,
    editorHidden: true,
    hideInLegend: true,
    hideInScriptEditor: true,
    ignoreWhenScaling: true
};

// ═══════════════════════════════════════════════════════════════════════════════
// HELPER CALCULATIONS
// ═══════════════════════════════════════════════════════════════════════════════

const barCount = close.length;
const lastIdx = barCount - 1;

function highestSeries(src, period) {
    const res = Array(src.length).fill(null);
    for (let i = 0; i < src.length; i++) {
        if (i < period - 1) continue;
        let m = -Infinity;
        for (let k = i - period + 1; k <= i; k++) {
            if (src[k] > m) m = src[k];
        }
        res[i] = m;
    }
    return res;
}

function lowestSeries(src, period) {
    const res = Array(src.length).fill(null);
    for (let i = 0; i < src.length; i++) {
        if (i < period - 1) continue;
        let m = Infinity;
        for (let k = i - period + 1; k <= i; k++) {
            if (src[k] < m) m = src[k];
        }
        res[i] = m;
    }
    return res;
}

// Ichimoku Lines
const tenkanHi = highestSeries(high, tenkanLen);
const tenkanLo = lowestSeries(low, tenkanLen);
const tenkan = for_every(tenkanHi, tenkanLo, (h, l) => (h !== null && l !== null) ? (h + l) / 2 : null);

const kijunHi = highestSeries(high, kijunLen);
const kijunLo = lowestSeries(low, kijunLen);
const kijun = for_every(kijunHi, kijunLo, (h, l) => (h !== null && l !== null) ? (h + l) / 2 : null);

const senkouBHi = highestSeries(high, senkouBLen);
const senkouBLo = lowestSeries(low, senkouBLen);
const senkouB = for_every(senkouBHi, senkouBLo, (h, l) => (h !== null && l !== null) ? (h + l) / 2 : null);

const senkouA = for_every(tenkan, kijun, (t, k) => (t !== null && k !== null) ? (t + k) / 2 : null);

// Heikin-Ashi Candles
const haClose = for_every(open, high, low, close, (o, h, l, c) => (o + h + l + c) / 4);
const haOpen = Array(barCount).fill(null);
for (let i = 0; i < barCount; i++) {
    if (i === 0) {
        haOpen[i] = (open[i] + close[i]) / 2;
    } else {
        haOpen[i] = (haOpen[i - 1] + haClose[i - 1]) / 2;
    }
}
const haGreen = for_every(haClose, haOpen, (c, o) => c > o);
const haRed   = for_every(haClose, haOpen, (c, o) => c < o);

// ATR (Wilder Smoothing) & True Range
const atrVal = Array(barCount).fill(null);
const trArr = Array(barCount).fill(0);

let atrSum = 0;
for (let i = 1; i < barCount; i++) {
    const tr = Math.max(high[i] - low[i], Math.abs(high[i] - close[i - 1]), Math.abs(low[i] - close[i - 1]));
    trArr[i] = tr;
    if (i <= atrLen) {
        atrSum += tr;
        if (i === atrLen) atrVal[i] = atrSum / atrLen;
    } else {
        atrVal[i] = (atrVal[i - 1] * (atrLen - 1) + tr) / atrLen;
    }
}

// Volume Filter MA
const volHasData = (typeof volume !== 'undefined') && volume !== null && volume.length === barCount;
const volSma = volHasData ? sma(volume, volLookback) : null;

// Raw CD ATR Levels
const hiCD = highestSeries(close, cdLen);
const loCD = lowestSeries(close, cdLen);

const rawUpper = Array(barCount).fill(null);
const rawLower = Array(barCount).fill(null);
for (let i = 0; i < barCount; i++) {
    if (hiCD[i] !== null && loCD[i] !== null && atrVal[i] !== null) {
        rawUpper[i] = hiCD[i] - atrVal[i] * atrMult;
        rawLower[i] = loCD[i] + atrVal[i] * atrMult;
    }
}

// Persistent Trailing Bands
const upperTrail = Array(barCount).fill(null);
const lowerTrail = Array(barCount).fill(null);

for (let i = 0; i < barCount; i++) {
    if (i === 0 || rawUpper[i] === null) {
        upperTrail[i] = rawUpper[i];
        lowerTrail[i] = rawLower[i];
        continue;
    }
    const prevUp = upperTrail[i - 1];
    const prevDn = lowerTrail[i - 1];

    upperTrail[i] = (prevUp === null || rawUpper[i] < prevUp || close[i - 1] > prevUp) ? rawUpper[i] : prevUp;
    lowerTrail[i] = (prevDn === null || rawLower[i] > prevDn || close[i - 1] < prevDn) ? rawLower[i] : prevDn;
}

// ═══════════════════════════════════════════════════════════════════════════════
// REGIME ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

// 1. ADX / DI
const dmPlus = Array(barCount).fill(0);
const dmMinus = Array(barCount).fill(0);

for (let i = 1; i < barCount; i++) {
    const upMove = high[i] - high[i - 1];
    const dnMove = low[i - 1] - low[i];
    dmPlus[i] = (upMove > dnMove && upMove > 0) ? upMove : 0;
    dmMinus[i] = (dnMove > upMove && dnMove > 0) ? dnMove : 0;
}

const smoothTR = Array(barCount).fill(null);
const smoothDP = Array(barCount).fill(null);
const smoothDM = Array(barCount).fill(null);
const dxVal  = Array(barCount).fill(null);
const adxVal = Array(barCount).fill(null);
const diPArr = Array(barCount).fill(null);
const diMArr = Array(barCount).fill(null);

let sumTR = 0, sumDP = 0, sumDM = 0;
for (let i = 1; i < barCount; i++) {
    if (i <= adxPeriod) {
        sumTR += trArr[i];
        sumDP += dmPlus[i];
        sumDM += dmMinus[i];
        if (i === adxPeriod) {
            smoothTR[i] = sumTR;
            smoothDP[i] = sumDP;
            smoothDM[i] = sumDM;
        }
    } else {
        smoothTR[i] = smoothTR[i - 1] - (smoothTR[i - 1] / adxPeriod) + trArr[i];
        smoothDP[i] = smoothDP[i - 1] - (smoothDP[i - 1] / adxPeriod) + dmPlus[i];
        smoothDM[i] = smoothDM[i - 1] - (smoothDM[i - 1] / adxPeriod) + dmMinus[i];
    }

    if (smoothTR[i] !== null && smoothTR[i] > 0) {
        const diP = (smoothDP[i] / smoothTR[i]) * 100;
        const diM = (smoothDM[i] / smoothTR[i]) * 100;
        diPArr[i] = diP;
        diMArr[i] = diM;
        const sumDI = diP + diM;
        const diffDI = Math.abs(diP - diM);
        dxVal[i] = sumDI > 0 ? (diffDI / sumDI) * 100 : 0;
    }
}

let sumDX = 0;
for (let i = 1; i < barCount; i++) {
    if (dxVal[i] !== null) {
        if (i < adxPeriod * 2) {
            sumDX += dxVal[i];
            if (i === adxPeriod * 2 - 1) adxVal[i] = sumDX / adxPeriod;
        } else if (adxVal[i - 1] !== null) {
            adxVal[i] = (adxVal[i - 1] * (adxPeriod - 1) + dxVal[i]) / adxPeriod;
        }
    }
}

// 2. Choppiness Index
const chopPeriod = 14;
const chopVal = Array(barCount).fill(null);

for (let i = chopPeriod; i < barCount; i++) {
    let sumTRPeriod = 0;
    let maxH = -Infinity;
    let minL = Infinity;
    for (let k = i - chopPeriod + 1; k <= i; k++) {
        sumTRPeriod += trArr[k];
        if (high[k] > maxH) maxH = high[k];
        if (low[k] < minL) minL = low[k];
    }
    const range = maxH - minL;
    if (range > 0 && sumTRPeriod > 0) {
        chopVal[i] = 100 * (Math.log10(sumTRPeriod / range) / Math.log10(chopPeriod));
    }
}

// 3. Kaufman Efficiency Ratio
const erVal = Array(barCount).fill(null);
for (let i = erLen; i < barCount; i++) {
    const netMove = Math.abs(close[i] - close[i - erLen]);
    let pathLen = 0;
    for (let k = i - erLen + 1; k <= i; k++) pathLen += Math.abs(close[k] - close[k - 1]);
    erVal[i] = pathLen > 0 ? netMove / pathLen : 0;
}

// 4. RSI (Wilder)
const rsiVal = Array(barCount).fill(null);
{
    let avgG = 0, avgL = 0;
    for (let i = 1; i < barCount; i++) {
        const ch = close[i] - close[i - 1];
        const g = ch > 0 ? ch : 0;
        const l = ch < 0 ? -ch : 0;
        if (i <= rsiLen) {
            avgG += g; avgL += l;
            if (i === rsiLen) {
                avgG /= rsiLen; avgL /= rsiLen;
                rsiVal[i] = avgL === 0 ? 100 : 100 - 100 / (1 + avgG / avgL);
            }
        } else {
            avgG = (avgG * (rsiLen - 1) + g) / rsiLen;
            avgL = (avgL * (rsiLen - 1) + l) / rsiLen;
            rsiVal[i] = avgL === 0 ? 100 : 100 - 100 / (1 + avgG / avgL);
        }
    }
}

// 5. Range-vs-ATR
const rangeATR = Array(barCount).fill(null);
for (let i = 0; i < barCount; i++) {
    if (hiCD[i] !== null && loCD[i] !== null && atrVal[i] !== null && atrVal[i] > 0) {
        rangeATR[i] = (hiCD[i] - loCD[i]) / atrVal[i];
    }
}
const effMinRange = Math.max(minRangeATR, 2 * atrMult + 0.25);

// 6. Flatness checks
function isSenkouBFlat(i) {
    if (i < 5 || senkouB[i] === null || atrVal[i] === null) return false;
    const tol = atrVal[i] * 0.02 + 1e-12;
    let flatCount = 0;
    for (let k = i - 4; k <= i; k++) {
        if (senkouB[k] !== null && Math.abs(senkouB[k] - senkouB[i]) < tol) flatCount++;
    }
    return flatCount >= 4;
}

function isKijunFlat(i) {
    if (i < 5 || kijun[i] === null || kijun[i - 5] === null || atrVal[i] === null) return false;
    return Math.abs(kijun[i] - kijun[i - 5]) < kijunFlatATR * atrVal[i];
}

// 7. Displaced cloud (the cloud drawn under current price)
function cloudTop(i) {
    const j = i - cloudShift;
    if (j < 0 || senkouA[j] === null || senkouB[j] === null) return null;
    return Math.max(senkouA[j], senkouB[j]);
}
function cloudBot(i) {
    const j = i - cloudShift;
    if (j < 0 || senkouA[j] === null || senkouB[j] === null) return null;
    return Math.min(senkouA[j], senkouB[j]);
}

// Combine into Sideways flag
const isSideways = Array(barCount).fill(false);
const sidewaysScore = Array(barCount).fill(0);
let adxLowState = false;

for (let i = 0; i < barCount; i++) {
    if (adxVal[i] !== null) {
        if (adxVal[i] < adxThreshold) adxLowState = true;
        else if (adxVal[i] > adxThreshold + adxHysteresis) adxLowState = false;
    }

    let voteCount = 0;
    if (useSidewaysFilter && adxVal[i] !== null && adxLowState) voteCount++;
    if (useChopFilter && chopVal[i] !== null && chopVal[i] > chopThreshold) voteCount++;
    if (useERFilter && erVal[i] !== null && erVal[i] < erThreshold) voteCount++;
    if (useKijunFlat && isKijunFlat(i)) voteCount++;
    if (filterFlatCloud && isSenkouBFlat(i)) voteCount++;

    const tooNarrow = useRangeGate && rangeATR[i] !== null && rangeATR[i] < effMinRange;

    sidewaysScore[i] = voteCount;
    isSideways[i] = (voteCount >= minVotes) || tooNarrow;
}

// ═══════════════════════════════════════════════════════════════════════════════
// STATE MACHINE SIGNAL ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

const hiBrk = highestSeries(close, brkLen);
const loBrk = lowestSeries(close, brkLen);

const trendState = Array(barCount).fill(0);
const buySignal = Array(barCount).fill(false);
const sellSignal = Array(barCount).fill(false);
const buyLabel = Array(barCount).fill(null);
const sellLabel = Array(barCount).fill(null);
const blockedBuy = Array(barCount).fill(null);
const blockedSell = Array(barCount).fill(null);

const signalBars = [];
const signalEvents = [];
let lastSignalBar = -999;
let currentState = 0;

for (let i = 1; i < barCount; i++) {
    if (kijun[i] === null || upperTrail[i] === null || lowerTrail[i] === null || atrVal[i] === null) {
        trendState[i] = currentState;
        continue;
    }

    const atrNow = atrVal[i];
    const volOk = !useVolume || (!volHasData || (volSma && volSma[i] !== null && volume[i] >= volSma[i] * volMult));
    const closeAboveKijun = close[i] > kijun[i];
    const closeBelowKijun = close[i] < kijun[i];
    const trendingMarket = !isSideways[i];

    const baseBuy  = close[i] > upperTrail[i] && haGreen[i] && closeAboveKijun && volOk;
    const baseSell = close[i] < lowerTrail[i] && haRed[i]   && closeBelowKijun && volOk;

    const diBuy  = !useDI || (diPArr[i] !== null && diPArr[i] > diMArr[i]);
    const diSell = !useDI || (diPArr[i] !== null && diMArr[i] > diPArr[i]);

    const distOk = !useKijunDist || Math.abs(close[i] - kijun[i]) >= minKijunDist * atrNow;

    const cT = cloudTop(i), cB = cloudBot(i);
    const cloudBuy  = !useCloudGate || (cT !== null && close[i] > cT);
    const cloudSell = !useCloudGate || (cB !== null && close[i] < cB);

    const rsiBuy  = !useRSI || (rsiVal[i] !== null && rsiVal[i] >= rsiBull);
    const rsiSell = !useRSI || (rsiVal[i] !== null && rsiVal[i] <= rsiBear);

    const brkBuy  = !useBreakout || (hiBrk[i - 1] !== null && close[i] > hiBrk[i - 1]);
    const brkSell = !useBreakout || (loBrk[i - 1] !== null && close[i] < loBrk[i - 1]);

    const buyCond  = baseBuy  && trendingMarket && diBuy  && distOk && cloudBuy  && rsiBuy  && brkBuy;
    const sellCond = baseSell && trendingMarket && diSell && distOk && cloudSell && rsiSell && brkSell;

    let recentFlips = 0;
    for (let s = signalBars.length - 1; s >= 0; s--) {
        if (i - signalBars[s] <= whipLookback) recentFlips++; else break;
    }
    const strongTrend = adxVal[i] !== null && adxVal[i] >= strongAdx;
    const whipOk = !useWhipGuard || recentFlips < maxFlips || strongTrend;

    const cooldownPassed = (i - lastSignalBar) >= minCooldown;
    const canFire = cooldownPassed && whipOk;

    if (currentState !== 1 && buyCond && canFire) {
        currentState = 1;
        buySignal[i] = true;
        buyLabel[i] = '▲ BUY';
        lastSignalBar = i;
        signalBars.push(i);
        signalEvents.push({ bar: i, price: close[i], direction: 1 });
    } else if (currentState !== -1 && sellCond && canFire) {
        currentState = -1;
        sellSignal[i] = true;
        sellLabel[i] = '▼ SELL';
        lastSignalBar = i;
        signalBars.push(i);
        signalEvents.push({ bar: i, price: close[i], direction: -1 });
    } else if (showBlocked) {
        if (currentState !== 1 && baseBuy && cooldownPassed) blockedBuy[i] = '×';
        else if (currentState !== -1 && baseSell && cooldownPassed) blockedSell[i] = '×';
    }

    trendState[i] = currentState;
}

// ═══════════════════════════════════════════════════════════════════════════════
// TREND STRENGTH (drives every gradient)
// 0 = choppy / weak  ->  1 = clean, efficient, directional trend
// ═══════════════════════════════════════════════════════════════════════════════

const strengthArr = Array(barCount).fill(null);
for (let i = 0; i < barCount; i++) {
    if (trendState[i] === 0) continue;
    const adxPart = adxVal[i] !== null ? Math.min(1, adxVal[i] / 40) : 0;
    const erPart  = erVal[i] !== null ? Math.min(1, erVal[i] / 0.6) : 0;
    let s = 0.5 * adxPart + 0.5 * erPart;
    if (isSideways[i]) s *= 0.4;
    strengthArr[i] = Math.min(1, Math.max(0, s));
}

const buildShades = targetColor => {
    const shadeList = [];
    for (let k = 0; k <= SHADE_STEPS; k++) {
        const blendAmount = 30 + (65 * k) / SHADE_STEPS;
        shadeList.push(tinycolor.mix(COLOR_CORE, targetColor, blendAmount).toHexString());
    }
    return shadeList;
};
const bullShades = buildShades(bullColor);
const bearShades = buildShades(bearColor);
const bullGlowShades = bullShades.map(s => tinycolor(s).setAlpha(0.22).toRgbString());
const bearGlowShades = bearShades.map(s => tinycolor(s).setAlpha(0.22).toRgbString());

const shadeIndexOf = strengthValue => {
    const st = strengthValue == null ? 0 : Math.min(1, Math.max(0, strengthValue));
    return Math.round(st * SHADE_STEPS);
};
const shadeOf = (dir, st) => {
    if (dir === 1) return bullShades[shadeIndexOf(st)];
    if (dir === -1) return bearShades[shadeIndexOf(st)];
    return null;
};
const glowOf = (dir, st) => {
    if (dir === 1) return bullGlowShades[shadeIndexOf(st)];
    if (dir === -1) return bearGlowShades[shadeIndexOf(st)];
    return null;
};

// ═══════════════════════════════════════════════════════════════════════════════
// PLOTTING & VISUALS
// ═══════════════════════════════════════════════════════════════════════════════

// Regime-specific stop (bull stop = lowerTrail, bear stop = upperTrail, same as v2)
function regimeStop(i, regime) {
    return regime === 1 ? lowerTrail[i] : upperTrail[i];
}

const stopLine = Array(barCount).fill(null);
for (let i = 0; i < barCount; i++) {
    if (trendState[i] !== 0) stopLine[i] = regimeStop(i, trendState[i]);
}

const stopColorSeries = for_every(trendState, strengthArr, shadeOf);
const stopGlowSeries  = for_every(trendState, strengthArr, glowOf);

// ── Layered glow ribbon (nested bands toward price, fading outward) ─────────────
function ribbonEdge(regime, offsetSign, layerScale) {
    const out = Array(barCount).fill(null);
    if (!showRibbon) return out;
    for (let i = 0; i < barCount; i++) {
        const a = atrVal[i];
        const s = regimeStop(i, regime);
        if (a === null || s === null) continue;
        const prevDir = i > 0 ? trendState[i - 1] : 0;
        if (trendState[i] === regime || prevDir === regime) {
            out[i] = s + offsetSign * layerScale * a;
        }
    }
    return out;
}

const bullBaseRef = paint(ribbonEdge(1, 0, 0), Object.assign({ name: 'Bull Ribbon Base' }, hiddenLineOptions));
const bearBaseRef = paint(ribbonEdge(-1, 0, 0), Object.assign({ name: 'Bear Ribbon Base' }, hiddenLineOptions));

for (let L = 0; L < RIBBON_LAYERS.length; L++) {
    const layerScale = RIBBON_LAYERS[L] * ribbonWidth;
    const bullOuterRef = paint(ribbonEdge(1, 1, layerScale), Object.assign({ name: `Bull Ribbon ${L + 1}` }, hiddenLineOptions));
    const bearOuterRef = paint(ribbonEdge(-1, -1, layerScale), Object.assign({ name: `Bear Ribbon ${L + 1}` }, hiddenLineOptions));
    fill(bullOuterRef, bullBaseRef, bullColor, RIBBON_OPACITY[L], `Bull Glow ${L + 1}`);
    fill(bearBaseRef, bearOuterRef, bearColor, RIBBON_OPACITY[L], `Bear Glow ${L + 1}`);
}

// ── Kumo cloud (displaced, subtle two-tone) ─────────────────────────────────────
const dispA = Array(barCount).fill(null);
const dispB = Array(barCount).fill(null);
if (showKumo) {
    for (let i = 0; i < barCount; i++) {
        const j = i - cloudShift;
        if (j < 0) continue;
        dispA[i] = senkouA[j];
        dispB[i] = senkouB[j];
    }
}
const kBullTop = for_every(dispA, dispB, (a, b) => (a !== null && b !== null && a >= b) ? a : null);
const kBullBot = for_every(dispA, dispB, (a, b) => (a !== null && b !== null && a >= b) ? b : null);
const kBearTop = for_every(dispA, dispB, (a, b) => (a !== null && b !== null && b > a) ? b : null);
const kBearBot = for_every(dispA, dispB, (a, b) => (a !== null && b !== null && b > a) ? a : null);

const kBullTopRef = paint(kBullTop, Object.assign({ name: 'Kumo Bull Top' }, hiddenLineOptions));
const kBullBotRef = paint(kBullBot, Object.assign({ name: 'Kumo Bull Bottom' }, hiddenLineOptions));
const kBearTopRef = paint(kBearTop, Object.assign({ name: 'Kumo Bear Top' }, hiddenLineOptions));
const kBearBotRef = paint(kBearBot, Object.assign({ name: 'Kumo Bear Bottom' }, hiddenLineOptions));

fill(kBullTopRef, kBullBotRef, kumoBullTint, 0.10, 'Kumo Bull');
fill(kBearTopRef, kBearBotRef, kumoBearTint, 0.10, 'Kumo Bear');

// ── Sideways zones (soft slate wash) ────────────────────────────────────────────
const swHi = showSidewaysBg ? for_every(isSideways, high, (sw, h) => sw ? h : null) : Array(barCount).fill(null);
const swLo = showSidewaysBg ? for_every(isSideways, low, (sw, l) => sw ? l : null) : Array(barCount).fill(null);
const swHiRef = paint(swHi, Object.assign({ name: 'Sideways Top' }, hiddenLineOptions));
const swLoRef = paint(swLo, Object.assign({ name: 'Sideways Bottom' }, hiddenLineOptions));
fill(swHiRef, swLoRef, COLOR_MUTED, 0.16, 'Sideways Zone');

// ── Kijun ───────────────────────────────────────────────────────────────────────
const kijunSeries = showLines ? kijun : Array(barCount).fill(null);
paint(kijunSeries, {
    name: 'Kijun-sen',
    color: tinycolor(kijunColor).setAlpha(0.85).toRgbString(),
    style: 'line',
    thickness: 1
});

// ── Glow + core trailing stop (color = direction, vividness = trend strength) ────
const stopLineSeries = showLines ? stopLine : Array(barCount).fill(null);
paint(stopLineSeries, {
    name: 'Stop Glow',
    color: stopGlowSeries,
    style: 'line',
    thickness: 11,
    ignoreWhenScaling: true,
    hideInLegend: true,
    hideInScriptEditor: true,
    editorHidden: true
});

paint(stopLineSeries, {
    name: 'Kumo Stop',
    color: stopColorSeries,
    style: 'line',
    thickness: 3,
    lastValueLabelEnabled: true
});

// ── Candles graded by strength ──────────────────────────────────────────────────
const candleColorSeries = paintCandles
    ? for_every(trendState, strengthArr, shadeOf)
    : Array(barCount).fill(null);
color_candles(candleColorSeries);

// ── BUY / SELL pills ────────────────────────────────────────────────────────────
paint(buyLabel, {
    name: 'BUY',
    style: 'labels_below',
    color: COLOR_LABEL_ON_BULL,
    backgroundColor: bullColor,
    backgroundOpacity: 1,
    fontSize: 11,
    backgroundBorderRadius: 9,
    verticalOffset: 14
});

paint(sellLabel, {
    name: 'SELL',
    style: 'labels_above',
    color: COLOR_LABEL_ON_BEAR,
    backgroundColor: bearColor,
    backgroundOpacity: 1,
    fontSize: 11,
    backgroundBorderRadius: 9,
    verticalOffset: 14
});

const blockedBuySeries  = showBlocked ? blockedBuy  : Array(barCount).fill(null);
const blockedSellSeries = showBlocked ? blockedSell : Array(barCount).fill(null);

paint(blockedBuySeries,  { name: 'Blocked BUY',  style: 'labels_below', color: COLOR_TEXT, backgroundColor: COLOR_CORE, backgroundOpacity: 0.9, fontSize: 10, backgroundBorderRadius: 9, verticalOffset: 14 });
paint(blockedSellSeries, { name: 'Blocked SELL', style: 'labels_above', color: COLOR_TEXT, backgroundColor: COLOR_CORE, backgroundOpacity: 0.9, fontSize: 10, backgroundBorderRadius: 9, verticalOffset: 14 });

register_signal(buySignal, 'TM+HA Buy');
register_signal(sellSignal, 'TM+HA Sell');

// ═══════════════════════════════════════════════════════════════════════════════
// DASHBOARD PANEL
// ═══════════════════════════════════════════════════════════════════════════════

let rows = [];

if (showPanel) {
    const priceDecimals = current.decimals != null && isFinite(current.decimals)
        ? Math.min(Math.max(Math.round(current.decimals), 0), 8)
        : 2;
    const formatPrice = v => (v == null || !isFinite(v) ? 'n/a' : Number(v).toFixed(priceDecimals));
    const formatNum = (v, d) => (v == null || !isFinite(v) ? 'n/a' : Number(v).toFixed(d));

    const lastDir = trendState[lastIdx];
    const lastStr = strengthArr[lastIdx];
    const sideNow = isSideways[lastIdx];

    const trendText = lastDir === 1 ? 'Bullish' : (lastDir === -1 ? 'Bearish' : 'Waiting');
    const trendColor = lastDir === 1 ? bullColor : (lastDir === -1 ? bearColor : COLOR_MUTED);
    const trendSoft = lastDir === 1 ? COLOR_BULL_SOFT : (lastDir === -1 ? COLOR_BEAR_SOFT : COLOR_NEUTRAL_SOFT);

    const regimeText = sideNow ? 'Sideways' : 'Trending';
    const regimeColor = sideNow ? COLOR_MUTED : trendColor;
    const regimeSoft = sideNow ? COLOR_NEUTRAL_SOFT : trendSoft;

    const strengthPercent = lastStr == null ? null : lastStr * 100;
    const litSegments = lastStr == null ? 0 : Math.round(lastStr * GAUGE_SEGMENTS);

    const enabledVotes = [useSidewaysFilter, useChopFilter, useERFilter, useKijunFlat, filterFlatCloud].filter(x => x).length;

    let flipsNow = 0;
    for (let s = signalBars.length - 1; s >= 0; s--) {
        if (lastIdx - signalBars[s] <= whipLookback) flipsNow++; else break;
    }

    let lastSigText = 'none';
    let lastSigColor = COLOR_TEXT;
    if (signalEvents.length > 0) {
        const sigEvt = signalEvents[signalEvents.length - 1];
        lastSigText = (sigEvt.direction === 1 ? 'BUY' : 'SELL') + ' · ' + (lastIdx - sigEvt.bar) + ' bars';
        lastSigColor = sigEvt.direction === 1 ? bullColor : bearColor;
    }

    const signedStrength = for_every(trendState, strengthArr, (d, st) => (d === 0 || st == null ? 0 : d * st * 100));
    const sparkValues = signedStrength.slice(-SPARKLINE_BARS);
    const sparkLabels = sparkValues.map(() => '');

    const gaugeCells = [];
    for (let g = 0; g < GAUGE_SEGMENTS; g++) {
        const lit = g < litSegments;
        gaugeCells.push({
            text: ' ',
            width: '9px',
            height: '10px',
            padding: '0',
            fontSize: '1px',
            borderRadius: '1px',
            background: lit
                ? tinycolor(trendColor).setAlpha(0.60 + (0.40 * (g + 1)) / GAUGE_SEGMENTS).toRgbString()
                : 'rgba(120, 123, 134, 0.38)',
            lineHeight: '10px',
            overflow: 'hidden'
        });
    }

    const labelCell = (txt, tone) => ({
        text: String(txt), color: COLOR_MUTED, background: tone,
        padding: '3px 8px', fontSize: '10px', fontWeight: '600', whiteSpace: 'nowrap'
    });
    const valueCell = (txt, col, tone) => ({
        text: String(txt), color: col, background: tone,
        padding: '3px 8px', fontSize: '10px', fontWeight: '700', textAlign: 'right', whiteSpace: 'nowrap'
    });

    const adxNow = adxVal[lastIdx];
    const erNow = erVal[lastIdx];
    const chopNow = chopVal[lastIdx];
    const rsiNow = rsiVal[lastIdx];
    const rngNow = rangeATR[lastIdx];

    rows = [
        {
            cells: [{
                text: 'Kumo Matrix Pro', colspan: 2, color: COLOR_HEADLINE, background: COLOR_PANEL,
                padding: '5px 8px', fontSize: '10px', fontWeight: '700', letterSpacing: '0.06em',
                borderBottom: '1px solid rgba(120, 123, 134, 0.35)'
            }]
        },
        { cells: [labelCell('Trend', trendSoft), valueCell(trendText, trendColor, trendSoft)] },
        { cells: [labelCell('Regime', regimeSoft), valueCell(regimeText, regimeColor, regimeSoft)] },
        {
            cells: [
                labelCell('Strength', trendSoft),
                {
                    background: trendSoft, padding: '4px 8px', textAlign: 'right',
                    table: { cellSpacing: 2, marginLeft: 'auto', rows: [{ cells: gaugeCells }] }
                }
            ]
        },
        { cells: [labelCell('Strength Value', COLOR_ROW_A), valueCell(strengthPercent == null ? 'n/a' : strengthPercent.toFixed(0) + '%', COLOR_TEXT, COLOR_ROW_A)] },
        { cells: [labelCell('Last Signal', COLOR_ROW_B), valueCell(lastSigText, lastSigColor, COLOR_ROW_B)] },
        { cells: [labelCell('Stop', COLOR_ROW_A), valueCell(formatPrice(stopLine[lastIdx]), trendColor, COLOR_ROW_A)] },
        { cells: [labelCell('ADX', COLOR_ROW_B), valueCell(formatNum(adxNow, 1), adxNow != null && adxNow >= adxThreshold ? bullColor : COLOR_MUTED, COLOR_ROW_B)] },
        { cells: [labelCell('Efficiency', COLOR_ROW_A), valueCell(formatNum(erNow, 2), erNow != null && erNow >= erThreshold ? bullColor : COLOR_MUTED, COLOR_ROW_A)] },
        { cells: [labelCell('CHOP', COLOR_ROW_B), valueCell(formatNum(chopNow, 1), chopNow != null && chopNow <= chopThreshold ? bullColor : COLOR_MUTED, COLOR_ROW_B)] },
        { cells: [labelCell('RSI', COLOR_ROW_A), valueCell(formatNum(rsiNow, 1), COLOR_TEXT, COLOR_ROW_A)] },
        { cells: [labelCell('Range (ATR)', COLOR_ROW_B), valueCell(formatNum(rngNow, 1) + ' / ' + effMinRange.toFixed(1), rngNow != null && rngNow >= effMinRange ? bullColor : bearColor, COLOR_ROW_B)] },
        { cells: [labelCell('Sideways Votes', COLOR_ROW_A), valueCell(sidewaysScore[lastIdx] + ' / ' + enabledVotes + ' (need ' + minVotes + ')', sideNow ? COLOR_MUTED : COLOR_TEXT, COLOR_ROW_A)] },
        { cells: [labelCell('Whipsaw Guard', COLOR_ROW_B), valueCell(flipsNow + ' / ' + maxFlips, flipsNow >= maxFlips ? bearColor : COLOR_TEXT, COLOR_ROW_B)] },
        {
            cells: [{
                colspan: 2, background: COLOR_PANEL, padding: '4px 6px 6px 6px',
                borderTop: '1px solid rgba(120, 123, 134, 0.35)',
                chart: {
                    width: '186px', height: '58px', type: 'line',
                    data: {
                        labels: sparkLabels,
                        datasets: [{
                            data: sparkValues, borderColor: trendColor, borderWidth: 1.5,
                            pointRadius: 0, tension: 0.35,
                            fill: { value: 0, above: COLOR_BULL_SOFT, below: COLOR_BEAR_SOFT }
                        }]
                    },
                    options: {
                        plugins: { legend: { display: false } },
                        elements: { point: { radius: 0 } },
                        scales: { x: { display: false }, y: { display: false, suggestedMin: -100, suggestedMax: 100 } }
                    }
                }
            }]
        }
    ];
}

paint_overlay('Kumo Panel', { position: 'top_right', offset_x: -62, offset_y: 10 }, {
    background: showPanel ? COLOR_PANEL : 'transparent',
    border: showPanel ? '1px solid rgba(120, 123, 134, 0.45)' : 'none',
    borderRadius: '2px',
    cellSpacing: 0,
    overflow: 'hidden',
    rows: rows
});