Volatility surface
Volatility surface shows what this symbol's options cost as implied volatility (how big a move option prices expect).

Tiles show it per expiry (the day the option ends) at the strike (the option's price level) nearest the price. Under them, a heatmap shows every strike and expiry, its colour stronger where options cost more. A card adds the skew (how much more puts cost than calls): pricier puts mean traders fear a drop. Use it to spot cheap or dear options before you trade, on any chart whose symbol has listed options.
Under the hood: the recipe reads options_chain.cells with venue: "auto" (Data sources, Chain page views). It asks for two book folds, surface in its IV lens and vol_term, the numbers the chart's built-in Options Surface and Term Structure draw. The options kit's BookStamp, SurfaceMatrix and VolTerm read them (Book folds). It feeds two frames to a panel.tiles and a panel.heatmap, with a summary row, a highlighted row and a per-run caption (Cards, frames and panels). It spells each strike as the built-in does, with a TextBuilder (A second builder). It adds a render.hud card in the chart's default look (HUD cards, The default look). It also adds a corner render.label, and a render.legend entry for the term word (Legend). It is also the iv-surface template, the Volatility Surface card under Beyond the time axis in the editor's starter list, and it compiles as written.
The wrun indicator
// Volatility Surface: what this symbol's options cost, as implied volatility (how big a move option prices expect).
// High implied volatility means pricey options and big expected swings. A strike (the option's price level) and an
// expiry (the day the option ends) place each option. Tiles under the candles show, for each expiry, the implied
// volatility at the strike nearest the price. Near dates come first, so read left to right they are the term structure
// (near expiries' prices against far ones). Under them, a heatmap shows every strike and expiry, its colour stronger
// where options cost more. A card names the nearest expiry's implied volatility and its skew (how much more puts cost
// than calls). Pricier puts mean traders fear a drop. It also says whether far dates cost more than near ones. Use it
// to spot cheap or dear options before you trade them.
//
// Technical notes: the chart's own live option chain (OPRA on a US stock or ETF chart, the CME chain of a futures
// root, Deribit on a coin) as implied volatility by strike and expiry, read from the data plane's surface fold, the
// matrix the chart's built-in Options Surface draws in its IV mode: the nearest live expiries as columns, nearest
// first, and the 21 strikes nearest the book's spot inside the moneyness range as rows, the highest at the top, a
// heatmap below the candles with the row nearest the chart's price marked (the strike nearest the live bar's close
// where it reads in the strikes' dollars, not the book's own spot, which sits off the chart's price after hours or
// between chain snapshots) and each expiry's ATM implied volatility in the summary row. A cell is the strike's
// out-of-the-money IV on that expiry, empty where the expiry quotes none. Under it, one tile per expiry with its ATM
// implied volatility and days to expiry: the term structure read left to right. The card at the top left answers one
// question first: what does the nearest expiry's ATM option cost, as implied volatility; then the 25-delta skew of
// that expiry (call IV minus put IV: below 0 while puts carry the premium) and the one-week ATM against the
// three-month ATM (contango while the far point sits above the near one). Those readings are the data plane's term
// structure fold, the per-expiry numbers the chart's built-in Term Structure draws, read beside the surface in the same
// answer: each one is a listed expiry's own (the nearest expiry at least 12 h away, and the listed expiries nearest one
// week and three months away by the fold's days to expiry). Every number is the folds' own, priced once a chain update
// over the whole book (the ATM IV at each expiry's forward); the package only picks and draws them. The folds are read
// on the live bar: history bars draw nothing. A book with no contract, no spot or no row draws an empty surface and
// says so, never the last answer's cells.
section("Surface");
param.int("expiries", 6, { min: 2, max: 6, label: "Expiries", description: "How many expiry dates the surface and the tiles show, nearest first. An expiry is the day the option ends." });
param.number("range_pct", 20, { min: 5, max: 40, label: "Strike range, percent", description: "How far from the price the strikes reach, in percent each way. The surface shows the 21 strikes nearest the price inside it." });
input("close", ohlcv.close); // the chart's bars and price: the folds are read on the last bar, the bold row at its close
input("chain", options_chain.cells, { max_cells: 225, venue: "auto", page_views: ["surface", "vol_term"], lens: 2, window_pct: "@range_pct", columns: "@expiries", rows: 21, description: "This symbol's live options as IV by strike and expiry, with each expiry's at-the-money IV and skew. US listed options on a stock, CME options on a future, Deribit options on a coin." }); // rows of 16 values (the widest word's, vol_term): the one book stamp row (BookStamp), the surface's [16, tag, at, value] rows (SurfaceMatrix) and one term row per live expiry (VolTerm); max_cells counts rows: the stamp, 2 x 6 + 21 + 1 + 6 x 21 surface rows and 64 term rows
market.zone(); // the market's clock: each expiry's trade date, its label's year
market.quote_is_usd(); // 1 when the chart's prices are in US dollars, the strikes' currency on every chain read here
market.option_contract(); // 1 on an option contract's own chart: its close is the contract's premium, not a price
// The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars.
output("atm_near", none, overlay, { format: "%", description: "At-the-money IV of the nearest expiry at least 12 hours away, in percent. Live bar only." });
output("skew_25d", none, overlay, { description: "The nearest expiry's skew in IV points: the 25-delta call's IV minus the 25-delta put's. Below 0, puts cost more than calls." });
output("atm_1w", none, overlay, { description: "At-the-money IV of the expiry nearest one week away, in percent" });
output("atm_3m", none, overlay, { description: "At-the-money IV of the expiry nearest three months away, in percent" });
output("term_spread", none, overlay, { description: "The three-month at-the-money IV minus the one-week one, in IV points. Above 0 is contango (far dates cost more), below 0 backwardation (near dates cost more)." });
string("skew_text", { max_bytes: 32 }); // the card's skew row: "-4.2 pts, puts pricier"
string("term_text", { max_bytes: 32 }); // the card's term row: "33.0% to 41.2%"
string("term_word", { max_bytes: 16 }); // the legend entry: Contango or Backwardation
string("notice", { max_bytes: 64 }); // the one sentence at the top right when the chain gives no usable expiry
render.legend("term", { text: "term_word", color: "theme.muted" }); // the legend reads "term Contango"
render.label("notice_tag", { position: "top_right", text: "notice", color: "theme.muted", style: "plain", offset: [12, 8] });
const heat = frame("heat", { max_bytes: 8192 }); // the surface: one cell per strike and expiry, the summary row, the highlight
const termRows = frame("term_rows", { max_bytes: 2048 }); // the tiles: one per expiry
// The term structure first, right under the candles: six tiles in one row, label the expiry, value its ATM IV,
// caption the days to expiry (the caption shows in the tile's hover card, and on the tile itself once the panel is
// maximized; the chart's own floating button sits at the bottom left of the cell, so the tiles stay above the
// surface). Together the two panels take 0.35 of the chart.
panel.tiles({ name: "term_tiles", title: "At-the-money IV by expiry", x: "category", place: "below", frame: termRows, columns: 6, accent: "neutral", hover_card: true, maximize: true, format: "0.0", unit: "%", height_frac: 0.12 });
// The surface: expiry on x, strike on y (the highest at the top, like the price axis), IV percent in the cell, on the
// chart's one-ink ramp from faint (the cheapest options, at the money) to full (the dearest wings); the row nearest
// the chart's price marked, the ATM summary row and the term word as the caption (written per run), a hover card on
// every cell titled by its two labels after the built-in's axis nouns, "Strike 64,000 · Expiry 27 Dec", over its IV.
panel.heatmap({ name: "surface", title: "Implied volatility", x: "category", place: "below", frame: heat, scale: "palette", row_title: "Strike", col_title: "Expiry", hover_card: true, maximize: true, format: "0.0", unit: "%", height_frac: 0.23 });
// The card, at the top left under the legend (the top right keeps the notice): the nearest ATM IV leads as the
// headline, then the two rows with dotted leaders.
render.hud("surface_card", {
position: "top_left",
title: "Volatility surface",
columns: 1,
width: 236,
safe_area: true,
tiles: [
tile.value("ATM IV, nearest expiry", "atm_near", { format: "%", headline: true, hint: "The implied volatility (IV) of the option nearest the price, on the nearest expiry at least 12 hours away. High IV means options are expensive and traders expect big swings." }),
tile.rows([
["Skew", "skew_text"],
["1 week vs 3 months", "term_text"],
], { leader: "dots" }),
],
});
const MAX_COLUMNS = 6; // expiry columns the surface fold answers at most (the Expiries setting's cap)
const ROWS = 21; // strike rows the surface fold answers at most, as many as the built-in Options Surface shows
const MAX_TERM = 64; // term rows the vol_term fold answers at most: one per live expiry
const MIN_AHEAD_DAYS = 0.5; // an expiry inside 12 h is settling, not the card's reading (the fold's days to expiry)
const stamp = new BookStamp(); // the book the folds read: its priced instant and its spot
const matrix = new SurfaceMatrix(MAX_COLUMNS, ROWS); // the surface: expiry columns, strike rows, the ATM summaries
const term = new VolTerm(MAX_TERM); // the term structure: each live expiry's days, ATM IV and 25-delta risk reversal
const strikeText = new TextBuilder(24); // a strike's label, spelled by the built-in's rule, copied into the frame
const LABEL_BYTES = 24; // a strike label's bytes at most: the label builder's capacity
const MAX_DECIMALS = 8; // the most decimals a strike row's label takes when two rows would read alike
// Every row at up to N decimals, the trailing zeros dropped, by N: the masks of a matrix whose rows would read alike.
const DECIMAL_MASKS: string[] = ["#,##0", "#,##0.#", "#,##0.##", "#,##0.###", "#,##0.####", "#,##0.#####", "#,##0.######", "#,##0.#######", "#,##0.########"];
const rowLabels = new StaticArray<u8>(ROWS * LABEL_BYTES); // each strike row's label, to find two that read alike
const rowLabelBytes = new StaticArray<i32>(ROWS);
const timedColumn = new StaticArray<bool>(MAX_COLUMNS); // a column whose date another column shares: its label adds the time
let clock = new Clock("UTC"); // an expiry's time of day on the market's own clock, set in onStart()
let zone = 0; // the market's clock, read in onStart()
let quoteIsUsd = 0; // the chart's quote: 1 US dollars, 2 another currency or coin (USDT and USDC too), 0 unknown
let optionContract = false; // the chart is one option contract's own: its close is a premium
let strikeDecimals = -1; // the decimals every strike row's label takes; -1: the built-in's, by the strike's size
let pricedAtMs: f64 = NaN; // the instant the data plane priced the book
let cellsRead = 0; // the matrix cells the surface fold carried (an empty cell rides no row)
let surfaceDrawn = false; // the surface fold carried a column and a row
let termCount = 0; // term rows read; a book with no spot gives no reading, as the built-in Term Structure plots none
let nearRow = -1; // the card's expiry: the nearest at least 12 h away with an ATM IV; -1 when none
let skew25: f64 = NaN; // the readings, picked on the live bar
let atm1w: f64 = NaN;
let atm3m: f64 = NaN;
let oneExpiry = false; // the one-week and three-month picks are the same listed expiry: no term word
function onStart(): void {
zone = i32(p_market_zone());
clock = new Clock(SESSION_TZ_IDS[zone]);
quoteIsUsd = i32(p_market_quote_is_usd());
optionContract = i32(p_market_option_contract()) == 1;
}
// ── The folds, read on the live bar ──
// The surface draws when the answer carries a book stamp, an expiry column and a strike row; an empty book (no
// contract), no spot and an answer with no surface row carry none. The readings are the term rows' own: the nearest
// expiry at least 12 h away that quotes an ATM IV (the headline, and the skew's expiry), and the listed expiries at
// least 12 h away nearest one week and three months by days to expiry (the first on a tie).
function read(cells: StaticArray<f64>, n: i32): void {
cellsRead = 0;
surfaceDrawn = false;
termCount = 0;
nearRow = -1;
skew25 = NaN;
atm1w = NaN;
atm3m = NaN;
oneExpiry = false;
strikeDecimals = -1;
for (let c = 0; c < MAX_COLUMNS; c += 1) unchecked((timedColumn[c] = false));
// Every reader reads the block at its rows' width: the widest word's, vol_term's 16.
if (!stamp.load(cells, n, OPTION_VIEW_ROW_VOL_TERM)) return;
pricedAtMs = stamp.pricedAtMs();
cellsRead = matrix.load(cells, n, OPTION_VIEW_ROW_VOL_TERM);
surfaceDrawn = cellsRead >= 0 && matrix.columns() > 0 && matrix.rows() > 0;
if (surfaceDrawn) labelApart();
termCount = term.load(cells, n, OPTION_VIEW_ROW_VOL_TERM);
if (!(stamp.spot() > 0.0)) return; // no spot: no reading, as the built-in Term Structure reads none
let w = -1;
let m = -1;
for (let i = 0; i < termCount; i += 1) {
const days = term.days(i);
if (!(days > MIN_AHEAD_DAYS)) continue; // settling
if (nearRow < 0 && isFinite(term.atmIv(i))) nearRow = i;
if (w < 0 || Math.abs(days - 7.0) < Math.abs(term.days(w) - 7.0)) w = i;
if (m < 0 || Math.abs(days - 90.0) < Math.abs(term.days(m) - 90.0)) m = i;
}
if (nearRow < 0) return;
skew25 = term.rr25(nearRow); // call minus put
atm1w = term.atmIv(w);
atm3m = term.atmIv(m);
oneExpiry = w == m;
}
// ── The labels ──
// A strike as the built-in Options Surface spells it: grouped, at most four decimals under 10, two under 1,000 and none
// from 1,000, the trailing zeros dropped, rounded half away from zero ("64,000", "662.5", "0.55"). The chart lays a
// heatmap's rows and columns out by their labels, so two that read alike would merge into one: CME's yen options list
// 0.00425 and 0.0043, both "0.0043" at four decimals. While two strike rows read alike, every row takes the fewest
// decimals, from the built-in's most, that tell each row apart ("0.00425", "0.0043"), the highlighted row its row's
// label. An expiry column reads its trade date, the kit's label; two columns of one date (an AM and a PM expiry) each
// add the expiry's time on the market's clock ("16 Oct 09:30"), and its tile follows its column.
function spellStrike(strike: f64, decimals: i32): void { // into strikeText: the built-in's mask at -1, else `decimals` at most
if (decimals < 0) strikeText.clear().mask(strike, strike < 10.0 ? "#,##0.####" : strike < 1000.0 ? "#,##0.##" : "#,##0");
else strikeText.clear().mask(strike, unchecked(DECIMAL_MASKS[decimals]));
}
function rowsReadApart(decimals: i32): bool { // every strike row's label differs from every other row's at `decimals`
for (let r = 0; r < matrix.rows(); r += 1) {
spellStrike(matrix.rowStrike(r), decimals);
const bytes = strikeText.length(); // at most LABEL_BYTES, the builder's capacity
const at = <usize>strikeText.ptr();
for (let i = 0; i < bytes; i += 1) unchecked((rowLabels[r * LABEL_BYTES + i] = load<u8>(at + <usize>i)));
unchecked((rowLabelBytes[r] = bytes));
for (let q = 0; q < r; q += 1) {
if (unchecked(rowLabelBytes[q]) != bytes) continue;
let same = true;
for (let i = 0; i < bytes && same; i += 1) same = unchecked(rowLabels[q * LABEL_BYTES + i]) == unchecked(rowLabels[r * LABEL_BYTES + i]);
if (same) return false;
}
}
return true;
}
function labelApart(): void { // the strike rows' decimals and the expiry columns that add their time
if (!rowsReadApart(-1)) {
let decimals = 0; // from the built-in's most decimals over the rows: no row reads coarser than the built-in's
for (let r = 0; r < matrix.rows(); r += 1) {
const strike = matrix.rowStrike(r);
const own = strike < 10.0 ? 4 : strike < 1000.0 ? 2 : 0;
if (own > decimals) decimals = own;
}
while (decimals < MAX_DECIMALS && !rowsReadApart(decimals)) decimals += 1;
strikeDecimals = decimals;
}
for (let c = 0; c < matrix.columns(); c += 1) {
const day = optionsTradeDay(matrix.columnExpiryMs(c), zone); // the date its label names
for (let d = 0; d < c; d += 1) {
if (optionsTradeDay(matrix.columnExpiryMs(d), zone) != day) continue;
unchecked((timedColumn[c] = true));
unchecked((timedColumn[d] = true));
}
}
}
function fbStrike(strike: f64): void {
if (!isFinite(strike)) {
fb_text("NaN");
return;
}
spellStrike(strike, strikeDecimals);
const at = <usize>strikeText.ptr();
for (let i = 0; i < strikeText.length(); i += 1) {
const code = i32(load<u8>(at + <usize>i));
if (code >= 0x30 && code <= 0x39) fb_int(code - 0x30);
else if (code == 0x2c) fb_text(",");
else if (code == 0x2e) fb_text(".");
else if (code == 0x2d) fb_text("-");
}
}
function fbStrikeKey(r: i32): void {
fb_text("\"");
fbStrike(matrix.rowStrike(r));
fb_text("\"");
}
function fbExpiryKey(c: i32): void { // "16 Oct", "15 Jan '27" in another year, "16 Oct 09:30" beside a column of its date
fb_text("\"");
fbExpiryLabel(matrix.columnExpiryMs(c), pricedAtMs, zone);
if (unchecked(timedColumn[c])) fbExpiryTime(matrix.columnExpiryMs(c));
fb_text("\"");
}
function fbExpiryTime(ms: f64): void { // " 09:30": the expiry's time on the market's clock
clock.update(Math.floor(ms / 1000.0));
fb_text(" ");
fbPad(clock.hour());
fb_text(":");
fbPad(clock.minute());
}
function fbPad(value: i32): void { // two digits, zero first
if (value < 10) fb_text("0");
fb_int(value);
}
// ── The frames, written on the live bar ──
// The bold row: the strike row nearest the live bar's close, the higher on a tie (the data plane's rule), where the
// close reads in the strikes' US dollars (every chain read here: OPRA, CME's futures options, Deribit's coin options):
// a chart priced in US dollars (unknown counts), no option contract's own (its close is the premium), the close within
// half to twice the book's spot. Else (a coin quoted in KRW, BTC, EUR or a stablecoin, a premium) and while the close
// is NaN, the fold's own highlight, highlightRow(): the row nearest the book's spot, which sits off the chart's price
// after hours and between chain snapshots.
function closeOnLadder(close: f64): f64 {
if (optionContract || quoteIsUsd == 2) return NaN; // a premium axis, or another currency or coin
const s0 = stamp.spot();
if (!(close >= 0.5 * s0 && close <= 2.0 * s0)) return NaN; // another unit, whatever the facts say
return close;
}
function boldRow(price: f64): i32 {
if (!isFinite(price)) return matrix.highlightRow(); // no price: the book's own pick, the row nearest its spot
let best = -1;
let gap = Infinity;
for (let r = 0; r < matrix.rows(); r += 1) {
const d = Math.abs(matrix.rowStrike(r) - price); // NaN for a row with no strike, never picked
if (d < gap) {
gap = d;
best = r;
}
}
return best;
}
function writeSurface(): void {
fb_clear();
fb_text("{\"rows\":[");
let first = true;
for (let r = 0; r < matrix.rows() && surfaceDrawn; r += 1) { // row 0 is the highest strike: the top row, like the price axis
for (let c = 0; c < matrix.columns(); c += 1) {
if (!first) fb_text(",");
first = false;
fb_text("[");
fbExpiryKey(c);
fb_text(",");
fbStrikeKey(r);
fb_text(",");
fb_num(matrix.value(r, c)); // the fold's IV, vol points; null for an empty cell
fb_text("]");
}
}
fb_text("]");
if (surfaceDrawn && cellsRead > 0) { // the summary row rides with the cells, as on the built-in
fb_text(",\"summary\":[{\"label\":\"ATM\",\"values\":[");
for (let c = 0; c < matrix.columns(); c += 1) {
if (c > 0) fb_text(",");
fb_num(matrix.summary(c)); // each expiry's ATM IV; null where it quotes none
}
fb_text("]}]");
}
const h = boldRow(closeOnLadder(bar.close())); // the row nearest the chart's price
if (surfaceDrawn && h >= 0 && h < matrix.rows()) {
fb_text(",\"highlight\":{\"row\":");
fbStrikeKey(h);
fb_text("}");
}
fb_text(",\"caption\":\"");
if (isNaN(atm1w) || isNaN(atm3m)) fb_text("Term structure: no reading");
else if (oneExpiry) fb_text("Term structure: one expiry listed");
else { // "Contango: 1w 31.1%, 3m 36.6%" (the title row shows about 30 characters of caption)
fb_text(atm3m > atm1w ? "Contango: 1w " : "Backwardation: 1w ");
fb_f64(atm1w, 1);
fb_text("%, 3m ");
fb_f64(atm3m, 1);
fb_text("%");
}
fb_text("\"}");
writeFrameBuffer(FRAME_HEAT);
}
function writeTiles(): void {
fb_clear();
fb_text("{\"rows\":[");
for (let c = 0; c < matrix.columns() && surfaceDrawn; c += 1) {
if (c > 0) fb_text(",");
fb_text("[");
fbExpiryKey(c);
fb_text(",");
const i = term.indexOf(matrix.columnExpiryMs(c)); // the expiry's term row: its ATM IV and days, the Term Structure's
if (i >= 0 && isFinite(term.atmIv(i))) fb_num(term.atmIv(i));
else fb_text("\"no IV\""); // a tile's value is never empty: the expiry quotes no ATM IV
if (i >= 0 && isFinite(term.days(i))) {
fb_text(",\"");
fb_f64(term.days(i), 1);
fb_text(" days\"]");
} else fb_text(",null]");
}
fb_text("]}");
writeFrameBuffer(FRAME_TERM_ROWS);
}
// onBar() runs once per bar: history rows carry an empty block and read nothing; the live bar reads the folds, writes
// the readings as numbers (NaN on history rows), the two frames and the card's words. With neither a surface nor a
// reading both frames are written empty, so the panels clear instead of keeping the last answer's cells. The chart
// runs the live bar again as its candle moves, with the newest chain answer, so the bold row follows the price.
function onBar(): void {
if (bar.isLast()) read(in_chain_view(), in_chain_cells());
const measured = bar.isLast() && nearRow >= 0;
out_atm_near(measured ? term.atmIv(nearRow) : NaN);
out_skew_25d(measured ? skew25 : NaN);
out_atm_1w(measured ? atm1w : NaN);
out_atm_3m(measured ? atm3m : NaN);
out_term_spread(measured ? atm3m - atm1w : NaN);
if (!bar.isLast()) return;
if (surfaceDrawn || measured) {
writeSurface();
writeTiles();
sb_clear();
if (!measured) sb_text("no options data");
else if (isNaN(skew25)) sb_text("no 25-delta reading");
else {
sb_signed(skew25, 1);
sb_text(skew25 <= 0.0 ? " pts, puts pricier" : " pts, calls pricier");
}
str_skew_text_sb();
sb_clear();
if (!measured) sb_text("no options data");
else if (isNaN(atm1w) || isNaN(atm3m)) sb_text("no reading");
else if (oneExpiry) sb_text("one expiry listed");
else {
sb_f64(atm1w, 1);
sb_text("% to ");
sb_f64(atm3m, 1);
sb_text("%");
}
str_term_text_sb();
sb_clear();
if (measured && !isNaN(atm1w) && !isNaN(atm3m) && !oneExpiry) sb_text(atm3m > atm1w ? "Contango" : "Backwardation");
str_term_word_sb();
sb_clear();
str_notice_sb(); // no notice: the folds gave a surface or a reading
} else {
// No usable expiry: the one sentence at the top right, the card's rows say why, both panels cleared.
writeFrame(FRAME_HEAT, "{\"rows\":[]}");
writeFrame(FRAME_TERM_ROWS, "{\"rows\":[]}");
sb_clear();
sb_text("No usable expiry in this symbol's options");
str_notice_sb();
sb_clear();
sb_text("no options data");
str_skew_text_sb();
sb_clear();
sb_text("no options data");
str_term_text_sb();
sb_clear();
str_term_word_sb();
}
}How it works
Two folds, one input. input("chain", options_chain.cells, { max_cells: 225, venue: "auto", page_views: ["surface", "vol_term"], lens: 2, window_pct: "@range_pct", columns: "@expiries", rows: 21 }) asks the data plane for two book folds of the chart's own live chain (OPRA on a US stock or ETF chart, the CME chain of a futures root, the coin's Deribit chain elsewhere): surface with lens: 2, implied volatility as a strike by expiry matrix, its columns the Expiries setting, its window_pct the Strike range setting (each bound with "@<param>", so the chart writes the setting's value on every run) and its rows 21, and vol_term, a row per live expiry quoting an IV or holding open interest. The data plane folds both once a chain update over the chain's whole book, priced at one instant with each expiry's ATM IV at its forward, so they are the numbers the built-in Options Surface and Term Structure draw. The answer is one block of rows 16 values wide, the widest word's (vol_term): the one book stamp row, the surface's [16, tag, at, value] rows and the term rows. max_cells counts rows: 225 holds the stamp, the surface's 2 x 6 + 21 + 1 + 6 x 21 rows at the settings' caps (a header and a summary per column, a header per row, the highlight, a cell per strike and expiry) and 64 term rows. The block is the live row's only: history bars carry an empty block and read nothing, so everything is read under bar.isLast(), and the five data-only readings (atm_near, skew_25d, atm_1w, atm_3m, term_spread) are NaN on history bars.
The surface is the fold's matrix. On the live bar each reader reads the block at the input's row width, OPTION_VIEW_ROW_VOL_TERM (16), its own layouts, and skips the rest. BookStamp reads the stamp (an answer with none reads nothing), the book's spot and the instant the data plane priced the book (pricedAtMs(), the clock each expiry's label reads its year against). SurfaceMatrix reads the surface: the expiry columns, nearest first (columns(), columnExpiryMs(c)), the strike rows, the highest first (rows(), rowStrike(r)), each cell's IV in vol points (value(r, c), NaN for an empty cell, which rides no row), each expiry's ATM IV (summary(c)) and the fold's own highlight, the row nearest the book's spot (highlightRow()). The columns are the nearest live expiries, as the data plane counts them; the rows are the 21 strikes nearest the book's spot inside the moneyness range, so a range that holds fewer strikes shows fewer rows. The surface draws when the answer carries a column and a row: an empty book (no contract), a book with no spot and an answer with no surface row carry none.
The card reads the term structure. VolTerm reads a row per live expiry: its days to expiry, its ATM IV and its 25-delta risk reversal (days(i), atmIv(i), rr25(i)). With a spot, the card's expiry is the nearest one at least 12 h away (an expiry inside 12 h is settling) that quotes an ATM IV: its ATM IV is the headline, atm_near, and its risk reversal the skew, skew_25d (rr25(): the 25-delta call's IV minus the 25-delta put's, in IV points, below 0 while puts carry the premium). The one-week and three-month points are the listed expiries at least 12 h away nearest 7 and 90 days by the fold's days to expiry, the first on a tie, over every term row, not only the surface's columns, so the term word holds even when the six nearest expiries all sit inside a month; term_spread is the three-month ATM minus the one-week ATM, above 0 contango. When the two picks are the same listed expiry there is no term word. Without a spot the vol term gives no reading, as the built-in Term Structure plots none.
Two frames feed two panels. frame("term_rows") carries one [label, value, caption] row per surface column (the expiry's label; its ATM IV from its term row, found by indexOf(columnExpiryMs(c)), or the text no IV where it quotes none; its days to expiry, the fold's; the label is the kit's fbExpiryLabel, the expiry's trade date on the market's clock read against the book's priced instant, 16 Oct, or 15 Jan '27 in another year, and the heatmap's columns read it too) and feeds panel.tiles with columns: 6, accent: "neutral" (IV has no sign, so the text keeps its ink) and format: "0.0" with unit: "%", so a tile reads 27.1%. frame("heat") carries one [expiry, strike, value] cell per strike row and expiry column, written from the highest strike down so the top row is the highest strike, like the price axis, the value null for an empty cell. Each strike is spelled as the built-in Options Surface spells it: grouped, at most four decimals under 10, two under 1,000 and none from 1,000, trailing zeros dropped, rounded half away from zero (64,000, 662.5, 0.55), built with a TextBuilder mask and copied into the frame. The chart lays the heatmap's rows and columns out by their labels, so two that read alike would merge into one: while two strike rows would read alike (CME's yen options list 0.00425 and 0.0043, both 0.0043 at four decimals), every row takes the fewest decimals, from the built-in's most, that tell the rows apart (0.00425, 0.0043), and two columns of one date (an AM and a PM expiry) each add the expiry's time on the market's clock (16 Oct 09:30), the tiles following their columns; every other matrix keeps the built-in's spelling. Beside the cells the frame carries a summary row, ATM, each expiry's ATM IV under its column (null where it quotes none), a highlight naming the row nearest the chart's price, and the caption written per run (the title row shows about 30 characters of it). It feeds panel.heatmap with scale: "palette" and no palette, so the cells ramp from the chart's background to the text colour, row_title: "Strike" and col_title: "Expiry", the built-in's axis nouns, which prefix each label in the hover card's title ("Strike 64,000 · Expiry 27 Dec"), and hover_card: true printing each cell's exact value under the pointer. Both frames are written with the fb_* builders and writeFrameBuffer, and the two panels take 0.35 of the chart together.
The bold row follows the chart's price. boldRow(closeOnLadder(bar.close())) picks the strike row nearest the live bar's close, the higher strike on a tie. The fold's own highlight, highlightRow(), is the row nearest the book's spot, the median underlying of its nearest expiry, and that spot can sit off the chart's price: a stock trading after hours while its options are shut, or the moves between two chain snapshots. The close stands in for the price only where it reads in the strikes' units. Every chain the package reads quotes its strikes in US dollars, so closeOnLadder() hands the close back only on a chart priced in US dollars (market.quote_is_usd(), an unknown quote included) that is no option contract's own (market.option_contract(): its close is the contract's premium), and only within half to twice the book's spot. A coin quoted in KRW, BTC, EUR or a stablecoin, or a premium, reads NaN there, and boldRow() takes highlightRow() for NaN. The chart runs the live bar again as its candle moves, with the newest chain answer, so the bold row follows the price between chain updates while the cells keep the last answer's.
The card reads an output and two slots. render.hud("surface_card", { position: "top_left", columns: 1, width: 236, safe_area: true, tiles: [...] }) names the anchor and two tiles; with no look, the card draws the chart's default look. tile.value("ATM IV, nearest expiry", "atm_near", { format: "%", headline: true, hint: "..." }) leads as the headline and reads the data-only output, its hint saying how the number is read; tile.rows with leader: "dots" reads two string slots written on the live bar under the labels Skew and 1 week vs 3 months, skew_text ("-4.2 pts, puts pricier", from sb_signed; 0 reads puts pricier too) and term_text ("31.4% to 36.6%"). safe_area: true keeps the card under the legend, and the top right stays free for the notice.
The term word rides the legend, the notice the corner. render.legend("term", { text: "term_word", color: "theme.muted" }) prints the slot's words after the indicator's name as "term Contango", in the theme's muted ink. render.label("notice_tag", { position: "top_right", text: "notice", color: "theme.muted", style: "plain", offset: [12, 8] }) is a label placed by a corner position rather than by x and y: it prints the notice slot in the muted colour at the top right, and the slot is empty while the folds give a surface or a reading.
What the settings do
- Expiries: How many expiry dates the surface and the tiles show, nearest first, from 2 to 6.
- Strike range, percent: How far from the price the strikes reach, in percent each way, with up to 21 strikes shown.
- ATM IV, nearest expiry: The implied volatility of the option nearest the price, on the nearest expiry at least 12 hours away.
- Skew: The call's IV minus the put's at the same distance from the price: below 0, puts cost more.
- 1 week vs 3 months: The at-the-money IV one week out against three months out: higher far out is the calm, usual shape.
Where it runs
It works on any chart whose symbol has listed options. A coin chart reads Deribit's options for that coin (BTC, ETH and the rest of its list) on any exchange. Deribit is a crypto options exchange. A US stock or ETF chart reads its US listed options. They run 15 minutes behind unless you have real-time US options data. A CME (Chicago futures exchange) futures chart reads the options on that future, 10 minutes behind unless you have real-time CME data. A copy you run from the editor (the code panel beside the chart) reads crypto, US stock and CME options. On a CME chart, accept the CME market data terms first. Run on Cloud (the editor switch that runs a copy on OpenMarket's servers) cannot read these option prices yet. Nor can a Protected copy (published so its code stays on those servers). Each stops and says why. On a symbol with no listed options, the run stops at once and says why. The candles' exchange and timeframe change nothing on the surface. Only the bold strike follows the candles, at their last close. The surface reads the live bar only, so past bars show nothing. The tiles sit right under the candles, and the surface sits under the tiles. Its strike labels stay clear of the chart's round button. With the default settings the surface shows six expiries by 21 strikes plus the at-the-money summary, over six tiles.
When data is missing
With no usable expiry, the top right reads "No usable expiry in this symbol's options" and both panels clear. The card's skew and term lines then read "no options data", and the headline shows no number. The legend drops its term word. The five readings in the editor's Console (the panel under the code) stay empty. The same happens before the first options update arrives, and when the options carry no contract or no price. Only the live bar holds readings, so the surface has no history. With no expiry 12 hours out or more that has an at-the-money IV, the surface still draws. The card lines then read "no options data". When that expiry has no 25-delta options, the skew line reads "no 25-delta reading". When the one-week or three-month expiry has no at-the-money IV, the caption reads "Term structure: no reading". The term line then reads "no reading". When both are the same expiry, the caption reads "Term structure: one expiry listed" and the legend drops its word. A square stays blank where an expiry has no IV at that strike. A tile reads "no IV" when its expiry has no at-the-money IV.
Customize it
- Fewer expiries.
expiries(6, from 2 to 6) is the surface fold'scolumns: how many of the nearest live expiries make the surface and the tiles; the one-week and three-month picks still read every term row. - A wider or narrower smile.
range_pct(20, from 5 to 40) is the surface fold'swindow_pct: the moneyness range each side of the book's spot inside which the surface shows the 21 strikes nearest it, fewer where the range holds fewer. - More strikes.
rowson the input (21, up to 64) sets the strike rows. RaiseROWSwith it, sinceSurfaceMatrix(MAX_COLUMNS, ROWS)holds that many and refuses a block that carries more, raisemax_cellsby seven for each row added (its header and six cells), and raise the heat frame'smax_bytes(8192): a cell takes 25 to 28 bytes on the recorded books (38 at most) and the summary, highlight and caption about 180, so at six columns a row adds about 160 bytes and the frame passes 8192 near 35 to 47 rows, where the run refuses it whole (wrun_frame_too_large; a frame is never truncated). - Another wing. The skew reads the vol term's 25-delta risk reversal,
term.rr25();rr15()orrr10()reads the 15- or 10-delta one (name the delta in the card'sSkewrow label). - Another corner.
positionon the card takes any of the nine anchors,top_lefttobottom_right; the top right holds the notice sentence, so keep the two apart. - A look of its own. The card declares no
look, so it draws the chart's default look. When it should stand apart from the chart, addlook:with any of the twelve shipped looks (Looks), or pick one on the Look row of the indicator's Style page without code, "As made" first (The Style page).
Run it
- In the editor's Explorer, press the Templates icon ("Browse starter templates") and pick Volatility Surface under Beyond the time axis.
- Press Run on a BTC or ETH chart on any venue (BTCUSDT on Binance Futures at 15m, say): the six tiles and the surface mount below the candles, the card at the top left under the legend, and the legend reads the term word. Rest the pointer on a cell for its exact IV.
- At the editor's Console prompt, type
last 20 atm_nearto read the nearest expiry's ATM implied volatility on the last 20 bars: only the live bar carries a number, since the folds are read on the live bar only.
Concepts used
- Book folds for
BookStamp,SurfaceMatrixandVolTerm, the rows each reads and the row width they share, and Chain page views for thesurfaceandvol_termwords, their knobs bound to settings with"@<param>"and the hosted runs' refusal - Cards, frames and panels for frames,
panel.tiles,panel.heatmapwithrow_titleandcol_title(Heatmap), a heatmap frame'ssummary,highlightandcaption(Panel frames),fbExpiryLabelandwriteFrameBuffer - HUD cards for
render.hud, its anchors,widthandsafe_area, and arender.labelwith apositionas a corner readout - The default look for what a card with no
lookdraws, and Looks for the twelve it can name - Blocks and tiles for the headline
tile.value, itshintandtile.rowswithleader: "dots" - The Style page for the Look row that switches the look without code
- Legend for
render.legendand a string slot's words in the legend - Text formatting for the
sb_*andfb_*builders andsb_signed, and A second builder for theTextBuildermask that spells each strike