Today's volume against a normal day — and which way price went while it happened. #TSBuild26
Most relative-volume tools give you a number. Volume Pace Curve shows you the shape and puts price on the same clock: today's cumulative volume drawn over a fan of the last ten sessions, expected pace through the middle, today's price across the same chart. One glance says whether the tape is heavy or light, and whether the volume was buying or selling.
ON THE PANEL
- Projected close as % of the 20-day average, big and color-coded: dead · light · slightly light · on pace · heavy. Projected volume, pace vs expected and % elapsed sit under it.
- The curve — today vs expected, filled green when ahead, red when behind. Dotted projection to the close with an end marker; the unplayed day dimmed.
- Price on the curve — today's price over the volume picture, green or red vs prior close, dashed reference line so a gap shows at 09:30. Switchable to a time-aligned sparkline, a day-range gauge, or off.
- Bucket RVOL bars — 26 bars, one per 15 minutes, colored by relative volume: when the volume showed up. Peak bucket and above-average count beside them.
- Read-out — % change vs prior close, share of volume on up or down bars, day low and high.
- State banner in words: HEAVY SELLING · 155% OF AVG. ON PACE · BUYING. LIGHT TAPE. DEAD TAPE. The direction word needs a 1% move and 60% of volume on that side; both thresholds are yours.
HOW IT READS
Heavy day, line above the fan, price climbing: the market is behind the move. Heavy day, price sliding: heavy selling, and the banner says so. Light day, line under the fan, price flat on the reference: nobody's behind it.
NEW IN v2.0
Price overlay on the pace chart, same 09:30–16:00 clock as the volume, dashed line at prior close. Sparkline and gauge modes too.
- Direction in the banner: HEAVY DAY TRACKING becomes HEAVY SELLING or HEAVY BUYING when price moved and volume leaned that way.
- Price read-out row: % vs prior close (or open), up/down-bar volume share, low and high.
- Signals rescaled to the number on the panel: Volume Pace Negative fires below your light threshold (default 90% of avg), Projected Volume Above Average above your heavy threshold (default 100%). A 96% day no longer flags negative.
- 1-hour charts supported; the forming bar is cut at the live exchange clock, so pace is exact mid-bar from 1m to 1h.
- Price, direction share and buckets all come from the same 15-minute reference bars, so the panel reads identically on every timeframe.
- The Rock theme (Bottom Catcher palette) is the default; six others remain.
NEW IN 2.1
- Price dots: a dot at every 15-minute bucket on the price line, green or red by that bucket's direction.
UNDER THE HOOD
Pace is measured against a time-of-day profile from a fixed 15-minute regular-hours reference, so the reading is the same on a 1m and a 1h chart and unaffected by extended-hours settings. Level comes from the composite daily bar, so it reconciles with the daily chart. Median profile by default, so one earnings blowout doesn't bend the shape for two weeks.
Same pace engine as the free Volume Pace & Projection: that's the table, this is the picture.
Signals for scanners and alerts: Volume Pace Negative, Projected Volume Above Average. Settings: average window, profile depth, median/mean, fan, price display, change basis, direction and signal thresholds, seven themes, UI scale, panel sizes, bars and banner toggles.
Works on 1-minute through 1-hour charts, on any symbol with daily volume history.
// ─────────────────────────────────────────────────────────────────────────────
// ⌖ Volume Pace Curve — v2.1
// ─────────────────────────────────────────────────────────────────────────────
// Today's volume against a normal day, as a picture — and which way price went
// while it happened.
//
// HERO Projected end-of-day volume as % of the N-day average, on a
// tier-colored block. Under it: projected volume, pace vs expected,
// today's volume and % of session elapsed.
// CURVE Today's cumulative volume (scaled to composite units, pinned to
// the daily bar) over a fan of the last P sessions (min–max and
// 25–75% bands), expected pace dashed through the middle. Fill is
// green when ahead, red when behind. Dotted projection to 16:00
// with a close marker; the rest of the day is dimmed.
// PRICE Today's price (15m closes) drawn on the curve on a hidden right
// axis — green/red vs the change basis, dashed reference line, end
// dot. Alternatives: Sparkline (time-aligned mini-chart in the price
// row), Gauge (day-range bar only), Off.
// BARS 26 bucket RVOL bars (one per 15m), tier-colored, 100% line, with
// peak bucket and count above average.
// READ-OUT % change vs prior close (or open), up/down-bar volume share,
// day low and high.
// BANNER State in words: HEAVY DAY TRACKING · 147% OF AVG / ON PACE /
// SLIGHTLY LIGHT / LIGHT TAPE / DEAD TAPE. Gains a direction word
// (HEAVY SELLING, ON PACE · BUYING) when price is ≥ Move% from the
// change basis AND ≥ Share% of today's volume traded on bars of
// that side.
//
// Tiers: <50 red · 50–79 yellow · 80–89 orange · 90–105 green · >105 lime.
//
// ENGINE: same pace model as the free Volume Pace & Projection. Shape = fixed
// 15m RTH profile (own request, independent of chart timeframe and ext-hours);
// level = composite N-day daily average; today = composite daily bar. The 15m
// feed under-reports vs the daily bar (auction + off-exchange prints), so
// intraday cumulative is scaled by todayDaily ÷ todayIntradaySum. Prior-session
// fan curves are scaled by their own ratio. Median profile by default so a
// single blowout session doesn't bend the shape. The forming bar is cut at the
// live exchange clock, so pace is exact mid-bar on any timeframe (1m–1h).
// Direction share and price series come from the same 15m reference bars, so
// they are identical on every chart timeframe.
//
// Signals read the hero number (projected % of average) directly:
// 'Volume Pace Negative' fires when hero < Light Signal (default 90)
// 'Projected Volume Above Average' fires when hero > Heavy Signal (default 100)
// Both inherit the projection's early-session gate.
//
// Lineage: Pace Curve v0.1–v0.5e (quiet card) → Pace Curve Bold v0.1–v0.1d →
// Volume Pace Curve v1.0–v1.3b (signals rescaled, 1h support, price row, price
// overlay, prior-close basis). v2.0 = first store release with price.
// v2.1: Price Dots — a dot at every 15m bucket on the price overlay, colored
// by that bucket's close vs the previous bucket (green up / red down /
// grey flat), Underlying Chart Overlay style; the end dot stays larger.
// Gauge current-price tick in the theme info color (Rock's edit).
// ─────────────────────────────────────────────────────────────────────────────
describe_indicator('Volume Pace Curve', { shortName: '⌖ Volume Pace Curve v2.1' });
// ─── Inputs ──────────────────────────────────────────────────────────────────
const volDays = input.number('Volume Days', 20, { min: 1, max: 200, step: 1 });
const profileDays = input.number('Pace Profile Days', 10, { min: 3, max: 20, step: 1 });
const profileMode = input('Profile Collapse', 'Median', ['Median', 'Mean']);
const fanMode = input('Fan', 'Both', ['Both', 'Quartiles', 'Off']);
const themeChoice = input('Theme', 'The Rock', ['The Rock', 'Midnight', 'Carbon', 'Ocean', 'Solar', 'Light', 'Paper']);
const uiScaleIn = input.number('UI Scale (%)', 100, { min: 50, max: 200, step: 5 });
const chartWidth = input.number('Chart Width (px)', 420, { min: 240, max: 900, step: 20 });
const chartHeight = input.number('Chart Height (px)', 150, { min: 90, max: 400, step: 10 });
const barsHeight = input.number('Bars Height (px)', 50, { min: 40, max: 160, step: 10 });
const showPanel = input.boolean('Show Panel', true);
const showProjExt = input.boolean('Projection Line', true);
const showPxDots = input.boolean('Price Dots', true);
const showBars = input.boolean('Bucket Bars', true);
const showBanner = input.boolean('State Banner', true);
const priceMode = input('Price Display', 'Overlay', ['Overlay', 'Sparkline', 'Gauge', 'Off']);
const showPrice = priceMode !== 'Off';
const chgBasis = input('Change Basis', 'Prior Close', ['Prior Close', 'Open']);
const dirMinMove = input.number('Direction Min Move (%)', 1.0, { min: 0, max: 20, step: 0.25 });
const dirMinShare = input.number('Direction Min Share (%)', 60, { min: 50, max: 100, step: 5 });
const showFooter = input.boolean('Footer Timestamp', false);
const heavySigPct = input.number('Heavy Signal (% of avg)', 100, { min: 1, max: 500, step: 5 });
const lightSigPct = input.number('Light Signal (% of avg)', 90, { min: 1, max: 200, step: 5 });
// ─── UI scale ────────────────────────────────────────────────────────────────
const uiScale = Number.isFinite(uiScaleIn) && uiScaleIn > 0 ? uiScaleIn : 100;
function scaleVal(n) { return Math.max(1, Math.round(n * uiScale / 100)); }
function px(n) { return scaleVal(n) + 'px'; }
function pad(v, h) { return px(v) + ' ' + px(h); }
const baseFont = scaleVal(12);
const heroFont = scaleVal(44);
const chartW = scaleVal(chartWidth);
const chartH = scaleVal(chartHeight);
const barsH = scaleVal(barsHeight);
// ─── Status colors (shared across themes) ────────────────────────────────────
const STATUS = { up: '#26a65b', dn: '#e74c3c', yellow: '#ffd54a', orange: '#ff9d3c', lime: '#7ed957' };
// ─── Themes ──────────────────────────────────────────────────────────────────
// accent = header band + fan tint + title. Light themes use a saturated accent
// so the band still reads as a band.
const THEMES = {
// Bottom Catcher palette: header #6200FF, rows #2a353b, white text, P&L green/red.
'The Rock': { bg: '#2a353b', border: '#6200ff', accent: '#6200ff', title: '#ffffff', header: '#b9c4cc', text: '#ffffff', expected: '#cfd8dc', up: '#00a000', dn: '#e01414', info: '#FFDF20' },
Midnight: { bg: '#0d1117', border: '#30363d', accent: '#1f6feb', title: '#ffffff', header: '#8b949e', text: '#ffffff', expected: '#8b949e', info: '#ffdf20' },
Carbon: { bg: '#0e0e10', border: '#2a2a2e', accent: '#3a3a40', title: '#ffffff', header: '#7a7a80', text: '#ffffff', expected: '#8a8a90', info: '#ffdf20' },
Ocean: { bg: '#06202a', border: '#1f7a8c', accent: '#1f7a8c', title: '#ffffff', header: '#6fa3b0', text: '#ffffff', expected: '#6fa3b0', info: '#ffdf20' },
Solar: { bg: '#221810', border: '#e0932f', accent: '#b8690f', title: '#ffffff', header: '#c9a878', text: '#f5ead6', expected: '#c9a878', info: '#ffb347' },
Light: { bg: '#f7f8fa', border: '#c9ced6', accent: '#1a56b0', title: '#ffffff', header: '#5a6473', text: '#1c2430', expected: '#7a8494', lime: '#4caf50', yellow: '#c9a227', info: '#1a56b0' },
Paper: { bg: '#f5efe2', border: '#d6c9ad', accent: '#3d5a80', title: '#ffffff', header: '#8a7f6a', text: '#2b2418', expected: '#9a8f78', lime: '#4caf50', yellow: '#b8860b', orange: '#e07b1f', info: '#FB2BFF' }
};
const base = THEMES[themeChoice] || THEMES['The Rock'];
const T = {
bg: base.bg, border: base.border, accent: base.accent, title: base.title, header: base.header, text: base.text,
expected: base.expected, fan: base.accent, info: base.info || base.title,
up: base.up || STATUS.up, dn: base.dn || STATUS.dn,
yellow: base.yellow || STATUS.yellow, orange: base.orange || STATUS.orange, lime: base.lime || STATUS.lime
};
function rgba(hex, a) {
const m = /^#([0-9a-f]{6})$/i.exec(hex);
if (!m) return hex;
const n = parseInt(m[1], 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
}
// Dark text on bright tier blocks (yellow/lime/orange), white on the rest.
function onTier(hex) { return (hex === T.yellow || hex === T.lime || hex === T.orange) ? '#14181c' : '#ffffff'; }
// ─── Constants / helpers ─────────────────────────────────────────────────────
const REF_TF = '15';
const REF_MIN = 15;
const RTH_OPEN = 9 * 60 + 30;
const RTH_END = 16 * 60;
const MIN_DEPTH = 3;
const MIN_PROJ_FRAC = 0.05;
const SETTLED_FRAC = 0.20;
const minOfDay = (t) => { const d = time_of(t); return d.hours * 60 + d.minutes; };
const dayKey = (t) => time_of(t).dayOfYear;
const hhmm = (m) => `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
const moment = library('moment-timezone');
// ─── Data requests (depth 0) ─────────────────────────────────────────────────
const daily = await request.history(current.ticker, 'D');
assert(!daily.error, `Error fetching daily data: ${daily.error}`);
const ref = await request.history(current.ticker, REF_TF);
assert(!ref.error, `Error fetching ${REF_TF}m reference data: ${ref.error}`);
// ─── Session / timeframe context ─────────────────────────────────────────────
const lastIdx = close.length - 1;
const todayKey = dayKey(time[lastIdx]);
const tfMin = parseInt(constants.resolution, 10);
const isIntraday = Number.isFinite(tfMin) && tfMin <= 60;
const barStartMin = minOfDay(time[lastIdx]);
// Forming-bar cutoff: the bar's scheduled end, clamped to the real exchange
// clock when the session is live (so a 1h bar at 10:05 counts 35 min, not 60).
// Only applied when the clock falls inside the current bar; otherwise (closed
// session, historical bar) the scheduled end stands.
const barEndMin = barStartMin + (Number.isFinite(tfMin) ? tfMin : 0);
let nowMin = Math.min(barEndMin, RTH_END);
{
const nyNow = moment.tz(Date.now(), 'America/New_York');
const nowClk = nyNow.hours() * 60 + nyNow.minutes();
const today = dayKey(time[lastIdx]);
const clockIsToday = nyNow.dayOfYear() === today;
if (clockIsToday && nowClk >= barStartMin && nowClk < barEndMin) nowMin = Math.min(nowClk, RTH_END);
}
// ─── Daily level ─────────────────────────────────────────────────────────────
const dvol = daily.volume || [], dtime = daily.time || [];
const dlen = dvol.length;
const dailyByDay = {};
for (let i = 0; i < dlen; i++) if (Number.isFinite(dvol[i])) dailyByDay[dayKey(dtime[i])] = dvol[i];
let volSum = 0, cnt = 0;
for (let i = dlen - 2; i >= 0 && cnt < volDays; i--) {
if (Number.isFinite(dvol[i])) { volSum += dvol[i]; cnt++; }
}
const avgDailyVol = cnt > 0 ? volSum / cnt : 0;
const todayDailyVol = (dlen > 0 && dayKey(dtime[dlen - 1]) === todayKey && Number.isFinite(dvol[dlen - 1])) ? dvol[dlen - 1] : null;
// ─── Reference feed: per-session buckets ─────────────────────────────────────
const rVol = ref.volume || [], rTime = ref.time || [], rClose = ref.close || [];
const rOpen = ref.open || [];
const todayPx = {}; // minuteOfDay -> 15m close (today)
let refUpVol = 0, refDnVol = 0, refBars = 0; // today's 15m direction
const bucket = {}, todayBucket = {}, sessSum = {}, sessOrder = [], sessBuckets = {};
for (let i = 0; i < rTime.length; i++) {
if (!Number.isFinite(rVol[i])) continue;
const m = minOfDay(rTime[i]);
if (m < RTH_OPEN || m >= RTH_END) continue;
const k = dayKey(rTime[i]);
if (k === todayKey) {
todayBucket[m] = (todayBucket[m] || 0) + rVol[i];
if (Number.isFinite(rClose[i])) todayPx[m] = rClose[i];
if (Number.isFinite(rOpen[i]) && Number.isFinite(rClose[i])) {
refBars++;
if (rClose[i] > rOpen[i]) refUpVol += rVol[i];
else if (rClose[i] < rOpen[i]) refDnVol += rVol[i];
}
continue;
}
if (!bucket[m]) bucket[m] = [];
bucket[m].push(rVol[i]);
if (!Number.isFinite(sessSum[k])) { sessSum[k] = 0; sessOrder.push(k); sessBuckets[k] = {}; }
sessSum[k] += rVol[i];
sessBuckets[k][m] = (sessBuckets[k][m] || 0) + rVol[i];
}
function collapse(w) {
if (profileMode === 'Mean') return w.reduce((r, x) => r + x, 0) / w.length;
const sorted = w.slice().sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
const bucketAvg = {};
let minDepth = Infinity;
Object.keys(bucket).forEach(k => {
const w = bucket[k].slice(-profileDays);
bucketAvg[k] = collapse(w);
if (w.length < minDepth) minDepth = w.length;
});
if (!Number.isFinite(minDepth)) minDepth = 0;
const minutes = Object.keys(bucketAvg).map(Number).sort((a, b) => a - b);
const bucketsTotal = minutes.length;
let fullDayProfile = 0;
minutes.forEach(m => { fullDayProfile += bucketAvg[m]; });
const depthOK = minDepth >= MIN_DEPTH && bucketsTotal > 0 && fullDayProfile > 0;
// ─── Series: 09:30 = 0, then bucket END times ────────────────────────────────
const labels = [''], expCum = [0], rawCum = [0];
const xLabel = (mEnd) => (mEnd % 60 === 0 || mEnd === RTH_END) ? String(Math.floor(mEnd / 60)) : '';
let cumProfile = 0, cumRaw = 0, elapsedProfile = 0, bucketsElapsed = 0;
minutes.forEach(m => {
cumProfile += bucketAvg[m];
labels.push(xLabel(m + REF_MIN));
expCum.push(depthOK && avgDailyVol > 0 ? avgDailyVol * (cumProfile / fullDayProfile) : null);
if (m < nowMin) { cumRaw += (todayBucket[m] || 0); elapsedProfile += bucketAvg[m]; bucketsElapsed++; rawCum.push(cumRaw); }
else rawCum.push(null);
});
const todayIntraSum = cumRaw;
const lastActualIdx = bucketsElapsed;
const closeIdx = labels.length - 1;
const nPts = labels.length;
const ratioNow = (todayDailyVol !== null && todayIntraSum > 0) ? todayDailyVol / todayIntraSum : null;
const actCum = rawCum.map(v => (v === null || ratioNow === null) ? null : v * ratioNow);
if (ratioNow !== null) actCum[0] = 0;
// ─── Fan: per-session scaled cumulative curves → percentile bands ────────────
// Each prior session's cum curve × (its daily bar ÷ its 15m RTH sum) puts it in
// composite units. Percentiles taken per point across the last P sessions.
const fanCurves = [];
sessOrder.slice(-profileDays).forEach(k => {
const dv = dailyByDay[k], is = sessSum[k];
if (!Number.isFinite(dv) || !Number.isFinite(is) || is <= 0) return;
const r = dv / is, curve = [0];
let c = 0;
minutes.forEach(m => { c += (sessBuckets[k][m] || 0); curve.push(c * r); });
fanCurves.push(curve);
});
const fanN = fanCurves.length;
function pctile(arr, p) {
const s = arr.slice().sort((a, b) => a - b);
const pos = (s.length - 1) * p, lo = Math.floor(pos), hi = Math.ceil(pos);
return lo === hi ? s[lo] : s[lo] + (s[hi] - s[lo]) * (pos - lo);
}
const fanMin = [], fanQ1 = [], fanQ3 = [], fanMax = [];
for (let i = 0; i < nPts; i++) {
if (fanN < MIN_DEPTH) { fanMin.push(null); fanQ1.push(null); fanQ3.push(null); fanMax.push(null); continue; }
const col = fanCurves.map(cv => cv[i]);
fanMin.push(pctile(col, 0)); fanQ1.push(pctile(col, 0.25)); fanQ3.push(pctile(col, 0.75)); fanMax.push(pctile(col, 1));
}
const fanOn = fanMode !== 'Off' && fanN >= MIN_DEPTH;
const fanFull = fanMode === 'Both';
// ─── Pace + projection ───────────────────────────────────────────────────────
let shapeFrac = null, expectedByNow = null, volPace = null, pacePct = null;
if (isIntraday && depthOK && avgDailyVol > 0 && todayDailyVol !== null) {
shapeFrac = Math.max(0, Math.min(elapsedProfile / fullDayProfile, 1));
expectedByNow = avgDailyVol * shapeFrac;
volPace = todayDailyVol - expectedByNow;
pacePct = expectedByNow > 0 ? (volPace / expectedByNow) * 100 : null;
}
let projClose = null, projPctOfAvg = null;
if (shapeFrac !== null && shapeFrac >= MIN_PROJ_FRAC && todayDailyVol > 0) {
projClose = todayDailyVol / shapeFrac;
projPctOfAvg = avgDailyVol > 0 ? Math.round(projClose / avgDailyVol * 100) : null;
}
const projSettled = shapeFrac !== null && shapeFrac >= SETTLED_FRAC;
// Projection extension / converged marker
const projSeries = labels.map(() => null), projRadius = labels.map(() => 0), todayRadius = labels.map(() => 0);
const converged = lastActualIdx >= closeIdx;
if (showProjExt && projClose !== null && actCum[lastActualIdx] !== null) {
if (!converged) { projSeries[lastActualIdx] = actCum[lastActualIdx]; projSeries[closeIdx] = projClose; projRadius[closeIdx] = scaleVal(4); }
else todayRadius[closeIdx] = scaleVal(4);
}
// ─── Signals ─────────────────────────────────────────────────────────────────
const paceNegSignal = series_of(false);
if (projPctOfAvg !== null && projPctOfAvg < lightSigPct) paceNegSignal[lastIdx] = true;
register_signal(paceNegSignal, 'Volume Pace Negative');
const projHotSignal = series_of(false);
if (projPctOfAvg !== null && projPctOfAvg > heavySigPct) projHotSignal[lastIdx] = true;
register_signal(projHotSignal, 'Projected Volume Above Average');
// ─── Formatters / colors ─────────────────────────────────────────────────────
function fmtVol(v) {
if (!Number.isFinite(v)) return '—';
const a = Math.abs(v);
if (a >= 1e9) return (v / 1e9).toFixed(2) + ' B';
if (a >= 1e6) return (v / 1e6).toFixed(1) + ' M';
if (a >= 1e3) return (v / 1e3).toFixed(0) + ' K';
return String(Math.round(v));
}
function fmtSigned(v) { return Number.isFinite(v) ? (v >= 0 ? '+' : '−') + fmtVol(Math.abs(v)) : '—'; }
function fmtPct(v) { return Number.isFinite(v) ? (v >= 0 ? '+' : '−') + Math.abs(v).toFixed(0) + '%' : '—'; }
function tierColor(pct) {
if (pct == null) return T.header;
return pct > 105 ? T.lime : pct >= 90 ? T.up : pct >= 80 ? T.orange : pct >= 50 ? T.yellow : T.dn;
}
const paceColor = volPace == null ? T.header : (volPace >= 0 ? T.up : T.dn);
const projColor = projSettled ? tierColor(projPctOfAvg) : T.header;
const todayColor = projSettled ? tierColor(projPctOfAvg) : paceColor;
// Chart display units (tick callbacks don't run in the overlay renderer)
const unitDiv = avgDailyVol >= 1e9 ? 1e9 : avgDailyVol >= 1e6 ? 1e6 : avgDailyVol >= 1e3 ? 1e3 : 1;
const toUnit = (arr) => arr.map(v => v === null ? null : v / unitDiv);
// Y ceiling so the future-dim block can fill full height
let yMaxRaw = 0;
[expCum, actCum, projSeries, fanMax].forEach(arr => arr.forEach(v => { if (v !== null && v > yMaxRaw) yMaxRaw = v; }));
if (avgDailyVol * 1.05 > yMaxRaw) yMaxRaw = avgDailyVol * 1.05;
const yMax = yMaxRaw > 0 ? (yMaxRaw * 1.06) / unitDiv : undefined;
const futureDim = labels.map((_, i) => (yMax !== undefined && i >= lastActualIdx) ? yMax : null);
// Hour hairlines + "now" via per-index grid colors (no gridlines elsewhere)
const gridColors = labels.map((lab, i) => {
if (i === lastActualIdx && !converged) return rgba(T.header, 0.35);
return lab !== '' ? rgba(T.header, 0.10) : 'rgba(0,0,0,0)';
});
// ─── Bucket RVOL per bucket (hero units) ─────────────────────────────────────
const canHeat = ratioNow !== null && avgDailyVol > 0 && fullDayProfile > 0;
const bucketPct = [], bucketCol = [], bucketLbl = [];
minutes.forEach(m => {
const expB = canHeat ? avgDailyVol * (bucketAvg[m] / fullDayProfile) : 0;
const actB = canHeat ? (todayBucket[m] || 0) * ratioNow : 0;
const done = m + REF_MIN <= nowMin, forming = !done && m < nowMin;
const pct = (expB > 0 && (done || forming)) ? actB / expB * 100 : null;
bucketPct.push(pct === null ? null : Math.min(pct, 300));
bucketCol.push(pct === null ? rgba(T.header, 0.12) : rgba(tierColor(pct), forming ? 0.45 : 0.95));
bucketLbl.push((m + REF_MIN) % 60 === 0 || m + REF_MIN === RTH_END ? String(Math.floor((m + REF_MIN) / 60)) : '');
});
// Bars read-out: peak bucket and how many completed buckets ran above average.
let peakIdx = -1, peakPct = -1, aboveN = 0, doneN = 0;
minutes.forEach((m, i) => {
if (m + REF_MIN > nowMin) return; // completed only
const p = bucketPct[i];
if (p === null) return;
doneN++;
if (p > 100) aboveN++;
if (p > peakPct) { peakPct = p; peakIdx = i; }
});
const barsRead = doneN === 0 ? 'bucket rvol'
: `peak ${hhmm(minutes[peakIdx])} · ${Math.round(peakPct)}%`;
const barsRead2 = doneN === 0 ? '' : `${aboveN} of ${doneN} above avg`;
// ─── Price context: day range, up/down-bar volume ────────────────────────────
const dOpen = daily.open || [], dHigh = daily.high || [], dLow = daily.low || [];
const haveDailyOHL = todayDailyVol !== null && Number.isFinite(dOpen[dlen - 1]) && Number.isFinite(dHigh[dlen - 1]) && Number.isFinite(dLow[dlen - 1]);
let dayOpen = haveDailyOHL ? dOpen[dlen - 1] : null;
let dayHigh = haveDailyOHL ? dHigh[dlen - 1] : null;
let dayLow = haveDailyOHL ? dLow[dlen - 1] : null;
const curPx = close[lastIdx];
// Chart-bar fallback for up/down volume (used only if the 15m reference has no
// bars for today) and fallback O/H/L if the daily bar is missing.
let upVol = 0, dnVol = 0, fbOpen = null, fbHigh = -Infinity, fbLow = Infinity;
for (let i = lastIdx; i >= 0; i--) {
if (dayKey(time[i]) !== todayKey) break;
const m = minOfDay(time[i]);
if (m < RTH_OPEN || m >= RTH_END) continue;
if (!Number.isFinite(volume[i])) continue;
if (close[i] > open[i]) upVol += volume[i];
else if (close[i] < open[i]) dnVol += volume[i];
fbOpen = open[i]; // walking backward → last assignment = first RTH bar
if (high[i] > fbHigh) fbHigh = high[i];
if (low[i] < fbLow) fbLow = low[i];
}
if (dayOpen === null && fbOpen !== null) { dayOpen = fbOpen; dayHigh = fbHigh; dayLow = fbLow; }
if (dayHigh !== null && curPx > dayHigh) dayHigh = curPx;
if (dayLow !== null && curPx < dayLow) dayLow = curPx;
// Prefer the 15m reference for direction share (timeframe-independent).
if (refBars > 0) { upVol = refUpVol; dnVol = refDnVol; }
// Reference price for % change: prior daily close, or today's open.
const dClose = daily.close || [];
let priorClose = null;
if (dlen > 0) {
const todayHasBar = dayKey(dtime[dlen - 1]) === todayKey;
const idx = todayHasBar ? dlen - 2 : dlen - 1;
if (idx >= 0 && Number.isFinite(dClose[idx])) priorClose = dClose[idx];
}
const refPx = (chgBasis === 'Prior Close' && priorClose !== null) ? priorClose : dayOpen;
const refLabel = (chgBasis === 'Prior Close' && priorClose !== null) ? 'vs prior close' : 'from open';
const dirVol = upVol + dnVol;
const upShare = dirVol > 0 ? upVol / dirVol * 100 : null;
const dnShare = dirVol > 0 ? dnVol / dirVol * 100 : null;
const pxMove = (refPx !== null && refPx > 0) ? (curPx - refPx) / refPx * 100 : null;
// Price series on the pace clock: index 0 = today's open, then each bucket's close.
// Forming bucket uses the chart's live close so the line reaches "now".
const pxSeries = labels.map(() => null);
if (dayOpen !== null) {
pxSeries[0] = dayOpen;
minutes.forEach((m, i) => {
if (m >= nowMin) return;
const done = m + REF_MIN <= nowMin;
const v = done ? todayPx[m] : curPx;
if (Number.isFinite(v)) pxSeries[i + 1] = v;
});
}
const openLine = labels.map(() => refPx);
let dirWord = null; // 'BUYING' | 'SELLING' | null
if (pxMove !== null && upShare !== null) {
if (pxMove >= dirMinMove && upShare >= dirMinShare) dirWord = 'BUYING';
else if (pxMove <= -dirMinMove && dnShare >= dirMinShare) dirWord = 'SELLING';
}
const pxColor = pxMove === null ? T.header : (pxMove >= 0 ? T.up : T.dn);
// ─── State text ──────────────────────────────────────────────────────────────
let stateText;
if (!isIntraday) stateText = 'USE A 1M–1H CHART';
else if (!depthOK) stateText = 'PROFILE TOO THIN';
else if (todayDailyVol === null) stateText = 'NO DAILY BAR';
else if (projPctOfAvg === null) stateText = 'WAITING FOR OPEN';
else if (!projSettled) stateText = `PROJECTION SETTLING · ${projPctOfAvg}%`;
else {
const p = projPctOfAvg;
let w = p > 105 ? 'HEAVY DAY TRACKING' : p >= 90 ? 'ON PACE' : p >= 80 ? 'SLIGHTLY LIGHT' : p >= 50 ? 'LIGHT TAPE' : 'DEAD TAPE';
if (dirWord) w = p > 105 ? `HEAVY ${dirWord}` : `${w} · ${dirWord}`;
stateText = `${w} · ${p}% OF AVG`;
}
const stateColor = projSettled ? tierColor(projPctOfAvg) : T.header;
// ─── Cells ───────────────────────────────────────────────────────────────────
function cell(text, o) {
o = o || {};
const c = {
text: text, color: o.color || T.text, background: o.bg || T.bg,
padding: o.padding || pad(2, 10), fontWeight: o.bold ? 'bold' : 'normal',
textAlign: o.align || 'left', fontSize: o.fs || baseFont
};
if (o.colspan) c.colspan = o.colspan;
if (o.rowspan) c.rowspan = o.rowspan;
return c;
}
// ─── Curve chart ─────────────────────────────────────────────────────────────
const FS = { outer: 0.18, inner: 0.32, edge: 0.55 };
const datasets = [];
if (fanOn && fanFull) {
datasets.push({ label: 'max', data: toUnit(fanMax), borderWidth: 1, pointRadius: 0, fill: '+1', backgroundColor: rgba(T.fan, FS.outer), borderColor: rgba(T.fan, FS.edge) });
datasets.push({ label: 'min', data: toUnit(fanMin), borderWidth: 1, pointRadius: 0, fill: false, borderColor: rgba(T.fan, FS.edge) });
}
if (fanOn) {
datasets.push({ label: 'q3', data: toUnit(fanQ3), borderWidth: 0, pointRadius: 0, fill: '+1', backgroundColor: rgba(T.fan, FS.inner), borderColor: 'rgba(0,0,0,0)' });
datasets.push({ label: 'q1', data: toUnit(fanQ1), borderWidth: 0, pointRadius: 0, fill: false, borderColor: 'rgba(0,0,0,0)' });
}
const expIdx = datasets.length;
datasets.push({ label: 'expected', data: toUnit(expCum), borderColor: rgba(T.text, 0.8), borderWidth: scaleVal(1.5), borderDash: [4, 3], fill: false, spanGaps: false, pointRadius: 0 });
datasets.push({ label: 'glow', data: toUnit(actCum), borderColor: rgba(todayColor, 0.28), borderWidth: scaleVal(12), fill: false, spanGaps: false, pointRadius: 0 });
datasets.push({
label: 'today', data: toUnit(actCum), borderColor: todayColor, borderWidth: scaleVal(3.5),
fill: { target: expIdx, above: rgba(T.up, 0.28), below: rgba(T.dn, 0.28) }, backgroundColor: rgba(todayColor, 0.25),
spanGaps: false, pointRadius: todayRadius, pointBackgroundColor: projColor, pointBorderColor: T.bg, pointBorderWidth: 2
});
datasets.push({
label: 'projection', data: toUnit(projSeries), borderColor: projColor, borderWidth: scaleVal(2), borderDash: [3, 3],
fill: false, spanGaps: true, pointRadius: projRadius, pointBackgroundColor: projColor, pointBorderColor: T.bg, pointBorderWidth: 2
});
datasets.push({ label: 'future', data: futureDim, borderWidth: 0, pointRadius: 0, fill: 'origin', backgroundColor: rgba(T.header, 0.10), borderColor: 'rgba(0,0,0,0)', stepped: true });
// Price overlay on a hidden right axis (Overlay mode only)
const haveRange = dayOpen !== null && dayHigh !== null && dayLow !== null && dayHigh > dayLow;
const pxOverlayOn = priceMode === 'Overlay' && haveRange;
const pxLoAll = haveRange ? Math.min(dayLow, refPx === null ? dayLow : refPx) : null;
const pxHiAll = haveRange ? Math.max(dayHigh, refPx === null ? dayHigh : refPx) : null;
const pxPad = haveRange ? (pxHiAll - pxLoAll) * 0.08 : 0;
// Dots: one per real price point, colored by that bucket's close vs the
// previous bucket's close. The last point is larger (the "now" dot).
const pxRadius = labels.map(() => 0);
const pxDotCol = labels.map(() => pxColor);
let pxLastIdx = -1, pxPrev = null;
for (let i = 0; i < pxSeries.length; i++) {
const v = pxSeries[i];
if (v === null) continue;
pxLastIdx = i;
if (showPxDots) {
pxRadius[i] = scaleVal(3.5);
pxDotCol[i] = pxPrev === null ? T.header : v > pxPrev ? T.up : v < pxPrev ? T.dn : T.header;
}
pxPrev = v;
}
if (pxLastIdx >= 0) { pxRadius[pxLastIdx] = scaleVal(3.5); pxDotCol[pxLastIdx] = pxColor; }
if (pxOverlayOn) {
datasets.push({ label: 'open', data: openLine, yAxisID: 'px', borderColor: rgba(T.text, 0.45), borderWidth: 1, borderDash: [2, 3], fill: false, pointRadius: 0 });
datasets.push({ label: 'price', data: pxSeries, yAxisID: 'px', borderColor: pxColor, borderWidth: scaleVal(2.5), fill: false, spanGaps: false, tension: 0.15,
pointRadius: pxRadius, pointBackgroundColor: pxDotCol, pointBorderColor: T.bg, pointBorderWidth: 1.5 });
// Halo AFTER the line: later datasets draw underneath earlier ones.
datasets.push({ label: 'pxhalo', data: pxSeries, yAxisID: 'px', borderColor: rgba(T.bg, 0.9), borderWidth: scaleVal(5), fill: false, spanGaps: false, pointRadius: 0, tension: 0.15 });
}
const curveCell = {
background: T.bg, padding: pad(2, 4),
chart: {
width: chartW + 'px', height: chartH + 'px', type: 'line',
options: {
responsive: true, maintainAspectRatio: false, animation: false,
plugins: { legend: { display: false }, title: { display: false }, tooltip: { enabled: false } },
layout: { padding: { top: 8, right: 10, bottom: 0, left: 6 } },
scales: {
x: { ticks: { color: T.header, font: { size: Math.max(8, baseFont - 3) }, maxRotation: 0, autoSkip: false, padding: 2 },
grid: { color: gridColors, drawTicks: false }, border: { display: false } },
y: { min: 0, max: yMax, display: false },
px: { position: 'right', display: false, min: haveRange ? pxLoAll - pxPad : undefined, max: haveRange ? pxHiAll + pxPad : undefined }
},
elements: { line: { tension: 0.25 } }
},
data: { labels: labels, datasets: datasets }
}
};
// ─── Bucket bars chart ───────────────────────────────────────────────────────
const barsCell = {
background: T.bg, padding: pad(0, 4),
chart: {
width: chartW + 'px', height: barsH + 'px', type: 'bar',
options: {
responsive: true, maintainAspectRatio: false, animation: false,
plugins: { legend: { display: false }, title: { display: false }, tooltip: { enabled: false } },
layout: { padding: { top: 2, right: 10, bottom: 0, left: 6 } },
scales: {
x: { ticks: { display: false }, grid: { display: false }, border: { display: false } },
y: { min: 0, max: 300, display: false }
}
},
data: {
labels: bucketLbl,
datasets: [
{ type: 'bar', label: 'rvol', data: bucketPct.map(v => v === null ? 0 : v), backgroundColor: bucketCol, borderWidth: 0, barPercentage: 0.9, categoryPercentage: 0.95 },
{ type: 'line', label: 'norm', data: bucketLbl.map(() => 100), borderColor: rgba(T.text, 0.55), borderWidth: 1, borderDash: [3, 3], pointRadius: 0, fill: false }
]
}
}
};
// ─── Price row: range gauge + read-out ───────────────────────────────────────
// Gauge = three floating horizontal bars on one category, drawn ungrouped so
// they overlap: grey LOD→min(open,cur), colored min→max(open,cur) (the move
// from the open), grey max→HOD. Thin white tick at the open, bright tick at
// current. Floating [start,end] bars are Chart.js 3; `grouped: false` keeps
// them from sitting side by side.
let gaugeCell = null, pxLine1 = 'price —', pxLine2 = '';
if (haveRange) {
const lo = dayLow, hi = dayHigh, rng = hi - lo, eps = rng * 0.012;
const a = Math.min(dayOpen, curPx), b = Math.max(dayOpen, curPx);
const segCol = pxMove !== null && pxMove >= 0 ? T.up : T.dn;
const fb = (s0, s1, col) => ({ type: 'bar', data: [[s0, s1]], backgroundColor: col, borderWidth: 0, grouped: false, barPercentage: 1, categoryPercentage: 0.9 });
gaugeCell = {
background: T.bg, padding: pad(0, 4),
chart: {
width: chartW + 'px', height: scaleVal(25) + 'px', type: 'bar',
options: {
indexAxis: 'y', responsive: true, maintainAspectRatio: false, animation: false,
plugins: { legend: { display: false }, title: { display: false }, tooltip: { enabled: false } },
layout: { padding: { top: 0, right: 10, bottom: 0, left: 6 } },
scales: {
x: { min: lo - rng * 0.02, max: hi + rng * 0.02, display: false },
y: { display: false }
}
},
data: { labels: ['today'], datasets: [
fb(lo, hi, rgba(T.header, 0.22)),
fb(a, b, rgba(segCol, 0.85)),
fb(dayOpen - eps, dayOpen + eps, rgba(T.text, 0.9)),
fb(curPx - eps, curPx + eps, T.info)
] }
}
};
pxLine1 = `${pxMove >= 0 ? '+' : '−'}${Math.abs(pxMove).toFixed(1)}% ${refLabel}`;
const shareTxt = upShare === null ? '' : (upShare >= 50 ? `${Math.round(upShare)}% up vol` : `${Math.round(dnShare)}% dn vol`);
const fmtPx = (v) => v >= 1000 ? v.toFixed(0) : v >= 100 ? v.toFixed(1) : v.toFixed(2);
pxLine2 = [shareTxt, `L ${fmtPx(lo)} · H ${fmtPx(hi)}`].filter(x => x).join(' · ');
}
// Sparkline cell (Sparkline mode): price on the same x-axis as the curve.
let sparkCell = null;
if (priceMode === 'Sparkline' && haveRange) {
const pxPad2 = (pxHiAll - pxLoAll) * 0.08;
sparkCell = {
background: T.bg, padding: pad(0, 4),
chart: {
width: chartW + 'px', height: scaleVal(60) + 'px', type: 'line',
options: {
responsive: true, maintainAspectRatio: false, animation: false,
plugins: { legend: { display: false }, title: { display: false }, tooltip: { enabled: false } },
layout: { padding: { top: 4, right: 10, bottom: 0, left: 6 } },
scales: {
x: { ticks: { display: false }, grid: { color: gridColors, drawTicks: false }, border: { display: false } },
y: { display: false, min: pxLoAll - pxPad2, max: pxHiAll + pxPad2 }
},
elements: { line: { tension: 0.15 } }
},
data: { labels: labels, datasets: [
{ label: 'open', data: openLine, borderColor: rgba(T.text, 0.45), borderWidth: 1, borderDash: [2, 3], fill: false, pointRadius: 0 },
{ label: 'price', data: pxSeries, borderColor: pxColor, borderWidth: scaleVal(2), fill: { target: 0, above: rgba(T.up, 0.25), below: rgba(T.dn, 0.25) }, spanGaps: false, pointRadius: 0 }
] }
}
};
}
// ─── Hero cells ──────────────────────────────────────────────────────────────
const heroPct = projPctOfAvg === null ? '—' : `${projPctOfAvg}%`;
const heroBg = projSettled ? tierColor(projPctOfAvg) : T.header;
const heroFg = onTier(heroBg);
const subProj = (projClose === null ? 'proj —' : `proj ${fmtVol(projClose)}`) + ` · of ${cnt}d avg`;
const subPace = volPace === null ? 'pace —' : `pace ${fmtSigned(volPace)} · ${fmtPct(pacePct)}`;
const subVol = todayDailyVol === null ? 'vol —' : `vol ${fmtVol(todayDailyVol)}${shapeFrac === null ? '' : ` · ${Math.round(shapeFrac * 100)}% elapsed`}`;
const heroRows = [
{ text: heroPct, color: heroFg, background: heroBg, fontWeight: 'bold', fontSize: heroFont, textAlign: 'center', padding: pad(6, 12) },
cell(subProj, { color: T.text, fs: Math.max(9, baseFont - 1) }),
cell(subPace, { color: paceColor, bold: true, fs: baseFont + 1 }),
cell(subVol, { color: T.text, fs: Math.max(9, baseFont - 1) })
];
// ─── Rows ────────────────────────────────────────────────────────────────────
const rows = [];
// Header band
rows.push({ cells: [
{ text: `⌖ ${current.ticker}`, color: T.title, background: T.accent, fontWeight: 'bold', fontSize: baseFont + 2, padding: pad(6, 12) },
{ text: 'PACE CURVE', color: rgba('#ffffff', 0.85), background: T.accent, fontWeight: 'bold', fontSize: Math.max(9, baseFont - 1), textAlign: 'right', padding: pad(6, 12) }
]});
// Hero + curve (side by side via rowspan)
rows.push({ cells: [heroRows[0], Object.assign({ rowspan: heroRows.length }, curveCell)] });
for (let i = 1; i < heroRows.length; i++) rows.push({ cells: [heroRows[i]] });
// Bucket bars
if (showBars) {
rows.push({ cells: [cell(barsRead, { color: T.text, bold: true, fs: Math.max(9, baseFont - 1), padding: pad(0, 10) }), Object.assign({ rowspan: 2 }, barsCell)] });
rows.push({ cells: [cell(barsRead2, { color: T.header, fs: Math.max(9, baseFont - 2), padding: pad(0, 10) })] });
}
// Price row: sparkline (Sparkline mode) or gauge (Overlay / Gauge modes)
const priceRight = priceMode === 'Sparkline' ? sparkCell : gaugeCell;
if (showPrice && priceRight) {
rows.push({ cells: [cell(pxLine1, { color: pxColor, bold: true, fs: baseFont, padding: pad(0, 10) }), Object.assign({ rowspan: 2 }, priceRight)] });
rows.push({ cells: [cell(pxLine2, { color: T.info, bold: true, fs: Math.max(9, baseFont - 1), padding: pad(0, 10) })] });
}
// State banner
if (showBanner) {
rows.push({ cells: [{
colspan: 2, text: stateText, color: onTier(stateColor), background: stateColor,
fontWeight: 'bold', fontSize: baseFont + 1, textAlign: 'center', padding: pad(6, 12)
}]});
}
// ─── Footer ──────────────────────────────────────────────────────────────────
if (showFooter) {
rows.push({ cells: [cell(moment(Date.now()).format('M/D/YY h:mm:ss A'), { colspan: 2, color: T.header, fs: Math.max(9, baseFont - 2), padding: pad(3, 10) })] });
}
// ─── Render (unconditional) ──────────────────────────────────────────────────
paint_overlay('Pace Curve Position', { position: 'top_right', offset_x: 0, offset_y: 0, order: 'above_all' }, {
fontSize: baseFont,
background: T.bg,
border: `2px solid ${T.accent}`,
rows: showPanel ? rows : []
});