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

TSBuild26 — NEXUS Engine is an institutional dual-regime buy/sell execution system combining a Zero-Lag 2D State-Space Kalman Filter, Lo-MacKinlay Variance Ratio regime routing, and automated Half-Kelly risk sizing.

KEY ARCHITECTURAL FEATURES
• Kalman Kinematic Spine: Tracks latent price velocity without the phase lag of standard moving averages.
• Variance Ratio Router: Dynamically distinguishes persistent trend expansion (VR > 1.05) from mean-reverting compression (VR

// #TSBuild26 — NEXUS: Dual-Regime Buy/Sell & Kelly Engine
describe_indicator('NEXUS: Dual-Regime Buy/Sell & Kelly Engine', 'price', {
    shortName: 'NEXUS',
    decimals: 'by_symbol'
});

// ─── 1. COMPILER-SAFE INPUTS ─────────────────────────────────────────────────
const kalmanGain    = input.number('Kalman Gain', 0.14, { min: 0.03, max: 0.50 });
const vrPeriod      = input.number('VR Window', 20, { min: 8, max: 80 });
const stopAtrMult   = input.number('Stop Mult', 2.0, { min: 0.8, max: 5.0 });
const tp1Multiple   = input.number('Target 1 R', 1.5, { min: 0.5, max: 6.0 });
const tp2Multiple   = input.number('Target 2 R', 3.0, { min: 1.5, max: 12.0 });
const enableSprings = input.boolean('Allow Springs', true);
const colorBars     = input.boolean('Color Candles', true);
const hudCorner     = input('HUD Position', 'top_right', ['top_right', 'bottom_right', 'top_left', 'bottom_left']);

// ─── 2. ZERO-LAG KALMAN KINEMATICS & VARIANCE RATIO ──────────────────────────
const n = close.length;
const tr         = series_of(0);
const medTr      = series_of(null);
const kalmanEst  = series_of(null);
const kalmanVel  = series_of(0);
const varRatio   = series_of(1.0);
const volDeltaZ  = series_of(0);
const swingHigh  = series_of(null);
const swingLow   = series_of(null);

let kState = close[0] || 0;
let kVel   = 0;
let pCov   = 1.0;

for (let i = 0; i < n; i++) {
    const prevC = i > 0 ? close[i - 1] : open[i];
    const rng = high[i] - low[i];
    tr[i] = Math.max(rng, Math.abs(high[i] - prevC), Math.abs(low[i] - prevC));

    const predState = kState + kVel;
    pCov = pCov + kalmanGain;
    const innovation = close[i] - predState;
    const kWeight = pCov / (pCov + 1.0);
    kState = predState + kWeight * innovation;
    kVel   = kVel + (kalmanGain * 0.5) * innovation;
    pCov   = (1 - kWeight) * pCov;

    kalmanEst[i] = kState;
    kalmanVel[i] = kVel;

    if (i >= vrPeriod) {
        const trWin = [];
        let maxH = -Infinity, minL = Infinity;
        let sumVol = 0;

        for (let j = i - vrPeriod + 1; j <= i; j++) {
            trWin.push(tr[j]);
            if (j < i) {
                if (high[j] > maxH) maxH = high[j];
                if (low[j] < minL)  minL = low[j];
            }
            sumVol += (volume[j] || 1);
        }
        trWin.sort((a, b) => a - b);
        const mid = Math.floor(trWin.length / 2);
        medTr[i] = trWin.length % 2 !== 0 ? trWin[mid] : (trWin[mid - 1] + trWin[mid]) / 2;
        swingHigh[i] = maxH;
        swingLow[i]  = minL;

        const curClv = rng > 0 ? ((close[i] - low[i]) - (high[i] - close[i])) / rng : 0;
        const avgVol = sumVol / vrPeriod;
        volDeltaZ[i] = avgVol > 0 ? ((curClv * (volume[i] || 1)) / avgVol) : 0;

        const q = Math.max(2, Math.floor(vrPeriod / 4));
        let var1 = 0, varQ = 0;
        for (let j = i - vrPeriod + 1; j <= i; j++) {
            const r1 = close[j] - close[j - 1];
            var1 += r1 * r1;
            if (j >= q) {
                const rq = close[j] - close[j - q];
                varQ += rq * rq;
            }
        }
        varRatio[i] = (var1 > 0 && q > 0) ? (varQ / (q * var1)) : 1.0;
    }
}

// ─── 3. DUAL-REGIME EXECUTION & RATCHETING BREAKEVEN STATE MACHINE ───────────
const dynamicTrail = series_of(null);
const bullTrail    = series_of(null);
const bearTrail    = series_of(null);
const bullKalman   = series_of(null);
const bearKalman   = series_of(null);

const activeEntry  = series_of(null);
const activeStop   = series_of(null);
const beStopLine   = series_of(null);
const activeTp1    = series_of(null);
const activeTp2    = series_of(null);

const sigBuyTrend  = series_of(false);
const sigSellTrend = series_of(false);
const sigBuySpring = series_of(false);
const sigSellTrap  = series_of(false);
const sigTpReached = series_of(false);

const buyBadges    = series_of(null);
const sellBadges   = series_of(null);
const exitBadges   = series_of(null);

let posDir = 0;
let entryPx = null, stopPx = null, tp1Px = null, tp2Px = null, initRisk = null;
let tp1Locked = false, tp2Locked = false;
let cooldown = 0;

let totalClosed = 0, totalWins = 0, sumWinR = 0, sumLossR = 0;
let cumR = 0, peakR = 0, maxDrawdownR = 0;
const recentOutcomes = [];

function recordTradeOutcome(rVal) {
    totalClosed++;
    if (rVal > 0) {
        totalWins++;
        sumWinR += rVal;
    } else {
        sumLossR += Math.abs(rVal);
    }
    cumR += rVal;
    if (cumR > peakR) peakR = cumR;
    const dd = peakR - cumR;
    if (dd > maxDrawdownR) maxDrawdownR = dd;
    recentOutcomes.push(cumR);
    if (recentOutcomes.length > 12) recentOutcomes.shift();
}

for (let i = vrPeriod; i < n; i++) {
    const mtr = medTr[i] || tr[i] || (close[i] * 0.01);
    const kEst = kalmanEst[i] !== null ? kalmanEst[i] : close[i];
    const upB = kEst + mtr * stopAtrMult;
    const dnB = kEst - mtr * stopAtrMult;

    const prevTrail = dynamicTrail[i - 1] !== null ? dynamicTrail[i - 1] : kEst;
    if (close[i] >= prevTrail) {
        dynamicTrail[i] = Math.max(prevTrail, dnB);
        bullTrail[i]  = dynamicTrail[i];
        bullKalman[i] = kEst;
    } else {
        dynamicTrail[i] = Math.min(prevTrail, upB);
        bearTrail[i]  = dynamicTrail[i];
        bearKalman[i] = kEst;
    }

    if (cooldown > 0) cooldown--;

    if (posDir === 1) {
        if (!tp1Locked && high[i] >= tp1Px) {
            tp1Locked = true;
            stopPx = entryPx;
            exitBadges[i] = 'TP1 hit BE';
            sigTpReached[i] = true;
        }
        if (!tp2Locked && high[i] >= tp2Px) {
            tp2Locked = true;
            exitBadges[i] = 'TP2 +3R';
            sigTpReached[i] = true;
        }
        if (tp2Locked && dnB > stopPx) stopPx = dnB;

        if (low[i] <= stopPx) {
            const realizedR = tp2Locked ? tp2Multiple : (tp1Locked ? tp1Multiple * 0.6 : -1.0);
            recordTradeOutcome(realizedR);
            if (!tp1Locked) exitBadges[i] = 'STOP -1R';
            posDir = 0;
            cooldown = 2;
        }
    } else if (posDir === -1) {
        if (!tp1Locked && low[i] <= tp1Px) {
            tp1Locked = true;
            stopPx = entryPx;
            exitBadges[i] = 'TP1 hit BE';
            sigTpReached[i] = true;
        }
        if (!tp2Locked && low[i] <= tp2Px) {
            tp2Locked = true;
            exitBadges[i] = 'TP2 +3R';
            sigTpReached[i] = true;
        }
        if (tp2Locked && upB < stopPx) stopPx = upB;

        if (high[i] >= stopPx) {
            const realizedR = tp2Locked ? tp2Multiple : (tp1Locked ? tp1Multiple * 0.6 : -1.0);
            recordTradeOutcome(realizedR);
            if (!tp1Locked) exitBadges[i] = 'STOP -1R';
            posDir = 0;
            cooldown = 2;
        }
    }

    const isBullFlip = close[i] > dynamicTrail[i] && close[i - 1] <= (dynamicTrail[i - 1] || close[i - 1]);
    const isBearFlip = close[i] < dynamicTrail[i] && close[i - 1] >= (dynamicTrail[i - 1] || close[i - 1]);

    const bullMomentum = isBullFlip && kalmanVel[i] > 0 && volDeltaZ[i] > 0.15 && varRatio[i] >= 0.92;
    const bearMomentum = isBearFlip && kalmanVel[i] < 0 && volDeltaZ[i] < -0.15 && varRatio[i] >= 0.92;

    const bullSpring = enableSprings && cooldown === 0 && posDir !== 1 &&
                       swingLow[i] !== null && low[i] < swingLow[i] &&
                       close[i] > swingLow[i] && close[i] > open[i] && volDeltaZ[i] > 0.45;

    const bearUpthrust = enableSprings && cooldown === 0 && posDir !== -1 &&
                         swingHigh[i] !== null && high[i] > swingHigh[i] &&
                         close[i] < swingHigh[i] && close[i] < open[i] && volDeltaZ[i] < -0.45;

    if ((bullMomentum || bullSpring) && posDir !== 1) {
        if (posDir === -1) {
            const flipR = tp2Locked ? tp2Multiple : (tp1Locked ? tp1Multiple * 0.6 : ((entryPx - close[i]) / (initRisk || mtr)));
            recordTradeOutcome(Math.max(-1.0, Math.min(tp2Multiple, flipR)));
        }
        posDir = 1;
        entryPx = close[i];
        initRisk = Math.max(mtr * stopAtrMult, close[i] - Math.min(low[i], dynamicTrail[i]));
        stopPx = entryPx - initRisk;
        tp1Px  = entryPx + initRisk * tp1Multiple;
        tp2Px  = entryPx + initRisk * tp2Multiple;
        tp1Locked = false;
        tp2Locked = false;

        if (bullSpring && !bullMomentum) {
            sigBuySpring[i] = true;
            buyBadges[i] = 'SPRING BUY';
        } else {
            sigBuyTrend[i] = true;
            buyBadges[i] = 'NEXUS BUY';
        }
    } else if ((bearMomentum || bearUpthrust) && posDir !== -1) {
        if (posDir === 1) {
            const flipR = tp2Locked ? tp2Multiple : (tp1Locked ? tp1Multiple * 0.6 : ((close[i] - entryPx) / (initRisk || mtr)));
            recordTradeOutcome(Math.max(-1.0, Math.min(tp2Multiple, flipR)));
        }
        posDir = -1;
        entryPx = close[i];
        initRisk = Math.max(mtr * stopAtrMult, Math.max(high[i], dynamicTrail[i]) - close[i]);
        stopPx = entryPx + initRisk;
        tp1Px  = entryPx - initRisk * tp1Multiple;
        tp2Px  = entryPx - initRisk * tp2Multiple;
        tp1Locked = false;
        tp2Locked = false;

        if (bearUpthrust && !bearMomentum) {
            sigSellTrap[i] = true;
            sellBadges[i] = 'TRAP SELL';
        } else {
            sigSellTrend[i] = true;
            sellBadges[i] = 'NEXUS SELL';
        }
    }

    if (posDir !== 0) {
        activeEntry[i] = entryPx;
        if (tp1Locked) beStopLine[i] = stopPx;
        else activeStop[i] = stopPx;
        activeTp1[i] = tp1Px;
        activeTp2[i] = tp2Px;
    }
}

// ─── 4. SANITIZED RENDERING ──────────────────────────────────────────────────
paint(kalmanEst, { name: 'Kalman Spine', color: '#38BDF8', thickness: 1 });
const pBullT = paint(bullTrail,  { name: 'Bull Trail', color: '#10B981', thickness: 2 });
const pBearT = paint(bearTrail,  { name: 'Bear Trail', color: '#F43F5E', thickness: 2 });
const pBullK = paint(bullKalman, { name: 'Bull K Ref', color: '#10B981', hidden: true });
const pBearK = paint(bearKalman, { name: 'Bear K Ref', color: '#F43F5E', hidden: true });

fill(pBullK, pBullT, '#10B981', 0.16, 'Bull Zone');
fill(pBearK, pBearT, '#F43F5E', 0.16, 'Bear Zone');

paint(activeEntry, { name: 'Entry Line',   color: '#94A3B8', style: 'dotted', thickness: 1, ignoreWhenScaling: true });
paint(activeStop,  { name: 'Initial Stop', color: '#EF4444', style: 'ladder', thickness: 2, ignoreWhenScaling: true });
paint(beStopLine,  { name: 'BE Stop',      color: '#FBBF24', style: 'ladder', thickness: 2, ignoreWhenScaling: true });
paint(activeTp1,   { name: 'Target 1',     color: '#10B981', style: 'ladder', thickness: 1, ignoreWhenScaling: true });
paint(activeTp2,   { name: 'Target 2',     color: '#06B6D4', style: 'ladder', thickness: 2, ignoreWhenScaling: true });

paint(buyBadges,  { name: 'Buy Signal',  style: 'labels_below', color: '#10B981', backgroundColor: '#064E3B', fontColor: '#A7F3D0' });
paint(sellBadges, { name: 'Sell Signal', style: 'labels_above', color: '#F43F5E', backgroundColor: '#4C0519', fontColor: '#FECDD3' });
paint(exitBadges, { name: 'Trade Tag',   style: 'labels_above', color: '#FBBF24', backgroundColor: '#1E293B', fontColor: '#FDE68A' });

const barColors = close.map((c, i) => {
    if (!colorBars || dynamicTrail[i] === null) return null;
    const isBull = c >= dynamicTrail[i];
    const strongFlow = Math.abs(volDeltaZ[i]) > 0.35;
    return isBull ? (strongFlow ? '#10B981' : '#059669') : (strongFlow ? '#F43F5E' : '#BE123C');
});
color_candles(barColors);

// ─── 5. STATIC-NAME HUD OVERLAY & SIGNALS ────────────────────────────────────
const last = n - 1;
const winProb = totalClosed > 0 ? (totalWins / totalClosed) : 0.55;
const avgWin  = totalWins > 0 ? (sumWinR / totalWins) : tp1Multiple;
const losses  = totalClosed - totalWins;
const avgLoss = losses > 0 ? (sumLossR / losses) : 1.0;
const winLossRatio = avgLoss > 0 ? (avgWin / avgLoss) : tp1Multiple;

const rawKelly = winLossRatio > 0 ? (winProb - ((1 - winProb) / winLossRatio)) : 0;
const halfKellyPct = Math.max(0.5, Math.min(5.0, rawKelly * 50)).toFixed(2) + '%';

const sparkChars = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
let equitySpark = 'Calibrating';
if (recentOutcomes.length >= 2) {
    let minEq = Infinity, maxEq = -Infinity;
    for (let k = 0; k < recentOutcomes.length; k++) {
        if (recentOutcomes[k] < minEq) minEq = recentOutcomes[k];
        if (recentOutcomes[k] > maxEq) maxEq = recentOutcomes[k];
    }
    const eqSpan = maxEq - minEq;
    equitySpark = '';
    for (let k = 0; k < recentOutcomes.length; k++) {
        const norm = eqSpan > 0 ? (recentOutcomes[k] - minEq) / eqSpan : 0.5;
        const idx = Math.max(0, Math.min(7, Math.round(norm * 7)));
        equitySpark += sparkChars[idx];
    }
    equitySpark += ` (${cumR >= 0 ? '+' : ''}${cumR.toFixed(1)}R)`;
}

const vrVal = varRatio[last] || 1.0;
const regimeMode = vrVal > 1.05 ? 'MOMENTUM VR>1' : (vrVal < 0.95 ? 'MEAN-REVERT VR<1' : 'TRANSITION');
const posStatus = posDir === 1 ? (tp1Locked ? 'LONG BE LOCKED' : 'LONG ACTIVE') : (posDir === -1 ? (tp1Locked ? 'SHORT BE LOCKED' : 'SHORT ACTIVE') : 'FLAT');
const pfScore = sumLossR > 0 ? (sumWinR / sumLossR).toFixed(2) : (sumWinR > 0 ? 'Max' : '1.00');

paint_overlay('NEXUS HUD', { position: hudCorner, order: 'above_all' }, {
    background: '#090D16F2',
    border: '1px solid #1E293B',
    borderRadius: '8px',
    fontSize: '11px',
    rows: [
        { cells: [{ colspan: 2, text: 'NEXUS KALMAN-VARIANCE ENGINE', color: '#F8FAFC', fontWeight: 'bold', padding: '7px 12px', background: '#1E293B' }] },
        { cells: [{ text: 'Variance Regime', color: '#94A3B8', padding: '4px 12px' }, { text: regimeMode, color: '#38BDF8', fontWeight: 'bold', padding: '4px 12px' }] },
        { cells: [{ text: 'Position State', color: '#94A3B8', padding: '4px 12px' }, { text: posStatus, color: posDir >= 0 ? '#10B981' : '#F43F5E', fontWeight: 'bold', padding: '4px 12px' }] },
        { cells: [{ text: 'Win Rate / PF', color: '#94A3B8', padding: '4px 12px' }, { text: `${(winProb * 100).toFixed(1)}% (${totalWins}/${totalClosed}) | ${pfScore}`, color: '#10B981', fontWeight: 'bold', padding: '4px 12px' }] },
        { cells: [{ text: 'Equity Curve', color: '#94A3B8', padding: '4px 12px' }, { text: equitySpark, color: cumR >= 0 ? '#00F5D4' : '#F43F5E', fontWeight: 'bold', padding: '4px 12px' }] },
        { cells: [{ text: 'Max Drawdown', color: '#94A3B8', padding: '4px 12px' }, { text: `-${maxDrawdownR.toFixed(2)}R`, color: '#FBBF24', padding: '4px 12px' }] },
        { cells: [{ text: 'Half-Kelly Risk', color: '#94A3B8', padding: '5px 12px' }, { text: `${halfKellyPct} Equity`, color: '#A78BFA', fontWeight: 'bold', padding: '5px 12px' }] }
    ]
});

register_signal(sigBuyTrend,  'NEXUS Trend Buy');
register_signal(sigSellTrend, 'NEXUS Trend Sell');
register_signal(sigBuySpring, 'NEXUS Spring Buy');
register_signal(sigSellTrap,  'NEXUS Trap Sell');
register_signal(sigTpReached, 'NEXUS Target Hit');