Options kit

View as MarkdownOpen the editor

The chart serves a coin's listed options as options_chain cells, one ten-value tuple per contract, on the live bar only (Data sources).

The ./sdk/options module is the arithmetic a gamma map runs over that block, with nothing to import: The numbers a card prints as net GEX, the dealer regime, the gamma flip and the expected move come from GammaCurve and ExpectedMoves, one rule each, loaded at the chain's as-of (optionsAsOfMs, the live bar's close) on the market's clock and kind, where a US stock or ETF expiry stays live and priced until 15 minutes past its stamp and a US index expiry until its stamp (optionsLiveUntilMs, optionsYearsToGo): read The canonical numbers first. OptionsChain takes the chain, filters it by expiry and strike window, aggregates every contract into a strike table sorted ascending, and answers gamma exposure by strike, the call and put walls, max pain and the put/call open-interest ratio: the per-strike profile and the levels the Strike matrix recipe draws beside its board. Its older totals keep their numbers for the packages that read them, under rules a card must not print as the canonical words: totalNetGex() sums the chain's served gammas at each contract's own underlying, and zeroGamma() is the first crossing of a running sum over the strikes, which can sit far from spot and contradict the regime. Construct the object in onStart(), load it once on the live bar, read it in the same bar; no call allocates after construction, so the module never grows memory per bar. The same module prices the chain too: Greeks for one contract's greeks, IvTerm for the at-the-money IV by expiry and at constant maturities, and the free functions for the normal curve, the expected move and the market's own date (Pricing the chain).

ExportSignatureDefinition
OPTIONS_TUPLEconst OPTIONS_TUPLE: i32 = 10f64 values per contract in an options_chain block: [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega], side +1 for a call and -1 for a put
OptionsChainnew OptionsChain(maxStrikes); .load(cells, count, nowMs, spot, nearest = 0, windowPct = 0.0): i32; .loadExpiry(cells, count, nowMs, spot, expiryMs, windowPct = 0.0): i32; .loadTable(cells, count, rowWidth, spot, windowPct = 0.0): i32; .strikes(), .strike(i), .callOi(i), .putOi(i), .callGex(i), .putGex(i), .netGex(i), .callPain(i), .putPain(i); .totalCallGex(), .totalPutGex(), .totalNetGex(); .zeroGamma(), .callWall(), .putWall(), .maxPain(), .putCallRatio()One chain measured by strike: load() keeps the contracts expiring after nowMs (the nearest soonest expiries when nearest > 0, the strikes within windowPct percent of spot when windowPct > 0), sums open interest and gamma exposure per strike and side, and returns the strike count kept; loadExpiry() keeps one expiry alone; the readers answer for the chain last loaded. totalNetGex() and zeroGamma() keep their older numbers; the canonical net GEX and flip are GammaCurve's
Greeksnew Greeks(); .spot(side, s, strike, years, iv, rate = 0.04): f64; .forward(side, f, strike, years, iv, rate = 0.04): f64; fields price, delta, gamma, vega, theta, vanna, charm, d1, d2One contract priced by Black-Scholes on spot with no dividend, or by Black-76 on a forward; returns the price and fills every field (Greeks)
IvTermnew IvTerm(maxExpiries); .load(cells, count, nowMs, spot, zone = 0, rate = 0.0): i32; .expiries(), .expiry(i), .years(i), .days(i), .underlying(i), .forward(i), .atmStrike(i), .callIv(i), .putIv(i), .atmIv(i), .impliedMove(i); .front(), .nearest(days), .indexOf(expiryMs); .iv(days); .deltaStrike(i, side, delta), .deltaIv(i, side, delta)The at-the-money IV of every live expiry and at a constant maturity and the strikes at a target delta (The at-the-money term); impliedMove(i) keeps its older numbers, and the canonical expected move is ExpectedMoves.expectedMove(i)
GammaCurvenew GammaCurve(maxContracts, maxFlips = 8); .load(cells, count, asOfMs, nearest = 0, spot = NaN, zone = 0, kind = 0): i32; .loadStrikes(cells, count, asOfMs, multiplier, nearest = 0, spot = NaN, zone = 0, kind = 0): i32; .contracts(), .spot(), .gexAt(x), .netGex(), .regime(), .flip(), .flipCount(), .flipNear(k)Gamma exposure as a curve over hypothetical spot: the one rule behind net GEX, the dealer regime (its sign at spot) and the gamma flip (its root nearest spot) (The canonical numbers)
ExpectedMovesnew ExpectedMoves(maxContracts, maxExpiries = 64); .load(cells, count, asOfMs, spot = NaN, zone = 0, kind = 0): i32; .expiries(), .expiry(i), .years(i), .hours(i), .forward(i), .atmStrike(i), .atmIv(i), .expectedMove(i), .oneSigma(i), .indexOf(expiryMs); .horizonIv(years)Per live expiry the forward, the at-the-money IV, the expected move and the 1σ range, and the at-the-money IV at any horizon (The canonical numbers)
dealerRegimedealerRegime(netGex: f64): f64The regime by the sign of net GEX: 1 long gamma, -1 short gamma, 0 neutral, NaN with no reading
bsGammabsGamma(s, strike, iv, years): f64Black-Scholes gamma with no rate, per 1 of the underlying; the rule the chart prices the chain's gammas by
straddleExpectedMove, oneSigmaMovestraddleExpectedMove(price, iv, years): f64, oneSigmaMove(price, iv, years): f64The expected move (0.85 of the at-the-money straddle) and the one-standard-deviation range, in price (The expected move)
GAMMA_FLIP_REACH, GAMMA_FLIP_STEPconst ...: f64 = 0.5, 0.0025The flip search's reach either side of spot and its step, fractions of spot
normCdf, normPdfnormCdf(x: f64): f64, normPdf(x: f64): f64The standard normal distribution and density
expectedMove, straddleMoveexpectedMove(spot, iv, days): f64, straddleMove(spot, iv, days): f64The one-standard-deviation move under a deprecated name (read oneSigmaMove), and the straddle rule on calendar days (The expected move)
optionsTradeDayoptionsTradeDay(ms: f64, zone: i32): f64An instant's or an expiry stamp's trade date on the market's own clock, days since 1970-01-01
optionsAsOfMsoptionsAsOfMs(barOpenMs: f64, intervalMs: f64): f64The as-of a bar's options data is read at: the bar's close time, barOpenMs + intervalMs (bar.time() * 1000 and chart.interval_sec() * 1000), the bar's open where the host writes no interval; the chain and the strike rows of one bar read one clock (The market's own date and the chain's clock)
optionsLiveUntilMsoptionsLiveUntilMs(expiryMs: f64, zone: i32, kind: i32 = 0): f64The instant an expiry stops trading, its chain's last trade: 15 minutes past the stamp on a US stock or ETF chain (zone 1, OPRA: a PM expiry stamped 16:00 trades to 16:15), the stamp itself on a US index chain (kind 5, market.kind()), on Chicago and on UTC; a kind left out reads a stock; an expiry is live while it is after the as-of
optionsYearsToGooptionsYearsToGo(expiryMs: f64, asOfMs: f64, zone: i32, kind: i32 = 0): f64The time a contract is priced at, in 365-day years: on a US stock or ETF chain every contract to optionsLiveUntilMs, never under a second while it trades; on a US index chain, Chicago and UTC to the stamp; 0 or less once it has stopped trading
chainPricedAtMs, pricedAtFromGammachainPricedAtMs(cells, count, barOpenMs): f64, pricedAtFromGamma(...)Deprecated as the chain's clock: a time solved back from one contract's gamma, kept with its numbers for the packages that call it. Read the chain at optionsAsOfMs
totalVarianceIvtotalVarianceIv(years1, iv1, years2, iv2, years): f64The IV years out between two expiries, interpolated in total variance: the constant maturity IvTerm.iv(days) reads between its two anchors (The at-the-money term)
OPTIONS_YEAR_MSconst OPTIONS_YEAR_MS: f64 = 31536000000.0The 365-day year the chain's IV and greeks are quoted on
OPTION_PRINTS_TUPLE, OPTION_CONTRACT_FLOW_TUPLE, OPTION_CONTRACT_STATE_TUPLE, OPTION_SURFACE_TUPLE, OPTION_PRINTS_V2_TUPLEconst ...: i32 = 16, 17, 13, 9, 19f64 values per tuple in the option_prints, option_contract_flow, option_contract_state, option_surface and option_prints_v2 blocks, on crypto, CME and US stock charts (US listed options, Option surface, Block and RFQ prints), each ending with its present mask
OPTION_VIEW_ROW_CHAIN, OPTION_VIEW_ROW_STATE, VIEW_*const ...: i32 = 11, 16; the row layouts VIEW_CLASS_TUPLE 0 to VIEW_GEX_SUMS 9f64 values per row of a view block on options_chain and on option_contract_state, and the layout column 0 of each row names (Chain page views)
viewTuplesviewTuples(cells, count, rowWidth, tuple, out): i32Copies a view block's class tuples out as a class block, so code that read the whole block reads a projection unchanged
ExposureTable, GexCurve, ChainTotals, OiBoardnew ExposureTable(maxStrikes, maxExpiries = 64), new GexCurve(maxPoints), new ChainTotals(), new OiBoard(maxContributions, maxStrikes = 4096); each .load(cells, count, rowWidth)The fold views' readers: exposure by strike, day bucket and expiry; net GEX over a grid of spots; the chain summary's counts and sums; the open interest board's contributions and the change by strike (Chain page views)
BookStamp, OptionNumbers, VolTerm, SmileRows, SurfaceMatrix, StrikeProfilenew BookStamp(), new OptionNumbers(maxExpiries = 64), new VolTerm(maxExpiries = 64), new SmileRows(maxPoints), new SurfaceMatrix(maxColumns = 16, maxRows = 64), new StrikeProfile(maxStrikes, maxPoints = 1000); each .load(cells, count, rowWidth)The book folds' readers: the stamp, the options numbers, the term structure, the smile, the surface matrix and the strike profile; ExpectedMoves.loadNumbers(cells, count, rowWidth) reads the numbers' expiry rows into ExpectedMoves (Book folds)
DayHistorynew DayHistory(capacity); .push(day, value): bool; .count(), .capacity(), .span(window); .value(ago), .day(ago), .agoOf(day); .min(window), .max(window), .mean(window), .stdev(window), .rank(window), .percentile(window), .zscore(window), .quantile(window, q); .reset()One reading per trade day of a daily statistic, the newest last, and the readings of a window over it: the IV rank, the IV percentile, the z-score, the quantiles (A history of daily statistics)
NodeBoard, roleWord, NODE_ROLE_*new NodeBoard(maxStrikes); .load(strikes, values, count, spot, pct = 15.0): i32; .strikes(), .strike(i), .value(i); .top(), .gate(), .floor(), .ceiling(); .role(i), .standout(i), .isSignificant(i), .pctOfTop(i); .standoutCount(), .aboveNet(), .belowNet(); roleWord(code): string; the role codes NODE_ROLE_NORMAL 0 to NODE_ROLE_TOP 7One signed reading per strike sorted into the nodes a strike board labels: the top, the gate, the floor, the ceiling, the standouts and the significant strikes (Node roles)
expiryPresetCount, thirdFridayMs, EXPIRY_PRESET_*expiryPresetCount(expiries, count, nowMs, zone, preset, n): i32; thirdFridayMs(year, month, zone): f64; the presets EXPIRY_PRESET_FRONT 0 to EXPIRY_PRESET_COUNT 7How many of the sorted live expiries a preset keeps, on the market's trade days (Expiry presets)
StrikeVelocity, VELOCITY_WINDOWSnew StrikeVelocity(maxKeys, maxBars); .push(barMs, key, value): bool; .velocity(key, windowMin), .velocityPct(key, windowMin); .available(windowMin, hostIntervalMs): bool; .halo(key, w1, w2, w3): bool; .reset(); VELOCITY_WINDOWS 1, 5, 10, 15, 60, 240, 1440How each strike's reading moved over a window of minutes (Strike velocity)
flowSideCode, flowScoreflowSideCode(aggressor, outside): i32; flowScore(side, cp, moneyness, dteDays, sizeVsOi, repeatHits): f64The side of the quote a print hit and the print's signed score, -100 to 100 (Flow score)
DERIVED_ROOTS, derivedRootCount, derivedRoot, derivedRatioderivedRootCount(root): i32, derivedRoot(root, i): string, derivedRatio(close, rowUnderlying): f64The roots a chart's levels can be read through, and the ratio a derived level is drawn at (Derived roots)
The strike table on a price axis: call exposure drawn to the right of each strike and put exposure to the left, the call wall above spot and the put wall below it in the colored pencil, the running net sum climbing from the lowest strike and crossing the axis at the zero-gamma point, and max pain circled among the strikes.strikeput GEXcall GEX66k65k64k63k62k61k60k59k58k57kzero gammaspotcall wallput wallmax painnet GEX, summed from the lowest strike up
  1. Strikes on the price axis, ascending from the bottom: strike(i), with i 0 the lowest.
  2. Call GEX to the right of each strike and put GEX to the left: callGex(i) and putGex(i), both stored positive.
  3. The running net sum, calls minus puts from the lowest strike up: zeroGamma() is where it first crosses zero, placed between two strikes by the two sums' magnitudes. That is the older rule, kept for the packages that read it; the gamma flip a card prints is GammaCurve.flip() (The canonical numbers).
  4. Call wall, the strike at or above spot holding the most call open interest; put wall, the strike at or below spot holding the most put open interest.
  5. Max pain, the listed strike that pays holders the least, circled among the strikes.

Per contract, with spot_c the contract's underlying when above 0 and otherwise the spot you passed, and mult its multiplier when above 0 and otherwise 1:

  • callGex(i) and putGex(i) sum gamma * oi * mult * spot_c * spot_c * 0.01 over the calls and the puts at the i-th strike: the dollar change of the open interest's delta for a 1% move of spot, in USD per 1% move. Both are stored positive (a listed option's gamma is positive).
  • netGex(i) is callGex(i) - putGex(i): the dealer-naive sign convention, calls positive and puts negative, taking dealers as long the calls customers sold them and short the puts customers bought. totalCallGex(), totalPutGex() and totalNetGex() sum the table from the lowest strike up. totalNetGex() keeps that number for the packages that read it; it sums the chain's served gammas, so on a venue that serves its own greeks, or inside 15 minutes of an expiry, it can differ from the net GEX a card prints, GammaCurve.netGex(), which prices every gamma again at the chain's as-of.
  • callOi(i) and putOi(i) are the open interest summed per side at the strike, in the chain's own unit (coins on Deribit, contracts on CME). putCallRatio() is total put over total call open interest, NaN when the call side holds none.
  • callWall() is the strike at or above spot holding the most call open interest, putWall() the strike at or below spot holding the most put open interest; NaN when no strike on that side has any. Ties keep the lower strike.
  • maxPain() is the listed strike S minimising sum(callOi * max(0, S - K)) + sum(putOi * max(0, K - S)) over the table's strikes K, the settlement price that pays holders the least; ties keep the lower strike, NaN on an empty table.
  • zeroGamma() walks the strikes upward summing netGex: the strike where the running sum lands on exactly 0, or the point between the two strikes where it changes sign, placed by the two sums' magnitudes (prev + (next - prev) * |cum_prev| / (|cum_prev| + |cum_next|)); NaN when the sum never changes sign. It keeps that number for the packages that read it, under a deprecated name: it is not the gamma flip. Print GammaCurve.flip() as the flip.
  • strikes() is the table size, strike(i) the i-th strike ascending (0 the lowest); every indexed reader is NaN outside 0..strikes() - 1. Before the first load() the table is empty: the totals read 0, everything else NaN.

Reading the chain on the live bar

History bars carry an empty block and the chain arrives on the newest row, so the read sits under bar.isLast(): in_chain_cells() is the f64 count the bar carries (-1 on a bar without a block), in_chain_view() is the block itself, read in place from the one buffer the build reserves at module start, and load() takes that array, the count, the chain's as-of in milliseconds (optionsAsOfMs over the bar's open and chart.interval_sec(): the live bar's close) and the chart's close as spot; GammaCurve also takes the market's zone (market.zone()) and kind (market.kind(), a stock when left out), on which a US stock or ETF expiry stays live until 15 minutes past its stamp and a US index expiry until its stamp. The numbers hold on the following bars, so an output or a card written in onBar() reads the same chain until the next live bar refreshes it. Net GEX and the flip come from a GammaCurve over the same expiries; the strike table gives the walls and max pain.

wrun
param("nearest_expiries", 0, { min: 0, max: 24, description: "Expiries counted: 0 = every listed expiry, N = the N nearest" });
param("window_pct", 0, { min: 0, max: 50, description: "Strikes the walls read: percent around spot each side, 0 = the whole chain" });
input("close", ohlcv.close); // the chart's own close: spot
input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" });
market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp
chart.interval_sec(); // the bar's length: the chain is read at the live bar's close
output("net_gex", none, overlay, { description: "Net gamma exposure at spot over the counted expiries, USD per 1% move; live bar only" });
output("flip", none, overlay, { description: "The gamma flip over the counted expiries: the GEX curve's zero nearest spot" });
output("call_wall", none, overlay, { description: "The heaviest call strike at or above spot" });
output("put_wall", none, overlay, { description: "The heaviest put strike at or below spot" });
output("max_pain", none, overlay, { description: "The strike that pays option holders the least" });

let chain = new OptionsChain(1);
let curve = new GammaCurve(1);
let nearest: i32 = 0;
let windowPct: f64 = 0.0;
let zone: i32 = 0;
let intervalMs: f64 = 0.0;

function onStart(): void {
  // Construct here: the per-strike and per-contract buffers are the module's only allocation.
  chain = new OptionsChain(512);
  curve = new GammaCurve(in_chain_max_cells);
  nearest = i32(p_nearest_expiries());
  windowPct = p_window_pct();
  zone = i32(p_market_zone());
  intervalMs = p_chart_interval_sec() * 1000.0;
}

function onBar(): void {
  if (bar.isLast()) {
    const n = in_chain_cells();
    if (n >= OPTIONS_TUPLE) {
      const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer
      const asOfMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close
      chain.load(cells, n, asOfMs, bar.close(), nearest, windowPct);
      curve.load(cells, n, asOfMs, nearest, bar.close(), zone);
    }
  }
  out_net_gex(curve.netGex());
  out_flip(curve.flip());
  out_call_wall(chain.callWall());
  out_put_wall(chain.putWall());
  out_max_pain(chain.maxPain());
}

Read last 1 net_gex at the editor's Console prompt for the chain's net GEX, or loop chain.strikes() and draw chain.netGex(i) at chain.strike(i) into a frame for the docked profile the Greek exposure recipe shows.

Expiries, the strike window and the table size

The three load() filters as a funnel: every contract in the block enters at the top, about 1,550 on a BTC chain; the first cut drops contracts whose expiry is not after now, keeping the N nearest expiries when asked; the second drops strikes outside the window around spot; the third drops the strikes farthest from spot once the table holds maxStrikes; what comes out of the neck is the strike table, sorted ascending.droppedexpiry after nownowMs, neareststrikes within the windowspot, windowPctthe nearest maxStrikesfarthest from spot firstevery contractlive expiriesin the windownearest spot1,550 on BTC60k61k62kthe strike table, sorted ascending
  1. Every contract in the block enters at the top, about 1,550 on a BTC chain.
  2. Expiry: a contract whose expiry_ms is not after nowMs drops out; nearest > 0 keeps only the N soonest expiries.
  3. Strike window: windowPct > 0 drops the strikes outside the window around spot.
  4. Table size: once maxStrikes strikes are in, the strikes farthest from spot drop first.
  5. The strike table comes out of the neck, sorted ascending; load() returns its size.

load(cells, count, nowMs, spot, nearest, windowPct) applies three filters before anything is summed:

  • Expiry. Only contracts with expiry_ms > nowMs count; pass the chain's as-of, optionsAsOfMs(bar.time() * 1000.0, chart.interval_sec() * 1000.0), the live bar's close: the chain is served inside the live bar, and a coarse bar's open lags it by up to the bar, so an expiry settled since would still count (on a daily bar the close runs ahead by as much, so read a same-day expiry on an intraday chart). OptionsChain keeps each expiry to its stamp; GammaCurve and ExpectedMoves take the market's zone and kind and keep a US stock or ETF expiry 15 minutes past it. nearest > 0 keeps the nearest soonest of those expiries, so nearest = 1 is the front expiry alone and nearest = 2 the front two; asking for more expiries than the chain lists keeps them all, and 0 keeps every live expiry. There is no cap on distinct expiries. Whether an expiry is today is a calendar question, never the hours left: at 11:00 tomorrow's 10:00 expiry is 23 hours away and still 1 DTE. Compare the expiry's trade date with today's on the market's own clock: sessionTradeDate() with market.zone(), the calendar time.trade_date uses (The market's own calendar), as the Strike matrix recipe does.
  • Strike window. windowPct > 0 keeps the strikes within windowPct percent of spot on each side, bounds included (spot * (1 - windowPct / 100) to spot * (1 + windowPct / 100)); 0 keeps every strike. The window narrows the whole table: the walls, the totals, zeroGamma() and max pain are all measured over the strikes inside it. The Strike Matrix template narrows only its walls: its max pain is the reading of a chain loaded with windowPct 0, its walls those of a chain loaded with its window, and its flip comes from a GammaCurve over every live expiry; an indicator that wants both tables constructs two OptionsChain objects in onStart() and loads each.
  • Table size. maxStrikes (clamped to at least 1) is the most distinct strikes the table holds; the Strike Matrix keeps 512. When a chain lists more, the strikes farthest from spot are dropped first, whatever order the contracts arrive in (two strikes at the same distance: the lower goes first), so the table is always the maxStrikes strikes nearest the chart. The template instead refuses the strikes that arrive after its table is full.

A contract whose strike or open interest is not above 0 is skipped, so a strike only enters the table through live open interest; a contract whose expiry is not a number is skipped too. A gamma that is not a number poisons its strike's exposure and the totals, exactly as the template's sums do, and the walls, max pain and the open-interest ratio never read gamma, so they stay finite.

A strike matrix on the price axis

The per-strike readings are a table whose rows are prices, which is what plot.matrix draws: one row per strike docked on the price axis, one column per expiry, each cell filled from a diverging palette (Price canvases). Load one OptionsChain per expiry window on the live bar, write the board into a frame (prices ascending, one cell row per price, the ATM strike in highlight) and declare the matrix over it; the chart keeps the rows on their prices as you pan and zoom. The frame rides wrun-4, which a frame(...) declaration stamps for you.

wrun
input("close", ohlcv.close);
input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" });
const board = frame("board", { max_bytes: 65536 });
plot.matrix({ name: "gex_board", frame: board, dock: "right", columns: ["Front", "Next", "Third"], price_column: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, format: "si", tooltip: "{{column}} net GEX {{value:usd}} at {{price}}" });

The Strike Matrix recipe is the whole file: net gamma exposure by strike across the four nearest expiries (a setting), the ATM row highlighted, rewritten on every live bar.

Option strikes, bar by bar

The ./sdk/option-strikes module reads the option_strikes source (Data sources): every bar's own strike snapshot, twelve values per (expiry, strike) row, its exposures already in dollars and its open interest in the chain's own size (the coin on a crypto chain, contracts on US listed options and CME). OptionStrikes folds one block into a strike table sorted ascending and answers the questions OptionsChain answers, on every bar instead of the live one.

ExportSignatureDefinition
OPTION_STRIKES_TUPLEconst OPTION_STRIKES_TUPLE: i32 = 12f64 values per row in an option_strikes block: [strike, expiry_ms, net_gex, call_gex, put_gex, net_dex, net_vex, call_oi, put_oi, call_iv, put_iv, underlying]
strikesPricedAtMsstrikesPricedAtMs(cells, count, multiplier, barOpenMs, intervalMs = 0): f64Deprecated as the rows' clock: a time solved back from the rows' gamma, kept with its numbers for the packages that call it and for the kit fold's curve row (pricedAtMs()). Read the rows at optionsAsOfMs
OPTION_STRIKES_KIT_ROW, KIT_STRIKE_ROW, KIT_LEVELS_ROW, KIT_CURVE_ROWconst ...: i32 = 14, 0, 1, 2f64 values per row of a strike kit fold (fold: "kit"), and its row layouts
OptionStrikesnew OptionStrikes(maxStrikes); .load(cells, count, nearest = 0): i32; .loadLevels(cells, count): i32; .value(i); .strikeCount(), .strike(i), .netGex(i), .callGex(i), .putGex(i), .netDex(i), .netVex(i), .callOi(i), .putOi(i), .callIv(i), .putIv(i), .iv(i); .totalNetGex(), .totalCallGex(), .totalPutGex(), .totalNetDex(), .totalNetVex(), .totalCallOi(), .totalPutOi(), .putCallRatio(); .zeroGamma(), .callWall(), .putWall(), .maxPain(), .underlying(); .gexAtSpot(), .gammaRegime(), .gammaFlip(), .curveSpot(), .pricedAtMs(); .refused(), .refusedReason()One bar's snapshot by strike: load() keeps the rows of the nearest soonest expiries when nearest > 0, folds the rows of one strike into one table row and returns the strike count kept, or -1 when the kept rows hold more distinct strikes than maxStrikes; the five curve readers read a kit fold's curve row (NaN without one)

Where it differs from OptionsChain, each because the rows arrive measured:

  • netGex(i), callGex(i), putGex(i), netDex(i), netVex(i), callOi(i) and putOi(i) sum the strike's rows across its expiries; a NaN field (a side the strike does not list) counts as 0. callIv(i) and putIv(i) weight each row's IV by that side's open interest, and iv(i) weights both sides together, across every expiry: never a sum of percentages, NaN where no row reports one.
  • callWall() and putWall() are the strikes holding the largest call and put dollar gamma (callGex(i), putGex(i)), at any distance from spot; ties keep the lower strike, NaN when no strike has any.
  • zeroGamma() is a strike: the first one, walking up from the lowest, where the running sum of netGex reaches zero or turns to the other sign. It is never a point between two strikes, and NaN when the sum never turns. It keeps that number for the packages that read it, under a deprecated name: the gamma flip of the rows is GammaCurve.loadStrikes(...) and then flip(), below.
  • maxPain() is the chain's definition over the table's open interest, NaN when the table holds none; underlying() is the underlying price of the soonest kept expiry.
  • The table never truncates: a block with more distinct kept strikes than maxStrikes is refused whole. load() returns -1, every reading is empty and refused() is true until the next load. nearest filters before the table fills, and a table built with the input's in_<name>_max_cells never overflows.
  • Every bar loads its own block, so a bar with no snapshot (an empty block, count 0) empties the readings: the totals read 0, everything else NaN.

The front expiry's net gamma, flip and walls on every bar. A bar's rows are its newest minute of strike rows, and that fold minute closes when the bar does, so GammaCurve.loadStrikes() prices the curve at the bar's close, optionsAsOfMs(bar.time() * 1000, chart.interval_sec() * 1000), the clock a card reading the chain reads on the same bar, on the market's zone and kind (market.zone(), market.kind(): a US stock or ETF expiry stays live and priced until 15 minutes past its stamp, a US index expiry until its stamp); each row is a call and a put with that side's open interest and IV, and market.option_multiplier() declares the multiplier the curve reads:

wrun
input("close", ohlcv.close);
input("strikes", option_strikes.cells, { max_cells: 1200, expiries: "nearest:1" });
market.option_multiplier(); // 100 on a US stock, the point value on CME, 1 on a coin
market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp
chart.interval_sec(); // the bar's length: the rows are read at the bar's close, when their fold minute closes
output("net_gex", line, lower, { description: "Net gamma exposure of the front expiry at spot, USD per 1% move" });
output("flip", line, overlay, { description: "The gamma flip of the front expiry: the GEX curve's zero nearest spot" });
output("call_wall", line, overlay, { description: "The strike holding the most call gamma" });
output("put_wall", line, overlay, { description: "The strike holding the most put gamma" });

let strikes = new OptionStrikes(1);
let curve = new GammaCurve(1);

function onStart(): void {
  strikes = new OptionStrikes(in_strikes_max_cells);
  curve = new GammaCurve(in_strikes_max_cells * 2); // a call and a put per row
}

function onBar(): void {
  const n = in_strikes_cells();
  if (strikes.load(in_strikes_view(), n > 0 ? n : 0) <= 0) return;
  const multiplier = p_market_option_multiplier();
  const asOfMs = optionsAsOfMs(bar.time() * 1000.0, p_chart_interval_sec() * 1000.0); // the rows' as-of: the bar's close
  curve.loadStrikes(in_strikes_view(), n, asOfMs, multiplier, 0, bar.close(), i32(p_market_zone()));
  out_net_gex(curve.netGex());
  out_flip(curve.flip());
  out_call_wall(strikes.callWall());
  out_put_wall(strikes.putWall());
}

Chain page views

An input that names a view of the chain page (Data sources) reads less than the whole chain. A projection's contracts arrive as the class's own tuples, so every reader on this page reads them as it reads the whole block. A fold arrives as a view block: rows of OPTION_VIEW_ROW_CHAIN (11) f64 values on options_chain and OPTION_VIEW_ROW_STATE (16) on option_contract_state, column 0 the row's layout and the layout's fields after it. Size the input's max_cells for those rows. A projection the same input names rides the same block, one VIEW_CLASS_TUPLE row per contract.

LayoutRowReader
VIEW_CLASS_TUPLE (0)[0, the class tuple...]viewTuples(cells, count, rowWidth, tuple, out) copies them out as a class block
VIEW_STRIKE_TABLE (7)[7, strike, call_oi, put_oi, call_gex, put_gex]OptionsChain.loadTable(cells, count, rowWidth, spot, windowPct): every reader answers as after load() on the chain the view folded
VIEW_EXPOSURE_STRIKE (4), VIEW_EXPOSURE_BUCKET (5), VIEW_EXPOSURE_EXPIRY (6)[4, strike, calls, puts, readings], [5, strike, six day buckets], [6, expiry_ms, days, net, counted]ExposureTable: .strike(i), .calls(i), .puts(i), .net(i), .readings(i), .bucket(i, b), .expiries(), .expiry(e), .days(e), .expiryNet(e), .counted(e)
VIEW_GEX_POINT (8), VIEW_GEX_SUMS (9)[8, point, gex], [9, vex, dealer_delta, contracts]GexCurve: .points(), .gex(p), .vex(), .dealerDelta(), .contracts()
VIEW_TOTALS (1)[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]ChainTotals: one reader a field
VIEW_OI_CELL (2), VIEW_STRIKE_CHANGE (3)[2, strike, column, a, b], [3, strike, change]OiBoard: .strike(i), .column(i), .a(i), .b(i) per contribution in the chain's order; .changeStrike(k), .change(k) per strike

Each reader follows the module's contract: construct it in onStart() with the most rows it holds, load() it on the live bar, read it in the same bar; nothing allocates after construction, and a block larger than the reader holds is refused whole (load() returns -1). The fold's sums are the template's to the bit: the data plane sums in the chain's order with the template's operations.

wrun
input("close", ohlcv.close);
input("chain", options_chain.cells, { max_cells: 2000, page_views: ["strike_table"] });
output("net_gex", line, lower, { description: "Net gamma exposure, USD per 1% move" });

let chain = new OptionsChain(1);

function onStart(): void { chain = new OptionsChain(512); }

function onBar(): void {
  const n = in_chain_cells();
  if (!bar.isLast() || n <= 0) return;
  if (chain.loadTable(in_chain_view(), n, OPTION_VIEW_ROW_CHAIN, bar.close()) > 0) out_net_gex(chain.totalNetGex());
}

An option_strikes input declaring fold: "kit" reads each bar already measured with OptionStrikes' rules: rows of OPTION_STRIKES_KIT_ROW (14) values, one KIT_LEVELS_ROW with the bar's totals, walls, flip, max pain and spot when levels is set, then the KIT_STRIKE_ROW rows [0, strike, value] at the strikes the input's window draws, value the fold's lens. OptionStrikes.loadLevels(cells, count) reads them: every snapshot-wide reading as load() gives it, strike(i) and value(i) per strike (the other per-strike readers read NaN), and -1 with refused() true when the bar held more rows than the input's max_cells. With curve: true beside levels a KIT_CURVE_ROW [2, gex_at_spot, gamma_flip, curve_spot, priced_at_ms, contracts] follows each levels row. With the curve the fold reads each bar as the example under Option strikes, bar by bar reads it: at the bar's as-of (optionsAsOfMs, the bar's close), over the week of its rows (each expiry still trading then on the market's zone and kind, 7 or fewer trade days out), the levels row and the strike rows included; a bar whose week keeps no strike arrives empty. The curve row is GammaCurve.loadStrikes(...) over that week with nearest's live expiries, each live and priced to its chain's last trade (15 minutes past the stamp on a US stock or ETF chain, the stamp on a US index chain, the CME Group and crypto). gexAtSpot(), gammaRegime() and gammaFlip() read the numbers netGex(), regime() and flip() give there, curveSpot() its S0 and pricedAtMs() the as-of, each NaN without a curve row. One difference stays: where the nearest live expiry reports no underlying, the curve reads NaN, not the chart's close (a stored row always carries one).

Book folds

An options_chain input that names a book fold (numbers, vol_term, smile, surface, strike_profile; Data sources) reads the data plane's finished numbers over the chain page's whole book: the numbers the chart's own options panes draw. Its rows are as wide as its widest word (OPTION_VIEW_ROW_NUMBERS 12, OPTION_VIEW_ROW_VOL_TERM 16, OPTION_VIEW_ROW_SMILE 11, OPTION_VIEW_ROW_SURFACE 11, OPTION_VIEW_ROW_STRIKE_PROFILE 13): pass that width to every reader of the block, and size max_cells for the rows. Each reader reads its own layouts and skips the rest, so one block naming several words feeds every reader. A missing reading is NaN.

LayoutRowReader
VIEW_BOOK_STAMP (12)[12, priced_at_ms, s0, family, oi_unit, greeks, contracts, expiries, dropped, book_kind, version], once a blockBookStamp: .pricedAtMs(), .spot() (NaN when no contract's expiry has an anchor, which a book holding contracts can answer beside its rows), .family() (1 US, 2 CME Group, 3 crypto), .oiUnit() (0 coin, 1 contracts), .greeks() (0 the venue's, 1 a model's), .contracts(), .empty() (a book with no contract: the stamp alone, no fold row, the pane clears; a NaN spot alone is not empty)
VIEW_NUMBERS (10)[10, kind, ...]: NUMBERS_SCOPE rows (scope, S0, net GEX, regime, flip, roots, four more roots), NUMBERS_EXPIRY rows (expiry, forward, ATM strike, ATM IV, years, expected move, one sigma, hours, both moves in percent), NUMBERS_HORIZON rows (years, ATM IV, both moves as fractions of 1)OptionNumbers: .scopeIndex(scope), .netGex(i), .regime(i), .flip(i), .expiryMs(e), .atmIv(e), .expectedMove(e), .horizonIv(h); ExpectedMoves.loadNumbers answers ExpectedMoves' readers with the data plane's moves
VIEW_VOL_TERM (13)[13, expiry_ms, days, forward, atm_iv, str25, str15, rr25, rr15, rr10, fly25, fly15, oi, call_oi, put_oi, flags]VolTerm: one reader a field, .wingOutside(i), .oneSidedAtm(i), .noQuote(i)
VIEW_SMILE_SERIES (14), VIEW_SMILE_POINT (15)[14, series, expiry_ms, forward], [15, strike, iv0, iv1, iv2]SmileRows: .seriesPicked(s), .seriesExpiryMs(s), .points(), .strike(i), .iv(i, s)
VIEW_SURFACE_CELL (16)[16, tag, at, value]: tag -1 a column, -2 a row, -3 a column's summary, -4 the highlight, else a cell's rowSurfaceMatrix: .columns(), .rows(), .columnExpiryMs(c), .rowStrike(r), .highlightRow(), .summary(c), .value(r, c)
VIEW_PROFILE_STRIKE (17), VIEW_PROFILE_LEVELS (18), VIEW_PROFILE_POINT (19)[17, strike, call_oi, put_oi, call_gex, put_gex, net_gex, cum_net_gex, dex, vex], [18, max_pain, call_wall, put_wall, call_oi, put_oi, oi_total, pc_oi, net_gex, net_dex, net_vex, strikes, clipped_right], [19, x, gex]StrikeProfile: the strike rows, .maxPain(), .callWall(), .putWall(), .putCallRatio(), .totalNetGex(), .points(), .pointX(p), .pointGex(p)

SurfaceMatrix.highlightRow() is the row nearest the book's spot S0, the median underlying of its nearest live expiry: the row the chart's built-in Options Surface bolds. That spot can sit off the chart's price (after hours, between chain snapshots), so a bold row that says where the price is reads the chart's close instead, where the close is in the strikes' units: the row whose rowStrike(r) is nearest bar.close() on a chart priced in the strikes' currency (market.quote_is_usd() on the US dollar chains) that is no option contract's own (market.option_contract()), with the close within half to twice BookStamp.spot(); otherwise highlightRow() (Volatility surface does this).

Max pain's curve, one expiry at a time

loadExpiry(cells, count, nowMs, spot, expiryMs, windowPct) is load() over the contracts of ONE expiry, the one whose expiry_ms is exactly expiryMs: every reader then answers for that expiry alone, its walls, its zeroGamma() and its max pain (that expiry's gamma flip is GammaCurve.load(...) with nearest set to the expiry's rank). Under max pain sits a curve, one point per listed strike S:

  • callPain(i) is sum(callOi(k) * max(0, S - strike(k))): what the call holders collect if the expiry settles at the i-th strike;
  • putPain(i) is sum(putOi(k) * max(0, strike(k) - S)), the put holders' share;
  • maxPain() is the strike where the two summed are least.

The unit is open interest times price, no multiplier (47 contracts 10 below the settle read 470); times the multiplier it is money. Loop chain.strikes() and draw the two values at chain.strike(i) for the curve under one expiry's max pain, or load each listed expiry in turn (IvTerm's expiry(i) lists them) for max pain by expiry.

Pricing the chain

The chain carries each contract's mark IV, its gamma, its delta and its vega; everything else is priced from the IV. mark_iv rides the tuple in percentage points, so the IV every function below takes is mark_iv / 100, a decimal (0.152 for 15.2%), and time to expiry is in 365-day years, (expiry_ms - nowMs) / OPTIONS_YEAR_MS, the year the IV is quoted on.

Greeks: one contract priced

new Greeks() once in onStart(); then per contract greeks.spot(side, s, strike, years, iv, rate) (Black-Scholes on the spot s, no dividend) or greeks.forward(side, f, strike, years, iv, rate) (Black-76 on the forward f), each returning the price and filling the fields. side above 0 is a call, else a put, as the tuple's side; rate is a decimal, 0.04 when left out. Pick the model by what the underlying is: a US stock chain's underlying is the stock's spot (Black-Scholes, with the rate), a futures chain's is the futures price and a crypto chain's the venue's own forward (Black-76; crypto chains are quoted at a rate of 0).

FieldMeaningUnit
pricethe option's valueprice
deltathe price change for 1 of the underlying: a call 0 to 1, a put -1 to 0 (Black-76 discounts it by e^(-rate * years))per 1 of the underlying
gammathe delta change for 1 of the underlyingper 1 of the underlying
vegathe price change for one vol point (the IV up 0.01)per vol point
thetathe price change as one calendar day passes; negative for a long optionper calendar day
vannathe delta change for one vol pointper vol point
charmthe delta change as one calendar day passes, spot held: the delta a hedge sheds or gains overnightper calendar day
d1, d2the two Black-Scholes termsnone

At or past expiry (years not above 0) the price is the intrinsic value, the delta 1 (or -1 for a put) in the money, 0 out of it and a half at the strike, and every other greek 0. A strike or an underlying that is not above 0, an IV that is not above 0 before expiry, or any input that is not a number reads NaN in every field. Nothing allocates: price as many contracts per bar as the chain holds.

Exposure is a greek times open interest times the multiplier, signed by who holds it. With dealers long the calls and short the puts (the gamma map's convention), a strike's vanna exposure is the calls' vanna * oi * multiplier minus the puts': the shares the dealers' hedge must sell when the IV rises one point (buy, when the sum is negative).

The at-the-money term

IvTerm measures the chain's implied volatility the way volatility pages do. Per live expiry, the at-the-money IV is the mean of the call and the put IV at the strike nearest the expiry's forward (one side where the other has no IV), among the strikes within 20% of the expiry's underlying; the forward is the underlying times e^(rate * years), so pass the rate on a US stock's chain and 0 where the underlying already is the forward. Between two expiries the IV is interpolated in total variance, IV squared times years, to a constant maturity:

text
w(T) = w1 + (w2 - w1) * (T - T1) / (T2 - T1),   w = atm_iv^2 * years
iv(days) = sqrt(w(days / 365) / (days / 365))

An expiry that settles today is listed (days(i) reads 0) but never anchors the interpolation: its IV swings with the hours left. Before the first anchor iv(days) reads the first anchor's IV, past the last the last one's; with no anchor it reads NaN. The step between two anchors is totalVarianceIv(years1, iv1, years2, iv2, years), exported on its own: an Indicator that builds its own curve over the expiries (the Options sentiment recipe reads each expiry's at-the-money IV and wings from the surface) reads its constant maturities through the same arithmetic. It reads NaN when the variance it reaches or years is not above 0.

  • load(cells, count, nowMs, spot, zone, rate) keeps the contracts with a strike above 0 expiring after nowMs, the maxExpiries nearest expiries, and returns how many it kept, ascending. zone is the market.zone() code, the calendar days(i) counts on.
  • expiry(i), years(i), days(i) (its trade date minus today's, 0 on the expiry day), underlying(i), forward(i), atmStrike(i), callIv(i), putIv(i) and atmIv(i) read the i-th expiry, NaN outside 0..expiries() - 1.
  • iv(days) is the constant-maturity IV days calendar days out.
  • front() is the first expiry after today, nearest(days) the anchor whose time to expiry is nearest days (the expiry a "30-day" skew reads), indexOf(expiryMs) an expiry's row; each -1 when there is none.
  • deltaStrike(i, side, delta) is the strike of the i-th expiry where the absolute delta equals delta (0.25 for the 25 delta wing) on the calls (side above 0) or the puts, the delta read off each contract's IV at the expiry's forward without discounting (the convention skew is quoted in), interpolated between the two listed strikes around it; deltaIv(i, side, delta) is the IV there. A risk reversal is deltaIv(i, 1.0, 0.25) - deltaIv(i, -1.0, 0.25).
  • impliedMove(i) is straddleMove(underlying(i), atmIv(i), years(i) * 365), in price. It keeps that number for the packages that read it, but it prices the straddle on the expiry's underlying and this term's own at-the-money pick, so it is not the expected move a card prints: read ExpectedMoves.expectedMove(i), priced on the expiry's forward (its median underlying) at the mean of the IVs listed at the strike nearest it (The canonical numbers).

load keeps a reference to the block, never a copy: read deltaStrike and deltaIv on the bar that loaded it.

The expected move

The expected move is 0.85 times the at-the-money straddle, priced at the forward with no rate: the number flow desks quote and the one every OpenMarket surface prints as "Expected move". straddleExpectedMove(price, iv, years) is 0.85 * 2 * price * (2 * N(iv * sqrt(years) / 2) - 1), with price the expiry's forward or a horizon's anchor. The one-standard-deviation range is another number, oneSigmaMove(price, iv, years) = price * iv * sqrt(years), about 1.47 times the expected move for any short expiry; a card names it "1σ range (68%)", never "Expected move". Both are in price; divide by the price for a percent. ExpectedMoves reads both per expiry and at any horizon.

The older names keep their numbers: straddleMove(spot, iv, days) is the straddle rule on calendar days (30 days at a 14.9% IV reads 2.9% of spot, 3 days at 11% reads 0.68%), and expectedMove(spot, iv, days) is the one-standard-deviation move, iv * spot * sqrt(days / 365), under a name that says otherwise (deprecated: read oneSigmaMove).

The market's own date and the chain's clock

optionsTradeDay(ms, zone) is the trade date of an instant or an expiry stamp on the market's own clock, in days since 1970-01-01: New York's date on a US stock (zone 1), Chicago's on CME, whose trade day opens at 17:00 (zone 2), UTC on crypto (zone 0). A stamp at exactly 00:00 UTC is a date a venue stamped and reads as that date. Whether an expiry is today is a calendar question: optionsTradeDay(expiry, zone) == optionsTradeDay(now, zone), never the hours left.

optionsAsOfMs(barOpenMs, intervalMs) is the as-of a bar's options data is read at: the bar's close time, bar.time() * 1000 plus chart.interval_sec() * 1000, the bar's open where the host writes no interval. The chain names the moment it was served to no module, and a bar's strike rows are its newest minute, which closes when the bar does, so a card reading the chain and a card reading the strike rows read one clock on one bar, never a time solved back from a gamma (two solves of one minute name two times, and a same-day gamma scales with 1 / sqrt(T)). Pass it as nowMs (or asOfMs) wherever the hours to expiry matter.

optionsLiveUntilMs(expiryMs, zone, kind) is the instant an expiry stops trading, its chain's last trade, on the market's clock and kind: on a US stock or ETF chain (zone 1, OPRA) 15 minutes past the stamp, since a PM expiry is stamped 16:00 and its options trade to 16:15; on a US index chain (kind 5: SPX, NDX, XSP, VIX, RUT) the stamp itself, since index options stop at the close; on Chicago and UTC the stamp itself. A kind left out reads a stock, so pass i32(p_market_kind()) (declare market.kind();) beside the zone wherever the chain can be an index's. An expiry is live while it is after the as-of. optionsYearsToGo(expiryMs, asOfMs, zone, kind) is the time a contract is priced at, in 365-day years: on a stock or ETF chain every contract to that instant, before the stamp as after it (no jump at 16:00), and never under a second while it trades, so the same-day book keeps its gamma until 16:15; on an index chain, Chicago and UTC to the stamp. GammaCurve and ExpectedMoves read both on the zone and kind their loads are handed; IvTerm and OptionsChain keep each expiry to its stamp. The data plane and the chart read the same rule.

wrun
// The term and the greeks on the live bar: 30-day at-the-money IV, the 25 delta risk reversal near 30 days, the front expiry's expected move and the dealers' vanna.
input("close", ohlcv.close);
input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" });
market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME)
chart.interval_sec(); // the bar's length: the chain is read at the live bar's close
output("iv30", none, overlay, { description: "30-day constant-maturity at-the-money IV, percent" });
output("rr25", none, overlay, { description: "25 delta risk reversal near 30 days: call IV minus put IV, vol points" });
output("front_move", none, overlay, { description: "The front expiry's expected move, percent of its forward" });
output("net_vanna", none, overlay, { description: "Dealers' delta change per vol point, long the calls and short the puts" });

let term = new IvTerm(1);
let moves = new ExpectedMoves(1);
let greeks = new Greeks();
let zone = 0;
let intervalMs = 0.0;

function onStart(): void {
  // Construct here: the per-expiry buffers are the only allocation.
  term = new IvTerm(64);
  moves = new ExpectedMoves(in_chain_max_cells);
  greeks = new Greeks();
  zone = i32(p_market_zone());
  intervalMs = p_chart_interval_sec() * 1000.0;
}

function onBar(): void {
  if (!bar.isLast()) return;
  const n = in_chain_cells();
  if (n < OPTIONS_TUPLE) return;
  const cells = in_chain_view();
  const spot = bar.close();
  const nowMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close
  const rate = zone == 1 ? 0.04 : 0.0; // a stock's spot carries the rate to each forward; a futures or crypto underlying already is one
  term.load(cells, n, nowMs, spot, zone, rate);
  moves.load(cells, n, nowMs, spot, zone); // an OPRA expiry priced to 15 minutes past its stamp
  out_iv30(moves.horizonIv(30.0 / 365.0) * 100.0);
  const e = term.nearest(30.0);
  out_rr25((term.deltaIv(e, 1.0, 0.25) - term.deltaIv(e, -1.0, 0.25)) * 100.0);
  const today = optionsTradeDay(nowMs, zone);
  let front = -1; // the first expiry after today on the market's calendar
  for (let i = 0; i < moves.expiries() && front < 0; i += 1) if (optionsTradeDay(moves.expiry(i), zone) > today) front = i;
  out_front_move((moves.expectedMove(front) / moves.forward(front)) * 100.0);
  let vanna = 0.0;
  for (let i = 0; i + OPTIONS_TUPLE - 1 < n; i += OPTIONS_TUPLE) {
    if (!(cells[i + 3] > 0.0) || !(cells[i + 6] > 0.0)) continue;
    const years = optionsYearsToGo(cells[i + 1], nowMs, zone); // to the expiry's end: 0 or less once it stopped trading
    const under = cells[i + 7] > 0.0 ? cells[i + 7] : spot;
    if (zone == 1) greeks.spot(cells[i + 2], under, cells[i], years, cells[i + 6] / 100.0, rate);
    else greeks.forward(cells[i + 2], under, cells[i], years, cells[i + 6] / 100.0, rate);
    const multiplier = cells[i + 8] > 0.0 ? cells[i + 8] : 1.0;
    vanna += (cells[i + 2] > 0.0 ? 1.0 : -1.0) * greeks.vanna * cells[i + 3] * multiplier;
  }
  out_net_vanna(vanna);
}

The canonical numbers

Net GEX, the dealer regime, the gamma flip and the expected move each have one rule in the kit, so two cards on one chain never print two numbers for one word. Read them from GammaCurve and ExpectedMoves instead of summing, walking or pricing them in the Indicator.

GammaCurve is gamma exposure as a curve over hypothetical spot. Over the live contracts of a scope (an expiry whose end, optionsLiveUntilMs on the load's zone, is after the as-of; open interest and IV above 0; nearest 0 counts every live expiry, 1 the front expiry alone, N the N soonest):

  • spot() is S0, the median underlying of the nearest live expiry's contracts.
  • gexAt(x) sums side * oi * multiplier * bsGamma(u, strike, iv, years) * u * u * 0.01 with u the contract's own underlying times x / S0, so a dated future moves with the coin, and years the contract's optionsYearsToGo (to 15 minutes past the stamp on OPRA, at least a second). The unit is USD per 1% move, dealers long the calls and short the puts.
  • netGex() is gexAt(S0), and regime() is its sign through dealerRegime(netGex): 1 long gamma, -1 short gamma, 0 neutral. A flip never decides the regime.
  • flip() is the root of the curve nearest S0: the walk steps out from S0 by 0.25% on both sides at once, out to 50%, and bisects the first step that brackets a sign change to 1e-9 of S0. When both sides bracket at one step it takes the nearer root (the lower on a tie); it reads S0 when net GEX is 0 and NaN when no root lies within 50%. flipCount() and flipNear(k) read every root the walk brackets across the whole reach, nearest first.
  • A reading of exactly 0 brackets nothing: each side's bracket runs from its last nonzero reading. A curve that crosses 0 exactly at a step (a 0 between readings of opposite signs) is bisected across that step, and its root is found there. A curve that touches 0 and keeps its sign (a 0 between readings of the same sign) changes no regime, so it is no flip. That is the curve far from every strike, where each contract's gamma underflows to 0 and the curve fades out: a book of calls near spot has no flip, however far the walk goes.
  • The walk runs on the first flip(), flipNear() or flipCount() after a load, never inside it. A load of the same contracts at the same S0 (a bar that repeats its block, a live update between two reads of the chain) keeps every reading it already made, so a package walks the curve once per distinct block. The load keeps each contract's terms, so one gexAt costs one log of x / S0 and one exp per contract.
  • loadStrikes(...) reads option_strikes rows instead of the chain, each row a call and a put with that side's open interest and IV, at the rows' as-of, optionsAsOfMs(...): the bar's close, when their fold minute closes.

Because the regime is the sign of the same curve the flip is the root of, a long-gamma card always has spot on the long side of its flip. The older zeroGamma() readers keep their numbers: the first crossing of a running sum over the strikes, which can sit far from spot and contradict the sign. Do not print it as the flip.

ExpectedMoves reads each live expiry, nearest first. The forward is the median underlying of the expiry's contracts. The at-the-money IV is the mean of the call and the put mark IV at the strike nearest the forward (the lower on a tie). Then expectedMove(i) is straddleExpectedMove(forward, atmIv, years) and oneSigma(i) is oneSigmaMove(forward, atmIv, years). horizonIv(years) is the at-the-money IV at any horizon: total-variance interpolation between the two expiries around it, the nearest expiry's IV before it and the farthest's after it. A horizon's move is straddleExpectedMove(anchor, horizonIv(years), years) on the price the horizon is anchored at: the next 24 hours is years = 1 / 365.

Load both at optionsAsOfMs(...), the live bar's close, and on the market's zone and kind (market.zone(), market.kind()), so a US stock or ETF expiry counts, and keeps its gamma, until 15 minutes past its stamp and a US index expiry until its stamp. Say what each number covers where you print it, "all expiries" or the expiry's date for the front one.

wrun
// The canonical numbers on the live bar: net GEX, the dealer regime and the gamma flip over every live expiry, and the front expiry's expected move and 1σ range.
input("close", ohlcv.close);
input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" });
market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp
chart.interval_sec(); // the bar's length: the chain is read at the live bar's close
output("net_gex", none, overlay, { description: "Net GEX at spot, all expiries, USD per 1% move" });
output("regime", none, overlay, { description: "Dealer regime, all expiries: 1 long gamma, -1 short gamma, 0 neutral" });
output("gamma_flip", none, overlay, { description: "Gamma flip, all expiries: the root of the GEX curve nearest spot" });
output("expected_move", none, overlay, { description: "The front expiry's expected move, price: 0.85 of the at-the-money straddle" });
output("one_sigma", none, overlay, { description: "The front expiry's 1σ range, price" });

let curve = new GammaCurve(1);
let moves = new ExpectedMoves(1);
let zone = 0;
let intervalMs = 0.0;

function onStart(): void {
  // Construct here: the per-contract buffers are the only allocation.
  curve = new GammaCurve(in_chain_max_cells);
  moves = new ExpectedMoves(in_chain_max_cells);
  zone = i32(p_market_zone());
  intervalMs = p_chart_interval_sec() * 1000.0;
}

function onBar(): void {
  if (!bar.isLast()) return;
  const n = in_chain_cells();
  if (n < OPTIONS_TUPLE) return;
  const cells = in_chain_view();
  const asOfMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close
  curve.load(cells, n, asOfMs, 0, bar.close(), zone); // 0: every live expiry
  out_net_gex(curve.netGex());
  out_regime(curve.regime());
  out_gamma_flip(curve.flip());
  moves.load(cells, n, asOfMs, bar.close(), zone);
  out_expected_move(moves.expectedMove(0));
  out_one_sigma(moves.oneSigma(0));
}

A history of daily statistics

The US listed options statistics (option_daily, and option_stats_10m every ten minutes) land one row per session: declared with missing: "nan", a daily input lands its row on the session's own bar on a daily chart and on the first bar of its UTC day on an intraday chart, and every other bar reads NaN. DayHistory keeps those readings, one per day, the newest last, and answers what a history package asks of them: where today sits in its own past.

  • push(day, value) keeps value as day day's reading: a day after the newest appends (the oldest drops once capacity readings are held), the newest day again replaces its reading (a revised row), and an earlier day, or a day or a value that is not finite, is skipped. It returns true when the reading was kept. Use the bar's UTC day, Math.floor(bar.time() / 86400), so an intraday chart and a daily chart key the same sessions.
  • A window is the newest window readings, the newest among them; a window wider than the history reads the whole history, and span(window) says how many readings it holds. Compare span with the history the reading needs before you show it: a rank over five days is not a rank over a year.
  • rank(window): (newest - low) / (high - low) * 100, where the newest sits between the window's low (0) and high (100); NaN with fewer than two readings or a flat window.
  • percentile(window): the share of the window's earlier readings (every one but the newest) strictly below the newest, times 100.
  • zscore(window): the newest against the mean and the sample standard deviation of the window's earlier readings; NaN with fewer than three of them or no spread among them.
  • min, max, mean and stdev (the sample deviation) read the window with the newest included; quantile(window, q) reads its q quantile (0 to 1, clamped), linear between the two closest ranks.
  • value(ago) and day(ago) read the history itself, 0 the newest and NaN outside it; agoOf(day) finds a day's reading (-1 when it has none).

Construct it once, at module level or in onStart(): its rings and its sort buffer are allocated there, and no call allocates after.

wrun
// The 30-day IV's rank and percentile over a year of sessions, once the history holds 60 of them.
input("close", ohlcv.close);
input("iv30", option_daily.atm_iv_30d, { missing: "nan" }); // the session's row on one bar, NaN elsewhere
output("iv_rank", line, lower, { step: true, description: "Where the 30-day IV sits in its year, 0 to 100" });
output("iv_pct", line, lower, { step: true, description: "The share of the year's earlier sessions with a lower IV" });

const history = new DayHistory(260);
let rank: f64 = NaN;
let pct: f64 = NaN;

function onBar(): void {
  const iv = in_iv30();
  if (!isNaN(iv) && history.push(Math.floor(bar.time() / 86400.0), iv)) {
    const ready = history.span(252) >= 60; // a reading needs 60 sessions; until then say so instead of ranking
    rank = ready ? history.rank(252) : NaN;
    pct = ready ? history.percentile(252) : NaN;
  }
  out_iv_rank(rank); // held on every bar until the next session lands
  out_iv_pct(pct);
}

The IV rank, Variance risk premium, Skew history, Volatility regime, Exposure history, Options history, Option stance, Options sentiment gauge and Estimated dealer positioning recipes build on it.

The strike board

A strike board (a heatmap of strikes against expiries or time) reads one signed number per strike: net GEX, net DEX, open interest or another lens, summed over the expiries it shows. The kit names the nodes on that board, picks its expiry columns, measures how each strike's number moves, scores the prints on a flow tape, and maps a chart's root to the roots its levels can be read through. Construct each class once, at module level or in onStart(): none allocates after, and every function is plain arithmetic.

Node roles

NodeBoard.load(strikes, values, count, spot, pct) takes ascending strikes, one signed value per strike, the price the board is read against and the significance percent (15 when left out). A strike's share is pctOfTop(i), 100 * |value| / |top|, multiplied before the divide:

  • Top: the largest |value|. A tie goes to the strike nearest spot, then to the lower strike. When every value is 0 there is no top (top() reads -1) and every strike is normal.
  • Floor and ceiling: the largest |value| strictly below spot, and strictly above it.
  • Gate: the largest |value| strictly between spot and the top's strike, kept only when its share is at least 35.
  • Standouts: every strike but the top whose |value| is at least each neighbour's (a missing neighbour counts as 0) and whose share is at least 50, positive or negative by the value's sign.
  • Significant: a share of at least pct. Every other strike is normal.

role(i) is the strike's display role, the first that applies in the order top, gate, floor, ceiling, standout, significant, normal, as a code: 0 normal, 1 significant, 2 positive standout, 3 negative standout, 4 ceiling, 5 floor, 6 gate, 7 top (NODE_ROLE_NORMAL to NODE_ROLE_TOP). standout(i) (1, -1 or 0) and isSignificant(i) read the sets the order can hide: a standout that is also the floor shows the floor's role. aboveNet() and belowNet() sum the values above and below spot; a strike at spot counts in neither. roleWord(code) is the code's word for a label: top, gate, floor, ceiling, standout, significant or normal.

Expiry presets

expiryPresetCount(expiries, count, nowMs, zone, preset, n) returns how many of the leading expiries a preset keeps. The expiries are the live ones in epoch milliseconds, ascending, so every preset is a prefix. Days are trade days on the market's clock (zone, from market.zone()), read through optionsTradeDay, and a dated preset keeps the expiries on or before its last day:

PresetCodeKeeps
EXPIRY_PRESET_FRONT0The first expiry
EXPIRY_PRESET_TO_FRIDAY1Through the first Friday on or after today
EXPIRY_PRESET_TO_NEXT_FRIDAY2Through the Friday a week after that one
EXPIRY_PRESET_TO_OPEX3Through this month's third Friday, or next month's once it has passed
EXPIRY_PRESET_TO_NEXT_OPEX4Through the third Friday of the month after that one
EXPIRY_PRESET_TO_Q_OPEX5Through the next third Friday of March, June, September or December
EXPIRY_PRESET_ALL6Every expiry
EXPIRY_PRESET_COUNT7The first n

thirdFridayMs(year, month, zone) is the instant a month's third Friday opens its trade day on the market's clock: 00:00 UTC on crypto, 00:00 New York on US listed options, 17:00 Chicago the evening before on CME.

Strike velocity

new StrikeVelocity(maxKeys, maxBars) keeps a ring of maxBars readings per key, where a key is an id from 0 the Indicator gives each strike (or each strike and expiry column). Push each key's reading once per bar with push(barMs, key, value), bars in time order:

  • velocity(key, w): the reading on the newest bar minus the reading on the newest bar at or before w minutes earlier; NaN when the key has no reading on the newest bar or its history does not reach that far.
  • velocityPct(key, w): 100 * velocity / |the earlier reading|; NaN when that reading is 0.
  • available(w, hostIntervalMs): false for a window shorter than the chart's bar or beyond the bars held, so a picker hides it.
  • halo(key, w1, w2, w3): the velocity has one sign on at least 2 of the windows given (0 leaves a window out).

VELOCITY_WINDOWS lists the windows a board offers, in minutes: 1, 5, 10, 15, 60, 240 and 1440. The rings take maxKeys * maxBars * 16 bytes, and a day of 1-minute bars needs 1441 of them. The movers (the significant strikes with the largest |velocityPct|) are the Indicator's to rank: it knows which strikes are significant.

Flow score

flowSideCode(aggressor, outside) reads an option_prints tuple's two side columns. On US listed options aggressor is +1 at the ask, -1 at the bid, 0 at the mid and 2 when no quote sided the print, and outside is +1 above the ask and -1 below the bid; on crypto and CME chains aggressor is the taker's side and outside reads 0. The code is +2 above the ask, -2 below the bid, +1 at the ask (or a taker's buy), -1 at the bid (or a taker's sale), and 0 at the mid or unsided.

flowScore(side, cp, moneyness, dteDays, sizeVsOi, repeatHits) scores a print from -100 to 100, positive for a bought call or a sold put:

  • The base is 100 * s * cp: s is 1, 0.8, 0, -0.8 or -1 for the codes +2 to -2, and cp is +1 for a call, -1 for a put.
  • The base times three factors, multiplied together first: moneyness (0 out of the money 1.0, 1 at the money 0.9, 2 in the money 0.6), days to expiry (up to 7 1.0, up to 30 0.85, up to 90 0.7, else 0.55) and size over open interest (above 1 1.0, an open interest of 0 included; above 0.5 0.9; else 0.75).
  • Plus 10 in the base's sign at 3 repeat hits or more, then clamped to -100 and 100. A side of 0 scores 0.

Derived roots

DERIVED_ROOTS maps a chart's root to the roots whose option chains its levels can be read through: ES to SPX and SPY, NQ to NDX and QQQ, GC to GLD, SI to SLV, YM to DIA, RTY to IWM, SPY to SPX and QQQ to NDX. derivedRootCount(root) and derivedRoot(root, i) read it (0 and the empty string for a root it does not list). A derived level is drawn at derivedRatio(close, rowUnderlying), the chart's close over the row's underlying, so a derived strike is strike * ratio.

Limits

  • The chain is the live row's only. options_chain fills the newest row and leaves every history row an empty block (Limitations); read it under bar.isLast() and keep the readings for the bars that follow. A gamma map over past bars reads option_strikes instead (Option strikes, bar by bar), on crypto, CME and US stock charts, one book of the chain venue picks (book).
  • The chains are the chart's. venue: "auto" reads the chart's own options venue when it lists options (on a US stock or ETF chart its OPRA chain, on a CME futures chart its CME chain, each at your own tier), else the coin's Deribit chain; a venue's name (deribit, cme, ...) pins one. Open interest and the multiplier arrive as the venue reports them: Deribit in coins with a multiplier of 1, CME in contracts with the point value as the multiplier, OPRA in contracts with a multiplier of 100, which is why the exposure is in USD on all three. A venue the chart cannot serve is refused by name.
  • One book per block. The tuple names no symbol, so GammaCurve and ExpectedMoves read a block as one book of one chain and cannot tell two books apart: a block that carries a coin's two Deribit books (BTC and BTC_USDC) sums both books' open interest into net GEX and averages both surfaces' quotes at the at-the-money strike.
  • Size max_cells for the chain. A BTC chain is about 1,550 contracts; a crypto block over max_cells refuses the run instead of being truncated, and the cells array costs max_cells * 10 * 8 bytes of module memory (Limits). On a governed chain (OPRA, CME) max_cells is the budget the chart sizes the read to: the expiries that fit at 8 strikes each side of the money, then a wider window up to 80 strikes.
  • Where the chain is served. The chart serves options_chain when the indicator runs in your browser. A Protected indicator on OpenMarket's servers reads a coin's Deribit chain only (venue: "auto" or "deribit"): the US stock and CME chains and the other venue words are refused there by name. Alerts and your OpenMarket runner refuse an indicator that declares it, by name. option_strikes is served by the chart alone too; every other host refuses it by name.

From Pine

Nothing on this page maps to Pine. Pine cannot read an options chain, so there is no request.* call or ta.* function to translate: gamma exposure, the walls and max pain are computed from cells the chart serves to the indicator, and the class is this chart's arithmetic for them.