Spread Map puts the bid/ask spread of every strike on a grid — calls on the left, strikes down the middle, puts on the right — so you can see in one glance whether a contract is cheap to get into or whether the spread will eat the trade before it starts.
Every options tool shows you where the activity is. None of them tells you what it costs to act on it.
Reading the colors
Five bands, anchored to two thresholds you set:
| Deep green | at or inside your tight threshold — take the fill |
| Green | still cheap |
| Gold | starting to cost you |
| Orange | expensive — use a limit, don't pay the offer |
| Red | past wide — work the order toward mid, or size down |
Red isn't "don't trade it." It's "don't trade it carelessly." A wide market still fills if you work a limit and give it time. The point is knowing before you click, not after.
The middle three bands divide evenly between tight and wide, so moving either threshold stretches the whole ramp rather than just shifting the ends. Defaults are 2% and 15%.
Reading the numbers
Cells show the spread in cents by default, because that's the number you act on without doing arithmetic. Switch to percent to compare across strikes — a nickel wide is nothing on a $12 contract and punishing on a $0.15 one. The color is always percent-banded, so even in cents mode the shading tells you the real cost.
× means no two-sided quote.
· means the contract is under your minimum price, where the reading would be noise.
Per-column footers give the average spread and a count of genuinely tight strikes, so you can see which expiration is actually worth trading.
Session-aware
Quotes are live, and outside market hours the book thins and every spread looks terrible. The header shows LIVE, PRE, AFTER or CLOSED with a warning strip when the numbers aren't current. Holidays are caught by checking whether the market actually traded today rather than trusting the clock.
Scanner
Registers Tight ATM Spread — fires when the at-the-money contract in the front expiration is inside your tight threshold. Sweep a watchlist for names that are cheap to trade right now.
By default the signal only fires during live market hours, since a prior close isn't a live book. Turn off Require Live Session to scan outside RTH. The footer marks the ATM reading ✓ gated when the spread qualifies but the session doesn't, so you always know why a name did or didn't come back.
Settings
Calls, puts or both. Cents or percent. Expirations and strikes shown. Tight and wide thresholds. Minimum price floor. Session gate on the signal. Density and UI scale.
#TSBuild26
// ─────────────────────────────────────────────────────────────────────────────
// 💧 Spread Map v1.0a — Options Liquidity Grid
//
// Strike × expiration heatmap of bid/ask spread width. Answers "where can I
// actually get filled" rather than "where is the activity".
//
// v1.0a — SESSION GATE MADE OPTIONAL.
// The scanner signal was hard-gated on a live session, so it could never
// match outside market hours — a weekend scan returned nothing on every
// ticker regardless of how tight the spreads were. The gate was defensible
// (stale Friday quotes are not a live book, so "cheap to trade right now"
// would be a false claim) but it made the signal impossible to test and
// broke scheduled pre-market scans.
//
// Now an input, defaulting ON. Turn it off to test, to scan outside RTH, or
// to treat the last close as a usable proxy. The footer says when the gate
// is the reason a name did not qualify, so the behaviour is never silent.
//
// v1.0 — SUBMISSION VERSION. 2026 TrendSpider Hackathon, Most Unique Options.
//
// Border is DFI gold (#D4AC0D) to match the flagship, so the suite reads as
// one set rather than unrelated tools.
//
// What this does that the other options tools do not: every one of them
// shows you where the activity, the gamma or the open interest IS. None of
// them tells you what it COSTS to act on it. A strike can be the most
// interesting thing on the board and still cost you more to get into than
// the idea is worth.
//
// v0.7 — themes tried and dropped.
// A five-theme chrome system (v0.6) was built and rejected on sight. The
// reason is structural, not cosmetic: the band cells cover most of the
// panel and the bands are deliberately NOT themed, so the only surfaces
// left to vary were the header strip, the border and the footer. Five
// variants came out nearly identical, and the Light theme was worse than
// that — a pale frame around a still-dark grid.
//
// Letting each theme carry its own ramp would have fixed the sameness, but
// the ramp is the reading. Trading legibility for variety is a bad deal in
// a tool whose entire job is to be read at a glance.
//
// One look, tuned. Do not revive unless the band question is settled first.
//
// v0.5 changes (production):
// - BAND INVERSION FIXED. Tight % and Wide % were independent inputs with
// no relationship enforced. Setting tight above wide collapsed the three
// middle bands: with tight=20 / wide=15, everything up to 20% read tight
// and 20.5% jumped straight to the top band. Wide is now floored just
// above tight, so the ramp always has somewhere to go.
// - CENTS MODE UNIT FIX. A 25¢ spread showed "25¢" and a $1.25 spread
// showed "1.25" — side by side in a column, that second value reads as
// 1.25¢, which is off by 100x. Dollar values now carry a $ prefix.
// - Placeholder series hidden. SpreadRef was appearing in the chart legend
// as a togglable yellow line.
// - STALE QUOTE GUARD. Holidays and half-days read LIVE from a pure clock
// check. Comparing the last bar's date against today catches any session
// the market did not trade, without hardcoding a holiday calendar.
// - Default strikes each side 3 → 4.
// - REMOVED two inputs. "Show Values" turned off the numbers while leaving
// the colour — but colour is percent-banded and the values are cents, so
// they are two halves of the read, not a duplicate. Nobody unchecks it
// twice. "Show Panel" rendered an empty overlay; an indicator is hidden
// from the indicator list, not from inside itself, and it carried a dead
// empty-rows branch purely to satisfy the toggle.
//
// v0.4 changes (submission prep):
// - SCANNER SIGNAL. The tool was display-only, which wastes TrendSpider's
// main strength. "Tight ATM Spread" fires when the at-the-money contract
// in the front expiration is at or inside the tight threshold, so a
// watchlist can be scanned for names that are cheap to trade right now.
// - Avg footer now respects the MEASURE setting. It always printed a
// percentage average even in Cents mode, so "6.0" sat under a column of
// "13¢ 8¢ 5¢" with no indication the units differed.
// - Strike fetch count now derives from Strikes Each Side. It was pinned at
// 30 while the input allowed 20 per side, so anything above 15 ran out of
// fetched strikes before it ran out of rows.
// - Percent mode appends % — it printed bare numbers while Cents mode
// appended ¢, which left the unit ambiguous.
// - Dropped the unused rowBg parameter from dataCell.
//
// v0.3 changes:
// - MARKET SESSION FLAG. Quotes are live, so the book thins outside RTH and
// every spread widens. Without a flag, anyone opening this on a weekend
// sees a wall of red and concludes the tool is broken rather than that
// the market is shut. LIVE / PRE / AFTER / CLOSED now sits in the header,
// and a warning strip appears whenever the session is not LIVE.
// - Default measure is now CENTS. The tool earns its keep as an instant
// eyeball check on whether a spread is too wide to jump into, and cents
// is what a trader reads without doing arithmetic. Percent remains
// available and is still the analytically correct comparison unit.
//
// v0.2 changes:
// - Adopted the Options Chain Grid display model: Both / Calls Only /
// Puts Only, with calls left, strike spine centered, puts right.
// - Expiration order is MIRRORED across the spine. Call side runs
// furthest→nearest left to right; put side runs nearest→furthest. D0 ends
// up adjacent to the strike column on both sides, which is where the eye
// goes first.
// - Chain Grid theme palette and spacer/spine conventions for suite
// consistency.
// - Per-side footer: average spread and tight-strike count.
//
// Design notes:
// - Coloring is ABSOLUTE, not percentile rank. A 2% spread is 2% on any
// ticker and any expiration, so bands mean the same thing everywhere and
// across symbols. No adaptive threshold, no column muting — those exist in
// Vol/OI Heatmap only because raw ratios aren't comparable between names.
// - Relative spread (a-b)/mid is the default because it's what actually
// costs you. A $0.05/$0.10 quote is a 67% spread and genuinely
// punishing even though it's "only 5 cents wide" — you are giving up a
// third of the position on the round trip unless you work the order.
// - No bid means no exit; no ask means no entry. Either way the cell is
// marked × rather than colored.
// - QUOTES ARE LIVE. Outside RTH the book thins and spreads blow out, so
// this reads garbage after hours. Mid-morning is a fairer look than 9:31.
//
// Deferred:
// - Size at the inside quote (not in the current field list)
// - Best-tradeable-strike marker per side
// - Cross-reference against Vol/OI to flag "busy but expensive to enter"
// ─────────────────────────────────────────────────────────────────────────────
describe_indicator('Spread Map', { shortName: '💧 Spread Map v1.0a' });
var moment = library('moment-timezone');
// Hidden — this exists only so the platform has a series to register. Without
// `hidden` it shows in the chart legend as a togglable yellow line.
paint(close.map(function() { return NaN; }), {
name: 'SpreadRef', style: 'line', color: '#00FF51', hidden: true
});
// ─── Inputs ──────────────────────────────────────────────────────────────────
var displayMode = input.select('Display', 'Both', ['Both', 'Calls Only', 'Puts Only']);
var modeIn = input.select('Measure', 'Cents', ['Cents', 'Percent']);
var expCountIn = input.number('Expirations', 4, { min: 1, max: 8, step: 1 });
var rowsPerSideIn = input.number('Strikes Each Side', 3, { min: 3, max: 20, step: 1 });
var minPriceIn = input.number('Min Mid Price', 0.05,{ min: 0, step: 0.05 });
var tightPctIn = input.number('Tight % (green)', 2.0, { min: 0.1, step: 0.5 });
var widePctIn = input.number('Wide % (red)', 15.0,{ min: 1, step: 1 });
var densityIn = input.select('Density', 'Tight', ['Tight', 'Compact', 'Roomy']);
var requireLiveIn = input.boolean('Signal: Require Live Session', true);
var uiScale = input.number('UI Scale %', 100, { min: 50, max: 200, step: 5 });
// Derived, not fixed. At 30 the fetch ran out of strikes before the display
// did whenever Strikes Each Side went above 15. The +6 is headroom for the
// union across expirations, where sparser ladders leave gaps.
var STRIKE_COUNT = Math.max(30, rowsPerSideIn * 2 + 6);
var FIELDS = ['b', 'a', 'oi'];
var EXP_MODE = 'all';
var showCalls = displayMode !== 'Puts Only';
var showPuts = displayMode !== 'Calls Only';
// ─── Theme (Chain Grid palette) ──────────────────────────────────────────────
var TH = {
bg: '#0d1117',
panelBg: '#08244f',
rowAlt1: '#0c1824',
rowAlt2: '#101e2e',
border: '#D4AC0D', // DFI gold — suite consistency
text: '#d1d5db',
muted: '#9ca3af',
title: '#FFFFFF',
callBg: '#0a2818',
callHi: '#00ffaa',
putBg: '#2a0f12',
putHi: '#ff5555',
atmBg: '#5C5C5C',
atmText: '#00FFFF',
warn: '#FFD700',
deadBg: '#161b22',
deadFg: '#4a5560'
};
// ─── Helpers ─────────────────────────────────────────────────────────────────
function num(v, fb) { return (v === null || v === undefined || isNaN(v)) ? fb : Number(v); }
function scaleVal(n) { return Math.max(1, Math.round(n * uiScale / 100)); }
function px(n) { return scaleVal(n) + 'px'; }
// Cell padding. Numbers are small because this grid is denser than Chain Grid:
// nCols x 2 sides plus spine, so horizontal padding compounds fast.
var PAD_V = densityIn === 'Tight' ? 1 : (densityIn === 'Roomy' ? 4 : 2);
var PAD_H = densityIn === 'Tight' ? 3 : (densityIn === 'Roomy' ? 7 : 4);
function codeToDte(code) {
var cs = String(code);
if (cs.length !== 6) return 99999;
var ed = moment('20' + cs, 'YYYYMMDD').startOf('day');
var td = moment().startOf('day');
return ed.diff(td, 'days');
}
function expCodeToMD(code) {
var cs = String(code);
if (cs.length !== 6) return '';
var m = parseInt(cs.substring(2, 4), 10);
var d = parseInt(cs.substring(4, 6), 10);
if (!isFinite(m) || !isFinite(d)) return '';
return m + '/' + d;
}
function fmtVal(pct, cents) {
if (pct === null) return '–';
if (modeIn === 'Cents') {
// The $ prefix matters: without it a $1.25 spread printed "1.25" directly
// beside a "25¢" cell, which reads as 1.25 cents — wrong by 100x.
if (cents >= 1) return '$' + cents.toFixed(2);
return (cents * 100).toFixed(0) + 'u00A2';
}
if (pct >= 100) return Math.round(pct) + '%';
if (pct >= 10) return pct.toFixed(0) + '%';
return pct.toFixed(1) + '%';
}
function fmtSk(v) {
var f = Math.abs(v - Math.round(v));
return f < 0.001 ? Number(v).toFixed(0) : Number(v).toFixed(2);
}
// ─── Absolute spread bands ───────────────────────────────────────────────────
// Anchored to the two user inputs so the ramp stretches with them rather than
// snapping to hardcoded cutoffs.
function bandOf(pct) {
var t = tightPctIn;
// Wide must sit above tight or the three middle bands collapse and the ramp
// becomes a cliff — tight=20 / wide=15 made everything under 20% read tight
// and 20.5% read top-band. Both are free inputs, so this is reachable.
var w = Math.max(widePctIn, tightPctIn + 0.5);
if (pct <= t) return 0;
if (pct <= t + (w - t) * 0.25) return 1;
if (pct <= t + (w - t) * 0.50) return 2;
if (pct <= w) return 3;
return 4;
}
function bandBg(b) {
if (b === 0) return '#1b5e3a';
if (b === 1) return '#2f6d3f';
if (b === 2) return '#8a7415';
if (b === 3) return '#a85520';
return '#8e2020';
}
function bandFg(b) {
return (b === 0 || b >= 3) ? '#ffffff' : '#d8e2c8';
}
// ─── Market session ──────────────────────────────────────────────────────────
// Clock-based, plus a data-based staleness check.
//
// The clock alone cannot see holidays — Thanksgiving at 11am reads LIVE and
// the panel shows last Wednesday's quotes as if they were current. Rather
// than hardcode a holiday calendar that goes out of date, compare the last
// BAR's date against today: if the chart has no bar for today, the market did
// not trade, whatever the clock says.
//
// Still not caught: half-day closes (1pm on Christmas Eve and similar). The
// chart does have a bar for those days, so the data cannot distinguish them.
function lastBarIsToday() {
if (!time || time.length === 0) return false;
var lastT = time[time.length - 1];
if (!lastT) return false;
var barDay = moment(lastT).tz('America/New_York').format('YYYY-MM-DD');
var today = moment().tz('America/New_York').format('YYYY-MM-DD');
return barDay === today;
}
function marketSession() {
var nyc = moment().tz('America/New_York');
var dow = nyc.day(); // 0 Sun .. 6 Sat
var mins = nyc.hour() * 60 + nyc.minute();
if (dow === 0 || dow === 6) {
return { tag: 'CLOSED', live: false, color: '#ff5555',
note: 'weekend u2014 quotes are last Fridayu2019s close' };
}
if (mins >= 570 && mins < 960) { // 9:30 - 16:00
// Clock says the session is open — confirm the market actually traded
// today before trusting the quotes.
if (!lastBarIsToday()) {
return { tag: 'HOLIDAY', live: false, color: '#ff5555',
note: 'no bar for today u2014 market closed, quotes are the last close' };
}
return { tag: 'LIVE', live: true, color: '#00ffaa', note: '' };
}
if (mins >= 240 && mins < 570) { // 4:00 - 9:30
return { tag: 'PRE', live: false, color: '#FFD700',
note: 'pre-market u2014 thin book, spreads read wide' };
}
if (mins >= 960 && mins < 1200) { // 16:00 - 20:00
return { tag: 'AFTER', live: false, color: '#FFD700',
note: 'after hours u2014 thin book, spreads read wide' };
}
return { tag: 'CLOSED', live: false, color: '#ff5555',
note: 'outside session u2014 quotes are the last close' };
}
var session = marketSession();
// ─── Fetch ───────────────────────────────────────────────────────────────────
var chartTicker = current.ticker || current.symbol || '';
var allData = null;
var fetchError = '';
try {
allData = await request.options_data_for_all_expirations(chartTicker, STRIKE_COUNT, FIELDS, EXP_MODE);
} catch (e) {
fetchError = 'primary: ' + (e && e.message ? e.message : 'unknown');
}
if (allData && allData.error) fetchError = 'api: ' + String(allData.error);
if (!chartTicker) fetchError = 'no ticker resolved from current.*';
// ─── Spot ────────────────────────────────────────────────────────────────────
var spot = 0;
if (allData && allData.underlyingSymbolQuote) {
var q = allData.underlyingSymbolQuote;
if (num(q.lastPrice, 0) > 0) spot = Number(q.lastPrice);
else if (num(q.last, 0) > 0) spot = Number(q.last);
else if (num(q.close, 0) > 0) spot = Number(q.close);
}
if (spot <= 0 && close && close.length > 0) spot = close[close.length - 1];
// ─── Expiration columns ──────────────────────────────────────────────────────
var selectedExps = [];
if (allData && allData.resultByExpiration) {
var expCodes = Object.keys(allData.resultByExpiration);
var pairs = [];
for (var i = 0; i < expCodes.length; i++) {
var d = codeToDte(expCodes[i]);
if (d >= 0 && d < 99999) pairs.push({ code: expCodes[i], dte: d });
}
pairs.sort(function(a, b) { return a.dte - b.dte; });
selectedExps = pairs.slice(0, expCountIn);
}
// ─── Strike ladder around spot ───────────────────────────────────────────────
var masterStrikes = [];
if (selectedExps.length > 0 && spot > 0) {
var union = {};
for (var e = 0; e < selectedExps.length; e++) {
var ed = allData.resultByExpiration[selectedExps[e].code];
if (!ed) continue;
var sks = Object.keys(ed);
for (var s = 0; s < sks.length; s++) {
var k = parseFloat(sks[s]);
if (isFinite(k)) union[k] = true;
}
}
var allStrikes = Object.keys(union).map(parseFloat).filter(function(v) { return isFinite(v); });
allStrikes.sort(function(a, b) { return a - b; });
var aboveArr = [];
var belowArr = [];
for (var a2 = 0; a2 < allStrikes.length; a2++) {
if (allStrikes[a2] >= spot) aboveArr.push(allStrikes[a2]);
else belowArr.push(allStrikes[a2]);
}
var pick = belowArr.slice(Math.max(0, belowArr.length - rowsPerSideIn))
.concat(aboveArr.slice(0, rowsPerSideIn));
masterStrikes = pick.sort(function(a, b) { return b - a; });
}
// ─── Build one side's columns ────────────────────────────────────────────────
function buildSide(sideKey) {
var cols = [];
for (var ci = 0; ci < selectedExps.length; ci++) {
var code = selectedExps[ci].code;
var expData = allData.resultByExpiration[code];
var col = {
code: code, dte: selectedExps[ci].dte,
byStrike: {}, sumPct: 0, sumCents: 0, liveCount: 0, tightCount: 0,
colPct: null, colCents: null
};
for (var r = 0; r < masterStrikes.length; r++) {
var strike = masterStrikes[r];
var bkt = expData ? (expData[strike] || expData[String(strike)]) : null;
var leg = (bkt && bkt[sideKey]) ? bkt[sideKey] : null;
var bid = leg ? num(leg.b, 0) : 0;
var ask = leg ? num(leg.a, 0) : 0;
var mid = (bid + ask) / 2;
var noQuote = (bid <= 0) || (ask <= 0) || (ask < bid);
var tooCheap = (mid < minPriceIn);
var dead = noQuote || tooCheap;
var cents = dead ? null : (ask - bid);
var pct = dead ? null : ((ask - bid) / mid * 100);
if (pct !== null) {
col.sumPct += pct;
col.sumCents += cents;
col.liveCount++;
if (bandOf(pct) === 0) col.tightCount++;
}
col.byStrike[strike] = { pct: pct, cents: cents, dead: dead, noQuote: noQuote };
}
if (col.liveCount > 0) {
col.colPct = col.sumPct / col.liveCount;
col.colCents = col.sumCents / col.liveCount;
}
cols.push(col);
}
return cols;
}
var callCols = [];
var putCols = [];
if (allData && allData.resultByExpiration && masterStrikes.length > 0) {
if (showCalls) callCols = buildSide('C');
if (showPuts) putCols = buildSide('P');
}
// Mirror: calls run furthest→nearest so D0 lands against the spine.
var callColsOrdered = callCols.slice().reverse();
var putColsOrdered = putCols.slice();
// ─── ATM row ─────────────────────────────────────────────────────────────────
var nearestIdx = -1;
if (masterStrikes.length > 0 && spot > 0) {
var bestD = 1e12;
for (var n = 0; n < masterStrikes.length; n++) {
var dd = Math.abs(masterStrikes[n] - spot);
if (dd < bestD) { bestD = dd; nearestIdx = n; }
}
}
// ─── Scanner signal ──────────────────────────────────────────────────────────
// The point of putting this in a scanner: sweep a watchlist for names whose
// at-the-money contract is cheap to get into RIGHT NOW. Keyed to the FRONT
// expiration and the ATM strike, because that is the contract most people
// actually trade, and to the tight threshold the user already set rather than
// a second hidden number.
//
// Guarded on session. Outside RTH the book thins and spreads widen, so a
// signal fired at 3am would be an artifact of the market being shut.
var atmSpreadPct = null;
if (masterStrikes.length > 0 && nearestIdx >= 0) {
var atmStrike = masterStrikes[nearestIdx];
var frontCall = (callCols.length > 0) ? callCols[0] : null;
var frontPut = (putCols.length > 0) ? putCols[0] : null;
var cCell = frontCall ? frontCall.byStrike[atmStrike] : null;
var pCell = frontPut ? frontPut.byStrike[atmStrike] : null;
var cPct = (cCell && !cCell.dead) ? cCell.pct : null;
var pPct = (pCell && !pCell.dead) ? pCell.pct : null;
// Whichever side is tighter — if either leg is cheap to trade, the name
// qualifies. Both sides are shown by default, so taking the min matches
// what the user sees.
if (cPct !== null && pPct !== null) atmSpreadPct = Math.min(cPct, pPct);
else if (cPct !== null) atmSpreadPct = cPct;
else if (pPct !== null) atmSpreadPct = pPct;
}
// Threshold test and session test kept separate so the footer can say which
// one failed. Outside RTH the quotes are a prior close — defensible as a
// proxy, but not a live book, which is why the gate defaults on.
var atmIsTight = (atmSpreadPct !== null) && (atmSpreadPct <= tightPctIn);
var sessionOk = session.live || !requireLiveIn;
var tightAtm = atmIsTight && sessionOk;
var tightAtmSignal = close.map(function() { return 0; });
if (tightAtm) tightAtmSignal[tightAtmSignal.length - 1] = 1;
register_signal(tightAtmSignal, 'Tight ATM Spread');
// ─── Cell builders ───────────────────────────────────────────────────────────
function mkCell(text, opts) {
opts = opts || {};
return {
text: String(text),
color: opts.color || TH.text,
background: opts.bg || 'transparent',
fontWeight: opts.bold ? 'bold' : 'normal',
fontSize: opts.fontSize || px(12),
paddingTop: px(PAD_V), paddingBottom: px(PAD_V),
paddingLeft: px(PAD_H), paddingRight: px(PAD_H),
textAlign: opts.align || 'right',
colspan: opts.colspan || 1
};
}
function hdrCell(text, opts) {
opts = opts || {};
return mkCell(text, {
color: opts.color || TH.muted,
bg: opts.bg || TH.panelBg,
bold: true,
align: opts.align || 'center',
colspan: opts.colspan,
fontSize: opts.fontSize
});
}
function spacer(bg) {
return {
text: '',
background: bg || 'transparent',
paddingLeft: px(1), paddingRight: px(1)
};
}
function dataCell(c) {
if (!c || c.dead) {
return mkCell(c && c.noQuote ? 'u00D7' : 'u00B7', {
color: TH.deadFg, bg: TH.deadBg, fontSize: px(11)
});
}
var b = bandOf(c.pct);
return mkCell(fmtVal(c.pct, c.cents), {
color: bandFg(b), bg: bandBg(b), bold: (b === 0 || b === 4)
});
}
// The Avg footer has to speak the same units as the cells above it. v0.3
// always printed a percentage, so "6.0" sat under a column reading "13¢ 8¢ 5¢".
function fmtColAvg(col) {
if (!col || col.colPct === null) return 'u2013';
if (modeIn === 'Cents') {
return (col.colCents >= 1)
? '$' + col.colCents.toFixed(2)
: Math.round(col.colCents * 100) + 'u00A2';
}
return col.colPct.toFixed(1) + '%';
}
// ─── Layout math ─────────────────────────────────────────────────────────────
var nCols = selectedExps.length;
var totalCols = (showCalls ? nCols + 1 : 0) + 1 + (showPuts ? nCols + 1 : 0);
// ─── Assemble ────────────────────────────────────────────────────────────────
var overlayRows = [];
if (fetchError) {
overlayRows.push({ cells: [ mkCell('Spread Map — ' + fetchError, {
color: '#e08080', bg: TH.panelBg, bold: true, align: 'left'
}) ] });
} else if (masterStrikes.length === 0 || nCols === 0) {
overlayRows.push({ cells: [ mkCell('Spread Map — no option data for ' + chartTicker, {
color: '#e08080', bg: TH.panelBg, bold: true, align: 'left'
}) ] });
} else {
var modeTag = displayMode === 'Calls Only' ? ' · Calls'
: displayMode === 'Puts Only' ? ' · Puts'
: '';
var titleText = 'uD83DuDCA7 ' + chartTicker + ' Spread Map' + modeTag +
' · Spot: $' + spot.toFixed(2);
// Title carries the session badge in its own cell so the colour can differ
// from the title text — a red CLOSED has to be readable at a glance.
overlayRows.push({ cells: [
{
text: titleText,
color: TH.title, background: TH.panelBg, fontWeight: 'bold',
fontSize: px(14), textAlign: 'center', colspan: Math.max(1, totalCols - 1),
paddingTop: px(PAD_V + 2), paddingBottom: px(PAD_V + 2),
paddingLeft: px(6), paddingRight: px(6)
},
{
text: (session.live ? 'u25CF ' : 'u25CB ') + session.tag,
color: session.color, background: TH.panelBg, fontWeight: 'bold',
fontSize: px(12), textAlign: 'right', colspan: 1,
paddingTop: px(PAD_V + 2), paddingBottom: px(PAD_V + 2),
paddingLeft: px(4), paddingRight: px(8)
}
]});
// Warning strip — only when the session is not live.
if (!session.live) {
overlayRows.push({ cells: [{
text: 'u26A0 ' + session.note,
color: session.color, background: '#1a0f0f', fontWeight: 'bold',
fontSize: px(11), textAlign: 'center', colspan: totalCols,
paddingTop: px(PAD_V + 1), paddingBottom: px(PAD_V + 1)
}]});
}
// Section labels
var sectionCells = [];
if (showCalls) {
sectionCells.push(hdrCell('— CALLS —', {
bg: TH.callBg, color: TH.callHi, colspan: nCols, fontSize: px(13)
}));
sectionCells.push(spacer(TH.bg));
}
sectionCells.push(hdrCell(' ', { bg: TH.bg }));
if (showPuts) {
sectionCells.push(spacer(TH.bg));
sectionCells.push(hdrCell('— PUTS —', {
bg: TH.putBg, color: TH.putHi, colspan: nCols, fontSize: px(13)
}));
}
overlayRows.push({ cells: sectionCells });
// Column headers
var headerCells = [];
if (showCalls) {
for (var ch = 0; ch < callColsOrdered.length; ch++) {
headerCells.push(hdrCell('D' + callColsOrdered[ch].dte + ' ' + expCodeToMD(callColsOrdered[ch].code), {
fontSize: px(11)
}));
}
headerCells.push(spacer(TH.bg));
}
headerCells.push(hdrCell('Strike', { color: TH.warn }));
if (showPuts) {
headerCells.push(spacer(TH.bg));
for (var ph = 0; ph < putColsOrdered.length; ph++) {
headerCells.push(hdrCell('D' + putColsOrdered[ph].dte + ' ' + expCodeToMD(putColsOrdered[ph].code), {
fontSize: px(11)
}));
}
}
overlayRows.push({ cells: headerCells });
// Data rows
for (var ri = 0; ri < masterStrikes.length; ri++) {
var sk = masterStrikes[ri];
var isATM = (ri === nearestIdx);
var altBg = (ri % 2 === 0) ? TH.rowAlt1 : TH.rowAlt2;
var rowCells = [];
if (showCalls) {
for (var cc = 0; cc < callColsOrdered.length; cc++) {
rowCells.push(dataCell(callColsOrdered[cc].byStrike[sk]));
}
rowCells.push(spacer(TH.bg));
}
rowCells.push(mkCell((isATM ? 'u25B6 ' : ' ') + fmtSk(sk), {
bg: isATM ? TH.atmBg : TH.panelBg,
color: isATM ? TH.atmText : TH.title,
bold: true, align: 'center'
}));
if (showPuts) {
rowCells.push(spacer(TH.bg));
for (var pc = 0; pc < putColsOrdered.length; pc++) {
rowCells.push(dataCell(putColsOrdered[pc].byStrike[sk]));
}
}
overlayRows.push({ cells: rowCells });
}
// Footer — average spread per column
var avgCells = [];
if (showCalls) {
for (var af = 0; af < callColsOrdered.length; af++) {
avgCells.push(mkCell(fmtColAvg(callColsOrdered[af]), {
bg: TH.callBg, color: TH.callHi, bold: true, fontSize: px(11)
}));
}
avgCells.push(spacer(TH.bg));
}
avgCells.push(mkCell('Avg', { bg: TH.panelBg, color: TH.warn, bold: true, align: 'center', fontSize: px(11) }));
if (showPuts) {
avgCells.push(spacer(TH.bg));
for (var af2 = 0; af2 < putColsOrdered.length; af2++) {
avgCells.push(mkCell(fmtColAvg(putColsOrdered[af2]), {
bg: TH.putBg, color: TH.putHi, bold: true, fontSize: px(11)
}));
}
}
overlayRows.push({ cells: avgCells });
// Footer — tight-strike count per column
var tightCells = [];
if (showCalls) {
for (var tf = 0; tf < callColsOrdered.length; tf++) {
tightCells.push(mkCell(String(callColsOrdered[tf].tightCount), {
bg: TH.callBg, color: callColsOrdered[tf].tightCount > 0 ? TH.callHi : TH.deadFg,
bold: true, fontSize: px(11)
}));
}
tightCells.push(spacer(TH.bg));
}
tightCells.push(mkCell('Tight', { bg: TH.panelBg, color: TH.warn, bold: true, align: 'center', fontSize: px(11) }));
if (showPuts) {
tightCells.push(spacer(TH.bg));
for (var tf2 = 0; tf2 < putColsOrdered.length; tf2++) {
tightCells.push(mkCell(String(putColsOrdered[tf2].tightCount), {
bg: TH.putBg, color: putColsOrdered[tf2].tightCount > 0 ? TH.putHi : TH.deadFg,
bold: true, fontSize: px(11)
}));
}
}
overlayRows.push({ cells: tightCells });
// Settings strip — measure and band thresholds live here rather than in the
// title so the header stays to ticker and spot.
// The scanner fires on this number, so the panel shows it — otherwise a
// user cannot tell why a name did or did not come back in a scan.
// The scanner fires on this number, so the panel shows it — and says when
// the session gate, not the spread, is what stopped a match.
var atmMark = tightAtm ? ' u2713'
: (atmIsTight ? ' u2713 gated' : '');
var atmTxt = (atmSpreadPct === null)
? 'ATM u2013'
: ('ATM ' + atmSpreadPct.toFixed(1) + '%' + atmMark);
var legendText = (modeIn === 'Cents' ? 'Spread u00A2' : 'Spread %') +
' · tight u2264' + tightPctIn + '%' +
' · wide >' + widePctIn + '%' +
' · ' + atmTxt +
' · u00D7 no quote u00B7 under $' + minPriceIn;
overlayRows.push({ cells: [{
text: legendText,
color: TH.muted, background: TH.panelBg, fontWeight: 'normal',
fontSize: px(11), textAlign: 'center', colspan: totalCols,
paddingTop: px(PAD_V + 1), paddingBottom: px(PAD_V + 1),
paddingLeft: px(6), paddingRight: px(6)
}]});
}
// ─── Always paint overlay ────────────────────────────────────────────────────
paint_overlay(
'SpreadMapV10a',
{ position: 'bottom_left', offset_y: 0, order: 'above_all' },
{
background: TH.bg,
border: '2px solid ' + TH.border,
borderRadius: px(6),
padding: px(3),
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
rows: overlayRows
}
);