Top contracts
Top Contracts lists this symbol's most active option contracts right now, in a table under the chart.
Rank them by today's volume, open interest (contracts still held open), premium (the money paid) or price gain. Dashed lines mark the three most traded strikes (option price levels), and dotted lines the three with most open interest. A card leads with the top contract, and put/call volume above 1 means more puts (bets on a fall) traded. Use it on a US stock, coin or CME (Chicago futures exchange) future to see where bets crowd today.
Under the hood: a celled option_contract_state.cells input is read on the live bar naming the top and totals page views. Every setting is bound, so the data plane sends only the contracts the settings can rank and the summary's totals (Data sources, Chain page views). The options kit's viewTuples and ChainTotals read them (Options kit). Its present bits are read with hasBit(), and its option roots are spelled from their symbol codes (The present mask and partial bars). TextBuilder.expiry and fbExpiryLabel give each contract's expiry (A second builder, Panel frames). market.option_contract() marks an option contract's own chart (Quick reference). A panel.table reads a frame of styled cells (Cards, frames and panels). Line and label handles draw the six levels named V1 to V3 and OI1 to OI3 (Drawing objects). A render.hud card draws in the chart's default look (HUD cards, The default look). This is also the top-contracts template: the Top Contracts card under HUDs in the editor's starter list, and it compiles as written.
The wrun indicator
// Top Contracts: this symbol's most active option contracts right now, in a table under the chart. A contract is one
// option, a call (a bet on a rise) or a put (a bet on a fall). Rank them by volume today, open interest (contracts
// still held open), premium (the money paid) or gain. Lines mark the strikes (option price levels) with the most volume
// and open interest. A card leads with the top contract. Use it to see which bets the market crowds into today.
//
// Under the hood: the chart's most active option contracts on the newest bar, from its own option chain summary (the
// option_contract_state source). The Rank setting orders them by the day's volume, the open interest, the premium (the
// day's volume at the last price times the market's option multiplier, 100 shares on a US stock: an estimate, since the
// summary carries no traded premium; none where the host does not know the multiplier), or the gain since the prior
// session's close (a contract needs the Smallest volume to rank by gain), and a table under the chart lists the top
// ones with the last price, the change, the volume, the open interest, volume over open interest, the premium and the
// share of the day's volume. The strikes of the three most traded contracts (dashed) and of the three with the most
// open interest (dotted) are drawn across the chart as muted levels, each with its contract as plain text at the axis
// (on the underlying's own chart: the close inside the strikes the summary lists; never on an option contract's own
// chart, market.option_contract(), whose price axis is the contract's premium: there the table keeps filling and its
// caption says so), and a card leads with the top contract. A contract names its expiry as 17 Oct, or 15 Jan '27 in
// another year. The summary is a snapshot of now: history bars draw nothing, and everything is measured on the last
// bar. The data plane sends the contracts the table and the levels can rank on the settings, in the summary's order,
// and the summary's totals.
section("Ranking");
param.choice("rank", ["volume", "oi", "premium", "gain"], "volume", { label: "Rank by", description: "volume ranks by today's contracts traded. oi ranks by open interest (contracts still held open). premium ranks by the money paid today, the volume times the last price and contract size, an estimate. gain ranks by the change since the prior close." });
param.choice("side", ["both", "calls", "puts"], "both", { label: "Calls or puts", description: "Ranks calls (bets on a rise), puts (bets on a fall) or both, in the table and the levels." });
param.int("rows", 10, { min: 3, max: 25, label: "Contracts listed", description: "How many contracts the table shows." });
param.int("min_volume", 100, { min: 0, max: 1000000, label: "Smallest volume for gain", when: "rank=3", description: "Today's volume a contract needs to rank by gain. It counts contracts on US stocks and CME, coins on crypto." });
param.bool("levels", true, { label: "Strike levels", description: "Draws lines at the strikes (option price levels) of the three most traded and three most held contracts. Most held means the most open interest (contracts still held open)." });
input("close", ohlcv.close); // the chart's own close: whether the strikes belong on this chart's price axis
input("state", option_contract_state.cells, { max_cells: 64, expiries: "nearest:24", strike_window_pct: 10, page_views: ["top", "totals"], rank: "@rank", side: "@side", rows: "@rows", min_volume: "@min_volume", description: "This symbol's options summary on the newest bar, for the 24 nearest expiries and strikes within 10% of the price. It holds the contracts your settings rank and the summary's totals." }); // view rows of OPTION_VIEW_ROW_STATE f64s: [0, root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present, 0, 0] per ranked contract, in the summary's order, then [1, contracts, expiries, partial, low_strike, high_strike, traded, traded_volume, call_volume, put_volume, day_volume, total_oi, missing, counted, call_change, put_change]
market.zone(); // the market's clock: each expiry's trade date
market.option_multiplier(); // the chain's USD per price unit and size unit: 100 on a US stock, 50 on ES, 1 on a coin; 0 unknown
market.option_contract(); // 1 on an option contract's own chart: its price axis is the contract's premium, so no strike levels
// The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars.
output("top_strike", none, overlay, { description: "The top contract's strike (its price level). Live bar only." });
output("top_value", none, overlay, { description: "The top contract's value for Rank by, in contracts, USD or percent." });
output("total_volume", none, overlay, { description: "Today's volume of every contract listed, in contracts." });
output("call_volume", none, overlay, { description: "Today's volume of calls (bets on a rise), in contracts." });
output("put_volume", none, overlay, { description: "Today's volume of puts (bets on a fall), in contracts." });
output("put_call_volume", none, overlay, { description: "Put volume divided by call volume. Above 1 means more puts (bets on a fall) traded than calls." });
output("traded", none, overlay, { description: "Contracts that traded today." });
output("partial", none, overlay, { description: "1 when this symbol's options data arrived incomplete, else 0." });
output("top_side", none, overlay, { description: "Colour code for the top contract: 0 a put, 1 none, 2 a call. A call bets on a rise, a put on a fall." });
string("read", { max_bytes: 64 }); // the headline: the top contract and its reading, or why there is none
string("title", { max_bytes: 80 }); // the card's title: the rank and what the summary held
string("tag", { max_bytes: 48 }); // one bounded slot the six level texts are written through, one at a time
const top = frame("top", { max_bytes: 16384 }); // the table's rows
panel.table({ name: "top_contracts", title: "Most active contracts", x: "category", place: "below", frame: top, height_frac: 0.25, header_column: true, header_text_color: "theme.muted", grid_lines: "rows", grid_color: "theme.grid", grid_width: 1, valign: "middle", cell_padding: 4, font_size: 11, series: [{ name: "Contract" }, { name: "Last", align: "right", format: "0.00" }, { name: "Change", align: "right", format: "0.0", signed: true, unit: "%" }, { name: "Volume", align: "right", format: "int" }, { name: "OI", align: "right", format: "int" }, { name: "Vol/OI", align: "right", format: "0.00" }, { name: "Premium", align: "right", format: "usd" }, { name: "Share", align: "right", format: "0.0", unit: "%" }] });
handles.line({ width: 1, extend: "both" }); // the six strike levels, across the whole chart
handles.label({ anchor: "right", align: "right", size: 11, color: "theme.muted", style: "plain" }); // their text: x in pixels from the right edge, y in price
// The card: the top contract leads as the headline, up on a call and down on a put, then the day's volume and its
// split.
render.hud("top_contracts", {
position: "bottom_center",
title: "{{title}}",
columns: 2,
tiles: [
tile.pill("Top contract", "read", { headline: true, color_by: "top_side", colors: ["theme.down", "theme.muted", "theme.up"] }),
tile.value("Day volume", "total_volume", { format: "si" }),
tile.value("Put/call volume", "put_call_volume", { format: "0.00" }),
tile.rows([
["Top strike", "top_strike", "price"],
["Its value", "top_value", "auto"],
["Calls traded", "call_volume", "si"],
["Puts traded", "put_volume", "si"],
["Contracts that traded", "traded", "int"],
]),
],
});
const TUPLE = 13; // f64s per contract: root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present
const BIT_LAST = 6; // present bits: last, prev_close, volume_day, oi
const BIT_PREV_CLOSE = 7;
const BIT_VOLUME = 9;
const BIT_OI = 10;
const MAX_ROWS = 25; // the Rows setting's cap
const LEVELS = 3; // levels per list: the most traded, the most open interest
const RANK_VOLUME = 0;
const RANK_OI = 1;
const RANK_PREMIUM = 2;
const RANK_GAIN = 3;
const RANK_WORDS: String[] = ["volume", "open interest", "premium", "gain"];
const SYMBOL_CHARS: String[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "."]; // a symbol code's characters, value 1 to 37
const LEVEL = theme.MUTED; // every level: a strike, never a sign
const ranked = new StaticArray<f64>(in_state_max_cells * TUPLE); // the contracts the data plane ranked for the settings, in the summary's order
const totals = new ChainTotals(); // the summary's counts and sums over every contract
const rankAt = new StaticArray<i32>(MAX_ROWS); // the table: each contract's offset in ranked, and its key, the largest first
const rankKey = new StaticArray<f64>(MAX_ROWS);
const volAt = new StaticArray<i32>(LEVELS); // the most traded contracts, for the levels
const volKey = new StaticArray<f64>(LEVELS);
const oiAt = new StaticArray<i32>(LEVELS); // the contracts with the most open interest
const oiKey = new StaticArray<f64>(LEVELS);
const rootDigits = new StaticArray<i32>(10); // a root's characters, the last first, while it is spelled
const lines: LineHandle[] = [draw.line(0), draw.line(1), draw.line(2), draw.line(3), draw.line(4), draw.line(5)]; // the three volume levels, then the three open interest levels
const tags: LabelHandle[] = [draw.label(6), draw.label(7), draw.label(8), draw.label(9), draw.label(10), draw.label(11)]; // ids are one space across kinds
const tagPrices = new StaticArray<f64>(6); // the tags placed so far on this bar, so a level near another steps inward
const tagSlots = new StaticArray<i32>(6); // the step inward each placed tag took
const expiryText = new TextBuilder(16); // an expiry's label, the kit's spelling, copied into the line by sbContract()
let rank = RANK_VOLUME; // settings, read in onStart()
let side = 0; // 0 both, 1 calls, 2 puts
let rowsWanted = 10;
let minVolume = 100.0;
let drawLevels = true;
let zone = 0;
let optMult: f64 = NaN; // NaN where the host does not know the multiplier: no premium, never 0
let optionContract = false; // the chart is one option contract's own: no levels on its premium axis
let close: f64 = NaN; // this bar
let t: f64 = NaN;
let firstT: f64 = NaN; // the first bar's open time: where the levels start
let rankCount = 0;
let volCount = 0;
let oiCount = 0;
let expiries = 0; // distinct expiries the summary lists
let contracts = 0; // contracts it lists
let traded = 0; // contracts with volume today
let partial = false;
let totalVolume = 0.0;
let callVolume = 0.0;
let putVolume = 0.0;
let lowStrike: f64 = NaN; // the strikes the summary lists, lowest and highest
let highStrike: f64 = NaN;
function onStart(): void {
rank = i32(p_rank());
side = i32(p_side());
rowsWanted = i32(p_rows());
if (rowsWanted > MAX_ROWS) rowsWanted = MAX_ROWS;
minVolume = p_min_volume();
drawLevels = pb_levels();
zone = i32(p_market_zone());
optMult = p_market_option_multiplier() > 0.0 ? p_market_option_multiplier() : NaN;
optionContract = i32(p_market_option_contract()) == 1;
}
// ── The rankings: insertion into a short list, the largest first, ties kept in the summary's order ──
function insert(at: StaticArray<i32>, keys: StaticArray<f64>, count: i32, cap: i32, offset: i32, key: f64): i32 { // returns the new count
let k = count < cap ? count : cap;
if (k == cap && key <= keys[cap - 1]) return count;
if (k == cap) k = cap - 1;
while (k > 0 && keys[k - 1] < key) {
keys[k] = keys[k - 1];
at[k] = at[k - 1];
k -= 1;
}
keys[k] = key;
at[k] = offset;
return count < cap ? count + 1 : cap;
}
function sideKept(isCall: bool): bool {
return side == 0 || (side == 1) == isCall;
}
function keyOf(cells: StaticArray<f64>, i: i32): f64 { // the contract's reading on the Rank setting; NaN when it does not rank
const present = cells[i + 12];
const volume = hasBit(present, BIT_VOLUME) ? cells[i + 9] : NaN;
const last = hasBit(present, BIT_LAST) ? cells[i + 6] : NaN;
if (rank == RANK_VOLUME) return volume > 0.0 ? volume : NaN;
if (rank == RANK_OI) return hasBit(present, BIT_OI) && cells[i + 10] > 0.0 ? cells[i + 10] : NaN;
if (rank == RANK_PREMIUM) return volume > 0.0 && last > 0.0 ? volume * last * optMult : NaN;
const prev = hasBit(present, BIT_PREV_CLOSE) ? cells[i + 7] : NaN;
if (!(volume >= minVolume) || !(volume > 0.0) || !(last > 0.0) || !(prev > 0.0)) return NaN; // gain: traded enough, both prices
return (last / prev - 1.0) * 100.0;
}
// ── The summary, measured on the live bar: the totals the data plane summed, the rankings over what it sent ──
function measure(n: i32): void {
const view = in_state_view(); // the live view rows in place: the first n values of the build's own buffer
rankCount = 0;
volCount = 0;
oiCount = 0;
const loaded = totals.load(view, n); // contracts, expiries (at most 64), partial, the strikes and the volumes
expiries = loaded ? i32(totals.expiries()) : 0;
contracts = loaded ? i32(totals.contracts()) : 0;
traded = loaded ? i32(totals.traded()) : 0;
partial = loaded && totals.partial();
totalVolume = loaded ? totals.tradedVolume() : 0.0;
callVolume = loaded ? totals.callVolume() : 0.0;
putVolume = loaded ? totals.putVolume() : 0.0;
lowStrike = totals.lowStrike(); // NaN with no contract
highStrike = totals.highStrike();
const m = viewTuples(view, n, OPTION_VIEW_ROW_STATE, TUPLE, ranked); // the ranked contracts' tuples, in the summary's order
for (let i = 0; i + TUPLE - 1 < m; i += TUPLE) {
const present = ranked[i + 12];
const strike = ranked[i + 3];
if (!(strike > 0.0) || !isFinite(ranked[i + 1])) continue;
const isCall = ranked[i + 2] > 0.0;
const volume = hasBit(present, BIT_VOLUME) ? ranked[i + 9] : 0.0;
if (!sideKept(isCall)) continue;
const key = keyOf(ranked, i);
if (!isNaN(key)) rankCount = insert(rankAt, rankKey, rankCount, rowsWanted, i, key);
if (volume > 0.0) volCount = insert(volAt, volKey, volCount, LEVELS, i, volume);
if (hasBit(present, BIT_OI) && ranked[i + 10] > 0.0) oiCount = insert(oiAt, oiKey, oiCount, LEVELS, i, ranked[i + 10]);
}
}
// ── Text helpers, written into the frame buffer and the line buffer without allocating ──
function rootCount(code: f64): i32 { // the characters of the root a symbol code names, the last first in rootDigits; 0 when it names none
if (!isFinite(code) || code < 1.0 || code > 6278211847988223.0 || code != Math.floor(code)) return 0;
let rest = u64(code);
let count = 0;
while (rest > 0) {
const value = i32(rest % 38);
if (value == 0 || count >= 10) return 0; // no text encodes to a zero digit
rootDigits[count] = value;
count += 1;
rest = rest / 38;
}
return count;
}
function strikeDecimals(v: f64): i32 { // a strike as it is quoted: 660, 662.5, 0.25
return v == Math.floor(v) ? 0 : v * 10.0 == Math.floor(v * 10.0) ? 1 : 2;
}
function fbContract(cells: StaticArray<f64>, i: i32): void { // "\"SPY 17 Oct 660C\"", a root that spells nothing as "?"
fb_text("\"");
const count = rootCount(cells[i]);
if (count == 0) fb_text("?");
for (let k = count - 1; k >= 0; k -= 1) fb_text(SYMBOL_CHARS[rootDigits[k] - 1]);
fb_text(" ");
fbExpiryLabel(cells[i + 1], t * 1000.0, zone); // the expiry's trade date: 17 Oct, or 15 Jan '27 in another year
fb_text(" ");
const decimals = strikeDecimals(cells[i + 3]);
if (decimals == 0) fb_int(i64(cells[i + 3]));
else fb_f64(cells[i + 3], decimals);
fb_text(cells[i + 2] > 0.0 ? "C\"" : "P\"");
}
function sbContract(cells: StaticArray<f64>, i: i32): void { // the same words in the line buffer, unquoted
const count = rootCount(cells[i]);
if (count == 0) sb_text("?");
for (let k = count - 1; k >= 0; k -= 1) sb_text(SYMBOL_CHARS[rootDigits[k] - 1]);
sb_text(" ");
expiryText.clear().expiry(cells[i + 1], t * 1000.0, zone);
for (let k = 0; k < expiryText.length(); k += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>k));
sb_text(" ");
const decimals = strikeDecimals(cells[i + 3]);
if (decimals == 0) sb_int(i64(cells[i + 3]));
else sb_f64(cells[i + 3], decimals);
sb_text(cells[i + 2] > 0.0 ? "C" : "P");
}
function sbShort(v: f64): void { // "84.2K", "1.3M", "850"
const a = Math.abs(v);
if (v < 0.0) sb_text("-");
if (a >= 1.0e9) {
sb_f64(a / 1.0e9, 2);
sb_text("B");
} else if (a >= 1.0e6) {
sb_f64(a / 1.0e6, 1);
sb_text("M");
} else if (a >= 1.0e3) {
sb_f64(a / 1.0e3, 1);
sb_text("K");
} else sb_f64(a, 0);
}
// ── The table, appended as JSON text without allocating ──
function writeTable(): void {
const cells = ranked;
fb_clear();
fb_text("{\"caption\":\"");
if (rankCount == 0) fb_text("No contract ranks on this setting");
else if (optionContract && drawLevels) fb_text("On a contract's own chart, no levels"); // the card's title names the rank
else {
fb_text("Ranked by ");
fb_text(RANK_WORDS[rank]);
if (rank == RANK_PREMIUM) fb_text(": volume at the last price, an estimate");
}
fb_text("\",\"rows\":[");
for (let k = 0; k < rankCount; k += 1) {
const i = rankAt[k];
const present = cells[i + 12];
const last = hasBit(present, BIT_LAST) ? cells[i + 6] : NaN;
const prev = hasBit(present, BIT_PREV_CLOSE) ? cells[i + 7] : NaN;
const volume = hasBit(present, BIT_VOLUME) ? cells[i + 9] : NaN;
const oi = hasBit(present, BIT_OI) ? cells[i + 10] : NaN;
if (k > 0) fb_text(",");
fb_text("[");
fbContract(cells, i);
fb_text(",");
fb_num(last);
fb_text(",");
const change = last > 0.0 && prev > 0.0 ? (last / prev - 1.0) * 100.0 : NaN;
if (isNaN(change)) fb_text("null");
else {
fb_text("{\"value\":");
fb_num(change);
fb_text(change >= 0.0 ? ",\"text_color\":\"theme.up\"}" : ",\"text_color\":\"theme.down\"}");
}
fb_text(",");
fb_num(volume);
fb_text(",");
fb_num(oi);
fb_text(",");
fb_num(volume >= 0.0 && oi > 0.0 ? volume / oi : NaN);
fb_text(",");
fb_num(volume >= 0.0 && last > 0.0 ? volume * last * optMult : NaN);
fb_text(",");
fb_num(volume >= 0.0 && totalVolume > 0.0 ? (100.0 * volume) / totalVolume : NaN);
fb_text("]");
}
fb_text("]}");
writeFrameBuffer(top);
}
// ── The levels: the most traded strikes and the strikes with the most open interest, named at the price axis ──
function near(a: f64, b: f64): bool { // two levels within 0.3% of each other would share a text row
return !isNaN(a) && !isNaN(b) && Math.abs(a - b) <= Math.abs(b) * 0.003;
}
function stepTaken(which: i32, price: f64, step: i32): bool { // an earlier text within 0.3% of this price already sits at this step
for (let j = 0; j < which; j += 1) if (tagSlots[j] == step && near(tagPrices[j], price)) return true;
return false;
}
function clearLevel(which: i32): void {
lines[which].delete(); // no-ops when never drawn
tags[which].delete();
tagPrices[which] = NaN;
tagSlots[which] = -1;
}
function drawLevel(which: i32, cells: StaticArray<f64>, i: i32, word: String, value: f64, ink: i32, style: LineStyle): void {
const strike = cells[i + 3];
lines[which].set(firstT, strike, t, strike).color(ink).width(1.0).style(style).extend(Extend.Both);
let step = 0; // the first step inward that no earlier text within 0.3% holds
while (stepTaken(which, strike, step)) step += 1;
tagPrices[which] = strike;
tagSlots[which] = step;
sb_clear();
sb_text(word);
sb_text(" ");
sbContract(cells, i);
sb_text(" ");
sbShort(value);
tags[which].set(56.0 + 132.0 * f64(step), strike).text(str_tag_sb).valign(VALIGN_BOTTOM); // plain muted text (the label template) whose box sits on the line, so the line never runs through it; 56 px in from the right edge clears the axis tags; each step is 132 px further in
}
function writeLevels(onThisChart: bool): void {
const cells = ranked;
for (let k = 0; k < LEVELS; k += 1) {
if (drawLevels && onThisChart && k < volCount) drawLevel(k, cells, volAt[k], k == 0 ? "V1" : k == 1 ? "V2" : "V3", volKey[k], LEVEL, LineStyle.Dashed);
else clearLevel(k);
}
for (let k = 0; k < LEVELS; k += 1) {
if (drawLevels && onThisChart && k < oiCount) drawLevel(LEVELS + k, cells, oiAt[k], k == 0 ? "OI1" : k == 1 ? "OI2" : "OI3", oiKey[k], LEVEL, LineStyle.Dotted);
else clearLevel(LEVELS + k);
}
}
// ── The card's words ──
function writeWords(): void {
const cells = ranked;
sb_clear();
if (rankCount == 0) sb_text(traded == 0 ? "No contract traded today" : "No contract ranks on this setting");
else {
sbContract(cells, rankAt[0]);
sb_text(": ");
if (rank == RANK_PREMIUM) sb_text("$");
sbShort(rankKey[0]);
if (rank == RANK_GAIN) sb_text("%");
}
str_read_sb();
sb_clear();
sb_text("Top contracts by ");
sb_text(RANK_WORDS[rank]);
sb_text(", ");
sb_int(expiries);
sb_text(expiries == 1 ? " expiry, " : " expiries, ");
sb_int(contracts);
sb_text(" contracts");
if (partial) sb_text(", partial summary");
str_title_sb();
}
// onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar measures the summary,
// writes the readings (NaN on history rows), the table, the levels and the card's words.
function onBar(): void {
close = bar.close();
t = bar.time();
if (isNaN(firstT) && !isNaN(t)) firstT = t;
let measured = false; // the live bar carried a summary with a contract in it
let served = false; // the live bar carried a summary: a contract, or the data plane's partial mark
if (bar.isLast() && !isNaN(t)) {
const n = in_state_cells();
if (n >= OPTION_VIEW_ROW_STATE) {
measure(n);
measured = contracts > 0;
served = measured || partial;
}
}
const cells = ranked;
const topAt = measured && rankCount > 0 ? rankAt[0] : -1;
out_top_strike(topAt >= 0 ? cells[topAt + 3] : NaN);
out_top_value(topAt >= 0 ? rankKey[0] : NaN);
out_total_volume(measured ? totalVolume : NaN);
out_call_volume(measured ? callVolume : NaN);
out_put_volume(measured ? putVolume : NaN);
out_put_call_volume(measured && callVolume > 0.0 ? putVolume / callVolume : NaN);
out_traded(measured ? f64(traded) : NaN);
out_partial(measured ? (partial ? 1.0 : 0.0) : NaN);
out_top_side(topAt >= 0 ? (cells[topAt + 2] > 0.0 ? 2.0 : 0.0) : bar.isLast() ? 1.0 : NaN);
if (!bar.isLast()) return;
if (measured) {
writeTable();
// The levels belong on the underlying's own chart (its close inside the strikes the summary lists), never on an
// option contract's own chart, whose price axis is the contract's premium.
writeLevels(!optionContract && !isNaN(close) && close >= lowStrike && close <= highStrike);
writeWords();
} else {
writeLevels(false);
sb_clear();
sb_text(served ? "No contract in the summary" : "Waiting for the option chain summary"); // an empty summary's totals count no contract
str_read_sb();
sb_clear();
sb_text("Top contracts, no summary read");
str_title_sb();
}
}How it works
The summary is a snapshot of now. input("state", option_contract_state.cells, { max_cells: 64, expiries: "nearest:24", strike_window_pct: 10, page_views: ["top", "totals"], rank: "@rank", side: "@side", rows: "@rows", min_volume: "@min_volume" }) asks the data plane for two views of the summary of the 24 nearest expiries with a strike within 10% of the underlying, on the live row: top, the contracts the settings can rank (the top Contracts listed on the ranking and the three most traded and the three most held on Calls or puts), each the summary's own 13-value tuple in the summary's order, and totals, the summary's counts and sums over every contract (the contracts, the expiries, the strikes it lists, the volumes and the partial mark). viewTuples() copies the ranked contracts out and ChainTotals reads the totals; at most 32 rows arrive, so max_cells: 64 holds them. History bars carry an empty block, so the ranking runs on the last bar.
The four rankings. A contract ranks only on readings its present mask carries:
- volume: the day's volume (bit 9), above 0;
- oi: the open interest (bit 10), above 0;
- premium: the day's volume times the last price (bit 6) times the market's option multiplier, the chart's market fact
market.option_multiplier(): 100 shares on a US stock, the future's point value on CME (50 on ES), 1 on a coin. The summary carries no traded premium, so this is the day's volume valued at the last price: an estimate that reads high when the price rose through the day and low when it fell. Where the chart does not know the multiplier, no contract ranks on premium and the column prints nothing, never a guessed 100; - gain: the last price over the prior session's close (bit 7), minus 1, in percent, among the contracts that traded at least Smallest volume for gain today (100 by default: contracts on a US stock and on CME, coins on crypto), so a contract that changed hands once does not lead.
Calls or puts keeps the calls or the puts alone. The top Contracts listed (10 by default, at most 25) are kept by insertion as the summary is read, the largest first, ties in the summary's order.
The table. Each row names the contract (SPY 17 Oct 660C: the root from its symbol code, ? when the code spells nothing, the expiry's label, its trade date on the market's clock, 15 Jan '27 in another year, the strike, C or P), then the last price, the change over the prior close in the up or down colour, the day's volume, the open interest, volume over open interest (above 1 when the day traded more than the open interest: positions opened or turned over), the premium as above and the contract's share of the day's volume across the summary. A reading a contract does not carry prints nothing. The caption names the ranking and, on premium, says it is an estimate; on an option contract's own chart with Strike levels on, it reads "On a contract's own chart, no levels" instead.
The levels. The three most traded contracts on the Calls or puts setting draw their strikes as dashed muted lines across the chart (V1 SPY 17 Oct 660C 84.2K) and the three with the most open interest as dotted muted lines (OI1 ...), each named in plain muted text at the price axis, since a level marks a strike, never a sign; a name within 0.3% of an earlier one steps 132 px inward, and every name is written through the one bounded tag slot, 48 bytes. They draw only on the underlying's own chart: never on an option contract's own chart, which market.option_contract() marks (i32(p_market_option_contract()) reads 1 there), since its price axis is the contract's premium and the strikes are not on it, and only where the close lies inside the strikes the summary lists, the rule that keeps them off a contract's chart where the host writes 0. The table fills on either chart. Strike levels turns them off.
The card. The headline is the top contract and its reading (SPY 17 Oct 660C: 84.2K, a dollar amount on premium, a percent on gain), in the up colour on a call and the down colour on a put; then the day's volume, put volume over call volume, the top strike and its value, the calls and the puts traded, and the contracts that traded at all. The title names the ranking and how many expiries and contracts the summary held, and says "partial summary" when the data plane marked it so.
What the settings do
- Rank by: Ranks by today's volume, oi (open interest: contracts still held open), premium (the money paid) or price gain.
- Calls or puts: Ranks calls (bets on a rise), puts (bets on a fall) or both.
- Contracts listed: How many contracts the table shows, from 3 to 25.
- Smallest volume for gain: The volume today a contract needs before it can rank by gain.
- Strike levels: Draws lines at the strikes (option price levels) of the three most traded and three most held contracts.
- Top contract: The top contract and its value, up colour for a call, down colour for a put.
- Day volume: Contracts traded today across every contract listed.
- Put/call volume: Put volume divided by call volume, where above 1 means more puts (bets on a fall) traded.
- Top strike: The top contract's strike (its price level).
- Its value: The top contract's value for Rank by, in contracts, USD or percent.
- Calls traded: Call contracts traded today.
- Puts traded: Put contracts traded today.
- Contracts that traded: How many contracts traded at least once today.
Where it runs
On crypto, it reads each coin's options summary, each contract's price, volume and open interest (contracts still held open). A copy you run from the editor (where you write and run indicators) reads it too. On a US stock or ETF with listed options, every indicator in your browser can read it. It is real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms (Limitations). It is real time if you have real-time CME data, and 10 minutes behind otherwise.
When data is missing
The headline says why instead of going blank. "Waiting for the option chain summary" means the live bar has no summary yet, or an empty one. "No contract in the summary" means the summary arrived incomplete, with no contract in it. "No contract traded today" shows before the open. "No contract ranks on this setting" means no contract has what the ranking needs. Gain needs the last price, the prior close and enough volume. An empty table keeps its caption.
Customize it
- Where the positions sit. Set Rank by to oi for the contracts with the most open interest; the levels already show both.
- The day's winners. Set Rank by to gain and raise Smallest volume for gain to keep it to contracts that really traded.
- Calls only. Set Calls or puts to calls: the table and the levels rank the calls.
- A longer list. Raise Contracts listed to 25.
Run it
- In the editor's Explorer, press the Templates icon ("Browse starter templates") and pick Top Contracts under HUDs.
- Press Run on a BTCUSDT chart: the table opens under the chart once the summary arrives, the six levels draw across it and the card sits at the bottom centre.
- At the editor's Console prompt, type
top_strike,total_volumeandput_call_volumeto read them on the live bar.
Concepts used
- Data sources for the
option_contract_statecelled class, its tuple, its knobs and the present mask - Chain page views for the
topandtotalsviews, and Options kit forviewTuplesandChainTotals - Cards, frames and panels for
panel.tableand its styled cells - Drawing objects for line handles extended across the chart and right-anchored labels
- A second builder for
TextBuilder.expiry, Panel frames forfbExpiryLabeland the Quick reference formarket.option_contract() - HUD cards and The default look for the card