Expected move
Options prices encode a crowd's bet on how far price can move, and this indicator draws that bet.
Solid lines mark the expected move around yesterday's close: the range the market gives about even odds, not a forecast. Dashed lines mark the wider 1σ range (one standard deviation, about two in three odds), and a cone runs ahead. A close outside the solid lines is a bigger move than the market priced: use them for stops and targets. It needs this symbol's options, on a coin, a CME (Chicago futures exchange) future or a US stock.
Under the hood: the expected move is 0.85 of the at-the-money straddle, the one rule every OpenMarket card means by "expected move". The 1σ range is the IV times the square root of the time, about 1.47 times as wide. Both come from the data plane's numbers of the chart's own option book, the ones the chart's built-in Implied Move draws. They are timed from the instant it priced the book. The lines start from the newest daily close (today's 00:00 UTC open on crypto) whatever the chart's interval. It reads the numbers and vol_term book folds through an options_chain.cells input on the live bar. The options kit's BookStamp, OptionNumbers, ExpectedMoves and VolTerm read them (Book folds, Chain page views). The daily candles come through CandleList (Calendar periods and candle lists). It draws four guide outputs tagged on the price axis (Lines, areas, columns, dots, marks). The cone and the levels draw as handles (Drawing objects), and the levels' pills through plot.levels (Docked profiles). A render.hud card in the chart's default look sits beside them (HUD cards). It is also the expected-move template, the Expected Move card under HUDs in the editor's starter list, which compiles as written.
The wrun indicator
// Expected Move: how far the options market thinks price can move, drawn on the chart. Options prices encode a
// crowd's bet on how far price can move by a date. The expected move is the range the market gives about even odds.
// Price is about as likely to end inside it as outside it. Two solid lines mark it above and below yesterday's
// close. Two dashed lines mark the wider 1σ range (one standard deviation), with about a two in three chance. Wider
// lines mean the market prices bigger moves. A close outside the solid lines is a bigger move than the market priced.
// A cone ahead of the live candle shows the same odds widening with time. A card at the bottom lists the numbers.
// Use it to size stops and targets, and to judge if a move is normal. These odds are the market's price of risk, not
// a forecast.
//
// Technical notes: the data plane's numbers of the chart's own option book (the ones the chart's built-in Implied
// Move draws), read as they come and timed from the book's priced
// instant. The expected move is 0.85 of the at-the-money straddle; the 1σ range beside it, the IV times the square
// root of the time, is about 1.47 times as wide and never called the expected move. The at-the-money IV 1, 5, 7, 14,
// 30, 60 and 90 calendar days out reads in a card at the bottom of the pane. Two pairs of rails run across the chart
// for the horizon the Horizon setting picks, its moves as shares of the band's anchor, yesterday's daily close read
// off the daily candles whatever the chart's interval (today's 00:00 UTC open on crypto), which the card names: the
// expected move (solid) and the 1σ range (dashed), guides in the muted text colour the chart tags on the price axis.
// Without daily candles the anchor is the prior session's last close from the bars (on bars longer than a day the
// prior bar's), and the card says so. The card also lists the next six expiries after today, each one's time to go (in
// hours under 48 hours, in days after) and its expected move in price and in percent of its forward. On a US stock or
// ETF it marks the earnings expiry, the first one after the report the Earnings date setting names, and the Earnings
// horizon sizes the rails to that expiry's own moves; every other market reads no earnings. The book rides the live
// bar only. A book with no contract draws nothing; one with no spot reads its moves and no skew (the chart's own term
// structure reads none without a spot).
//
// Ahead of the live bar one cone runs through every horizon drawn: the session's close (16:00 on the market's clock,
// the next 00:00 UTC on crypto), the next session's, this Friday's, the third Friday's (next month's once it has
// passed) and 30 calendar days on. Its legs run from the live bar's open to the farthest horizon's end. At each
// sample the time to go runs from the book's priced instant, never below 0 (so the legs hold the close up to it), the
// at-the-money IV is the one that far out, interpolated in total variance between the numbers' expiry rows around it,
// and the 1σ leg is the live close times that IV times the square root of the time in years: every horizon's end lies
// on it. With Skew priced on, the up leg reads the 25 delta call IV and the down leg the 25 delta put IV of the
// expiry after today nearest 30 days (its strangle plus and minus half its risk reversal): their ratios to that
// expiry's at-the-money IV scale every sample's IV. The samples step on the square root of time, densest by the
// apex. Cone style fills it: Fan, four nested bands at 0.5σ, 1σ, 1.5σ and 2σ in the
// chart's text colour, brightest in the middle, or Up and down tint, the upper half in the up colour and the lower
// half in the down colour, the 1σ to 2σ rings fainter; either holds its alpha to half way, then fades to nothing at
// the far end in one gradient a band, a straight fall with no step. The legs are open
// paths, the 1σ solid and the 2σ dotted. A dot marks each horizon's end on both 1σ legs, its prices beside it (Today
// 1σ 662.10 above, 655.40 below; the Cone labels setting), and the 2σ prices sit at the far end; a horizon
// ending close to the next one drawn keeps its dots and leaves its prices to that one. A horizon under 4 bars of the
// chart's interval is hidden, as is one past 10,000 bars unless Cone horizons names it alone; the cone stops short of
// a horizon past 200 bars (unless named alone), and a horizon ending with an earlier one draws once. The card lists
// every horizon's legs, marks the ones the earnings report falls inside, and checks the front horizon, the first one
// not hidden, against 0.85 of its at-the-money straddle and its 20-day realized move (the daily candles' last 20 log
// returns, over 365 days a year on crypto and 252 elsewhere).
// Levels at the past close draws the day, week and month 1σ and 2σ highs and lows from the band's anchor, dashed
// across the chart at the numbers' 1, 7 and 30 day 1σ moves in the muted text colour, each named in a pill at the
// price axis (Day +1σ, Wk −1σ) and by its name and price just above its line: the book rides the live bar only, so
// the moves are the live book's.
section("Horizon");
param.choice("horizon", ["1d", "5d", "7d", "14d", "30d", "60d", "90d", "earnings"], "1d", { label: "Rails horizon", description: "How far ahead the four lines (the rails) look: 1, 5, 7, 14, 30, 60 or 90 calendar days. The earnings choice runs them to the first expiry (the day the option ends) after the Earnings date. Earnings works on a US stock or ETF only." });
param.time("earnings_date", 0, { label: "Earnings date", description: "The company's next earnings report, in UTC, on a US stock or ETF. The card marks the first expiry (the day the option ends) after it and reads its expected move. The earnings choice of Rails horizon runs the lines to that expiry. 0 (1970-01-01) turns it off." });
section("Cones");
param.choice("cones", ["off", "1s", "1s+2s"], "1s+2s", { label: "Cones", description: "The cone ahead of the live candle shows how far price may travel as time passes. off hides it. 1s draws the 1σ cone (one standard deviation, about two in three odds). 1s+2s adds the wider 2σ cone." });
param.choice("horizons", ["close", "1d", "week", "opex", "30d", "all"], "all", { label: "Cone horizons", description: "The end dates the cone runs to. close: today's session close. 1d: the next session's close. week: this Friday's close. opex: the third Friday's close, the monthly options expiry, next month's once it passes. 30d: 30 calendar days out. all: every end date within 200 candles." });
param.choice("cone_style", ["Fan", "Up and down tint"], "Fan", { label: "Cone style", description: "Fan: four nested bands 0.5σ (half a standard deviation) apart, in the chart's text colour, brightest in the middle. The middle is where price is most likely to end. Up and down tint: the upper half in the up colour, the lower half in the down colour. Both fade out toward the far end." });
param.choice("cone_labels", ["near", "all", "off"], "all", { label: "Cone labels", description: "The prices printed beside each end date's dots. near prints them on the two nearest end dates, all on every one, off on none. An end date close to the next one leaves its prices to that one." });
param.choice("rail_labels", ["Tags", "Words"], "Tags", { label: "Rail labels", style_values: ["quiet", "words"], description: "How the four lines are labelled on the price axis. Tags puts each line's name and price in one soft capsule. Words puts the price on the axis and the name just above the line." });
param.bool("skew_priced", true, { label: "Skew priced", description: "On, the cone leans with skew: extra cost in puts (bets on a fall) or calls (bets on a rise). The up side uses the 25 delta call IV (implied volatility) and the down side the 25 delta put IV. 25 delta options have about a one in four chance to pay. Both come from the expiry nearest 30 days, where quoted. Off, both sides use the IV at today's price." });
section("Levels");
param.bool("past_levels", false, { label: "Levels at the past close", description: "Dashed lines at the day, week and month 1σ and 2σ highs and lows (one and two standard deviations). They run across the chart from the prior close, like the four lines." });
input("close", ohlcv.close); // the chart's own close: the prior session's close is the last one of the trade date before today's
input("chain", options_chain.cells, { max_cells: 256, venue: "auto", page_views: ["numbers", "vol_term"], description: "This symbol's options, summed up by OpenMarket. US listed options on a US stock, CME options on a future, Deribit options on BTC and ETH. For each expiry still trading: its forward price, IV (implied volatility) at today's price, expected move and 1σ range. Also the IV and both moves at seven horizons, and each expiry's 25 delta strangle and risk reversal (its skew)." }); // rows of 16 f64s, [layout, ...fields]: the book stamp, the numbers' scope, expiry and horizon rows, the vol_term rows; 256 rows hold the stamp, the scope, the eight horizons, 64 vol_term rows and 182 expiries
input("trade_date", time.trade_date); // the bar's trade date: the UTC date on crypto, New York's on a US stock, CME's from 17:00 Chicago
input("days", candles.cells, { interval: "1d", bars: 21, max_cells: 400, description: "The daily candles as they close, on any chart interval. The newest close is where the lines start. The last 21 give the realized move: how much price actually moved." }); // [offset_ms, open, high, low, close, volume] per closed day
market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME): the calendar and the anchor's words
market.kind(); // what the market trades: earnings read only on a stock or ETF (2)
chart.interval_sec(); // the bar's length: how many bars a horizon spans
// The readings: the card's tiles read them and the Console can too, each NaN on history bars; data-only but the rails.
output("iv_1d", none, overlay, { description: "IV (implied volatility) at today's price for exactly 1 calendar day ahead, in percent. Live candle only." });
output("iv_5d", none, overlay, { description: "IV (implied volatility) at today's price for 5 calendar days ahead, in percent." });
output("iv_7d", none, overlay, { description: "IV (implied volatility) at today's price for 7 calendar days ahead, in percent." });
output("iv_14d", none, overlay, { description: "IV (implied volatility) at today's price for 14 calendar days ahead, in percent." });
output("iv_30d", none, overlay, { description: "IV (implied volatility) at today's price for 30 calendar days ahead, in percent." });
output("iv_60d", none, overlay, { description: "IV (implied volatility) at today's price for 60 calendar days ahead, in percent." });
output("iv_90d", none, overlay, { description: "IV (implied volatility) at today's price for 90 calendar days ahead, in percent." });
output("prior_close", none, overlay, { description: "Where the lines start: yesterday's daily close, which is today's 00:00 UTC open on crypto. Without daily candles, the last close of the previous session." });
output("em_pct", none, overlay, { description: "The expected move for the horizon, in percent: the range with about even odds. It is 0.85 of the straddle (a call plus a put at today's price) at the horizon's IV." });
output("sd_pct", none, overlay, { description: "The 1σ range (one standard deviation) for the horizon, in percent: about a two in three chance. It is the horizon's IV times the square root of the horizon in years." });
// The rails: guides across the chart, tagged on the price axis by name, the move's pair solid, the 1σ range's dashed.
output("em_hi", line, overlay, { role: "guide", label: "Move high", axis_label: true, axis_look: "@rail_labels", color: "theme.muted", width: 1, line_style: "solid", omit_if_empty: true, description: "The prior close plus the expected move: the top of the even-odds range." });
output("em_lo", line, overlay, { role: "guide", label: "Move low", axis_label: true, axis_look: "@rail_labels", color: "theme.muted", width: 1, line_style: "solid", omit_if_empty: true, description: "The prior close minus the expected move: the bottom of the even-odds range." });
output("sd_hi", line, overlay, { role: "guide", label: "1σ high", axis_label: true, axis_look: "@rail_labels", color: "theme.muted", width: 1, line_style: "dashed", omit_if_empty: true, description: "The prior close plus the 1σ range (one standard deviation)." });
output("sd_lo", line, overlay, { role: "guide", label: "1σ low", axis_label: true, axis_look: "@rail_labels", color: "theme.muted", width: 1, line_style: "dashed", omit_if_empty: true, description: "The prior close minus the 1σ range (one standard deviation)." });
output("front_move_pct", none, overlay, { description: "The expected move to the first expiry after today, in percent of its forward price." });
output("earnings_move_pct", none, overlay, { description: "The expected move to the first expiry after the earnings report, in percent. US stocks and ETFs only. Empty with no report ahead." });
output("earnings_days", none, overlay, { description: "Days to that expiry, on the market's calendar." });
output("report_days", none, overlay, { description: "Days to the earnings report on the market's calendar, 0 on the day. Empty with no report ahead." });
output("rv_20d", none, overlay, { description: "Realized volatility: how much price actually moved over the last 20 daily moves, as a yearly percent. It counts 365 days a year on crypto and 252 elsewhere. Live candle only." });
output("cone_count", none, overlay, { description: "How many end dates the cone draws ahead of the live candle." });
output("call_skew", none, overlay, { description: "The 25 delta call IV divided by the IV at today's price, at the expiry nearest 30 days. It scales the cone's up side. Empty with Skew priced off, or without that quote or a spot price." });
output("put_skew", none, overlay, { description: "The 25 delta put IV divided by the IV at today's price, at the expiry nearest 30 days. It scales the cone's down side." });
output("front_up_pct", none, overlay, { description: "The nearest end date's 1σ up side, in percent of the live close. The nearest end date is the first one the settings pick and this chart interval shows." });
output("front_down_pct", none, overlay, { description: "The nearest end date's 1σ down side, in percent of the live close." });
output("front_straddle_pct", none, overlay, { description: "The nearest end date's expected move: 0.85 of the straddle (a call plus a put at today's price), in percent." });
output("front_realized_pct", none, overlay, { description: "The nearest end date's move if price keeps moving as it did over the last 20 days, in percent." });
output("event_horizons", none, overlay, { description: "The end dates that come after the earnings report, as a sum. 1 close, 2 next day, 4 week, 8 OPEX (the monthly expiry), 16 30 days. Empty with no report ahead." });
string("title", { max_bytes: 64 }); // the card's title: the horizon
string("move_text", { max_bytes: 48 }); // the headline: the move in percent and in price, or why there is none
string("anchor_text", { max_bytes: 32 }); // where the band starts: 00:00 UTC 82,704 on crypto, Prior close 660.10 elsewhere, Prior bar close without daily candles
string("tag", { max_bytes: 40 }); // one bounded slot the levels' and the cone's price texts are written through, one at a time
string("expiry_1", { max_bytes: 48 }); // the next six expiries: date, time to go, the expected move in price and percent
string("expiry_2", { max_bytes: 48 });
string("expiry_3", { max_bytes: 48 });
string("expiry_4", { max_bytes: 48 });
string("expiry_5", { max_bytes: 48 });
string("expiry_6", { max_bytes: 48 });
string("cone_close", { max_bytes: 48 }); // each horizon's row: its time to go, its 1σ up and down legs in percent, the earnings mark
string("cone_1d", { max_bytes: 48 });
string("cone_week", { max_bytes: 48 });
string("cone_opex", { max_bytes: 48 });
string("cone_30d", { max_bytes: 48 });
string("check_horizon", { max_bytes: 48 }); // the front horizon: its name, its time to go, the earnings mark
string("check_sd", { max_bytes: 48 }); // its 1σ legs in price
string("check_straddle", { max_bytes: 48 }); // 0.85 of its at-the-money straddle, in price and percent
string("check_realized", { max_bytes: 48 }); // its 20-day realized move, in price and percent
handles.line({ width: 1, extend: "both" }); // the twelve levels, across the whole chart
handles.label({ anchor: "right", align: "right", size: 11, color: "theme.muted", style: "plain" }); // price text: x in pixels from the right edge, y in price; the cone's dots and chips move to chart time
handles.polyline({ width: 1, color: "theme.text" }); // the cone: its legs, open, and its bands, filled with no outline
const level_rows = frame("level_rows", { max_bytes: 1024 }); // the levels at the past close, one row each, rising by price
plot.levels({ name: "level_names", frame: level_rows, dock: "right", width_px: 52, color: "theme.muted", opacity: 0.3, thickness_px: 14, font_size: 10, label_place: "axis" }); // a pill at the price axis on each level, the row's text its name
// The card: the expected move by the horizon leads as the headline, the 1σ range and the band's anchor beside each
// other, then the constant-maturity IVs and the next six expiries as rows, then the cones' legs and the front
// horizon's checks. A tile's label is fixed text, so the anchor, the expiry rows and the cones read their words from
// slots.
render.hud("expected_move", {
position: "bottom_center",
title: "{{title}}",
columns: 2,
tiles: [
tile.pill("Expected move", "move_text", { headline: true }),
tile.value("1σ range (68%)", "sd_pct", { format: "%" }),
tile.pill("Lines start at", "anchor_text"),
tile.rows("IV at today's price", [
["1 day", "iv_1d", "%"],
["5 days", "iv_5d", "%"],
["7 days", "iv_7d", "%"],
["14 days", "iv_14d", "%"],
["30 days", "iv_30d", "%"],
["60 days", "iv_60d", "%"],
["90 days", "iv_90d", "%"],
]),
tile.rows("Expected move by expiry", [
["1st", "expiry_1"],
["2nd", "expiry_2"],
["3rd", "expiry_3"],
["4th", "expiry_4"],
["5th", "expiry_5"],
["6th", "expiry_6"],
]),
tile.rows("Cones, 1σ up and down", [
["Close", "cone_close"],
["Next day", "cone_1d"],
["Week", "cone_week"],
["OPEX", "cone_opex"],
["30 days", "cone_30d"],
]),
tile.rows("Nearest horizon", [
["Horizon", "check_horizon"],
["1σ up, down", "check_sd"],
["Straddle, 0.85x", "check_straddle"],
["Realized, 20 days", "check_realized"],
]),
],
});
const ROW: i32 = OPTION_VIEW_ROW_VOL_TERM; // f64s per row of the chain's block: its widest word's (vol_term, 16)
const LISTED = 6; // expiries in the card's list
const HORIZON_DAYS: f64[] = [1.0, 5.0, 7.0, 14.0, 30.0, 60.0, 90.0];
const EARNINGS = 7; // the horizon setting's last choice: the rails run to the earnings expiry
const STOCK = 2; // market.kind(): a stock or ETF, the one market with earnings
const RAILS = 4; // the text rows hold the rails' four prices first, then the levels' twelve texts
const LEVELS = 12;
const lines: LineHandle[] = [ // the levels at the past close
draw.line(18), draw.line(19), draw.line(20), draw.line(21), draw.line(22), draw.line(23),
draw.line(24), draw.line(25), draw.line(26), draw.line(27), draw.line(28), draw.line(29),
];
const tags: LabelHandle[] = [ // their texts; ids are one space across kinds
draw.label(30), draw.label(31), draw.label(32), draw.label(33), draw.label(34), draw.label(35),
draw.label(36), draw.label(37), draw.label(38), draw.label(39), draw.label(40), draw.label(41),
];
const tagPrices = new StaticArray<f64>(RAILS + LEVELS); // the rows placed so far on this bar, so a level near another steps inward
const tagSlots = new StaticArray<i32>(RAILS + LEVELS); // the step inward each row holds (a rail's stays 0: its axis tag)
const expiryText = new TextBuilder(16); // an expiry's label, the kit's spelling, copied into the line by writeDate()
const stamp = new BookStamp(); // the book's readers, one block at its row width: its priced instant, spot and contracts
const numbers = new OptionNumbers(); // each expiry's moves and hours, each horizon's IV and moves
const moves = new ExpectedMoves(1); // the same expiry rows: the cones' IV that far out, in total variance
const term = new VolTerm(); // the term structure: the 25 delta wings
// The cone: one envelope through every horizon drawn, from the live bar's open to the farthest horizon's end. Its legs
// are open polylines (ids 8 to 11: the 1σ up and down legs, then the 2σ ones). Up to four bands fill it, 2 ids a band
// from id 100: a band's near half is one polygon at its full alpha, its far half one polygon whose gradient falls from
// that alpha to nothing at the far end. Each horizon's dots and chips are labels 42 to 61, four a horizon (its top
// dot, bottom dot, top chip, bottom chip), the far end's 2σ ones 62 to 65.
const HORIZONS = 5; // close, next day, week, OPEX, 30 days
const ALL = 5; // the Cone horizons setting's last choice: every horizon
const CONES_OFF = 0; // the Cones setting: off, 1σ, the 1σ cone over the 2σ cone
const CONES_BOTH = 2;
const STYLE_FAN = 0; // the Cone style setting: Fan, Up and down tint
const LABELS_NEAR = 0; // the Cone labels setting: the two nearest horizons drawn, every horizon, none
const LABELS_ALL = 1;
const NEAR_HORIZONS = 2; // the horizons Cone labels near prints
const LEG_POINTS = 31; // the samples on the square root of time, at most
const MIN_LEG_POINTS = 5;
const MIN_BARS = 4.0; // a horizon under this many bars of the chart's interval is hidden: no cone, no check
const MAX_BARS = 10000.0; // nor does one past this many show, unless Cone horizons names it alone
const DRAW_BARS = 200.0; // the cone stops short of a horizon past this many, unless named alone: the card still reads it
const CROWD_BARS = 4.0; // a horizon ending within this many bars of the next one drawn, or CROWD_SHARE of the cone's
const CROWD_SHARE = 0.05; // span in time if that is more, keeps its dots and leaves its chips to the farther one
const SKEW_DAYS = 30.0; // the wings price the legs at the expiry after today nearest 30 days
const RV_RETURNS = 20; // the realized move's daily log returns
const DAY_MS = 86400000.0;
const HORIZON_WORDS: String[] = ["Close", "Next day", "Week", "OPEX", "30 days"];
const CONE_WORDS: String[] = ["Today", "Next day", "Week", "OPEX", "30d"]; // the chips' words; the close reads Close once today's session has ended
const coneEnd = new StaticArray<f64>(HORIZONS); // per horizon: its end, epoch milliseconds
const coneYears = new StaticArray<f64>(HORIZONS); // its time from the book's priced instant, in 365-day years
const coneIv = new StaticArray<f64>(HORIZONS); // its at-the-money IV, a decimal
const coneUp = new StaticArray<f64>(HORIZONS); // its 1σ up leg, a share of the live close
const coneDown = new StaticArray<f64>(HORIZONS); // its 1σ down leg
const coneHidden = new StaticArray<bool>(HORIZONS); // the chart's interval hides it
const coneDrawn = new StaticArray<bool>(HORIZONS); // the cone runs through its end
const coneCrowded = new StaticArray<bool>(HORIZONS); // it ends close to the next horizon drawn: its dots draw, its chips not
const coneNear = new StaticArray<bool>(HORIZONS); // one of the two nearest of the rest: Cone labels near prints its chips
const nyClock = new Clock("America/New_York"); // a session's end on the market's own clock
const chicagoClock = new Clock("America/Chicago");
const dayClock = new Clock("UTC"); // a trade date's month, for its third Friday
const daily = new CandleList(RV_RETURNS + 1); // the newest 21 daily closes: the realized move
// The levels at the past close: the day, the week and the month, each its 1σ and 2σ highs and lows from the anchor.
const LEVEL_DAYS: StaticArray<f64> = [1.0, 7.0, 30.0];
const LEVEL_NAMES: String[] = [
"Day +1σ", "Day -1σ", "Day +2σ", "Day -2σ",
"Week +1σ", "Week -1σ", "Week +2σ", "Week -2σ",
"Month +1σ", "Month -1σ", "Month +2σ", "Month -2σ",
];
const LEVEL_PILLS: String[] = [ // each level's pill at the price axis, in LEVEL_NAMES' order
"Day +1σ", "Day −1σ", "Day +2σ", "Day −2σ",
"Wk +1σ", "Wk −1σ", "Wk +2σ", "Wk −2σ",
"Mo +1σ", "Mo −1σ", "Mo +2σ", "Mo −2σ",
];
const LEVEL_INK = theme.MUTED;
const levelAt = new StaticArray<f64>(LEVELS); // this bar's levels in that order, NaN where they do not draw
const pillName = new StaticArray<i32>(LEVELS); // the pills' rows, rising by price: each row's level
// The cone's looks. A band runs between two edges, each a number of 1σ legs from the live close: up legs above it when
// positive, down legs below it when negative. Fan's four bands, then Tint's: its upper and lower halves, then its rings.
const BANDS = 4;
const BAND_IDS = 2; // its near half, then its far half: a live tick resends 12 polylines, 4 legs and 8 halves
const BAND_TOP: StaticArray<f64> = [0.5, 1.0, 1.5, 2.0, 1.0, 0.0, 2.0, -1.0];
const BAND_BOTTOM: StaticArray<f64> = [-0.5, -1.0, -1.5, -2.0, 0.0, -1.0, 1.0, -2.0];
const FAN_ALPHA = 0.035; // a Fan band's fill in the text colour: four stack in the middle
const TINT_ALPHA = 0.17; // a Tint half's fill: the up colour above the close, the down colour below
const RING_ALPHA = 0.06; // a Tint ring's, 1σ to 2σ
const NO_STROKE = alpha(theme.TEXT, 0.0); // a band's outline: none, the legs are the only strokes
const LEG_K: StaticArray<f64> = [1.0, -1.0, 2.0, -2.0]; // the legs' edges: 1σ up and down, then 2σ
const DOT_PX = 6; // a dot's width in px
const CHIP_FILL = alpha(theme.TEXT, 0.06); // a chip's box: a faint fill and border in the text colour, muted text
const CHIP_BORDER = alpha(theme.TEXT, 0.15);
const CHIP_PAD = 4.0;
const coneLegs: PolylineHandle[] = [draw.polyline(8), draw.polyline(9), draw.polyline(10), draw.polyline(11)];
const coneBands = polylinesFrom(100, BANDS * BAND_IDS);
const coneMarks = labelsFrom(42, 4 * HORIZONS + 4);
const ENVELOPE_POINTS = 40; // the legs' vertices at most: the 31 samples, the as-of, the fade's start, four more ends
const envX = new StaticArray<f64>(ENVELOPE_POINTS); // each vertex's time, epoch seconds, rising
const envUp = new StaticArray<f64>(ENVELOPE_POINTS); // the 1σ up leg there, a share of the live close
const envDown = new StaticArray<f64>(ENVELOPE_POINTS); // the 1σ down leg
let envCount = 0;
let fadeAt = 0; // the vertex the fade starts at, half way to the far end in time
const spanX = new StaticArray<f64>(ENVELOPE_POINTS + 2); // one band polygon's times: its two ends, the vertices between
const conePoints = new StaticArray<f64>(4 * (ENVELOPE_POINTS + 2)); // one polyline's points, x and y pairwise
let horizonChoice = 0; // settings, read in onStart()
let horizon = 1.0;
let conesChoice = CONES_BOTH;
let horizonsChoice = ALL;
let styleChoice = STYLE_FAN;
let labelsChoice = LABELS_ALL;
let skewPriced = true;
let pastLevels = false;
let reportMs: f64 = NaN; // the report the card reads: the Earnings date setting's instant on a stock or ETF, NaN otherwise
let stock = false; // a stock or ETF: the one market whose card reads earnings
let zone = 0;
let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none
let close: f64 = NaN; // this bar
let t: f64 = NaN;
let firstT: f64 = NaN; // the first bar's open time: where the levels' lines start
let sessionKey: f64 = NaN; // the trade date the bars are in, days since 1970-01-01
let sessionClose: f64 = NaN; // the last close seen in it
let priorClose: f64 = NaN; // the last close of the trade date before it
let dayClose: f64 = NaN; // the newest closed daily candle's close: the band's anchor whatever the chart's interval
let prevT: f64 = NaN; // the bar before's open time
let minStep = Infinity; // the shortest gap between two bars, seconds: above a day the chart's bars are longer than a day
let nowMs: f64 = NaN; // the book's priced instant, the clock every row counts from; NaN without a book
let callSkew: f64 = NaN; // the 25 delta call and put IVs over the at-the-money IV at the expiry nearest 30 days
let putSkew: f64 = NaN;
let realized: f64 = NaN; // the 20-day realized volatility, a decimal; live bar only
let lead = -1; // the front horizon: the first one the settings name and the chart's interval shows
let coneCount = 0; // the horizons whose cones draw
let coneFar = -1; // the farthest horizon drawn, the cone's far end; -1 when the cone does not draw
let barStep: f64 = NaN; // the bar's length in seconds: the chart's interval, else the bars' spacing
let closeToday = true; // the close horizon ends today's session: its end labels read Today, else Close
function onStart(): void {
horizonChoice = i32(p_horizon());
horizon = horizonChoice == EARNINGS ? NaN : HORIZON_DAYS[horizonChoice];
conesChoice = i32(p_cones());
horizonsChoice = i32(p_horizons());
styleChoice = i32(p_cone_style());
labelsChoice = i32(p_cone_labels());
skewPriced = p_skew_priced() > 0.5;
pastLevels = p_past_levels() > 0.5;
stock = i32(p_market_kind()) == STOCK;
reportMs = p_earnings_date() > 0.0 && stock ? p_earnings_date() * 1000.0 : NaN; // no other market reports earnings
zone = i32(p_market_zone());
intervalMs = p_chart_interval_sec() * 1000.0;
}
// ── The prior session's close: the last close of the trade date before the one the bars are in ──
function trackSession(): void {
const date = in_trade_date(); // epoch seconds of the trade date, as the chart writes it
const key = isFinite(date) ? Math.floor(date / 86400.0) : optionsTradeDay(t * 1000.0, zone);
if (isNaN(key)) return;
if (isNaN(sessionKey)) sessionKey = key;
else if (key > sessionKey) {
priorClose = sessionClose; // a new trade date: the last close of the one before is the prior session's
sessionKey = key;
}
if (!isNaN(close)) sessionClose = close;
}
// ── The band's anchor: the newest closed daily candle's close, from the daily candles whatever the chart's interval ──
function trackDays(): void {
const block = in_days_view();
const cells = in_days_cells(); // six f64 per candle: [offset_ms, open, high, low, close, volume]; -1 or 0 carries none
const n = cells < block.length ? cells : block.length;
for (let i = 0; i + 6 <= n; i += 6) if (block[i + 4] > 0.0) dayClose = block[i + 4]; // oldest first: the last is the newest
daily.load(block, cells, t); // the same candles kept for the realized move
}
// ── The book: the live bar's block, read whole by every reader at its row width; whether it carried a stamp. A block
// holding no book (none yet, or the empty book: its stamp alone) reads as no rows, so nothing an earlier tick read stays.
function readBook(): bool {
const cells = in_chain_view(); // the view block in place: the first n values of the build's own buffer
const n = in_chain_cells() >= ROW ? in_chain_cells() : 0;
const stamped = stamp.load(cells, n, ROW);
const rows = stamped && !stamp.empty() && isFinite(stamp.pricedAtMs()) ? n : 0;
numbers.load(cells, rows, ROW);
moves.loadNumbers(cells, rows, ROW);
term.load(cells, rows, ROW);
nowMs = rows > 0 ? stamp.pricedAtMs() : NaN;
return stamped;
}
function horizonRow(days: f64): i32 { // the numbers' horizon row `days` calendar days after the book's priced instant
const years = (days * DAY_MS) / OPTIONS_YEAR_MS;
for (let h = 0; h < numbers.horizons(); h += 1) if (Math.abs(numbers.horizonYears(h) - years) <= years * 1e-9) return h;
return -1; // the block carries none
}
// ── The cones' calendar: each horizon's end on the market's own clock ──
function weekdayOf(day: f64): i32 { // 0 Sunday to 6 Saturday: day 0, 1970-01-01, was a Thursday
return i32((i64(day) + 4) % 7);
}
function tradesOn(day: f64): bool { // crypto trades every day, every other market Monday to Friday
const w = weekdayOf(day);
return zone == 0 || (w >= 1 && w <= 5);
}
function nextSession(day: f64): f64 { // the first trade date after day
let d = day + 1.0;
while (!tradesOn(d)) d += 1.0;
return d;
}
function sessionEndMs(day: f64): f64 { // a trade date's end: 16:00 New York or Chicago, the next 00:00 UTC on crypto
if (zone == 1) return nyClock.epochSec(1970, 1, 1 + i32(day), 16, 0) * 1000.0; // the clock normalises the day count
if (zone == 2) return chicagoClock.epochSec(1970, 1, 1 + i32(day), 16, 0) * 1000.0;
return (day + 1.0) * DAY_MS;
}
function thirdFriday(day: f64, monthsOn: i32): f64 { // the third Friday of day's month, monthsOn months later
dayClock.update(day * 86400.0);
const first = epochSec(dayClock.year(), dayClock.month() + monthsOn, 1) / 86400.0; // month 13 is next January
return first + f64((12 - weekdayOf(first)) % 7) + 14.0; // the first Friday, two weeks on
}
// ── The skew: the 25 delta wings at the expiry after today nearest 30 days, each over that expiry's at-the-money IV ──
// Its term structure row holds the strangle (the wings' mean) and the risk reversal (call less put), in vol points as
// its at-the-money IV. Without a spot the term structure reads nothing, as the chart's own term panes read it.
function measureSkew(measured: bool, todayKey: f64): void {
callSkew = NaN;
putSkew = NaN;
if (!measured || !skewPriced || !(stamp.spot() > 0.0)) return;
let row = -1;
for (let i = 0; i < term.expiries(); i += 1) {
if (term.noQuote(i) || !(term.atmIv(i) > 0.0) || !(optionsTradeDay(term.expiryMs(i), zone) > todayKey)) continue;
if (row < 0 || Math.abs(term.days(i) - SKEW_DAYS) < Math.abs(term.days(row) - SKEW_DAYS)) row = i; // ties the earlier
}
const call = term.str25(row) + 0.5 * term.rr25(row); // NaN without a row
const put = term.str25(row) - 0.5 * term.rr25(row);
if (!(call > 0.0) || !(put > 0.0)) return; // a wing missing: both legs read the at-the-money IV
callSkew = call / term.atmIv(row);
putSkew = put / term.atmIv(row);
}
// ── The cones: each horizon's end, its time, its IV and its legs ──
function measureCones(): void {
const today = optionsTradeDay(nowMs, zone);
let session = today; // the session the close reads: today's, the next one's once today's has ended
while (!tradesOn(session)) session += 1.0;
if (sessionEndMs(session) <= nowMs) session = nextSession(session);
closeToday = session == today;
let friday = today + f64((12 - weekdayOf(today)) % 7); // this Friday: the first on or after today
if (sessionEndMs(friday) <= nowMs) friday += 7.0;
let opex = thirdFriday(today, 0); // this month's third Friday, next month's once it has passed
if (opex < today || sessionEndMs(opex) <= nowMs) opex = thirdFriday(today, 1);
unchecked((coneEnd[0] = sessionEndMs(session)));
unchecked((coneEnd[1] = sessionEndMs(nextSession(session))));
unchecked((coneEnd[2] = sessionEndMs(friday)));
unchecked((coneEnd[3] = sessionEndMs(opex)));
unchecked((coneEnd[4] = nowMs + 30.0 * DAY_MS));
for (let h = 0; h < HORIZONS; h += 1) {
const years = (unchecked(coneEnd[h]) - nowMs) / OPTIONS_YEAR_MS;
const iv = moves.horizonIv(years); // between the expiry rows around the end, in total variance (totalVarianceIv)
unchecked((coneYears[h] = years));
unchecked((coneIv[h] = iv));
unchecked((coneUp[h] = oneSigmaMove(1.0, isNaN(callSkew) ? iv : iv * callSkew, years)));
unchecked((coneDown[h] = oneSigmaMove(1.0, isNaN(putSkew) ? iv : iv * putSkew, years)));
}
}
function named(h: i32): bool { // the Cone horizons setting names this horizon, or all of them
return horizonsChoice == ALL || horizonsChoice == h;
}
// Which horizons show: named, read, and wide enough for the chart's interval (and not too wide, unless named alone);
// the first shown is the front horizon the card checks. The cone runs through those ending within 200 bars (unless
// named alone) and after every earlier one drawn: the cap is the drawing's alone, the card reads every horizon shown.
// A horizon drawn that ends close to the next one drawn leaves its chips to it, and the two ending first of the rest
// are the ones Cone labels near prints.
function pickCones(measured: bool): void {
lead = -1;
coneCount = 0;
coneFar = -1;
barStep = intervalMs > 0.0 ? intervalMs / 1000.0 : minStep; // the bar's length, seconds: the chart's, else the bars' spacing
const sized = isFinite(barStep) && barStep > 0.0; // the bar caps need a bar's length
for (let h = 0; h < HORIZONS; h += 1) {
unchecked((coneHidden[h] = false));
unchecked((coneDrawn[h] = false));
if (!measured || !named(h) || !(close > 0.0) || isNaN(unchecked(coneUp[h])) || isNaN(unchecked(coneDown[h]))) continue;
const span = unchecked(coneEnd[h]) / 1000.0 - t; // the cone's width in seconds, from the live bar's open
const hidden = sized && (span < MIN_BARS * barStep || (horizonsChoice == ALL && span > MAX_BARS * barStep));
unchecked((coneHidden[h] = hidden));
if (hidden) continue;
if (lead < 0) lead = h;
if (conesChoice == CONES_OFF) continue;
if (sized && horizonsChoice == ALL && span > DRAW_BARS * barStep) continue; // shown and read, not drawn
let repeat = false; // a horizon ending with an earlier one draws once
for (let j = 0; j < h; j += 1) if (unchecked(coneDrawn[j]) && unchecked(coneEnd[j]) == unchecked(coneEnd[h])) repeat = true;
if (repeat) continue;
unchecked((coneDrawn[h] = true));
coneCount += 1;
if (coneFar < 0 || unchecked(coneEnd[h]) > unchecked(coneEnd[coneFar])) coneFar = h;
}
// Too close to the next horizon drawn: within CROWD_BARS bars or CROWD_SHARE of the cone's span from the live bar's
// open, whichever is more, its chips would sit on that one's. The far end has no next one and always keeps its own.
const crowd = coneFar < 0 ? 0.0 : Math.max(sized ? CROWD_BARS * barStep : 0.0, CROWD_SHARE * (unchecked(coneEnd[coneFar]) / 1000.0 - t));
for (let h = 0; h < HORIZONS; h += 1) {
unchecked((coneCrowded[h] = false));
if (!unchecked(coneDrawn[h])) continue;
let next = -1; // the horizon drawn that ends first after this one
for (let j = 0; j < HORIZONS; j += 1) {
if (!unchecked(coneDrawn[j]) || unchecked(coneEnd[j]) <= unchecked(coneEnd[h])) continue;
if (next < 0 || unchecked(coneEnd[j]) < unchecked(coneEnd[next])) next = j;
}
unchecked((coneCrowded[h] = next >= 0 && (unchecked(coneEnd[next]) - unchecked(coneEnd[h])) / 1000.0 <= crowd));
}
for (let h = 0; h < HORIZONS; h += 1) unchecked((coneNear[h] = false));
for (let pick = 0; pick < NEAR_HORIZONS; pick += 1) {
let next = -1;
for (let h = 0; h < HORIZONS; h += 1) {
if (!unchecked(coneDrawn[h]) || unchecked(coneCrowded[h]) || unchecked(coneNear[h])) continue;
if (next < 0 || unchecked(coneEnd[h]) < unchecked(coneEnd[next])) next = h;
}
if (next >= 0) unchecked((coneNear[next] = true));
}
}
// ── The realized move: the sample standard deviation of the last 20 daily log returns, annualized ──
function realizedVol(): f64 {
const held = daily.count();
if (held < RV_RETURNS + 1) return NaN; // 20 returns need 21 closes
let sum = 0.0;
for (let k = held - RV_RETURNS; k < held; k += 1) {
const before = daily.close(k - 1);
const after = daily.close(k);
if (!(before > 0.0) || !(after > 0.0)) return NaN;
sum += Math.log(after / before);
}
const mean = sum / f64(RV_RETURNS);
let squares = 0.0;
for (let k = held - RV_RETURNS; k < held; k += 1) {
const r = Math.log(daily.close(k) / daily.close(k - 1)) - mean;
squares += r * r;
}
return Math.sqrt(squares / f64(RV_RETURNS - 1)) * Math.sqrt(zone == 0 ? 365.0 : 252.0); // crypto trades every day
}
// ── The earnings report inside a horizon: after the book's priced instant, by the horizon's end ──
function holdsReport(h: i32): bool {
return reportMs > nowMs && reportMs <= unchecked(coneEnd[h]);
}
function reportBits(): f64 { // the horizons holding the report: 1 close, 2 next day, 4 week, 8 OPEX, 16 30 days
let bits = 0;
for (let h = 0; h < HORIZONS; h += 1) if (holdsReport(h)) bits |= 1 << h;
return f64(bits);
}
// ── Text helpers ──
function sbGrouped(n: i64): void { // 84210 -> 84,210
if (n >= 1000) {
sbGrouped(n / 1000);
sb_text(",");
const r = n % 1000;
if (r < 100) sb_text("0");
if (r < 10) sb_text("0");
sb_int(r);
} else sb_int(n);
}
function sbPrice(v: f64): void { // decimals follow the price's size: 6,652 / 660.10 / 48.125
if (v >= 1000.0) sbGrouped(i64(Math.round(v)));
else if (v >= 100.0) sb_f64(v, 2);
else sb_f64(v, 3);
}
function sbAmount(v: f64): void { // a move in price: 1,840 / 8.18
if (v >= 1000.0) sbGrouped(i64(Math.round(v)));
else sb_f64(v, 2);
}
function near(a: f64, b: f64): bool { // two levels within 0.3% of each other would share a text row
return !isNaN(a) && !isNaN(b) && Math.abs(a - b) <= Math.abs(b) * 0.003;
}
function stepTaken(which: i32, price: f64, step: i32): bool { // an earlier text within 0.3% of this price already sits at this step
for (let j = 0; j < which; j += 1) if (tagSlots[j] == step && near(tagPrices[j], price)) return true;
return false;
}
function drawLevel(level: i32, price: f64): void { // a level across the chart and its name and price just above it
const which = RAILS + level; // its text row, after the rails'
if (isNaN(price)) {
lines[level].delete(); // no-ops when never drawn
tags[level].delete();
tagPrices[which] = NaN;
tagSlots[which] = -1;
return;
}
lines[level].set(firstT, price, t, price).color(LEVEL_INK).width(1.0).style(LineStyle.Dashed).extend(Extend.Both);
let step = 0; // the first step inward that no earlier text within 0.3% holds
while (stepTaken(which, price, step)) step += 1;
tagPrices[which] = price;
tagSlots[which] = step;
sb_clear();
sb_text(LEVEL_NAMES[level]);
sb_text(" ");
sbPrice(price);
tags[level].set(56.0 + 112.0 * f64(step), 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; each step is 112 px further in
}
// The levels at the past close: the day, the week and the month, each anchor times one plus and minus one and two of
// its 1σ moves, the numbers' own that many calendar days out, then each named in a pill at the price axis.
function drawLevels(anchor: f64, measured: bool): void {
for (let p = 0; p < 3; p += 1) {
const move = numbers.horizonSigma(horizonRow(unchecked(LEVEL_DAYS[p]))); // a share of the anchor
for (let k = 0; k < 4; k += 1) { // +1σ, -1σ, +2σ, -2σ
const sigmas = k < 2 ? 1.0 : 2.0;
const sign = k % 2 == 0 ? 1.0 : -1.0;
const price = pastLevels && measured ? anchor * (1.0 + sign * sigmas * move) : NaN;
unchecked((levelAt[4 * p + k] = price));
drawLevel(4 * p + k, price);
}
}
writePills();
}
// The pills: one row of the docked level per level drawn, its name the row's text, the rows rising by price (a level
// on another's price keeps one pill), sent as the levels frame. No level, no frame, so no pill.
function writePills(): void {
let rows = 0;
let last = -Infinity;
while (rows < LEVELS) { // the lowest level above the last row's; a NaN level never compares, so it makes no row
let next = -1;
for (let i = 0; i < LEVELS; i += 1) {
const price = unchecked(levelAt[i]);
if (price > last && (next < 0 || price < unchecked(levelAt[next]))) next = i;
}
if (next < 0) break;
unchecked((pillName[rows] = next));
last = unchecked(levelAt[next]);
rows += 1;
}
if (rows == 0) return;
fb_clear();
fb_text("{\"prices\":[");
for (let r = 0; r < rows; r += 1) {
if (r > 0) fb_text(",");
fb_num(unchecked(levelAt[unchecked(pillName[r])]));
}
fb_text("],\"values\":[");
for (let r = 0; r < rows; r += 1) fb_text(r > 0 ? ",1" : "1"); // every pill the dock's width
fb_text("],\"labels_text\":[");
for (let r = 0; r < rows; r += 1) {
if (r > 0) fb_text(",");
fb_str(LEVEL_PILLS[unchecked(pillName[r])]);
}
fb_text("]}");
writeFrameBuffer(level_rows);
}
// The samples on the square root of time: one a bar on a cone narrower than 31 bars, at least 5, and odd, so the
// sample in the middle sits a quarter of the way to the end in time.
function legPoints(span: f64): i32 {
let n = LEG_POINTS;
if (isFinite(barStep) && barStep > 0.0) {
const bars = Math.ceil(span / barStep) + 1.0;
if (bars < f64(LEG_POINTS)) n = i32(bars);
}
if (n % 2 == 0) n += 1;
return n < MIN_LEG_POINTS ? MIN_LEG_POINTS : n;
}
// A leg at x, epoch seconds, a share of the live close: the time to go runs from the book's priced instant and never
// below 0, so the legs hold the close up to it; the at-the-money IV that far out, scaled by the wing's ratio when Skew
// priced reads one, and the kit's 1σ move.
function legAt(x: f64, skew: f64): f64 {
const years = Math.max(0.0, x * 1000.0 - nowMs) / OPTIONS_YEAR_MS;
const iv = moves.horizonIv(years);
return oneSigmaMove(1.0, isNaN(skew) ? iv : iv * skew, years);
}
function addVertex(x: f64): void { // a vertex at x, kept in time order; one already there is not repeated
let at = envCount;
while (at > 0 && unchecked(envX[at - 1]) > x) at -= 1;
if (at > 0 && unchecked(envX[at - 1]) == x) return;
for (let k = envCount; k > at; k -= 1) unchecked((envX[k] = envX[k - 1]));
unchecked((envX[at] = x));
envCount += 1;
}
// The legs' vertices from the live bar's open t to the far end: the samples stepping evenly in u, at u squared of the
// way (densest by the apex, where the legs bend most), the book's priced instant, the fade's start half way, and every
// horizon's end drawn, so each horizon's dots sit on a vertex. Then each vertex's legs.
function buildEnvelope(far: f64): void {
envCount = 0;
const n = legPoints(far - t);
for (let i = 0; i < n; i += 1) {
const u = f64(i) / f64(n - 1);
addVertex(i == n - 1 ? far : t + (far - t) * u * u);
}
const asOf = nowMs / 1000.0;
if (asOf > t && asOf < far) addVertex(asOf);
const half = t + (far - t) * 0.5;
addVertex(half);
for (let h = 0; h < HORIZONS; h += 1) if (unchecked(coneDrawn[h])) addVertex(unchecked(coneEnd[h]) / 1000.0);
for (let i = 0; i < envCount; i += 1) {
const x = unchecked(envX[i]);
if (x == half) fadeAt = i;
unchecked((envUp[i] = legAt(x, callSkew)));
unchecked((envDown[i] = legAt(x, putSkew)));
}
}
function edgeAt(k: f64, i: i32): f64 { // k 1σ legs from the live close at vertex i: up legs above it, down legs below
return k >= 0.0 ? close * (1.0 + k * unchecked(envUp[i])) : close * (1.0 + k * unchecked(envDown[i]));
}
// A band edge k 1σ legs from the live close at time x: a vertex's own at a vertex, and between two vertices a point
// on the straight line joining theirs, where the legs run straight too.
function edgeBetween(k: f64, x: f64): f64 {
let i = envCount - 1;
while (i > 0 && unchecked(envX[i]) > x) i -= 1; // the last vertex at or before x
const a = edgeAt(k, i);
if (i == envCount - 1 || unchecked(envX[i]) == x) return a;
return a + (edgeAt(k, i + 1) - a) * ((x - unchecked(envX[i])) / (unchecked(envX[i + 1]) - unchecked(envX[i])));
}
// One band from time xa to xb, its points in conePoints: its top edge out through xa, every vertex strictly between
// them and xb, its bottom edge back. Returns the points written.
function spanPoints(row: i32, xa: f64, xb: f64): i32 {
let n = 0;
unchecked((spanX[n] = xa));
n += 1;
for (let i = 0; i < envCount; i += 1) {
const x = unchecked(envX[i]);
if (x > xa && x < xb) {
unchecked((spanX[n] = x));
n += 1;
}
}
unchecked((spanX[n] = xb));
n += 1;
for (let i = 0; i < n; i += 1) {
const x = unchecked(spanX[i]);
const back = 2 * n - 1 - i;
unchecked((conePoints[2 * i] = x));
unchecked((conePoints[2 * i + 1] = edgeBetween(BAND_TOP[row], x)));
unchecked((conePoints[2 * back] = x));
unchecked((conePoints[2 * back + 1] = edgeBetween(BAND_BOTTOM[row], x)));
}
return 2 * n;
}
// The bands: Fan's 0.5σ, 1σ, 1.5σ and 2σ in the text colour, or Tint's halves in the up and down colours with its rings
// past them; the 1σ cone alone keeps the first two. Each band's near half, from the apex to the fade's start half way
// along, is one polygon at its full alpha; its far half, from there to the far end, is one polygon whose horizontal
// gradient falls from that alpha to 0, a straight fall the chart paints across the polygon's bounding box. Both go
// with no outline. Every id a band does not draw is deleted.
function drawBands(drawn: bool): void {
const far = drawn ? unchecked(envX[envCount - 1]) : NaN;
const half = drawn ? unchecked(envX[fadeAt]) : NaN;
for (let b = 0; b < BANDS; b += 1) {
const on = drawn && (b < 2 || conesChoice == CONES_BOTH);
const fan = styleChoice == STYLE_FAN;
const ink = fan ? theme.TEXT : b % 2 == 0 ? theme.UP : theme.DOWN;
const full = fan ? FAN_ALPHA : b < 2 ? TINT_ALPHA : RING_ALPHA;
const row = styleChoice * BANDS + b;
const nearHalf = coneBands[b * BAND_IDS];
const farHalf = coneBands[b * BAND_IDS + 1];
if (!on) {
nearHalf.delete(); // a no-op when it never drew
farHalf.delete();
continue;
}
nearHalf.setPoints(conePoints, spanPoints(row, unchecked(envX[0]), half)).fill(alpha(ink, full)).color(NO_STROKE);
farHalf.setPoints(conePoints, spanPoints(row, half, far));
farHalf.gradient(alpha(ink, full), alpha(ink, 0.0), GradientDirection.Horizontal).color(NO_STROKE);
}
}
// The legs: open paths through every vertex, the 1σ solid and the 2σ dotted, in the text colour (Tint: the up colour
// above the close, the down colour below).
function drawLegs(drawn: bool): void {
for (let k = 0; k < 4; k += 1) {
const leg = coneLegs[k];
if (!drawn || (k >= 2 && conesChoice != CONES_BOTH)) {
leg.delete();
continue;
}
for (let i = 0; i < envCount; i += 1) {
unchecked((conePoints[2 * i] = envX[i]));
unchecked((conePoints[2 * i + 1] = edgeAt(LEG_K[k], i)));
}
const fan = styleChoice == STYLE_FAN;
const ink = fan ? theme.TEXT : k % 2 == 0 ? theme.UP : theme.DOWN;
const one = k < 2;
const a = one ? (fan ? 0.6 : 0.75) : fan ? 0.35 : 0.45;
leg.setPoints(conePoints, envCount).color(alpha(ink, a)).width(one ? 1.3 : 1.1).style(one ? LineStyle.Solid : LineStyle.Dotted);
}
}
// A chip: the text in the tag slot, its box's right edge by x (the text ends at x), above y for a top chip and below
// it for a bottom one, in chart time and price where the label template's are the right edge's pixels.
function placeChip(chip: LabelHandle, on: bool, x: f64, y: f64, above: bool): void {
if (!on) {
chip.delete();
return;
}
chip.set(x, y).text(str_tag_sb).anchor(ANCHOR_CHART).valign(above ? VALIGN_BOTTOM : VALIGN_TOP).style(LabelStyle.Box);
chip.fill(CHIP_FILL).border(CHIP_BORDER).cornerRadius(4.0).padding(CHIP_PAD).size(10).fontWeight(FontWeight.Normal);
}
function placeDot(dot: LabelHandle, on: bool, x: f64, y: f64, a: f64): void { // a dot centred on (x, y)
if (!on) {
dot.delete();
return;
}
dot.set(x, y).mark().anchor(ANCHOR_CHART).align(ALIGN_CENTER).style(LabelStyle.Emblem).emblem(Emblem.Dot).size(DOT_PX).color(alpha(theme.TEXT, a));
}
// The dots and chips: a dot on both 1σ legs at each horizon's end; above the top one its word and price (Today 1σ
// 662.10), below the bottom one its price, on the horizons Cone labels picks, never one crowded by the next; at the far
// end the 2σ ones (2σ 668.70). The chips draw first, so each dot sits over its chip's corner.
function drawMarks(far: i32): void {
const both = far >= 0 && conesChoice == CONES_BOTH;
for (let pass = 0; pass < 2; pass += 1) {
for (let h = 0; h <= HORIZONS; h += 1) {
const last = h == HORIZONS; // the far end's 2σ
const at = last ? far : h;
const on = last ? both : unchecked(coneDrawn[h]);
const x = on ? unchecked(coneEnd[at]) / 1000.0 : NaN;
const sigmas = last ? 2.0 : 1.0;
const top = on ? close * (1.0 + sigmas * legAt(x, callSkew)) : NaN;
const bottom = on ? close * (1.0 - sigmas * legAt(x, putSkew)) : NaN;
if (pass == 1) {
placeDot(coneMarks[4 * h], on, x, top, last ? 0.55 : 0.9);
placeDot(coneMarks[4 * h + 1], on, x, bottom, last ? 0.55 : 0.9);
continue;
}
const labeled = on && !unchecked(coneCrowded[at]) && (labelsChoice == LABELS_ALL || (labelsChoice == LABELS_NEAR && unchecked(coneNear[at])));
sb_clear();
if (last) sb_text("2σ ");
else {
sb_text(h == 0 && !closeToday ? HORIZON_WORDS[0] : CONE_WORDS[h]);
sb_text(" 1σ ");
}
sbPrice(top);
placeChip(coneMarks[4 * h + 2], labeled, x, top, true);
sb_clear();
if (last) sb_text("2σ ");
sbPrice(bottom);
placeChip(coneMarks[4 * h + 3], labeled, x, bottom, false);
}
}
}
// The cone ahead of the live bar: the envelope to the farthest horizon drawn, its bands, its legs, its dots and chips.
function drawCones(): void {
if (coneFar >= 0) buildEnvelope(unchecked(coneEnd[coneFar]) / 1000.0);
drawBands(coneFar >= 0);
drawLegs(coneFar >= 0);
drawMarks(coneFar);
}
function polylinesFrom(first: i32, count: i32): PolylineHandle[] { // the handles of ids first.. first + count - 1
const out = new Array<PolylineHandle>(0);
for (let k = 0; k < count; k += 1) out.push(draw.polyline(first + k));
return out;
}
function labelsFrom(first: i32, count: i32): LabelHandle[] {
const out = new Array<LabelHandle>(0);
for (let k = 0; k < count; k += 1) out.push(draw.label(first + k));
return out;
}
function writeDays(days: f64): void { // "1 day", "5 days"
sb_int(i64(days));
sb_text(days == 1.0 ? " day" : " days");
}
function writeDate(ms: f64): void { // "24 Oct", or "15 Jan '27" in another year: an expiry's trade date on the market's clock, the kit's label
expiryText.clear().expiry(ms, nowMs, zone);
for (let i = 0; i < expiryText.length(); i += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>i));
}
function writeExpiry(slot: i32, e: i32, earningsRow: i32, todayKey: f64): void { // "21 Oct 11h ±398 0.48%", the earnings expiry marked
sb_clear();
if (e >= 0 && e < numbers.expiries()) {
writeDate(numbers.expiryMs(e)); // the expiry's trade date
sb_text(" ");
const hours = numbers.hours(e);
if (hours < 48.0) { // under two days: the hours to go from the book's priced instant, to the expiry's pricing instant
sb_int(i64(Math.round(hours)));
sb_text("h ");
} else { // the days to go on the market's calendar
sb_int(i64(optionsTradeDay(numbers.expiryMs(e), zone) - todayKey));
sb_text("d ");
}
const move = numbers.expectedMove(e);
if (isNaN(move)) sb_text("no IV");
else {
sb_text("±");
sbAmount(move);
sb_text(" ");
sb_f64(numbers.expectedMovePct(e), 2);
sb_text("%");
}
if (e == earningsRow) sb_text(" earnings");
}
if (slot == 0) str_expiry_1_sb();
else if (slot == 1) str_expiry_2_sb();
else if (slot == 2) str_expiry_3_sb();
else if (slot == 3) str_expiry_4_sb();
else if (slot == 4) str_expiry_5_sb();
else str_expiry_6_sb();
}
function writeToGo(endMs: f64, todayKey: f64): void { // 25m or 4h under 48 hours, the days on the market's calendar after
const hours = (endMs - nowMs) / 3600000.0;
if (hours < 1.0) {
sb_int(i64(Math.round(hours * 60.0)));
sb_text("m");
} else if (hours < 48.0) {
sb_int(i64(Math.round(hours)));
sb_text("h");
} else {
sb_int(i64(optionsTradeDay(endMs, zone) - todayKey));
sb_text("d");
}
}
function writeCone(h: i32, measured: bool, todayKey: f64): void { // "4h +0.42% / -0.45%", the report and the interval marked
sb_clear();
if (measured) {
if (!named(h)) sb_text("off");
else if (isNaN(unchecked(coneUp[h])) || isNaN(unchecked(coneDown[h]))) sb_text("no IV");
else {
writeToGo(unchecked(coneEnd[h]), todayKey);
sb_text(" +");
sb_f64(unchecked(coneUp[h]) * 100.0, 2);
sb_text("% / -");
sb_f64(unchecked(coneDown[h]) * 100.0, 2);
sb_text("%");
if (holdsReport(h)) sb_text(" earnings");
if (unchecked(coneHidden[h])) sb_text(" hidden");
}
}
if (h == 0) str_cone_close_sb();
else if (h == 1) str_cone_1d_sb();
else if (h == 2) str_cone_week_sb();
else if (h == 3) str_cone_opex_sb();
else str_cone_30d_sb();
}
function writeMove(share: f64): void { // "±1.91 (0.29%)": a move as a share of the live close, in price and percent
if (isNaN(share)) {
sb_text("no IV");
return;
}
sb_text("±");
sbAmount(close * share);
sb_text(" (");
sb_f64(share * 100.0, 2);
sb_text("%)");
}
function writeCheck(measured: bool, todayKey: f64): void { // the front horizon against its straddle and its realized move
sb_clear();
if (lead >= 0) {
sb_text(HORIZON_WORDS[lead]);
sb_text(", ");
writeToGo(unchecked(coneEnd[lead]), todayKey);
if (holdsReport(lead)) sb_text(", earnings inside");
} else if (measured) sb_text("None at this interval");
str_check_horizon_sb();
sb_clear();
if (lead >= 0) {
sb_text("+");
sbAmount(close * unchecked(coneUp[lead]));
sb_text(" / -");
sbAmount(close * unchecked(coneDown[lead]));
}
str_check_sd_sb();
sb_clear();
if (lead >= 0) writeMove(straddleExpectedMove(1.0, unchecked(coneIv[lead]), unchecked(coneYears[lead])));
str_check_straddle_sb();
sb_clear();
if (lead >= 0) {
if (isNaN(realized)) {
sb_text("Needs ");
sb_int(i64(RV_RETURNS + 1));
sb_text(" daily closes");
} else writeMove(realized * Math.sqrt(unchecked(coneYears[lead])));
}
str_check_realized_sb();
}
// onBar() runs once per bar: every bar feeds the session tracker and the daily candles; the live bar reads the book,
// writes the readings (NaN on history rows), the rails, the levels, the cones and the card's words.
function onBar(): void {
close = bar.close();
t = bar.time();
if (isNaN(firstT) && !isNaN(t)) firstT = t;
if (t > prevT) minStep = Math.min(minStep, t - prevT);
prevT = t;
trackSession();
trackDays();
const stamped = bar.isLast() && !isNaN(t) && readBook(); // the live bar carried the book's answer
const measured = stamped && numbers.expiries() > 0; // and the book a live expiry
// The band's anchor: the newest daily close (yesterday's, today's 00:00 UTC open on crypto) whatever the chart's
// interval; without daily candles, the prior session's last close from the bars. The rails and the headline's price
// wait for a book with a live expiry; the anchor's own tile does not.
const anchor = !isNaN(dayClose) ? dayClose : priorClose;
const centre = measured ? anchor : NaN;
const clockMs = measured ? nowMs : t * 1000.0;
const todayKey = optionsTradeDay(clockMs, zone);
// The front expiry: the first one after today on the market's calendar, whatever its IV.
let front = -1;
for (let e = 0; measured && e < numbers.expiries(); e += 1) {
if (optionsTradeDay(numbers.expiryMs(e), zone) > todayKey) {
front = e;
break;
}
}
// The earnings expiry: the first one to settle after the report's instant, while the report is ahead.
const reportAhead = bar.isLast() && reportMs > clockMs;
let earningsRow = -1;
if (measured && reportAhead) {
for (let e = 0; e < numbers.expiries(); e += 1) {
if (numbers.expiryMs(e) > reportMs) {
earningsRow = e;
break;
}
}
}
// The rails' horizon: the numbers' row that many days out (its moves shares of an anchor of 1), or the earnings
// expiry's own moves in percent of its forward; NaN without either (a reader answers NaN outside its rows).
const railRow = horizonChoice == EARNINGS || !measured ? -1 : horizonRow(horizon);
const emPct = horizonChoice == EARNINGS ? numbers.expectedMovePct(earningsRow) : numbers.horizonMove(railRow) * 100.0;
const sdPct = horizonChoice == EARNINGS ? numbers.oneSigmaPct(earningsRow) : numbers.horizonSigma(railRow) * 100.0;
const reportDays = reportAhead ? optionsTradeDay(reportMs, zone) - todayKey : NaN;
// The cones: the skew, each horizon's legs and which of them draw; the realized move on the live bar.
measureSkew(measured, todayKey);
if (measured) measureCones();
pickCones(measured);
realized = bar.isLast() ? realizedVol() : NaN;
out_iv_1d(measured ? numbers.horizonIv(horizonRow(1.0)) * 100.0 : NaN);
out_iv_5d(measured ? numbers.horizonIv(horizonRow(5.0)) * 100.0 : NaN);
out_iv_7d(measured ? numbers.horizonIv(horizonRow(7.0)) * 100.0 : NaN);
out_iv_14d(measured ? numbers.horizonIv(horizonRow(14.0)) * 100.0 : NaN);
out_iv_30d(measured ? numbers.horizonIv(horizonRow(30.0)) * 100.0 : NaN);
out_iv_60d(measured ? numbers.horizonIv(horizonRow(60.0)) * 100.0 : NaN);
out_iv_90d(measured ? numbers.horizonIv(horizonRow(90.0)) * 100.0 : NaN);
out_prior_close(centre);
out_em_pct(emPct);
out_sd_pct(sdPct);
out_em_hi(centre * (1.0 + emPct / 100.0));
out_em_lo(centre * (1.0 - emPct / 100.0));
out_sd_hi(centre * (1.0 + sdPct / 100.0));
out_sd_lo(centre * (1.0 - sdPct / 100.0));
out_front_move_pct(front >= 0 ? numbers.expectedMovePct(front) : NaN);
out_earnings_move_pct(earningsRow >= 0 ? numbers.expectedMovePct(earningsRow) : NaN);
out_earnings_days(earningsRow >= 0 ? optionsTradeDay(numbers.expiryMs(earningsRow), zone) - todayKey : NaN);
out_report_days(reportDays);
out_rv_20d(realized * 100.0);
out_cone_count(measured ? f64(coneCount) : NaN);
out_call_skew(measured ? callSkew : NaN);
out_put_skew(measured ? putSkew : NaN);
out_front_up_pct(lead >= 0 ? unchecked(coneUp[lead]) * 100.0 : NaN);
out_front_down_pct(lead >= 0 ? unchecked(coneDown[lead]) * 100.0 : NaN);
out_front_straddle_pct(lead >= 0 ? straddleExpectedMove(1.0, unchecked(coneIv[lead]), unchecked(coneYears[lead])) * 100.0 : NaN);
out_front_realized_pct(lead >= 0 ? realized * Math.sqrt(unchecked(coneYears[lead])) * 100.0 : NaN);
out_event_horizons(measured && reportAhead ? reportBits() : NaN);
if (!bar.isLast()) return;
// The rails are the guides above, drawn and tagged on the price axis by the chart: each tag reaches into the chart at
// its rail's price, so the rail holds the first step there (tagSlots stays 0) and a level's text near it steps inward.
tagPrices[0] = centre * (1.0 + emPct / 100.0);
tagPrices[1] = centre * (1.0 - emPct / 100.0);
tagPrices[2] = centre * (1.0 + sdPct / 100.0);
tagPrices[3] = centre * (1.0 - sdPct / 100.0);
drawLevels(anchor, measured);
drawCones();
// The card's words: the title, the headline, the anchor, the six expiries after today, the cones and the checks.
sb_clear();
if (horizonChoice == EARNINGS) sb_text("Expected move to earnings");
else {
sb_text("Expected move, ");
writeDays(horizon);
}
str_title_sb();
sb_clear();
if (!stamped) sb_text("Waiting for this symbol's options");
else if (!measured) sb_text("No options still trading");
else if (horizonChoice == EARNINGS && !stock) sb_text("No earnings on this market");
else if (horizonChoice == EARNINGS && !reportAhead) sb_text("No earnings report ahead");
else if (horizonChoice == EARNINGS && earningsRow < 0) sb_text("No expiry after the report");
else if (isNaN(emPct)) sb_text("No implied volatility for this horizon");
else {
sb_text("±");
sb_f64(emPct, 2);
sb_text("%");
if (!isNaN(centre)) {
sb_text(" (±");
sbAmount((centre * emPct) / 100.0);
sb_text(")");
}
if (horizonChoice == EARNINGS) {
sb_text(" by ");
writeDate(numbers.expiryMs(earningsRow));
} else {
sb_text(" in ");
writeDays(horizon);
}
}
str_move_text_sb();
sb_clear();
if (isNaN(anchor)) sb_text("No prior close yet");
else {
if (isNaN(dayClose) && minStep > 86400.0) sb_text("Prior bar close "); // no daily candles: the bars' own close, a week or a month back
else sb_text(zone == 0 ? "00:00 UTC " : "Prior close "); // on crypto yesterday's close is today's 00:00 UTC open
sbPrice(anchor);
}
str_anchor_text_sb();
for (let k = 0; k < LISTED; k += 1) writeExpiry(k, front >= 0 ? front + k : -1, earningsRow, todayKey);
for (let h = 0; h < HORIZONS; h += 1) writeCone(h, measured, todayKey);
writeCheck(measured, todayKey);
}How it works
The book's numbers. input("chain", options_chain.cells, { max_cells: 256, venue: "auto", page_views: ["numbers", "vol_term"] }) asks the data plane for two book folds of the chart's own option book: numbers (each live expiry's forward, at-the-money IV, expected move and 1σ range, then the at-the-money IV and both moves at the 1, 5, 7, 14, 30, 60 and 90 day horizons and over the next 24 hours) and vol_term (each expiry's term structure row). The data plane prices them once a chain update over the chain page's whole book at one instant, the book's priced instant (BookStamp.pricedAtMs()), and every time to go counts from it: to each expiry, to each horizon, to each point of the cone. The answer rides the live row as one block of rows 16 values wide, the widest word's (OPTION_VIEW_ROW_VOL_TERM): the book stamp, the numbers' scope, expiry and horizon rows, and the term rows. max_cells counts rows: 256 holds the stamp, the scope, the eight horizon rows, 64 term rows and 182 expiries. readBook() reads the block whole with every reader at that width: BookStamp, OptionNumbers, ExpectedMoves.loadNumbers() over the same expiry rows (the cone's IV at any time, below) and VolTerm. A block holding no book (none yet, or the empty book: its stamp alone) reads as no rows, so nothing an earlier tick read stays. iv_1d through iv_90d are the horizon rows' IVs in percent, each row found by its years after the priced instant (horizonRow()).
The expected move and the 1σ range. Both are the numbers fold's own, at the horizon's IV. On a horizon of days the rails read the horizon row that many days out: the expected move, 0.85 of the at-the-money straddle priced at that IV (horizonMove()), the number every OpenMarket card means by "expected move", and the 1σ range, that IV times the square root of the horizon in years (horizonSigma()), about a two-in-three chance the market closes the horizon inside it and about 1.47 times the expected move. Each is a share of an anchor of 1, so em_pct and sd_pct are those shares in percent. 30 days at a 14.9% IV reads an expected move of 2.9% and a 1σ range of 4.3%.
The band's anchor. input("days", candles.cells, { interval: "1d", bars: 21, max_cells: 400 }) streams the daily candles as they close, at one day whatever the chart's interval, and the newest one's close is the anchor: yesterday's close, which on crypto, trading around the clock, is today's 00:00 UTC open. The Lines start at tile says which (00:00 UTC 82,704 on crypto, Prior close 660.10 elsewhere), and it reads with or without a book; the rails and the headline's price wait for a book with a live expiry. On a weekly or monthly chart the anchor is still yesterday's daily close, never last week's or last month's bar. A host that serves no daily candles falls back to a tracker: the bar's time.trade_date is its session (the UTC date on crypto, New York's on a US stock, CME's trade day from 17:00 Chicago), and when it moves on, the last close of the session before becomes the anchor (optionsTradeDay() on the bar's time where a host writes no trade date). The live bar's own close never counts. On bars longer than a day that is the prior bar's close, and the tile names it so: Prior bar close 625.00.
The rails. em_hi and em_lo are the anchor plus and minus the expected move, sd_hi and sd_lo the same for the 1σ range. Each is a guide output (role: "guide"), written on the live bar and NaN before it: the chart draws one line across the chart at its value in the muted colour, the move's pair solid and the 1σ pair dashed, and omit_if_empty leaves a rail out while the chain gives it no value. axis_label: true tags each rail on the price axis with its label and price (Move high, 1σ low), and the chart lays those tags out with every other tag on the axis, an options GEX level's among them, so no rail's words run across the chart or under its own line. axis_look: "@rail_labels" binds the tag's look to Rail labels: Tags (quiet, the default) is one soft capsule holding the name and the price, and Words (words) is the price on the axis with the name in words just above the line. A chart that does not know the word draws its default pill.
The next six expiries. The card lists the six expiries after today (the trade date of the book's priced instant) on the market's own calendar, each as its label (an expiry in another year reads its year, 15 Jan '27), its time to go (under 48 hours, the numbers fold's hours from the priced instant to the expiry's pricing instant, hours(); in days on the market's calendar after), and its expected move in price and in percent of its forward (21 Oct 11h ±398 0.48%): the numbers fold's own, the straddle rule at the expiry's own at-the-money IV and time (expectedMove(), expectedMovePct()). front_move_pct is the first one's.
Earnings. Only a US stock or ETF reports earnings (market.kind() 2), so every other market reads none. The report is the instant Earnings date names, in UTC (0, 1970-01-01, is off): a setting, never a chart fill. The earnings expiry is the first expiry to settle strictly after that instant. It is marked earnings in the list (when it is one of the six), its expected move and days to go read out as earnings_move_pct and earnings_days, and the report's days to go as report_days. The Earnings horizon sizes the rails to that expiry's own moves, the numbers fold's expected move and 1σ range in percent of its forward (expectedMovePct(), oneSigmaPct()), from the same anchor as every horizon. A report that has passed reads nothing.
The card reads the outputs. The headline is the expected move by the horizon in percent and, once the anchor is known, in price (±5.05% (±33.34) by 24 Oct on the Earnings horizon); the 1σ range and the band's anchor follow it; then the seven IVs and the six expiries as rows. The title names the horizon (Expected move, 1 day, or Expected move to earnings).
The cone. On the live bar each horizon ends at an instant on the market's own clock. The close is the session's end: 16:00 New York on a US stock, 16:00 Chicago on CME, the next 00:00 UTC on crypto; once today's has passed it is the next session's. The next day is the session after that one. The week is this Friday's close, the first Friday on or after today, a week on once its session has ended. OPEX is the third Friday's close, next month's once this month's has passed. 30 days is the book's priced instant plus 30 calendar days. Stocks and CME trade Monday to Friday, crypto every day. One envelope runs from the live bar's open to the farthest horizon drawn. Its vertices step evenly in u, the square root of the share of the way there (u squared of the way along, densest by the apex, where the legs bend most), 31 of them or one a bar on a cone narrower than 31 bars (at least 5, always odd), plus the book's priced instant, the point half way and every horizon's end drawn. At each vertex the time to go runs from the book's priced instant and never below 0, so the legs hold the live close up to it. The 1σ leg there is the live close times oneSigmaMove at the at-the-money IV that far out, ExpectedMoves.horizonIv(): total-variance interpolation (IV squared times years) between the numbers fold's two expiry rows around it, the nearest expiry's IV before the first and the farthest's after the last (The canonical numbers); the 2σ leg is twice that. A horizon's end is a vertex at its own time and IV, so its 1σ move lies on the legs. The legs are open polylines, never closed: the 1σ solid and the 2σ dotted, in the text colour. Only handles draw past the live bar, so the cone is handles. A horizon that ends with an earlier one (the week and OPEX on the Thursday before a third Friday) draws once.
Skew priced. The vol_term fold holds each live expiry's 25 delta strangle (the wings' mean) and risk reversal (the call's IV less the put's), in vol points like its at-the-money IV. The skew reads the row of the expiry after today nearest 30 days by the fold's days to expiry (the earlier on a tie), passing over one that quotes no IV or no at-the-money IV: its 25 delta call IV is the strangle plus half the risk reversal (str25(), rr25()), its put IV the strangle minus half, and each is divided by that expiry's at-the-money IV. The up leg of every horizon is its IV times the call's ratio, the down leg its IV times the put's (call_skew, put_skew). On that expiry itself the legs are the wing IVs. Without either wing, without a spot (the chart's own term panes read no term structure then, and the package reads no skew), or with Skew priced off, both legs read the at-the-money IV.
Cone style. A polyline takes one flat fill, so each band is cut in two: its near half is one polygon at the band's alpha, and its far half is five slices, each a fifth of it wide and at the alpha a straight fall from the half way point to 0 at the far end reads at the slice's middle. Each band moves its slice edges a quarter slice on from the band before (its near half grows by that and its last slice still ends at the far end), so the stacked bands fade in twenty small steps rather than five large ones. A slice edge between two of the legs' vertices takes a point on the straight line joining them, where the legs run straight too. Every live tick sends the whole cone again, so it stays within 24 filled polygons, 28 polylines with the legs, and 640 points. The bands fill with no outline; the legs are the only strokes. Fan, the default, stacks four bands in the text colour at about 3.5% each, from the 0.5σ, 1σ, 1.5σ and 2σ legs above the close to the same below it, so the middle, where the price is most likely to be, is the brightest. Up and down tint fills from the close to the 1σ up leg in the up colour and to the 1σ down leg in the down colour at 17%, and the rings from 1σ to 2σ at 6%; its legs take the up and down colours. Cones 1s keeps the 1σ legs and the first two bands.
Hidden by the interval. A horizon under 4 bars of the chart's interval is hidden, as is one past 10,000 bars unless Cone horizons names it alone: the cone does not run through it, and the card still reads its legs and marks the row hidden. On a daily chart the close and the next day are hidden. The cone stops at 200 bars. The cone does not run through a horizon past 200 bars either, unless Cone horizons names it alone: on a 5-minute chart it runs to the close, on an hourly chart to the week, and Cone horizons 30d brings 30 days back on any interval. That cap is the drawing's alone: such a horizon is not hidden, and the card reads and checks it as any other. On a 1-minute chart even the close ends past 200 bars, so no cone draws while the card still checks the close.
The dots and chips. A dot marks each horizon's end on both 1σ legs: a label handle drawn with mark(), styled LabelStyle.Emblem with Emblem.Dot, 6 px across. Beside it a chip, a label in a box with a faint fill and border in the text colour and its text in the muted colour, ends at the dot's time: above the top dot its word, 1σ and the price (Today 1σ 662.10; the close reads Close once today's session has ended, then Next day, Week, OPEX or 30d), below the bottom dot the price alone. The far end adds its 2σ dots and chips (2σ 668.70). A horizon that ends close to the next one drawn, within 4 bars or a twentieth of the cone's span from the live bar's open, whichever is more, keeps its dots and leaves its chips to that farther one, so two chips never sit on each other: on a daily chart 30 days can end a day or two before OPEX, and OPEX keeps the chips. Cone labels all, the default, puts chips on every other horizon drawn, near on the two nearest of them (the 2σ ones go with the far end's), and off on none; the dots stay. The label template places text in pixels from the right edge; each dot and chip calls anchor(ANCHOR_CHART) to sit at the horizon's time and price instead, a chip keeps the template's align right so its text ends at the dot, and valign sets it above a top dot and below a bottom one.
The card's cones and checks. Each horizon's row is its time to go and its 1σ legs in percent (4h +0.42% / -0.45%). The front horizon is the first one the settings name and the interval shows (front_up_pct, front_down_pct). Its checks are its 1σ legs in price, 0.85 of its at-the-money straddle (front_straddle_pct), and its realized move: the realized volatility of the last 20 daily log returns, over 365 days a year on crypto and 252 elsewhere (rv_20d), times the square root of its time (front_realized_pct). The daily candles stream 21 deep for it.
Earnings inside a horizon. When the Earnings date report falls after the book's priced instant and by a horizon's end, the horizon's row ends earnings and event_horizons adds its bit: 1 close, 2 next day, 4 week, 8 OPEX, 16 30 days. The front horizon's check says earnings inside.
Levels at the past close. With Levels at the past close on, twelve dashed lines in the muted colour run across the chart from the band's anchor, the prior close: the day, the week and the month, each plus and minus one and two of its 1σ moves, the numbers fold's own horizon rows 1, 7 and 30 days out (horizonSigma()). The book rides the live bar only, so the moves are the live book's. Each line's name and price sit just above it, 56 px in from the right edge: valign(VALIGN_BOTTOM) rests the text's box on the line, so the line never runs through the words. A level within 0.3% of a rail or of an earlier level steps 112 px further in, clear of the rail's axis tag and of the other's text. Each level also carries a pill at the price axis that names it (Day +1σ, Wk −1σ, Mo +2σ): a plot.levels docked right reads the level_rows frame, one row per level rising by price, its labels_text the names. With the setting off no row is written, so no pill draws.
What the settings do
- Rails horizon: How far ahead the four lines (the rails) look. 1d to 90d count days ahead. The earnings choice runs them to the first expiry (the day the option ends) after the report.
- Earnings date: A US stock's next earnings report: the card marks the first expiry after it, and 0 turns it off.
- Cones: The cone ahead of the live candle: off hides it, and 1s draws the 1σ cone (one standard deviation). 1s+2s adds the wider 2σ cone.
- Cone horizons: Which end dates the cone reaches. close is today's close, 1d the next one, week this Friday's and opex the third Friday, when monthly options end. 30d is 30 days out, and all draws every one.
- Cone style: Fan draws bands brightest in the middle, and Up and down tint shades each half in its own colour.
- Cone labels: Prices beside the cone's end dates: near prints the two nearest, all prints every one, off prints none.
- Rail labels: How the four lines are named on the price axis: one capsule (Tags) or words above the line (Words).
- Skew priced: On, the cone leans toward the side whose options cost more (the skew), and off, it stays even.
- Levels at the past close: Adds dashed lines at the day, week and month 1σ and 2σ highs and lows from the prior close.
- Expected move: The expected move for the horizon in percent and in price: the range the market gives about even odds.
- 1σ range (68%): The wider 1σ range (one standard deviation) in percent, with about a two in three chance.
- Lines start at: The price the four lines start from: yesterday's close, or today's 00:00 UTC open on crypto.
- IV at today's price: The implied volatility (IV) at today's price from 1 to 90 days out: higher means the market expects bigger swings.
- Expected move by expiry: The next six expiries, each with its time to go and its expected move in price and percent.
- Cones, 1σ up and down: Each cone end date's time to go and its 1σ move up and down, in percent.
- Nearest horizon: The nearest end date shown, checked against its straddle (a call plus a put at today's price). The last 20 days' moves give a second check.
Where it runs
It works on charts of coins with Deribit (a crypto options exchange) options, such as BTC, ETH and SOL. A copy you run from the editor (the code panel beside the chart) reads them too. On a US stock chart it reads that stock's US listed options. The data is 15 minutes behind unless you have real-time US options data. On a CME (Chicago futures exchange) futures chart it reads the options on that future, 10 minutes behind unless you have real-time CME data. The legend names where the options come from. A copy you run from the editor and one you publish yourself both read US listed options and CME options. On a CME chart, accept the CME market data terms first. Copies that run on OpenMarket's servers cannot read these option numbers yet. That means Run on Cloud (the editor switch that runs a published copy there). It also means Protected copies (published so their code stays on those servers). They stop with the error wrun_option_views_unserved.
When data is missing
The card's headline says why instead of going blank. It reads "Waiting for this symbol's options" until the options arrive. It reads "No options still trading" when every expiry has passed, or the list holds none. It reads "No implied volatility for this horizon" when the horizon has no IV at today's price. With Rails horizon on earnings, it reads "No earnings on this market" on anything but a US stock or ETF. It reads "No earnings report ahead" without a report, and "No expiry after the report" when no expiry follows it. Until one daily candle has closed there is no starting price. Without daily candles, the chart must first cross into a new session. Until then the Lines start at tile reads "No prior close yet" and the lines do not draw. The headline then shows the move in percent only. In the card's expiry list, an expiry with no IV at today's price reads no IV. Without options no cone draws, and the card's cone entries stay empty. In the card's cone list, an end date with no IV reads no IV. Without a spot price there is no skew, so both sides of the cone use the IV at today's price. In the editor's Console (the panel under the code), the call_skew and put_skew readings stay empty. When the chart interval hides every end date, the card's Nearest horizon block reads "None at this interval". Until 21 daily candles have closed, its Realized, 20 days line reads "Needs 21 daily closes".
Customize it
- A longer horizon. Set Horizon to
7dor30dfor a weekly or monthly band; the rails widen with the square root of the days. - Into earnings. On a US stock or ETF, set Earnings date to the report's date and time and Horizon to
earnings: the rails span the move the market prices through the report. - Words on the rails. Set Rail labels to
Wordsfor each rail's price on the axis and its name in words just above its line. - One horizon. Set Cone horizons to
weekand Cones to1sfor the 1σ cone to Friday's close. - Up and down tint. Set Cone style to
Up and down tintfor the upper half in the up colour and the lower in the down colour. - A symmetric cone. Turn Skew priced off: both legs read the at-the-money IV.
- Fewer chips. Set Cone labels to
nearfor the prices of the two nearest horizons alone, orofffor the dots alone. - Levels for the session. Turn Levels at the past close on for the day, week and month 1σ and 2σ levels from the prior close.
Run it
- In the editor's Explorer, press the Templates icon ("Browse starter templates") and pick Expected Move under HUDs.
- Press Run on a BTC chart on a 1h interval: the four rails draw around today's 00:00 UTC open once the chain arrives, each tagged on the price axis, and the card appears at the bottom centre.
- At the editor's Console prompt, type
em_pct,sd_pctandiv_30dto read the expected move, the 1σ range and the 30-day IV on the live bar. - Look right of the live bar: the cone curves open through each horizon's end, a dot and its prices at each. Type
front_straddle_pctandfront_realized_pctto read the front horizon's checks.
Concepts used
- Data sources for the
options_chaincelled class and thevenueword - The market's own calendar for
time.trade_date - Book folds for
BookStamp,OptionNumbers,VolTermandExpectedMoves.loadNumbers, The canonical numbers forExpectedMoves.horizonIv, the expected move forstraddleExpectedMoveandoneSigmaMove, and the market's own date foroptionsTradeDay - A second builder for
TextBuilder.expiry, each expiry's label - Lines, areas, columns, dots, marks for the rails as guides tagged on the price axis (
axis_label,axis_look), and The Style page for bindingaxis_lookto Rail labels throughstyle_values - Drawing objects for the levels' line handles extended across the chart and their right-anchored texts, set just above each line with
valign - Docked profiles for
plot.levelsand its frame'slabels_text, the levels' pills - Every look a handle takes for
anchor,valignand the box and emblem looks on the cone's chips and dots - Paths built point by point for the cone's legs and filled bands, and Colors on a handle for
alphaon a theme colour - Chain page views for the
numbersandvol_termbook folds and the hosted runs' refusal - The clock for
Clock.epochSec, and Calendar periods and candle lists forCandleList - HUD cards, Blocks and tiles and The default look for the card, its tiles, the slot in the title and what a card with no
lookdraws