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

DeepShock is a price action and volume distribution engine designed to identify institutional liquidity shelves and volume absorption. By uniting multi-timeframe volume profiling with live market structure bias and aggressive order absorption wicks, DeepShock pinpoints high-probability turning points alongside automated trade management metrics.

Features:

  • Volume & ATR Processing:
    • Calculates 20-bar Relative Volume (RVOL) to identify institutional expansion.
    • Employs a 14-period Wilder Average True Range (ATR) for leg thresholds, zone caps, and stop loss buffers.
  • Market Structure Bias:
    • Tracks swing highs and lows via a multi-bar pivot matrix.
    • Establishes trend state:
    • BULLISH: Higher Highs + Higher Lows (HH / HL).
    • BEARISH: Lower Highs + Lower Lows (LH / LL).
    • RANGE: Mixed market structure.
  • Institutional Order Blocks:
    • Volume profiles are built for every confirmed market leg.
    • The zone is centered around the Point of Control (POC) and expanded outward while volume density exceeds the HVN threshold percentage.
    • Zones remain active until price closes beyond the opposite boundary, at which point the zone dies and flips polarity (Demand becomes Supply and vice versa).
  • Volume Profiles & Nodes:
    • Point of Control (POC): Price level with the highest traded volume in a session or swing.
    • High Volume Nodes (HVN): Accumulation/Distribution bands where price consolidates.
    • Low Volume Nodes (LVN): Liquidity voids where price moves rapidly due to thin order book depth.
  • Volume Absorption Concept:
    • Mechanism: Occurs when aggressive market orders are absorbed by large passive limit orders at key key boundary areas, preventing price from advancing and causing a sharp wick rejection.
    • Bullish Absorption: Long lower rejection wick at support/HVN, signaling aggressive sellers were absorbed by passive buyers.
    • Bearish Absorption: Long upper rejection wick at resistance/HVN, signaling aggressive buyers were absorbed by passive sellers.

Types of Signals:

ABS BUY (Profile Absorb Buy): Bullish absorption at a prior Session HVN with heavy volume. (Blue badge below candle)

ABS SELL (Profile Absorb Sell): Bearish absorption at a prior Session HVN with heavy volume. (Orange badge above candle)

OB BUY / OB SELL — absorption candle inside a live OB zone

OB BUY A+ / OB SELL A+

Bubble (Absorption Bubble): On-chart circle that grows larger as volume spikes higher (displaying volume multipliers like 1.5x, 2.5x, or 5x).

Supported Session Periods:

  • 15 Min / 30 Min
  • 1 Hour / 4 Hour
  • Daily (Default)
  • Weekly / Monthly

Profile Placement Modes

  1. Next Session Mode (Recommended / Non-Repainting):
    • Computes the volume profile for the fully completed prior session and projects it forward across the current session.
    • Ensures levels (POC, HVN, LVN) remain 100% static and non-repainting while trading the live session.
  2. Own Session Mode:
    • Draws the profile directly over the active session as volume develops in real-time.

Recommended Timeframe : 5M, 15M

TSBuild26

describe_indicator('DeepShock', 'price', { shortName: 'DSHOCK' });

//====================================================
// SECTION 1 - INPUTS
//====================================================
const swingLen       = input.number('Swing Length', 5, { min: 2, max: 20 });
const minLegAtr      = input.number('Min Leg ATR', 3, { min: 1, max: 10 });

const minRvol        = input.number('Min RVOL', 1.3, { min: 0.5, max: 5 });
const minWick        = input.number('Min Wick %', 35, { min: 10, max: 80 });
const sigGap         = input.number('Signal Cooldown', 8, { min: 1, max: 50 });
const ignoreLive     = input.boolean('Ignore Live Bar', true);

const showZones      = input.boolean('Show Order Blocks', true);
const showObSig      = input.boolean('Order Block Signals', true);

const swingProfOn    = input.boolean('Swing Profile', false);
const swingLegs      = input.number('Swing Profile Legs', 1, { min: 1, max: 3 });
const swingBlocksEnd = input.boolean('Swing Blocks At End', false);
const sessProfOn     = input.boolean('Session Profile', true);
const sessPeriod     = input.select('Session Period', 'Daily', ['15 Min', '30 Min', '1 Hour', '4 Hour', 'Daily', 'Weekly', 'Monthly']);
const sessBack       = input.number('Sessions Back', 3, { min: 1, max: 8 });
const sessOffset     = input.number('Session UTC Offset', -5, { min: -12, max: 14 });
const widthPct       = input.number('Profile Width %', 35, { min: 10, max: 90 });
const lvnPct         = input.number('LVN Threshold %', 50, { min: 10, max: 80 });
const nodeHvnPct     = input.number('Node HVN %', 65, { min: 40, max: 95 });
const placement      = input.select('Profile Placement', 'Next Session', ['Next Session', 'Own Session']);
const showNodes      = input.boolean('Show HVN/LVN', true);
const showBubbles    = input.boolean('Show Bubbles', true);
const bubbleRvol     = input.number('Bubble Min RVOL', 2, { min: 1, max: 6 });
const bubbleKeyOnly  = input.boolean('Bubbles at Key Areas Only', false);

const showProfSigP   = input.boolean('Profile Signals', true);
const showPoc        = input.boolean('Show POC', true);
const showSetup      = input.boolean('Show Setup 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 & DATA PREP
//====================================================
const n = close.length;

const TEAL  = '#26a69a';
const ROSE  = '#ef5350';
const GOLD  = '#ffca28';
const TXT   = '#e6edf3';
const MUTED = '#8b98a5';
const BG    = '#0f1923';
const BG2   = '#16222e';

const hasVol = (typeof volume !== 'undefined') && volume !== null && volume.length === n;
const volA = Array(n).fill(0);
for (let i = 0; i < n; i++) {
    const v = hasVol ? volume[i] : null;
    volA[i] = (typeof v === 'number' && v >= 0) ? v : (high[i] - low[i]);
}

// Relative volume vs. previous 20 bars
const vcs = Array(n + 1).fill(0);
for (let i = 0; i < n; i++) vcs[i + 1] = vcs[i] + volA[i];
const rvol = Array(n).fill(null);
for (let i = 20; i < n; i++) {
    const av = (vcs[i] - vcs[i - 20]) / 20;
    rvol[i] = av > 0 ? volA[i] / av : null;
}

// ATR (Wilder, 14)
const atrA = Array(n).fill(null);
(function () {
    const p = 14;
    if (n <= p + 1) return;
    let s = 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]));
        if (i <= p) {
            s += tr;
            if (i === p) atrA[i] = s / p;
        } else {
            atrA[i] = (atrA[i - 1] * (p - 1) + tr) / p;
        }
    }
})();

const atrNow = atrA[n - 1] !== null ? atrA[n - 1] : 0;
const lastEval = ignoreLive ? n - 2 : n - 1;
const spot = close[n - 1];

//====================================================
// SECTION 3 - SWINGS (zigzag of significant legs & market structure)
//====================================================
const pivots = [];
for (let i = swingLen; i < n - swingLen; i++) {
    let isH = true, isL = true;
    for (let k = 1; k <= swingLen; k++) {
        if (!(high[i] > high[i - k]) || !(high[i] >= high[i + k])) isH = false;
        if (!(low[i] < low[i - k]) || !(low[i] <= low[i + k])) isL = false;
        if (!isH && !isL) break;
    }
    if (isH && !isL) pivots.push({ i: i, p: high[i], t: 1 });
    else if (isL && !isH) pivots.push({ i: i, p: low[i], t: -1 });
}

const zz = [];
for (let k = 0; k < pivots.length; k++) {
    const pv = pivots[k];
    if (zz.length === 0) { zz.push(pv); continue; }
    const lastP = zz[zz.length - 1];
    if (pv.t === lastP.t) {
        if ((pv.t === 1 && pv.p > lastP.p) || (pv.t === -1 && pv.p < lastP.p)) zz[zz.length - 1] = pv;
    } else {
        const a = atrA[pv.i];
        if (a !== null && Math.abs(pv.p - lastP.p) >= minLegAtr * a) zz.push(pv);
    }
}

// Market structure bias from the last two swing highs and lows
let hi1 = null, hi2 = null, lo1 = null, lo2 = null;
for (let k = zz.length - 1; k >= 0; k--) {
    if (zz[k].t === 1) { if (hi1 === null) hi1 = zz[k].p; else if (hi2 === null) hi2 = zz[k].p; }
    else { if (lo1 === null) lo1 = zz[k].p; else if (lo2 === null) lo2 = zz[k].p; }
}
let biasTxt = 'RANGE';
let biasSub = 'mixed structure';
let biasColor = GOLD;
if (hi2 !== null && lo2 !== null) {
    if (hi1 > hi2 && lo1 > lo2) { biasTxt = 'BULLISH'; biasSub = 'HH / HL'; biasColor = TEAL; }
    else if (hi1 < hi2 && lo1 < lo2) { biasTxt = 'BEARISH'; biasSub = 'LH / LL'; biasColor = ROSE; }
}

const projBars = 20;
function projectionOf(value) {
    const arr = [];
    for (let i = 0; i < projBars; i++) arr.push(value);
    return arr;
}

//====================================================
// SECTION 4 - TRADITIONAL ORDER BLOCKS
//
//  Bullish OB = the last bearish candle (close < open) before a confirmed
//               swing LOW that launches an upward impulse.
//  Bearish OB = the last bullish candle (close > open) before a confirmed
//               swing HIGH that launches a downward impulse.
//
//  Zone = that candle's full high-to-low range.
//  Zone dies when price closes cleanly beyond its far side.
//  No volume profiling, no HVN maths — purely price-action based.
//====================================================

// Build a list of traditional OB zones from confirmed swing pivots
const zones = [];
(function () {
    // We need at least 2 confirmed pivot alternations to form an OB
    const zzC = [];   // working zigzag (same filter as main zz but tracks confirmation)
    for (let k = 0; k < pivots.length; k++) {
        const pv   = pivots[k];
        const conf = pv.i + swingLen;   // bar on which this swing is confirmed
        if (conf > n - 1) break;

        if (zzC.length === 0) { zzC.push(pv); continue; }
        const prev = zzC[zzC.length - 1];

        // Same-direction: keep the more extreme pivot (no new OB, just update)
        if (pv.t === prev.t) {
            if ((pv.t === 1 && pv.p > prev.p) || (pv.t === -1 && pv.p < prev.p))
                zzC[zzC.length - 1] = pv;
            continue;
        }

        // Opposite direction: must clear the ATR minimum leg size
        const a = atrA[pv.i];
        if (a === null || Math.abs(pv.p - prev.p) < minLegAtr * a) continue;
        zzC.push(pv);

        // The impulse leg ran FROM prev.i TO pv.i
        // Scan backwards from the swing point to find the last opposing candle
        //   before the impulse started (i.e. before prev.i).
        // pv.t === 1  => swing LOW confirmed => bullish OB => look for last bearish candle before prev.i
        // pv.t === -1 => swing HIGH confirmed => bearish OB => look for last bullish candle before prev.i
        const wantBull = pv.t === 1;   // true = we want the last bearish candle (bull OB)
        let obIdx = -1;
        const scanFrom = Math.max(0, prev.i - 1);
        for (let x = scanFrom; x >= Math.max(0, prev.i - 10); x--) {
            if (wantBull && close[x] < open[x]) { obIdx = x; break; }   // last bearish candle -> bull OB
            if (!wantBull && close[x] > open[x]) { obIdx = x; break; }  // last bullish candle -> bear OB
        }
        if (obIdx < 0) continue;

        zones.push({
            i:     obIdx,            // source candle index
            top:   high[obIdx],      // zone top  = candle high
            bot:   low[obIdx],       // zone bot  = candle low
            type:  wantBull ? 1 : -1, // 1 = demand (bull OB), -1 = supply (bear OB)
            s0:    conf,             // first visible bar (after swing confirmed)
            end:   n - 1,            // drawn until this bar
            alive: true,
            touches: 0
        });
    }
})();

// Zone lifecycle: count touches, mark broken zones
for (let zi = 0; zi < zones.length; zi++) {
    const z = zones[zi];
    let prevContact = false;
    for (let j = z.s0; j <= lastEval; j++) {
        // Zone is broken when price closes through its far side
        const broken = z.type === 1 ? close[j] < z.bot : close[j] > z.top;
        if (broken) { z.end = j; z.alive = false; break; }

        const contact = low[j] <= z.top && high[j] >= z.bot;
        if (contact && !prevContact) z.touches++;
        prevContact = contact;
    }
}

// Keep only up to 3 most-recent alive zones of each type
const aliveD = zones.filter(z => z.alive && z.type ===  1).sort((a, b) => b.s0 - a.s0).slice(0, 3);
const aliveS = zones.filter(z => z.alive && z.type === -1).sort((a, b) => b.s0 - a.s0).slice(0, 3);
const shownZones = aliveD.concat(aliveS);

// Nearest demand below / supply above current price (for dashboard)
let nearSup = null, nearRes = null;
for (let k = 0; k < shownZones.length; k++) {
    const z = shownZones[k];
    const mid = (z.top + z.bot) / 2;
    const d   = Math.abs(mid - spot);
    if (mid < spot) { if (nearSup === null || d < Math.abs((nearSup.top + nearSup.bot) / 2 - spot)) nearSup = z; }
    else            { if (nearRes === null || d < Math.abs((nearRes.top + nearRes.bot) / 2 - spot)) nearRes = z; }
}

// OB signal candidates: absorption candle inside a live OB zone
const obCand = Array(n).fill(0);
for (let j = 1; j <= lastEval; j++) {
    if (rvol[j] === null || rvol[j] < minRvol) continue;
    const rng = high[j] - low[j];
    if (!(rng > 0)) continue;
    const bodyHi = Math.max(open[j], close[j]);
    const bodyLo = Math.min(open[j], close[j]);
    let buyOk = false, sellOk = false, inDem = false, inSup = false;
    for (let zi = 0; zi < zones.length; zi++) {
        const z = zones[zi];
        if (j < z.s0) continue;
        const lastBar = z.alive ? n - 1 : z.end - 1;
        if (j > lastBar) continue;
        if (!(low[j] <= z.top && high[j] >= z.bot)) continue;
        if (z.type === 1) {
            inDem = true;
            // Bull candle with lower wick >= minWick%, closing inside or above zone
            if (close[j] > open[j] && (bodyLo - low[j]) / rng >= minWick / 100 && close[j] >= z.bot) buyOk = true;
        } else {
            inSup = true;
            // Bear candle with upper wick >= minWick%, closing inside or below zone
            if (close[j] < open[j] && (high[j] - bodyHi) / rng >= minWick / 100 && close[j] <= z.top) sellOk = true;
        }
    }
    if (inDem && inSup) continue;   // price inside overlapping zones = noise, skip
    if (buyOk && !sellOk)  obCand[j] =  1;
    else if (sellOk && !buyOk) obCand[j] = -1;
}

//====================================================
// SECTION 5 - VOLUME PROFILES (swing range + sessions), HVN / LVN
//====================================================
const PR = 4;   // profile rows (set to 4 to stay well under TrendSpider 70 out series limit)

function clusterRows(flags) {
    const out = [];
    let r = 0;
    while (r < PR) {
        if (flags[r]) {
            let e = r;
            while (e + 1 < PR && flags[e + 1]) e++;
            out.push({ r1: r, r2: e });
            r = e + 1;
        } else r++;
    }
    return out;
}

function makeProfile(a, b) {
    if (b - a + 1 < 4) return null;
    let lo = 1e12, hi = -1e12, tot = 0;
    for (let x = a; x <= b; x++) {
        if (low[x] < lo) lo = low[x];
        if (high[x] > hi) hi = high[x];
    }
    const rh = (hi - lo) / PR;
    if (!(rh > 0)) return null;
    const vr = Array(PR).fill(0);
    for (let x = a; x <= b; x++) {
        let r1 = Math.floor((Math.max(low[x], lo) - lo) / rh);
        let r2 = Math.floor((Math.min(high[x], hi) - lo) / rh);
        if (r1 < 0) r1 = 0;
        if (r2 > PR - 1) r2 = PR - 1;
        if (r2 < r1) r2 = r1;
        const part = volA[x] / (r2 - r1 + 1);
        for (let r = r1; r <= r2; r++) vr[r] += part;
        tot += volA[x];
    }
    if (!(tot > 0)) return null;
    let poc = 0;
    for (let r = 1; r < PR; r++) if (vr[r] > vr[poc]) poc = r;
    const mx = vr[poc];

    const isHv = [];
    for (let r = 0; r < PR; r++) isHv.push(vr[r] >= mx * nodeHvnPct / 100);
    const hvC = clusterRows(isHv);
    for (let k = 0; k < hvC.length; k++) {
        let pk = 0;
        for (let r = hvC[k].r1; r <= hvC[k].r2; r++) if (vr[r] > pk) pk = vr[r];
        hvC[k].v = pk;
    }
    hvC.sort((u, v) => v.v - u.v);
    const hvB = [];
    for (let k = 0; k < hvC.length && hvB.length < 2; k++) {
        const bl = lo + hvC[k].r1 * rh, bh = lo + (hvC[k].r2 + 1) * rh;
        hvB.push({ lo: bl, hi: bh, mid: (bl + bh) / 2 });
    }

    const isLv = [];
    let minV = 1e18, minR = -1;
    for (let r = 0; r < PR; r++) {
        isLv.push(!isHv[r] && vr[r] <= mx * lvnPct / 100);
        if (!isHv[r] && vr[r] < minV) { minV = vr[r]; minR = r; }
    }
    let anyLv = false;
    for (let r = 0; r < PR; r++) if (isLv[r]) anyLv = true;
    if (!anyLv && minR >= 0 && minV <= mx * 0.85) isLv[minR] = true;
    const lvC = clusterRows(isLv);
    for (let k = 0; k < lvC.length; k++) {
        let mn = 1e18;
        for (let r = lvC[k].r1; r <= lvC[k].r2; r++) if (vr[r] < mn) mn = vr[r];
        lvC[k].v = mn;
    }
    lvC.sort((u, v) => u.v - v.v);
    const lvB = [];
    for (let k = 0; k < lvC.length && lvB.length < 2; k++) {
        const bl = lo + lvC[k].r1 * rh, bh = lo + (lvC[k].r2 + 1) * rh;
        lvB.push({ lo: bl, hi: bh, mid: (bl + bh) / 2 });
    }
    return { a: a, b: b, da: a, db: b, lo: lo, hi: hi, rh: rh, vr: vr, mx: mx, poc: poc, hvB: hvB, lvB: lvB };
}
function rowMid(p, r) { return p.lo + (r + 0.5) * p.rh; }

// Session boundaries (15 Min ... Monthly)
const tScale = (n > 0 && time[0] > 1e11) ? 0.001 : 1;
function ymKey(days) {
    const z = days + 719468;
    const era = Math.floor(z / 146097);
    const doe = z - era * 146097;
    const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
    const y = yoe + era * 400;
    const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
    const mp = Math.floor((5 * doy + 2) / 153);
    const m = mp < 10 ? mp + 3 : mp - 9;
    return (m <= 2 ? y + 1 : y) * 12 + m;
}
function sessKey(i) {
    const tSec = time[i] * tScale + sessOffset * 3600;
    if (sessPeriod === '15 Min') return Math.floor(tSec / 900);
    if (sessPeriod === '30 Min') return Math.floor(tSec / 1800);
    if (sessPeriod === '1 Hour') return Math.floor(tSec / 3600);
    if (sessPeriod === '4 Hour') return Math.floor(tSec / 14400);
    const days = Math.floor(tSec / 86400);
    if (sessPeriod === 'Weekly') return Math.floor((days + 3) / 7);
    if (sessPeriod === 'Monthly') return ymKey(days);
    return days;
}

const allSess = [];
const nextMode = placement === 'Next Session';
const profAt = Array(n).fill(-1);
if (sessProfOn && n > 5) {
    const spans = [];
    let startI = 0;
    for (let i = 1; i < n; i++) {
        if (sessKey(i) !== sessKey(i - 1)) { spans.push({ a: startI, b: i - 1 }); startI = i; }
    }
    spans.push({ a: startI, b: n - 1 });
    for (let k = 0; k < spans.length; k++) {
        if (nextMode && k + 1 >= spans.length) break;
        const pf = makeProfile(spans[k].a, spans[k].b);
        if (pf === null) continue;
        if (nextMode) { pf.da = spans[k + 1].a; pf.db = spans[k + 1].b; }
        allSess.push(pf);
        if (nextMode) {
            const endX = pf.db < n - 1 ? pf.db - 1 : pf.db;
            for (let x = pf.da; x <= endX && x < n; x++) profAt[x] = allSess.length - 1;
        }
    }
}
const sessProfiles = allSess.slice(Math.max(0, allSess.length - sessBack));

let swingProfile = null;
if (swingProfOn && zz.length > swingLegs) {
    const ia = zz[zz.length - 1 - swingLegs].i;
    const ib = zz[zz.length - 1].i;
    swingProfile = makeProfile(ia, ib);
    if (swingProfile !== null) { swingProfile.da = swingProfile.a; swingProfile.db = n - 1; }
}

const prim = sessProfiles.length > 0 ? sessProfiles[sessProfiles.length - 1] : swingProfile;
const primLabel = sessProfiles.length > 0 ? (nextMode ? 'prior ' : '') + sessPeriod.toLowerCase() + ' session' : 'swing range';

const SESS_COLS  = ['#5c6bc0', '#29b6f6', '#26c6da', '#66bb6a', '#d4e157', '#ffa726'];
const SWING_COLS = ['#8e24aa', '#ec407a', '#ff7043', '#ffa726', '#ffee58', '#9ccc65'];
const POC_COL    = '#f9a825';
const HVN2_COL   = '#ff6d00';
const LVN_COL    = '#8e24aa';

function drawFamily(profs, tag, cols, barOp, anchorEnd, withRows) {
    const rowHi = [], rowLo = [];
    for (let r = 0; r < PR; r++) { rowHi.push(series_of(null)); rowLo.push(series_of(null)); }
    const pocA = series_of(null);
    const hvHi = [series_of(null)];
    const hvLo = [series_of(null)];
    const lvHi = [series_of(null)];
    const lvLo = [series_of(null)];
    const lvLine = [series_of(null)];

    for (let k = 0; k < profs.length; k++) {
        const pf = profs[k];
        const endX = pf.db < n - 1 ? pf.db - 1 : pf.db;
        const maxLen = Math.max(3, Math.round((pf.b - pf.a + 1) * widthPct / 100));
        for (let r = 0; r < PR; r++) {
            const len = Math.max(1, Math.round(pf.vr[r] / pf.mx * maxLen));
            const x0 = anchorEnd ? pf.b : pf.da;
            for (let x = x0; x < x0 + len && x <= endX && x < n; x++) {
                rowHi[r][x] = pf.lo + (r + 1) * pf.rh;
                rowLo[r][x] = pf.lo + r * pf.rh;
            }
        }
        for (let x = pf.da; x <= endX && x < n; x++) {
            if (showPoc) pocA[x] = rowMid(pf, pf.poc);
            if (showNodes) {
                for (let h = 0; h < Math.min(1, pf.hvB.length); h++) { hvHi[h][x] = pf.hvB[h].hi; hvLo[h][x] = pf.hvB[h].lo; }
                for (let l = 0; l < Math.min(1, pf.lvB.length); l++) { lvHi[l][x] = pf.lvB[l].hi; lvLo[l][x] = pf.lvB[l].lo; lvLine[l][x] = pf.lvB[l].mid; }
            }
        }
    }

    const lvCols = [LVN_COL];
    const hvCols = [GOLD];
    for (let l = 0; l < 1; l++) {
        const lh = paint(lvHi[l], { name: tag + ' LVN' + (l + 1) + ' Top', color: lvCols[l], style: 'line', thickness: 1, hidden: true });
        const ll = paint(lvLo[l], { name: tag + ' LVN' + (l + 1) + ' Bottom', color: lvCols[l], style: 'line', thickness: 1, hidden: true });
        fill(lh, ll, lvCols[l], showNodes ? 0.20 : 0);
        paint(lvLine[l], { name: tag + ' LVN' + (l + 1) + ' Line', color: lvCols[l], style: 'line', thickness: 2 });
    }
    for (let h = 0; h < 1; h++) {
        const hh = paint(hvHi[h], { name: tag + ' HVN' + (h + 1) + ' Top', color: hvCols[h], style: 'line', thickness: 1 });
        const hl = paint(hvLo[h], { name: tag + ' HVN' + (h + 1) + ' Bottom', color: hvCols[h], style: 'line', thickness: 1 });
        fill(hh, hl, hvCols[h], showNodes ? 0.22 : 0);
    }
    for (let r = 0; r < PR; r++) {
        const col = cols[r % cols.length];
        const h = paint(rowHi[r], { name: tag + ' Row' + (r + 1) + ' Top', color: col, style: 'line', thickness: 1, hidden: true });
        const l = paint(rowLo[r], { name: tag + ' Row' + (r + 1) + ' Bottom', color: col, style: 'line', thickness: 1, hidden: true });
        fill(h, l, col, withRows ? barOp : 0);
    }
    paint(pocA, { name: tag + ' POC', color: POC_COL, style: 'line', thickness: 2 });
}

drawFamily(sessProfiles, 'Session', SESS_COLS, 0.34, false, true);
drawFamily(swingProfile !== null ? [swingProfile] : [], 'Swing', SWING_COLS, 0.30, swingBlocksEnd, false);

const pocPx = (prim !== null && showNodes && showPoc) ? rowMid(prim, prim.poc) : null;
const projPoc = paint_projection(projectionOf(pocPx), { name: 'Profile POC Ahead', color: POC_COL, style: 'line', thickness: 1, ignoreWhenScaling: true, hideInLegend: true });
paint_label_at_line(projPoc, 10, (pocPx !== null ? 'POC / HVN ' + pocPx.toFixed(2) : ' '), { color: '#ffffff', background_color: pocPx !== null ? 'rgba(249,168,37,0.92)' : 'transparent', border_radius: 4, border_width: 0 });

const h2 = (prim !== null && showNodes && prim.hvB.length > 1) ? prim.hvB[1].mid : null;
const projH = paint_projection(projectionOf(h2), { name: 'Profile HVN Ahead', color: HVN2_COL, style: 'line', thickness: 1, ignoreWhenScaling: true, hideInLegend: true });
paint_label_at_line(projH, 10, (h2 !== null ? 'HVN 2 ' + h2.toFixed(2) : ' '), { color: '#ffffff', background_color: h2 !== null ? 'rgba(255,112,67,0.92)' : 'transparent', border_radius: 4, border_width: 0 });

const l1 = (prim !== null && showNodes && prim.lvB.length > 0) ? prim.lvB[0].mid : null;
const projL = paint_projection(projectionOf(l1), { name: 'Profile LVN Ahead', color: LVN_COL, style: 'line', thickness: 1, ignoreWhenScaling: true, hideInLegend: true });
paint_label_at_line(projL, 10, (l1 !== null ? 'LVN ' + l1.toFixed(2) : ' '), { color: '#ffffff', background_color: l1 !== null ? 'rgba(171,71,188,0.92)' : 'transparent', border_radius: 4, border_width: 0 });

//====================================================
// SECTION 6 - SIGNALS: OB + PROFILE (single cooldown pass)
//
//  OB signal     : absorption candle (RVOL + wick) inside a live order block
//  Profile signal: absorption candle at HVN/POC of the active session profile
//  A+            : OB signal and Profile signal agree on the SAME bar
//====================================================
function activeProfiles(j) {
    return (nextMode && profAt[j] >= 0) ? [allSess[profAt[j]]] : [];
}

// Profile signal candidates
const profCand = Array(n).fill(null);
for (let j = 1; j <= lastEval; j++) {
    if (rvol[j] === null || rvol[j] < minRvol) continue;
    const rng = high[j] - low[j];
    if (!(rng > 0)) continue;
    const bodyHi = Math.max(open[j], close[j]);
    const bodyLo = Math.min(open[j], close[j]);
    const bullShape = close[j] > open[j] && (bodyLo - low[j]) / rng >= minWick / 100;
    const bearShape = close[j] < open[j] && (high[j] - bodyHi) / rng >= minWick / 100;
    if (!bullShape && !bearShape) continue;

    const profs = activeProfiles(j);
    let hitPf = null, hitBand = null, dir = 0;
    for (let k = 0; k < profs.length && dir === 0; k++) {
        const pf = profs[k];
        for (let h = 0; h < pf.hvB.length; h++) {
            const b = pf.hvB[h];
            if (!(low[j] <= b.hi && high[j] >= b.lo)) continue;
            if (bullShape && close[j] >= b.lo) { dir = 1; hitPf = pf; hitBand = b; break; }
            if (bearShape && close[j] <= b.hi) { dir = -1; hitPf = pf; hitBand = b; break; }
        }
    }
    if (dir === 0) continue;

    // Target = nearest other HVN level beyond the entry
    let tgt = null;
    for (let h = 0; h < hitPf.hvB.length; h++) {
        const b = hitPf.hvB[h];
        if (b === hitBand) continue;
        if (dir === 1  && b.lo > close[j] && (tgt === null || b.lo < tgt)) tgt = b.lo;
        if (dir === -1 && b.hi < close[j] && (tgt === null || b.hi > tgt)) tgt = b.hi;
    }
    profCand[j] = { dir: dir, tgt: tgt };
}

// Single chronological cooldown pass
const sigList = [];
const dObBuy  = series_of(null), dObSell  = series_of(null);
const dObBuyA = series_of(null), dObSellA = series_of(null);
const dPrBuy  = series_of(null), dPrSell  = series_of(null);

let lastAny = -999;
for (let j = 1; j <= lastEval; j++) {
    if (j - lastAny < sigGap) continue;
    const oc = obCand[j];
    const pc = profCand[j];

    if (oc !== 0) {
        // OB signal: A+ if profile agrees on the same bar
        const agree = pc !== null && pc.dir === oc;
        const entry = { j: j, dir: oc, grade: agree ? 'A+' : '' };
        if (agree && pc.tgt !== null) entry.tgt = pc.tgt;
        if (showObSig) {
            if (oc === 1) { if (agree) dObBuyA[j] = 'BUY A+'; else dObBuy[j] = 'BUY'; }
            else          { if (agree) dObSellA[j] = 'SELL A+'; else dObSell[j] = 'SELL'; }
        }
        sigList.push(entry);
        lastAny = j;
    } else if (pc !== null) {
        // Profile-only signal (plain, no A+ without OB confluence)
        const entry = { j: j, dir: pc.dir, kind: 'P' };
        if (pc.tgt !== null) entry.tgt = pc.tgt;
        if (showProfSigP) {
            if (pc.dir === 1) dPrBuy[j]  = 'ABS BUY';
            else              dPrSell[j] = 'ABS SELL';
        }
        sigList.push(entry);
        lastAny = j;
    }
}

// Collect visible signals for setup + dashboard
const visSig = [];
for (let q = 0; q < sigList.length; q++) {
    const sg = sigList[q];
    const isP = sg.kind === 'P';
    if (!(isP ? showProfSigP : showObSig)) continue;
    sg.shownPlus = sg.grade === 'A+';
    visSig.push(sg);
}

//====================================================
// SECTION 7 - ABSORPTION BUBBLES
//====================================================
const bubbles       = series_of(null);
const bubblesColors = series_of(null);
const bullBubText   = series_of(null);
const bearBubText   = series_of(null);

for (let j = 1; j <= lastEval; j++) {
    if (rvol[j] === null || rvol[j] < bubbleRvol) continue;
    if (dObBuy[j] !== null || dObSell[j] !== null || dObBuyA[j] !== null || dObSellA[j] !== null ||
        dPrBuy[j] !== null || dPrSell[j] !== null) continue;

    if (bubbleKeyOnly) {
        let nearKey = false;
        for (let zi = 0; zi < zones.length; zi++) {
            const z = zones[zi];
            if (j >= z.s0 && (z.alive || j <= z.end) && low[j] <= z.top && high[j] >= z.bot) {
                nearKey = true; break;
            }
        }
        const aps = activeProfiles(j);
        if (!nearKey && aps.length > 0) {
            const pocP = rowMid(aps[0], aps[0].poc);
            const aVal = atrA[j] !== null ? atrA[j] : (high[j] - low[j]);
            if (Math.abs(close[j] - pocP) <= aVal * 0.75) nearKey = true;
        }
        if (!nearKey) continue;
    }

    const rng = high[j] - low[j];
    if (!(rng > 0)) continue;
    const bHi = Math.max(open[j], close[j]);
    const bLo = Math.min(open[j], close[j]);
    const lowW = (bLo - low[j]) / rng;
    const upW  = (high[j] - bHi) / rng;

    const isBull = lowW >= minWick / 100 && close[j] >= low[j] + rng * 0.5;
    const isBear = upW  >= minWick / 100 && close[j] <= high[j] - rng * 0.5;

    if (isBull || isBear) {
        const midPx = (high[j] + low[j]) / 2;
        const sz = Math.min(45, Math.max(12, 10 + Math.log10(Math.abs(rvol[j]) + 1) * 25));
        bubbles[j] = { y: midPx, z: sz };
        bubblesColors[j] = isBull ? '#00e676' : '#ff1744';
        const txt = rvol[j].toFixed(1) + 'x';
        if (isBull) bullBubText[j] = txt; else bearBubText[j] = txt;
    }
}

//====================================================
// SECTION 8 - ACTIVE SETUP (latest visible signal)
//====================================================
let setup = null;
if (visSig.length > 0) {
    const sg = visSig[visSig.length - 1];
    if (n - 1 - sg.j <= 12) {
        const a      = atrA[sg.j] !== null ? atrA[sg.j] : atrNow;
        const entry  = sg.dir === 1 ? high[sg.j] : low[sg.j];
        const stopPx = sg.dir === 1 ? low[sg.j] - 0.1 * a : high[sg.j] + 0.1 * a;
        const risk   = Math.abs(entry - stopPx);
        let tgt      = (sg.tgt !== undefined && sg.tgt !== null) ? sg.tgt : null;
        // Fallback: use the nearest opposing OB zone as target
        if (tgt === null) {
            for (let k = 0; k < zones.length; k++) {
                const z = zones[k];
                if (!z.alive || z.s0 > sg.j) continue;
                if (sg.dir === 1  && z.type === -1 && z.bot > entry && (tgt === null || z.bot < tgt)) tgt = z.bot;
                if (sg.dir === -1 && z.type ===  1 && z.top < entry && (tgt === null || z.top > tgt)) tgt = z.top;
            }
        }
        if (tgt === null) tgt = entry + sg.dir * 3 * risk;

        let done = false;
        for (let k = sg.j + 1; k < n; k++) {
            if (sg.dir === 1  && (low[k]  <= stopPx || high[k] >= tgt)) done = true;
            if (sg.dir === -1 && (high[k] >= stopPx || low[k]  <= tgt)) done = true;
        }
        if (!done && risk > 0)
            setup = { j: sg.j, dir: sg.dir, entry: entry, stop: stopPx, target: tgt, rr: Math.abs(tgt - entry) / risk };
    }
}

//====================================================
// SECTION 9 - PAINT ORDER BLOCKS
//   Demand zones (bull OB) = teal,  Supply zones (bear OB) = rose
//   Up to 3 of each type shown; most-recent first
//====================================================
const OB_SLOTS = 6;   // 3 demand + 3 supply
for (let s = 0; s < OB_SLOTS; s++) {
    const isDem = s < 3;
    const idx   = s % 3;
    const list  = isDem ? aliveD : aliveS;
    const z     = idx < list.length ? list[idx] : null;
    const tag   = (isDem ? 'Demand' : 'Supply') + (idx + 1);
    const col   = isDem ? TEAL : ROSE;
    const hiA   = series_of(null);
    const loA   = series_of(null);

    if (showZones && z !== null) {
        // Fade slightly when price has already touched the zone
        const op = z.touches > 0 ? 0.13 : 0.22;
        for (let j = z.s0; j <= z.end && j < n; j++) {
            hiA[j] = z.top;
            loA[j] = z.bot;
        }
        const hId = paint(hiA, { name: tag + ' Top',    color: col, style: 'line', thickness: 1, hidden: true });
        const lId = paint(loA, { name: tag + ' Bottom', color: col, style: 'line', thickness: 1, hidden: true });
        fill(hId, lId, col, op);
    } else {
        paint(hiA, { name: tag + ' Top',    color: col, style: 'line', thickness: 1, hidden: true });
        paint(loA, { name: tag + ' Bottom', color: col, style: 'line', thickness: 1, hidden: true });
    }

    // Projection label for the nearest demand / nearest supply
    const isTarget = showZones && z !== null && z.alive && (z === nearSup || z === nearRes);
    const projVal  = isTarget ? (z.top + z.bot) / 2 : null;
    const pr = paint_projection(projectionOf(projVal), {
        name: tag + ' Ahead', color: col, style: 'line', thickness: 1, ignoreWhenScaling: true, hideInLegend: true
    });
    const labelText = isTarget
        ? ((z.type === 1 ? 'DEMAND' : 'SUPPLY') + (z.touches > 0 ? ' (' + z.touches + 'x)' : ' (fresh)'))
        : ' ';
    paint_label_at_line(pr, 10, labelText, {
        color: '#ffffff',
        background_color: isTarget ? (z.type === 1 ? 'rgba(38,166,154,0.85)' : 'rgba(239,83,80,0.85)') : 'transparent',
        border_radius: 4, border_width: 0
    });
}

//====================================================
// SECTION 10 - PAINT SIGNALS, BUBBLES + SETUP LINES
//====================================================
// OB signals: teal / red; A+ (OB + profile confluence) = purple
paint(dObBuy,   { style: 'labels_below', name: 'OB BUY (est.)',     color: 'white',   backgroundColor: '#26a69a',   backgroundBorderRadius: 4 });
paint(dObSell,  { style: 'labels_above', name: 'OB SELL (est.)',    color: 'white',   backgroundColor: '#ef5350',   backgroundBorderRadius: 4 });
paint(dObBuyA,  { style: 'labels_below', name: 'OB BUY A+ (est.)', color: '#ffffff', backgroundColor: '#7b1fa2',   backgroundBorderRadius: 4 });
paint(dObSellA, { style: 'labels_above', name: 'OB SELL A+ (est.)',color: '#ffffff', backgroundColor: '#7b1fa2',   backgroundBorderRadius: 4 });

// Profile signals: blue / orange
paint(dPrBuy,  { style: 'labels_below', name: 'ABS BUY (est.)',  color: 'white', backgroundColor: '#2979ff', backgroundBorderRadius: 4 });
paint(dPrSell, { style: 'labels_above', name: 'ABS SELL (est.)', color: 'white', backgroundColor: '#ff6d00', backgroundBorderRadius: 4 });

paint(showBubbles ? bubbles : series_of(null), { style: 'bubble', color: bubblesColors, name: 'Absorption Bubbles' });
paint(showBubbles ? bullBubText : series_of(null), { style: 'labels_below', color: '#26a69a', name: 'Bull Absorb Text' });
paint(showBubbles ? bearBubText : series_of(null), { style: 'labels_above', color: '#ef5350', name: 'Bear Absorb Text' });

const entryLine = series_of(null);
const stopLine  = series_of(null);
const tgtLine   = series_of(null);
if (setup !== null && showSetup) {
    for (let j = setup.j; j < n; j++) {
        entryLine[j] = setup.entry;
        stopLine[j]  = setup.stop;
        tgtLine[j]   = setup.target;
    }
}
paint(entryLine, { name: 'Setup Entry',  color: '#9e9e9e', style: 'line', thickness: 1 });
paint(stopLine,  { name: 'Setup Stop',   color: '#e53935', style: 'line', thickness: 2 });
paint(tgtLine,   { name: 'Setup Target', color: '#00c853', style: 'line', thickness: 2 });

//====================================================
// SECTION 11 - DASHBOARD
//====================================================
const tableRows = [];

if (showTable) {
    function sec(text) {
        return { cells: [{ text: text, colspan: 2, color: GOLD, fontWeight: 'bold', fontSize: '10px', padding: '3px 8px', background: BG2, borderTop: '1px solid #243447', borderBottom: '1px solid #243447' }] };
    }
    function row(k, v, vc) {
        return { cells: [
            { text: k, color: MUTED, fontSize: '11px', padding: '2px 8px', background: BG, whiteSpace: 'nowrap' },
            { text: v, color: vc || TXT, 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 || MUTED, fontSize: '10px', padding: '2px 8px', background: BG, textAlign: 'center' }] };
    }

    tableRows.push({ cells: [{ text: 'DeepShock', colspan: 2, background: '#0b141c', color: TEAL, fontWeight: 'bold', fontSize: '12px', padding: '5px 8px', textAlign: 'center' }] });

    tableRows.push(sec('Market Structure'));
    tableRows.push(row('Bias', biasTxt + '  (' + biasSub + ')', biasColor));

    if (showZones) {
        tableRows.push(sec('Order Blocks'));
        const obFmt = function (z) {
            const pct = (Math.abs((z.top + z.bot) / 2 - spot) / spot) * 100;
            return z.bot.toFixed(2) + ' - ' + z.top.toFixed(2) + '  (' + pct.toFixed(2) + '%)';
        };
        tableRows.push(row('Demand', nearSup !== null ? obFmt(nearSup) : 'none', nearSup !== null ? TEAL : MUTED));
        tableRows.push(row('Supply', nearRes !== null ? obFmt(nearRes) : 'none', nearRes !== null ? ROSE : MUTED));

        // Show if price is currently sitting inside an OB
        let inside = null;
        for (let k = 0; k < shownZones.length; k++) {
            const z = shownZones[k];
            if (z.alive && spot <= z.top && spot >= z.bot) { inside = z; break; }
        }
        if (inside !== null)
            tableRows.push(row('Price at', 'INSIDE ' + (inside.type === 1 ? 'DEMAND' : 'SUPPLY'), inside.type === 1 ? TEAL : ROSE));
    }

    if (!compactTable && prim !== null) {
        tableRows.push(sec('Volume Profile (' + primLabel + ')'));
        const dist   = function (x) { return x.toFixed(2) + '  (' + (Math.abs(x - spot) / spot * 100).toFixed(2) + '%)'; };
        const rngTxt = function (b) { return b.lo.toFixed(2) + ' - ' + b.hi.toFixed(2); };
        tableRows.push(row('POC', dist(rowMid(prim, prim.poc)), POC_COL));
        tableRows.push(row('HVN', prim.hvB.length > 0 ? rngTxt(prim.hvB[0]) : 'none', prim.hvB.length > 0 ? '#ffd54f' : MUTED));
        if (prim.hvB.length > 1) tableRows.push(row('HVN 2', rngTxt(prim.hvB[1]), '#ffab91'));
        tableRows.push(row('LVN', prim.lvB.length > 0 ? rngTxt(prim.lvB[0]) : 'none', prim.lvB.length > 0 ? '#ce93d8' : MUTED));
        if (prim.lvB.length > 1) tableRows.push(row('LVN 2', rngTxt(prim.lvB[1]), '#b39ddb'));
    }

    if (setup !== null) {
        tableRows.push(sec('Setup (' + (setup.dir === 1 ? 'LONG' : 'SHORT') + ', estimate)'));
        tableRows.push(row('Entry', '$' + setup.entry.toFixed(2), TXT));
        tableRows.push(row('Stop', '$' + setup.stop.toFixed(2), ROSE));
        tableRows.push(row('Target', '$' + setup.target.toFixed(2), TEAL));
        tableRows.push(row('R:R', setup.rr.toFixed(1) + ' to 1', setup.rr >= 2 ? TEAL : TXT));
    }

    if (!compactTable) {
        tableRows.push(sec('Absorption (volume estimate)'));
        const rNow = rvol[n - 1];
        tableRows.push(row('Rel. Volume', rNow !== null ? rNow.toFixed(2) + 'x' : 'n/a', rNow !== null && rNow >= minRvol ? TEAL : TXT));
        if (visSig.length > 0) {
            const sg = visSig[visSig.length - 1];
            tableRows.push(row('Last Signal',
                (sg.kind === 'P' ? 'ABS ' : 'OB ') + (sg.dir === 1 ? 'BUY' : 'SELL') + (sg.shownPlus ? ' A+' : '') + '  ' + (n - 1 - sg.j) + ' bars ago',
                sg.dir === 1 ? TEAL : ROSE));
        } else {
            tableRows.push(row('Last Signal', 'none', MUTED));
        }
    }
    tableRows.push(note(hasVol ? 'Volume-based estimate, not footprint data' : 'No volume data - range used instead', hasVol ? MUTED : GOLD));
}

paint_overlay('DeepShockProTable', {
    position: 'top_right',
    parent: 'chart',
    order: 'above_all',
    offset_x: tableOffsetX,
    offset_y: tableOffsetY
}, {
    width: showTable ? '260px' : '0px',
    border: showTable ? '1px solid #243447' : 'none',
    borderRadius: '8px',
    background: showTable ? BG : 'transparent',
    overflow: 'hidden',
    rows: tableRows
});

//====================================================
// SECTION 12 - REGISTER SIGNALS
//====================================================
register_signal(dObBuy,   'Order Block BUY (volume estimate)');
register_signal(dObSell,  'Order Block SELL (volume estimate)');
register_signal(dObBuyA,  'Order Block BUY A+ (volume estimate)');
register_signal(dObSellA, 'Order Block SELL A+ (volume estimate)');
register_signal(dPrBuy,   'Profile ABS BUY (volume estimate)');
register_signal(dPrSell,  'Profile ABS SELL (volume estimate)');