Options sentiment

View as MarkdownOpen the editor

Today only: one score from -100 (bearish) to +100 (bullish) shows which way options traders lean.

One part asks where today's option volume trades, and volume at strikes (option price levels) above the price leans bullish. The other asks if calls (bets on a rise) cost more than puts (bets on a fall), also bullish. It shows bets, not a forecast: +20 and up reads bullish, -20 and down bearish. It needs this symbol's options: a coin, a US stock or a CME (Chicago futures exchange) future.

Under the hood: VWKS is the day's volume-weighted mean of each traded contract's strike over the underlying, minus 1. Each offset is capped at 50% either way. AVAR is the 25 delta call IV minus the 25 delta put IV at a 30-day constant maturity. Each is scaled to -1..+1 against a fixed bound, then blended 60% VWKS and 40% AVAR, times 100. It reads the option_contract_state summary on the live bar through its traded and extremes page views (US listed options, Chain page views). It reads the option_surface on every bar through its tenor_bracket pick (Option surface, The present mask and partial bars). It reads each wing at the maturity with totalVarianceIv (The at-the-money term). It checks market.option_contract() (Quick reference). It draws a split line (Plotting) and a line handle with a plain price label (Drawing objects). It also draws a render.hud card with a meter (HUD cards, Blocks and tiles). It is also the options-sentiment template, the Options Sentiment card under HUDs in the editor's starter list, which compiles as written.

The wrun indicator

// Options Sentiment: today only, one score from -100 (bearish) to +100 (bullish) for which way options traders lean.
// The volume gap asks if today's volume trades at strikes (option price levels) above the price. Above leans bullish,
// below bearish. The call-put gap asks if calls (options that pay when price rises) cost more than puts. Puts are
// options that pay when price falls. The card labels these two VWKS and AVAR. It leads with the score: +20 and up reads
// bullish, -20 and down bearish, neutral between. A line under the chart tracks the call-put gap, and a dashed line
// marks where today's volume centres. It reads traders' bets, not a forecast.
//
// Technical notes: where the day's option volume sits against the price, and how the options price upside against
// downside, blended into one score. VWKS, the volume-weighted strike offset, is the day's volume-weighted mean of each
// traded contract's strike over the underlying, minus 1, each offset capped at 50% either way (the option_contract_state
// source: the day's volume per contract on the newest bar; the eight nearest expiries, strikes within 20%). AVAR, the
// asymmetric volatility, is the 25 delta call IV minus the 25 delta put IV at a constant maturity (30 days by default),
// each wing interpolated in total variance between the volatility surface's expiries (the option_surface source, on
// every bar). Each is scaled to -1..+1 against a fixed bound (the settings), blended 60% VWKS and 40% AVAR and read as
// a score from -100 to +100: bullish at +20 and up, bearish at -20 and down, neutral between. A day with fewer traded
// contracts or less volume than the minimums reads no score, and neither does a surface without both 25 delta wings.
// AVAR runs as a line under the chart, the volume-weighted strike is drawn across the chart (on the underlying's own
// chart: the close inside the strikes the summary lists), and a card leads with the score. On an option contract's
// own chart (market.option_contract()) the price axis is the contract's premium: no level and no score are read
// there (VWKS needs the underlying's price), the card says so and its day's activity keeps filling.

section("Score");
param.number("vwks_bound_pct", 5, { min: 0.5, max: 50, step: 0.5, label: "VWKS bound, percent", description: "The VWKS (how far the day's volume sits above or below today's price) that counts as fully bullish or bearish." });
param.number("avar_bound", 15, { min: 1, max: 50, step: 0.5, label: "AVAR bound, IV points", description: "The AVAR that counts as fully bullish or bearish, in IV (implied volatility) points. AVAR is the 25 delta call IV minus the 25 delta put IV." });
param.int("tenor_days", 30, { min: 7, max: 120, label: "AVAR maturity, days", description: "How many days ahead AVAR reads the 25 delta call and put IV (implied volatility)." });
param.int("min_contracts", 15, { min: 1, max: 10000, label: "Smallest traded contracts", description: "How many different contracts must trade today before a score shows." });
param.int("min_volume", 500, { min: 1, max: 10000000, label: "Smallest day volume", description: "How many contracts in total must trade today before a score shows." });
input("close", ohlcv.close); // the chart's own close: the underlying each strike is measured against
input("state", option_contract_state.cells, { max_cells: 24000, expiries: "nearest:8", strike_window_pct: 20, page_views: ["traded", "extremes"], description: "Today's options summary on the live candle: the eight nearest expiries, strikes within 20% of the price. Only the contracts that traded today, plus the lowest and highest strike." }); // [root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present] per contract, in the summary's order
input("surface", option_surface.cells, { max_cells: 128, pick: "tenor_bracket", tenor: "@tenor_days", description: "This symbol's implied volatility (IV) by expiry, on every candle. Only the two expiries around the AVAR maturity." }); // [expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present] per expiry, in the surface's order
market.option_contract(); // 1 on an option contract's own chart: its close is the contract's premium, never the underlying
output("avar", line, lower, { color: "theme.text", width: 2, split: "level", up_color: "theme.up", down_color: "theme.down", format: "0.00", label: "AVAR", description: "AVAR: the 25 delta call IV minus the 25 delta put IV at the AVAR maturity, in IV points. Above zero, calls cost more than puts. It reads on each candle with IV data." });
// The readings, data-only: the card's tiles read them and the Console can too. VWKS and the score need the newest bar.
output("vwks", none, overlay, { description: "VWKS: how far the day's option volume sits above (+) or below (-) today's price, in percent. Each strike counts at most 50% away. Live candle only." });
output("vw_strike", none, overlay, { description: "The volume-weighted strike: the average strike of today's trades, weighted by volume. Live candle only." });
output("score", none, overlay, { description: "The score from -100 to +100: 60% VWKS and 40% AVAR, each scaled against its bound. Live candle only." });
output("direction", none, overlay, { description: "The score's reading and the meter's colour: 0 bearish (-20 and down), 1 neutral, 2 bullish (+20 and up)." });
output("avar_now", none, overlay, { description: "The newest AVAR at or before this candle, the one the score uses." });
output("traded", none, overlay, { description: "How many different contracts traded today." });
output("day_volume", none, overlay, { description: "Today's total volume of the listed contracts." });
output("put_call_volume", none, overlay, { description: "Puts traded for each call traded." });
output("surface_partial", none, overlay, { description: "1 on a candle whose IV data is partial, else 0. That happens on a chart finer than the 5-minute samples, or past how long they are kept." });
string("read", { max_bytes: 64 }); // the headline: the reading and the score, or why there is none
string("title", { max_bytes: 64 }); // the card's title: the maturity AVAR is read at
string("tag", { max_bytes: 40 }); // the volume-weighted strike's price text
handles.line({ width: 1, extend: "both" }); // the volume-weighted strike, across the whole chart
handles.label({ anchor: "right", align: "right", size: 11, color: "theme.muted", style: "plain" }); // its price text: x in pixels from the right edge, y in price

// The card: the reading leads as the headline, the score on a meter from -100 to +100 with marks at -20 and +20,
// coloured by its sign (down bearish, muted neutral, up bullish), then the two inputs and the day's activity.
render.hud("sentiment", {
  position: "bottom_center",
  title: "{{title}}",
  columns: 2,
  tiles: [
    tile.pill("Sentiment", "read", { headline: true }),
    tile.meter("Score", "score", { min: -100, max: 100, marks: [-20, 20], color_by: "direction", colors: ["theme.down", "theme.muted", "theme.up"] }),
    tile.value("VWKS", "vwks", { format: "%" }),
    tile.value("AVAR, IV points", "avar_now", { format: "0.00" }),
    tile.rows([
      ["Volume-weighted strike", "vw_strike", "price"],
      ["Contracts traded", "traded", "int"],
      ["Day volume", "day_volume", "si"],
      ["Put/call volume", "put_call_volume", "0.00"],
    ]),
  ],
});

const STATE_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 SURFACE_TUPLE = 9; // f64s per expiry: expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present
const BIT_VOLUME = 9; // option_contract_state: volume_day
const BIT_DTE = 1; // option_surface: dte_days, the two 25 delta wings
const BIT_P25 = 4;
const BIT_C25 = 5;
const VWKS_WEIGHT = 0.6; // the blend
const AVAR_WEIGHT = 0.4;
const MAX_OFFSET = 0.5; // each strike offset capped at 50% either way
const READ_WORDS: String[] = ["Bearish", "Neutral", "Bullish"];
const LEVEL = theme.MUTED; // the volume-weighted strike's ink: a level, never a sign
const wingDays = new StaticArray<f64>(in_surface_max_cells); // the surface's anchors this bar, ascending by days to expiry
const wingCall = new StaticArray<f64>(in_surface_max_cells); // their 25 delta call IV
const wingPut = new StaticArray<f64>(in_surface_max_cells); // their 25 delta put IV
const level = draw.line(0); // the volume-weighted strike
const tag = draw.label(1); // ids are one space across kinds

let vwksBound = 0.05; // settings, read in onStart()
let avarBound = 15.0;
let tenor = 30.0;
let minContracts = 15.0;
let minVolume = 500.0;
let optionContract = false; // the chart is one option contract's own: no level, no score
let t: f64 = NaN; // this bar
let firstT: f64 = NaN; // the first bar's open time: where the level starts
let avarNow: f64 = NaN; // the newest AVAR at or before this bar
let traded = 0.0; // the live summary: contracts with volume today
let volume = 0.0; // their volume
let callVolume = 0.0;
let putVolume = 0.0;
let offsetSum = 0.0; // the capped offsets, volume-weighted
let strikeSum = 0.0; // the strikes, volume-weighted
let lowStrike: f64 = NaN; // the strikes the summary lists, lowest and highest
let highStrike: f64 = NaN;

function onStart(): void {
  vwksBound = p_vwks_bound_pct() / 100.0;
  avarBound = p_avar_bound();
  tenor = p_tenor_days();
  minContracts = p_min_contracts();
  minVolume = p_min_volume();
  optionContract = i32(p_market_option_contract()) == 1;
}

// ── AVAR: each 25 delta wing at the maturity, linear in total variance between the anchors around it ──
function wingAt(iv: StaticArray<f64>, count: i32): f64 { // before the first anchor its IV, past the last the last's
  const years = tenor / 365.0;
  for (let k = 0; k < count; k += 1) {
    if (years <= wingDays[k] / 365.0) return k == 0 ? iv[0] : totalVarianceIv(wingDays[k - 1] / 365.0, iv[k - 1], wingDays[k] / 365.0, iv[k], years);
  }
  return iv[count - 1];
}
function avarOf(n: i32): f64 { // this bar's AVAR from its surface block; NaN without an anchor (an expiry past half a day out with both wings)
  const cells = in_surface_view(); // this bar's surface in place: the first n values of the build's own buffer
  let count = 0;
  for (let i = 0; i + SURFACE_TUPLE - 1 < n; i += SURFACE_TUPLE) {
    const present = cells[i + 8];
    if (!hasBit(present, BIT_DTE) || !hasBit(present, BIT_P25) || !hasBit(present, BIT_C25)) continue; // an absent wing reads 0: never an anchor
    const days = cells[i + 1];
    if (!(days > 0.5) || !(cells[i + 4] > 0.0) || !(cells[i + 5] > 0.0)) continue; // an expiry settling within half a day never anchors
    let k = count; // sorted insertion by days to expiry
    while (k > 0 && wingDays[k - 1] > days) {
      wingDays[k] = wingDays[k - 1];
      wingCall[k] = wingCall[k - 1];
      wingPut[k] = wingPut[k - 1];
      k -= 1;
    }
    wingDays[k] = days;
    wingCall[k] = cells[i + 5];
    wingPut[k] = cells[i + 4];
    count += 1;
  }
  if (count == 0) return NaN;
  return wingAt(wingCall, count) - wingAt(wingPut, count);
}
function surfacePartial(n: i32): bool {
  const cells = in_surface_view();
  for (let i = 0; i + SURFACE_TUPLE - 1 < n; i += SURFACE_TUPLE) if (isPartial(cells[i + 8])) return true;
  return false;
}

// ── The day's volume against the price ──
function measureVolume(n: i32, spot: f64): void {
  const cells = in_state_view(); // the live summary in place
  traded = 0.0;
  volume = 0.0;
  callVolume = 0.0;
  putVolume = 0.0;
  offsetSum = 0.0;
  strikeSum = 0.0;
  lowStrike = NaN;
  highStrike = NaN;
  for (let i = 0; i + STATE_TUPLE - 1 < n; i += STATE_TUPLE) {
    const strike = cells[i + 3];
    if (!(strike > 0.0)) continue;
    if (isNaN(lowStrike) || strike < lowStrike) lowStrike = strike;
    if (isNaN(highStrike) || strike > highStrike) highStrike = strike;
    if (!hasBit(cells[i + 12], BIT_VOLUME)) continue;
    const v = cells[i + 9];
    if (!(v > 0.0)) continue;
    traded += 1.0;
    volume += v;
    if (cells[i + 2] > 0.0) callVolume += v;
    else putVolume += v;
    strikeSum += strike * v;
    let offset = strike / spot - 1.0;
    if (offset > MAX_OFFSET) offset = MAX_OFFSET;
    else if (offset < -MAX_OFFSET) offset = -MAX_OFFSET;
    offsetSum += offset * v;
  }
}

// ── The volume-weighted strike across the chart, its price as plain text at the axis ──
function sbPrice(v: f64): void { // decimals follow the price's size: 6,652 / 660.10 / 48.125
  if (v >= 1000.0) sb_f64(v, 0);
  else if (v >= 100.0) sb_f64(v, 2);
  else sb_f64(v, 3);
}
function drawLevel(price: f64): void {
  if (isNaN(price)) {
    level.delete(); // no-ops when never drawn
    tag.delete();
    return;
  }
  level.set(firstT, price, t, price).color(LEVEL).width(1.0).style(LineStyle.Dashed).extend(Extend.Both);
  sb_clear();
  sb_text("Volume centre ");
  sbPrice(price);
  tag.set(56.0, price).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
}

// onBar() runs once per bar: every bar reads its surface into AVAR; the live bar measures the day's volume, blends the
// score and writes the card's words and the level.
function onBar(): void {
  const close = bar.close();
  t = bar.time();
  if (isNaN(firstT) && !isNaN(t)) firstT = t;
  const m = in_surface_cells();
  const avar = m >= SURFACE_TUPLE ? avarOf(m) : NaN;
  if (!isNaN(avar)) avarNow = avar;
  out_avar(avar);
  out_avar_now(avarNow);
  out_surface_partial(m >= SURFACE_TUPLE ? (surfacePartial(m) ? 1.0 : 0.0) : NaN);
  if (!bar.isLast()) {
    out_vwks(NaN);
    out_vw_strike(NaN);
    out_score(NaN);
    out_direction(NaN);
    out_traded(NaN);
    out_day_volume(NaN);
    out_put_call_volume(NaN);
    return;
  }
  const n = in_state_cells();
  const summary = n >= STATE_TUPLE && close > 0.0;
  if (summary) measureVolume(n, close);
  // The strikes belong to this chart's price only on the underlying's own chart: its close inside the listed strikes,
  // and never on an option contract's own chart.
  const onChart = summary && !optionContract && !isNaN(lowStrike) && close >= lowStrike && close <= highStrike;
  const vwks = onChart && volume > 0.0 ? offsetSum / volume : NaN; // a fraction
  const vwStrike = onChart && volume > 0.0 ? strikeSum / volume : NaN;
  const enough = traded >= minContracts && volume >= minVolume;
  let score: f64 = NaN;
  if (onChart && enough && !isNaN(vwks) && !isNaN(avarNow)) {
    const v = Math.max(-1.0, Math.min(1.0, vwks / vwksBound));
    const a = Math.max(-1.0, Math.min(1.0, avarNow / avarBound));
    score = 100.0 * (VWKS_WEIGHT * v + AVAR_WEIGHT * a);
  }
  const direction = isNaN(score) ? NaN : score >= 20.0 ? 2.0 : score <= -20.0 ? 0.0 : 1.0;
  out_vwks(vwks * 100.0);
  out_vw_strike(vwStrike);
  out_score(score);
  out_direction(direction);
  out_traded(summary ? traded : NaN);
  out_day_volume(summary ? volume : NaN);
  out_put_call_volume(summary && callVolume > 0.0 ? putVolume / callVolume : NaN);
  drawLevel(vwStrike);
  sb_clear();
  if (!summary) sb_text("Waiting for this symbol's options");
  else if (optionContract) sb_text("On a contract's own chart, no level or score");
  else if (!onChart) sb_text("Open the chart these options are on: strikes need its price");
  else if (!enough) {
    sb_text("Thin day: ");
    sb_f64(traded, 0);
    sb_text(" contracts, ");
    sb_f64(volume, 0);
    sb_text(" volume");
  } else if (isNaN(avarNow)) sb_text("No 25 delta call and put IV to read");
  else {
    sb_text(READ_WORDS[i32(direction)]);
    sb_text(", score ");
    if (score > 0.0) sb_text("+");
    sb_f64(score, 0);
  }
  str_read_sb();
  sb_clear();
  sb_text("Options sentiment, AVAR at ");
  sb_f64(tenor, 0);
  sb_text(" days");
  str_title_sb();
}

How it works

VWKS. On the live bar every contract of the summary whose present mask carries bit 9 (volume_day) and that traded today adds its strike over the chart's close, minus 1, capped at -50% and +50%, weighted by its volume; the sum over the day's volume is VWKS, in percent as vwks. The same weights give vw_strike, the volume-weighted mean strike itself (uncapped), drawn across the chart as "Volume centre". The summary is the eight nearest expiries with strikes within 20% of the underlying (expiries: "nearest:8", strike_window_pct: 20), where the day's volume concentrates. The strikes are measured against the chart's own close, so VWKS reads on the underlying's own chart only, where the close lies inside the strikes the summary lists. On an option contract's own chart, which market.option_contract() marks (i32(p_market_option_contract()) reads 1 there), the close is the contract's premium, never the underlying's price: no level and no score are read there, while the day's activity (the contracts traded, the day's volume, put volume over call volume) keeps reading. Where the host writes 0, the close test keeps the strikes off such a chart.

AVAR. On every bar the surface lists one tuple per expiry: days to expiry, the forward, the at-the-money IV and the 25 and 10 delta wings, in percent. An expiry anchors when its present mask carries bits 1, 4 and 5 (days, the 25 delta put and call IV) and it settles more than half a day out (a same-day expiry's IV swings with the hours left). Each wing is read at AVAR maturity (30 days) linearly in total variance between the two anchors around it, IV squared times years (totalVarianceIv, the step the kit's at-the-money term takes); before the first anchor it is the first's IV, past the last the last's. AVAR is the call wing minus the put wing in IV points: avar on its bar, and avar_now, the newest one at or before the bar, which the score blends. A bar the data plane marked partial (a chart finer than the surface's five-minute samples, or older than they are kept) still reads, and surface_partial says so.

The score. VWKS over VWKS bound (5%) and AVAR over AVAR bound (15 IV points), each clamped to -1..+1, blend as 100 * (0.6 * vwks + 0.4 * avar). The bounds are settings because no published source fixes them: an index whose puts always trade rich reads bearish on a tight AVAR bound, so widen it there. A day needs Smallest traded contracts (15) contracts with volume and Smallest day volume (500) contracts traded for a score.

The card. The headline reads the score in words (Bearish, score -32); the meter runs from -100 to +100 with marks at -20 and +20, coloured by the reading (the down colour bearish, muted neutral, the up colour bullish); then VWKS, AVAR, the volume-weighted strike, the contracts traded, the day's volume and put volume over call volume.

What the settings do

  • VWKS bound, percent: How far the day's volume centre must sit from today's price to count as fully bullish or bearish.
  • AVAR bound, IV points: How much more calls must cost than puts to count as fully bullish or bearish. It is in points of implied volatility (how big a move option prices expect).
  • AVAR maturity, days: How many days ahead the call-put gap reads the calls' and puts' implied volatility.
  • Smallest traded contracts: How many different contracts must trade today before a score shows.
  • Smallest day volume: How many contracts in total must trade today before a score shows.
  • Sentiment: The reading in words, bullish, neutral or bearish, with the score.
  • Score: The score on a meter from -100 to +100: +20 and up is bullish, -20 and down bearish.
  • VWKS: The volume gap: how far the day's option volume sits above (+) or below (-) today's price, in percent.
  • AVAR, IV points: The call-put gap: calls' implied volatility minus puts', both a moderate distance (25 delta) from price. Above zero, calls cost more.
  • Volume-weighted strike: The average strike traded today, weighted by volume, also drawn on the chart as Volume centre.
  • Contracts traded: How many different contracts traded today.
  • Day volume: How many contracts traded today in total.
  • Put/call volume: Puts traded for each call traded.

Where it runs

It works on coins with listed options. A copy you run from the editor (where you write and run your own indicators) reads the same data. On a US stock or ETF chart with US listed options, every indicator that runs in your browser reads it. The data is 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), every indicator that runs in your browser reads it too, once you accept the CME market data terms (Limitations). CME data is 10 minutes behind unless you have real-time CME data. The call-put gap reads implied volatility by expiry, which works on crypto, CME and US stock charts too (Option surface). It keeps five-minute samples for 30 days and a daily sample after that. So the AVAR line reaches back as far as the daily samples do.

When data is missing

The card's headline says why instead of going blank. It reads "Waiting for this symbol's options" until today's options summary arrives. It reads "On a contract's own chart, no level or score" on one option contract's own chart. Any other chart whose price is not among the strikes gets its own message. It reads "Open the chart these options are on: strikes need its price". That includes a contract's chart that the chart does not mark as one. It reads "Thin day: 9 contracts, 320 volume" below the minimums. It reads "No 25 delta call and put IV to read" while no expiry has both. A candle with no implied volatility data has no call-put gap, and the AVAR line breaks there. Some tools then fall back to a rougher reading of that gap. This score does not, because today's options summary lacks each contract's implied volatility.

Customize it

  • A shorter maturity. Set AVAR maturity to 7 for the front of the curve.
  • An index. Raise AVAR bound to 25 so the index's standing put skew does not pin the score bearish.
  • A stricter day. Raise Smallest day volume to score only busy days.

Run it

  1. In the editor's Explorer, press the Templates icon ("Browse starter templates") and pick Options Sentiment under HUDs.
  2. Press Run on a US stock or ETF chart: the AVAR line fills bar by bar, the volume centre draws across the chart and the card sits at the bottom centre.
  3. At the editor's Console prompt, type score, vwks and avar_now to read them on the live bar.

Concepts used