wrun by OpenMarket: the full documentation bundle. Generated by scripts/build-llms-txt.ts; do not edit. The page index is https://openmarket.xyz/wrun/llms.txt. # What is wrun **wrun is OpenMarket's engine for your own market logic.** Write an indicator in TypeScript syntax, and wrun runs it on every bar of the real market, compiled to WebAssembly, right in your browser. - **Compiled, not interpreted.** A 20-bar average over 10,000 bars computes in under a millisecond. - **Live without the lag.** A live update re-runs one bar, never your whole history. - **Nothing new to learn.** TypeScript syntax your AI already writes, checked by a real compiler before anything runs. - **The whole market.** The order book, trade tape, liquidations and options chains, plus 78 built-in indicators and stats to build on. ## How it works ![How wrun works: market data the chart serves (candles, trades, the order book, options and more) goes into your indicator, one file in TypeScript syntax that runs on every bar, and your chart draws what it writes: lines, boxes, labels and alerts](/wrun/images/diagrams/intro-overview.svg) 1. **Market data.** The file reads the data the chart serves, for the market on screen or another one ([What you can read](../core-concepts/what-you-can-read.md)). 2. **Your indicator.** One file, written in the chart's editor. There is nothing to install: **Run** compiles it in your browser, and its `onBar()` runs once per bar. 3. **Your chart.** The chart draws whatever the file writes ([What the chart shows](../presentation/overview.md)). Once published, anything it draws can trigger an alert. A strategy also places simulated orders in the Strategy Tester; wrun never places real ones. ## What a file looks like ![The file beside what it makes: param adds the Period setting and output adds the sma line; a variable outside a function holds state between bars; onStart() runs once, and onBar() runs on every bar and writes the value the chart draws](/wrun/images/diagrams/intro-anatomy.svg) 1. **Declarations** come first. `param` adds a setting, here the **Period** field; `output` adds something to draw, here the `sma` line and its legend entry. 2. **State** is any variable outside a function. It keeps its value from one bar to the next. 3. **`onStart()`** runs once, before the first bar. Here it sizes the average from the Period setting. 4. **`onBar()`** runs once per bar. Here it feeds the close into the average and writes the result. The whole file, ready to paste into the editor: ```typescript param("period", 20, { min: 1, max: 200 }); output("sma", line, overlay, { color: "#2563eb", width: 2, description: "20-period simple moving average" }); let sma = new Sma(20); function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { out_sma(sma.update(bar.close())); } ``` - **The kit.** `Sma` comes from the kit, the library of ready-made pieces every file can use by name with nothing to import: `Rsi`, `Cvd`, levels, market structure and more ([Quick reference](../reference/quick-reference.md)). - **The language.** TypeScript syntax over typed numbers (`f64`, `i32`); the dialect is AssemblyScript, so there is no `any` and no npm. If you can follow this file, you can write one: the **Moving Average** starter is this file with a comment on every line. ## Bar by bar ![Bar by bar, on graph paper: onBar() has run once for every bar, oldest first, and each run added one point to the average under the candles; the circled forming bar at the right runs again as new data arrives](/wrun/images/diagrams/intro-bar-by-bar.svg) 1. **`onStart()` runs once**, before any bar. 2. **`onBar()` runs once per bar**, oldest first, over every bar the chart has loaded. 3. **State carries forward.** Each call sees only its own bar. To use an earlier bar, keep it in a variable. 4. **Each call writes one value**, and the chart joins the values into the line. A bar where nothing is written stays blank. 5. **The forming bar re-runs** as new data arrives. Each run starts from the state of the last closed bar, so nothing counts twice. ## Where it runs ![Where an indicator runs: Run draws a draft in your browser; published with Compiled or Open source code, it runs in each reader's browser, and a padlock marks both as sandboxed; published as Protected, it runs on OpenMarket's servers; alerts on a published indicator run in OpenMarket's cloud](/wrun/images/diagrams/intro-where-it-runs.svg) 1. **Run** draws a draft on your chart for this session. It runs in a sandbox in your browser: no internet, no files, no access to your account. 2. **Publish** with **Compiled** or **Open source** code gives the indicator a name (`@yourname/name`) and a version, and it runs in the same sandbox in each reader's browser, so adding someone else's indicator is safe. Compiled keeps the code to you: readers get a compiled module, never the source. 3. **Publish** as **Protected** runs it on OpenMarket's servers. The code never leaves them; the chart shows the result. 4. **Alerts** on a published indicator run in OpenMarket's cloud, wherever the indicator runs. A published version never changes, and you choose who can use it: Everyone, Invite only, or Just me ([Sharing](../sharing/overview.md)). ## Next - **New here?** [Your first indicator](primer-first-indicator.md): from the Moving Average starter to a published indicator with an alert. - **Coming from Pine?** [wrun vs Pine](wrun-vs-pine.md): what wrun reads and draws that Pine can't, in one table. - **Writing with an AI?** [Write it with AI](write-with-ai.md): Copy for LLM gives any assistant the rules, the kit's API and your code in one paste. - **Want the tour?** [The editor](the-editor.md) lists every starter and every control. # Your first indicator ![Two moving averages with marks on each cross](/wrun/images/first-indicator.png) **From an empty editor to a published indicator with an alert, in six steps.** Run the Moving Average starter, grow it into an EMA crossover with a mark on every cross, then publish it and let OpenMarket's cloud watch it for you. ## Before you start - **Sign in.** The editor asks a signed-out visitor to sign in, and your account needs a verified email. - **On a CME market, accept the CME market data terms.** Run waits for them ("Accept the CME market data terms to run your own scripts on CME markets."). ## 1. Open the editor and run the starter 1. On the chart toolbar, press **Editor** (the code icon). When it is not pinned, it is in the **Panels** menu. 2. In the editor's Explorer, press **New indicator** and pick **Moving Average** under **Starters**. 3. Press **Run**. A 20-bar average draws on the chart. The tab's first line is the language marker, `//@lang=wrun-ts`, and the starter sits under it, a comment on every statement: ```typescript // A simple moving average, declared and computed in one file. Read it top to bottom. // Nothing is imported: every word below (param, output, Sma, bar, out_sma) is already there. // A param is a setting the chart user can change, declared by its kind: a whole number here, with its name, its default, then the allowed range and the label the dialog shows. param.int("period", 20, { min: 1, max: 200, label: "Period in bars" }); // An output is a per-bar number the Indicator sends back, here drawn as a line on the price panel under the label the legend shows. // output() returns a handle; bind it with a const only when a box() or segment() needs to name it. output("sma", line, overlay, { label: "Moving average" }); let sma = new Sma(20); // a moving-average helper that keeps its own window; onStart() rebuilds it at the chosen period // onStart() runs once before the first bar: read each setting through its p_ reader (i32() = whole bars). function onStart(): void { sma = new Sma(i32(p_period())); } // onBar() runs once per bar: bar.close() is this candle's close, and out_sma() writes the output. // Until the window holds period bars the average is NaN, and a NaN is not drawn. function onBar(): void { out_sma(sma.update(bar.close())); } ``` - **The parts** are the ones from [What is wrun](introduction.md): declarations, state, `onStart()` and `onBar()`. - **The first bars are empty.** The average is `NaN` until its window fills, and `NaN` draws nothing. ## 2. Swap in an EMA Replace the file under the marker with this, and press **Run**: ```typescript param("period", 20, { min: 1, max: 200, description: "EMA length in bars" }); output("avg", line, overlay, { color: "#2563eb", width: 2, description: "EMA of the close" }); let ema = new Ema(20); function onStart(): void { ema = new Ema(i32(p_period())); } function onBar(): void { out_avg(ema.update(bar.close())); } ``` - **`Ema`** weights recent bars more than `Sma`, so it turns sooner. - **The look is declared:** `color` and `width` style the line, and each `description` labels a setting or a line. ## 3. Add a faster average ```typescript param("fast", 9, { min: 1, max: 200, description: "Fast EMA length" }); param("slow", 21, { min: 2, max: 400, description: "Slow EMA length" }); output("fast", line, overlay, { color: "#2563eb", width: 2, description: "Fast EMA of the close" }); output("slow", line, overlay, { color: "#f97316", width: 2, description: "Slow EMA of the close" }); let fast = new Ema(9); let slow = new Ema(21); function onStart(): void { fast = new Ema(i32(p_fast())); slow = new Ema(i32(p_slow())); } function onBar(): void { const close = bar.close(); const fastValue = fast.update(close); const slowValue = slow.update(close); if (isNaN(slowValue)) return; out_fast(fastValue); out_slow(slowValue); } ``` - **A new `param`** comes with a `p_()` reader, and **a new `output`** with an `out_()` writer. - **`onBar()` returns early** until the slow average has a value, so both lines start on the same bar. ## 4. Mark every cross ```typescript // 1. Two settings. param("fast", 9, { min: 1, max: 200, description: "Fast EMA length" }); param("slow", 21, { min: 2, max: 400, description: "Slow EMA length" }); // 2. Two lines on the price pane. output("fast", line, overlay, { color: "#2563eb", width: 2, description: "Fast EMA of the close" }); output("slow", line, overlay, { color: "#f97316", width: 2, description: "Slow EMA of the close" }); // 3. A mark at the bar's low, drawn only where the gate is 1. output("cross_up", shape, overlay, { color: "#16a34a", shape_where: "is_cross_up", description: "Fast EMA crossed above slow EMA" }); const isCrossUp = output("is_cross_up", none); // 4. A signal the alert dialog offers once the indicator is published. alert("crossed_up", { when: isCrossUp, message: "{{symbol}}: fast EMA crossed above the slow EMA at {{close}}", description: "Fast EMA crossed above slow EMA" }); let fast = new Ema(9); let slow = new Ema(21); let cross = new Cross(); function onStart(): void { fast = new Ema(i32(p_fast())); slow = new Ema(i32(p_slow())); cross = new Cross(); } function onBar(): void { // The chart's own close for the averages, and its low to place the mark. const close = bar.close(); const low = bar.low(); const fastValue = fast.update(close); const slowValue = slow.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; out_fast(fastValue); out_slow(slowValue); out_cross_up(low); out_is_cross_up(crossed == 1 ? 1.0 : 0.0); } ``` - **`Cross`** answers `1` on the bar the fast average crosses above the slow one, `-1` on a cross down, `0` otherwise. - **`is_cross_up`** (plot kind `none`) holds that decision without drawing it; **`cross_up`** (plot kind `shape`) draws a mark at the bar's low only where `shape_where` says so. - **`alert(...)`** turns the decision into a signal the alert dialog offers once the indicator is published. ## 5. Change a setting Open the indicator's settings on the chart. Each `param` is a row labelled by its `description`: set **Fast EMA length** to 12 and **Slow EMA length** to 26, and the chart reruns without compiling again. ## 6. Publish it and add an alert 1. Press **Publish**, type a name after `@yourname/` (for example `ema-cross`), and publish. The first version is 0.1.0 ([Publishing](../functions/publishing.md)). 2. On the receipt, press **Open on chart**. 3. On that published indicator, open the alert dialog from its bell in the legend, pick the signal the file declared ("Fast EMA crossed above slow EMA"), and save. OpenMarket's cloud evaluates the alert and notifies you when it fires ([Alerts](../functions/alerts.md)). A draft can't carry one, so publish first. ## If something goes wrong - **Run stops.** The Console names the problem and a squiggle marks the line: fix the first one and press Run again ([Common errors](../faq/common-errors.md)). - **Nothing draws.** It is usually warm-up, and the Console says so: "Output 'sma' is NaN on all N ready bars, so nothing is drawn for it." ## Next - **Mark the crosses down too:** a second gate on `crossed == -1` and a second `shape` output at the bar's high. - **Build something real:** the [Cookbook](../cookbook/overview.md) has complete recipes to read and adapt. - **Read more than candles:** [What you can read](../core-concepts/what-you-can-read.md). - **See how it runs:** [Execution model](../core-concepts/execution-model.md). # The editor ![The editor beside the chart: the Explorer lists your scripts, each script opens in its own tab, the toolbar holds Run and Publish above the code, and the Console under it prints the run's receipt; Run draws the result on the chart at the left](/wrun/images/diagrams/editor-anatomy.svg) The chart's editor is where you write a wrun indicator: **New indicator** starts a file in TypeScript syntax, **Run** compiles it in your browser and draws it on the chart, the **Console** shows what stopped a run and what your file printed, and **Publish** puts a version on the OpenMarket registry. This page walks through every control, in the order you meet them. - The Explorer on the left: **New indicator**, the **Templates** icon beside it, and the tab's draft listed under them. - The tab strip, then the toolbar: the **Run on** chip (Browser), the save icon, **Publish**, **Docs** and **Run**. - The buffer with the Moving Average starter, the status bar under it (slots, line and column), and the **Console** with the run's receipt (Added "Moving Average" to the chart) and the prompt line. - On the chart, the drawn line on the price pane. ## Open it 1. On the chart toolbar, press **Editor** (the code icon). When it is not pinned to the toolbar, it is in the **Panels** menu. The editor needs a signed-in account with a verified email. 2. The toolbar's **Indicators** button opens the **Indicators** dialog. Its **Indicators** tab lists what you can add straight to the chart (**OpenMarket**, **Community**, and **Mine** when you are signed in). The lightning icon in the dialog, **Build**, closes it and opens the editor. ## New indicator and the template picker The editor's Explorer lists your indicators. **New indicator** at its top opens a new tab with the **New indicator** list over it ("Pick a starter, or begin with a blank tab."): pick a card and its complete file fills the tab, or pick **Blank indicator** for a tab that holds only the language marker. The **Templates** icon beside **New indicator** ("Browse starter templates") opens the same list on any tab you can edit. A pick fills an untouched new tab in place; on any other tab it opens in a new tab. The search box filters the cards by title and by the line under it, which says what the card draws. ![The New indicator list: the search box, then the Starters group with Blank indicator, Convert from Pine, Moving Average, Typed inputs tour and SMA with a box, then the On price group](/wrun/images/editor-templates.png) - The search box filters every group at once. - Starters lead: **Blank indicator** for the marker alone, **Convert from Pine** for a TradingView script, then the three starter files. - Each row names what the card draws on its second line; the groups below follow the table's order. | Group | Cards | | --- | --- | | Starters | Blank indicator, Convert from Pine, Moving Average (`sma-codefirst`), Typed inputs tour (`typed-inputs-tour`), SMA with a box (`sma-box`) | | On price | [Session map](../cookbook/session-map.md) (`session-map`), [Volume heat hours](../cookbook/volume-heat-hours.md) (`volume-heat-hours`), [Supply and demand zones](../cookbook/supply-demand-zones.md) (`supply-demand-zones`), [Trend alignment](../cookbook/trend-alignment.md) (`trend-alignment`), [Trend candles](../cookbook/trend-candles.md) (`trend-candles`), [Strike matrix](../cookbook/strike-matrix.md) (`strike-matrix`), [Session OI levels](../cookbook/session-oi-levels.md) (`session-oi-levels`) | | Order flow | [CVD divergence](../cookbook/cvd-divergence.md) (`cvd-divergence`), [Positioning regimes](../cookbook/positioning-regimes.md) (`positioning-regimes`), [Absorption](../cookbook/absorption.md) (`absorption`), [Liquidation bursts](../cookbook/liquidation-bursts.md) (`liquidation-bursts`), [Book heat](../cookbook/book-heat.md) (`book-heat`), [Liquidation heat](../cookbook/liquidation-heat.md) (`liquidation-heat`), [OI liquidation heat](../cookbook/liquidation-heat-oi.md) (`liquidation-heat-oi`), [Volume footprint](../cookbook/volume-footprint.md) (`volume-footprint`), [TPO letters](../cookbook/tpo-letters.md) (`tpo-letters`), [Session volume profile](../cookbook/session-volume-profile.md) (`session-volume-profile`), [Option prints](../cookbook/option-prints.md) (`option-prints`), [Flow tape](../cookbook/flow-tape.md) (`flow-tape`), [Flow marks](../cookbook/flow-marks.md) (`flow-marks`), [Contract sides](../cookbook/contract-sides.md) (`contract-sides`), [Strike footprint](../cookbook/strike-footprint.md) (`strike-footprint`), [Premium tide](../cookbook/premium-tide.md) (`premium-tide`), [Options market stats](../cookbook/options-market-stats.md) (`options-market-stats`), [Net flow](../cookbook/net-flow.md) (`net-flow`), [Flow VWAP](../cookbook/flow-vwap.md) (`flow-vwap`), [Options volume](../cookbook/options-volume.md) (`options-volume`), [Greek flow](../cookbook/greek-flow.md) (`greek-flow`), [NOPE](../cookbook/nope.md) (`nope`), [Interval flow](../cookbook/interval-flow.md) (`interval-flow`), [Premium by strike](../cookbook/premium-by-strike.md) (`premium-by-strike`), VP Buy Share (`vp-buy-share-codefirst`) | | Prediction markets | [Odds vs price](../cookbook/odds-vs-price.md) (`odds-vs-price`), Polymarket YES Odds (`polymarket-odds`), BTC Threshold Conviction (`conviction-score`), Event Asset Divergence (`event-asset-divergence`) | | HUDs | [Market HUD](../cookbook/market-hud.md) (`market-hud`), [Decision board](../cookbook/decision-board.md) (`decision-board`), [Order flow HUD](../cookbook/order-flow-hud.md) (`order-flow-hud`), [Order book HUD](../cookbook/order-book-hud.md) (`order-book-hud`), [Session HUD](../cookbook/session-hud.md) (`session-hud`), [Greek exposure](../cookbook/greek-exposure.md) (`greek-exposure`), [Risk reversal skew](../cookbook/skew.md) (`skew`), [Expected move](../cookbook/expected-move.md) (`expected-move`), [Volatility context](../cookbook/vol-context.md) (`vol-context`), [Contract odds](../cookbook/contract-odds.md) (`contract-odds`), [Options stats](../cookbook/options-stats.md) (`options-stats`), [Option stance](../cookbook/option-stance.md) (`option-stance`), [Options sentiment gauge](../cookbook/sentiment-gauge.md) (`sentiment-gauge`), [Day type](../cookbook/day-type.md) (`day-type`), [Estimated dealer positioning](../cookbook/dealer-positioning.md) (`dealer-positioning`), [Spot exposures](../cookbook/spot-exposures.md) (`spot-exposures`), [OI changes](../cookbook/oi-changes.md) (`oi-changes`), [Top contracts](../cookbook/top-contracts.md) (`top-contracts`), [Options sentiment](../cookbook/options-sentiment.md) (`options-sentiment`) | | Beyond the time axis | [Volume profile and value area](../cookbook/volume-profile-value-area.md) (`volume-profile-value-area`), [Open Interest Profile](../cookbook/open-interest-profile.md) (`open-interest-profile`), [Options dashboard](../cookbook/options-dashboard.md) (`options-dashboard`), [Spot ETF flow](../cookbook/etf-flows.md) (`etf-flows`), [Liquidation map](../cookbook/liquidation-map.md) (`liquidation-map`), [Options odds cloud](../cookbook/options-odds-cloud.md) (`options-odds-cloud`), [Who is trading](../cookbook/whos-trading.md) (`whos-trading`), [Rotation map](../cookbook/rotation-map.md) (`rotation-map`), [Correlation matrix](../cookbook/correlation-matrix.md) (`correlation-matrix`), [Venue share](../cookbook/venue-share.md) (`venue-share`), [Volatility surface](../cookbook/iv-surface.md) (`iv-surface`), [Volatility character](../cookbook/vol-character.md) (`vol-character`), [Strike breakdown](../cookbook/strike-breakdown.md) (`strike-breakdown`), [Market share](../cookbook/market-share.md) (`market-share`), [Premium by expiry](../cookbook/premium-by-expiry.md) (`premium-by-expiry`), [Options at price](../cookbook/options-at-price.md) (`options-at-price`), [IV rank](../cookbook/iv-rank.md) (`iv-rank`), [Variance risk premium](../cookbook/vrp.md) (`vrp`), [Skew history](../cookbook/skew-history.md) (`skew-history`), [Volatility regime](../cookbook/vol-regime.md) (`vol-regime`), [Exposure history](../cookbook/exposure-history.md) (`exposure-history`), [Options history](../cookbook/options-history.md) (`options-history`), [Seasonality grid](../cookbook/seasonality-grid.md) (`seasonality-grid`), [Depth curve](../cookbook/depth-curve.md) (`depth-curve`), [Yield curve](../cookbook/yield-curve.md) (`yield-curve`) | | Strategies | [Moving-average cross](../cookbook/strategy-ma-cross.md) (`strategy-ma-cross`), [Risk-sized reversion](../cookbook/strategy-risk-reversion.md) (`strategy-risk-reversion`) | | Feeds | [Feed with an alert line](../core-concepts/feeds-as-inputs.md) (`feed-alert-line`), [Feed events as labeled dots](../core-concepts/feeds-as-inputs.md) (`feed-events`), [Feed status card](../core-concepts/feeds-as-inputs.md) (`feed-status-card`) | Moving Average is a complete moving average with a comment on every statement, and **New indicator** seeds a new tab with it. The Strategies group shows where the chart offers the Strategy Tester. A linked card has a worked page in the [Cookbook](../cookbook/overview.md). The three Polymarket cards (Polymarket YES Odds, BTC Threshold Conviction, Event Asset Divergence) ship with a placeholder market: Run refuses until you paste the market's condition id (`0x` followed by 64 hex characters) into the odds input's `symbol`. ## The language marker The first non-blank line of an indicator tab is the language marker. A card or **Blank indicator** writes it, and it is how the editor knows the tab holds a wrun indicator; leave it there and write under it: ```text //@lang=wrun-ts ``` One indicator is one file: a `//@file=` line is refused ("One file per indicator for now.", with the file to move into the tab). There is nothing to import: the kit's classes and the readers and writers generated from your declarations are there by name, and an `import` line you write anyway resolves only to the kit's `./sdk/...` modules and the generated `./gen/...` accessors ([Reuse and libraries](../functions/publishing.md#reuse-and-libraries)). ## Write As you type, the editor compiles the file in the background and marks each problem with a squiggle. It completes names, shows types on hover and signature help while you fill in arguments, and **F12** jumps to a definition, into the kit's own read-only files when the name lives there. **Docs** in the toolbar opens these docs in a new tab, on the page for the word under the cursor when it has one: a TA class opens the TA library, `param` or `output` the script definition, a drawing word the drawing guide. ## Run **Run** compiles the file in a Web Worker in your browser with AssemblyScript 0.27.37, the compiler the kit pins, and reuses the compile that already ran as you typed; builds are cached in the browser and reused while the kit and the compiler stay the same. The module runs in a sandboxed worker, and the computation never leaves your browser: the only network traffic is the data your inputs declare (the candles come from what the chart already loaded) and a one-time download of the compiler. A compile gets 15 s and a run 20 s before the editor stops it. Where the draft goes: - On the price pane when any drawn output declares `overlay`; a strategy always goes there. - Otherwise in its own pane when the first output declares `lower`. - An indicator on the price pane with a drawn `lower` output also gets a pane below. Running again replaces the tab's previous overlay. A draft overlay lasts for the session and is not saved with the layout (Run again after a reload), and it takes one of the chart's indicator slots. On the live bar it refreshes at most about once a second: updates in between are folded together, and the last one always lands. The **Run on** chip in the toolbar picks **Browser** (the default) or **Cloud**. **Cloud** runs the published indicator on OpenMarket's servers, and it is offered only for an indicator published as **Never leaves OpenMarket** whose published version matches the file; otherwise it says "Publish first", "Publish the current version first", or "Runs in the browser. Only a Protected Indicator runs in the cloud." On a CME market the indicator runs in the browser once you have accepted the CME market data terms, and **Cloud** is not offered ("Cloud runs aren't available on CME markets. Choose Browser under Run on to run this script here."). A file that declares `strategy(...)` labels the button **Backtest**: the draft goes on the price pane, and the chart's Strategy Tester shows its trades and stats ([Strategies overview](../strategies/overview.md)). ## Settings Every setting is a row in the overlay's settings dialog, drawn as the control its kind names: a number field for `param(...)` and `param.int`, a toggle for `param.bool`, a menu for `param.choice`, a color picker for `param.color`, a market button for `param.symbol`, and so on, labelled by its `label` (else its `description`, else its name) and bounded by the `min` and `max` you declared. `page(...)` and `section(...)` lay the rows out as pages in the dialog's rail, and `presets(...)` adds a strip of named settings sets ([The settings dialog](../settings/overview.md)). Changing one reruns the compiled module over the loaded bars without compiling again; to change what a row offers, edit the declaration and Run again. An output's color, width, opacity and line style come from its declaration, and the dialog's **Style** page lets the user change them per output. The dialog also has **Plot Settings**, **Visibility** (by interval) and **Price marker** under a **Chart** caption. ## The Console When Run stops before the chart changes, the reason is in the editor's **Console**, tagged with the stage that produced it, and one problem hides the ones behind it. The status bar counts errors and warnings (click the count, **Open Problems**, to open the Console), and a blocked Run says how many errors must be fixed first. | Stage | What it checks | Typical message | | --- | --- | --- | | `declarations` | the `param` / `input` / `output` / shape statements, read from the text | `This indicator declares nothing. Add param(...), input(...), and output(...) statements (imported from ./sdk/declare) at the top level of the source; the metadata sheet is derived from them.` | | `lint` | raw positional slot literals in your source | `Raw slot literal 0 passed to getFloat(): raw positional slots rebind silently when the sheet changes` | | `metadata` | the sheet derived from your declarations, against the schema | `Output 'my value' has a name the sheet refuses: use letters, digits, dots, dashes and underscores, starting with a letter or digit (no spaces).` | | `compile` | the AssemblyScript compiler, with a hint beside its message | `Conversion from type 'f64' to 'i32' requires an explicit cast.` | | `validate` | the built module against the four-export contract and the sandbox | `console.* is not available in an Indicator (it runs in a sandbox with no console). Log through the debug output instead: ...` | | `compute` | after Run, what the run produced | `Output 'sma' is NaN on all 480 ready bars, so nothing is drawn for it.` | ![A blocked Run: the underlined line in the buffer, the error count in the status bar, and the Console with the compile message, its hint, the blocked-run line and the prompt](/wrun/images/editor-console-error.png) - The buffer underlines the expression the compiler refused; the Console prints the same line number in front of the message. - The hint after the message names the fix, and the link opens [Common errors](../faq/common-errors.md). - "Cannot run: 1 error(s) must be fixed first." is the blocked Run; the circled count at the right of the status bar is **Open Problems**, and the **current** block under the run is what it shows. - The prompt line stays under the Console. Fix the first one and Run again; [Common errors](../faq/common-errors.md) lists the messages with their fixes. A run that reaches the chart and draws nothing is usually not an error: an output left `NaN` on every bar (a warm-up that never ends), an output declared `none`, or a source the chart's market does not serve, for which the legend shows a **Could not load** chip with the reason and **Retry**, and the Console shows the same sentence ([Debugging](../faq/debugging.md)). To print from the module, declare a text slot named `debug` (`string("debug", { max_bytes: 256 })`) and write it from `onBar()` through the generated `str_debug(text)` sender: the Console prints each non-empty line after the bar's time in ISO 8601 UTC ([Debugging](../faq/debugging.md)). The prompt under the Console ("Type an expression, an output name, or / for commands") compiles one expression into your current file and runs it over the chart's candles without drawing anything. It also reads your last run: `rows`, `params`, `outputs`, `sheet`, an output by name, `[-n]` for n bars back, `last N `, and `at `. `/help` lists its commands. A strategy, or a file with an input other than candles and time, is refused at the prompt. ## Save and copy The editor saves a changed tab to your account about 1.2 s after an edit, or at once with the save icon (**Save now**). The first save creates a private draft in your account, which counts against your plan's limit of saved scripts ([Plans](../reference/limits.md#plans)). Your indicators are listed in the Explorer, where a published one carries a package icon ("Published as" and its name), and under **Mine** in the Indicators dialog, where a draft reads "Draft: publish it from the editor". - **Copy for LLM** (right-click the tab, or the command palette) copies one Markdown block: a short rules primer, the kit's API one line per class, your numbered source, every problem with its stage, the last run's status with up to 40 debug lines, and the sheet from the last good build ([Write it with AI](write-with-ai.md)). ## Publish and alerts **Publish** opens the **Publish Indicator** dialog once the current code has no errors; you need to be signed in, and the draft is saved first. You type the name after `@yourname/`, the first version is 0.1.0, and you choose **Who can use it** (Everyone, Invite only, Just me) and **Code** (Protected, Compiled, Open source), which also decides whether the indicator runs on OpenMarket's servers or in each reader's browser. On the receipt, **Open on chart** adds the published version to the chart. From then on the button reads **Publish a new version**: pick **Patch**, **Minor** or **Major** and write one line on what changed ([Publishing](../functions/publishing.md)). On an Invite only indicator, **People** beside **Publish** opens its People panel, where you invite people and see who has access ([Sharing](../sharing/overview.md)). A published indicator on the chart can carry alerts: open the alert dialog from its bell in the legend, the right-click menu, or **Alert on** > **Indicators** in the sidebar, pick an output or a signal the file declares with `alert(...)`, and a condition. OpenMarket's alerts engine evaluates it in the cloud with the overlay's settings; a draft is refused with "Publish the Indicator before adding an alert." ([Alerts](../functions/alerts.md)). # Write it with AI **Any AI assistant can write wrun.** It is TypeScript syntax, which assistants have read a great deal of, and the editor's compiler checks every draft before anything runs. ## The loop ![The AI loop: you describe your idea to any AI assistant together with Copy for LLM from the editor; you paste the file it writes into the editor and press Run; if the compiler names errors, Copy for LLM sends the code and every error back; when it compiles, it draws on your chart](/wrun/images/diagrams/ai-loop.svg) 1. **Open a tab.** In the editor, press **New indicator**, or open the indicator you want to change. 2. **Copy for LLM.** Right-click the editor tab and pick **Copy for LLM**. One paste carries the language rules, the kit's API, your numbered code, every error and your last run. 3. **Ask.** Paste it into any assistant and say what you want, naming everything it should draw (an example is below). 4. **Run.** Put the complete file it returns into the tab and press **Run**. The compiler names every mistake with a line and column. 5. **Repeat until it compiles.** Copy for LLM again and paste it back. When it compiles, it draws on your chart. ## Better results A request that names everything it wants drawn: ```text An RSI(14) in its own pane with bands at 30 and 70, a dot on every cross back inside the bands, and an alert on each cross. ``` - **Name everything you want drawn.** Assistants keep the lines and tend to drop labels, per-bar colors, fills, boxes, tables and alerts. List them in your request, then check the legend and the chart against it. - **Build long scripts in parts.** A few hundred lines can outgrow one answer. Ask for the settings and the plotted lines first and press **Run**; then ask for the drawings, then the alerts, each time with a fresh Copy for LLM. - **Check the numbers before you publish.** Compare the result with a version you trust, on the same market and timeframe. ## Porting from Pine Paste your Pine script with a **Copy for LLM** and ask for a port; the loop above takes it from there. [wrun vs Pine](wrun-vs-pine.md#bring-your-pine-scripts) shows one indicator in both languages, line for line. # wrun vs Pine Pine works from candles: it runs on TradingView's servers and draws lines, labels and boxes on the chart. A wrun indicator gets the market under the candles. Every level of the order book, buy and sell volume as the exchange tagged each trade, and the live options chain with its greeks arrive as numbers your code can do arithmetic on. It compiles to WebAssembly, runs in your browser, and draws its answer in whatever form fits: a line, a profile on the price axis, a heatmap below the chart, a card in the corner. ![How deep each one reads, one row per kind of market data: Pine reads candles, other markets and liquidations, funding and open interest in full, buy and sell volume by price and the order book only with limits, and stops before the options chain; wrun reads every row, and the options chain, implied volatility and skew, prediction odds and ETF flows only wrun reads](/wrun/images/diagrams/sees-depth.svg) **Indicators you can build in wrun and not in Pine:** - **Real delta.** Buy minus sell volume from the exchange's own trade tags ([Order flow HUD](../cookbook/order-flow-hud.md)). Pine's footprint infers the side from price moves, on Premium plans and up, one per script. - **Book walls.** The biggest resting bid and ask near price on every bar, and how the pressure between the two sides shifts ([Order book HUD](../cookbook/order-book-hud.md)). - **A live gamma map.** Gamma exposure at every strike, the gamma flip and the call and put walls, drawn against price from the options chain ([Greek exposure](../cookbook/greek-exposure.md), [Strike matrix](../cookbook/strike-matrix.md)). - **Who is trading.** Each bar's volume split by trade size, from trades under $1K to trades of $10M and up, buyers and sellers apart. - **Pictures, not just lines.** A volume profile docked on the price axis, an hour-by-weekday heatmap, a HUD of sparklines and gauges ([Volume heat hours](../cookbook/volume-heat-hours.md), [Market HUD](../cookbook/market-hud.md)). | | Pine | wrun | | --- | --- | --- | | Language | Pine Script, TradingView's own | TypeScript syntax, compiled to WebAssembly | | Where it runs | TradingView's servers only | Your browser, sandboxed; OpenMarket's servers when the code is protected | | Order book | Best bid and ask, on 1-tick charts only | Every level, up to 500 a side, on every bar | | Trades | Sides estimated from price moves | The exchange's own buy and sell tags, by price and by trade size | | Options | No chain, greeks or implied volatility | Every listed contract with greeks; implied volatility and skew by tenor | | Drawing | Lines, labels and boxes (500 each), polylines (100), tables | All of that, plus pies, scatters, curves, heatmaps and tiles below the chart, profiles on the price axis, HUD and hover cards | | History | Lookahead is a switch; TradingView estimates over 95% of indicators repaint | No lookahead to switch on: history shows what you would have seen live | | Limits | Memory is limited; the number is not published | Every limit is published, and a run that hits one stops and says which | **Already have Pine scripts?** Any AI [ports them](#bring-your-pine-scripts), and the compiler checks every line before anything runs. ## The whole order book **Walls, gaps and the pressure between bids and asks, on every bar.** ![The order book at one moment: Pine reads one bid and one ask, the best of each, on 1-tick charts only, while the rest of the book stays faint; wrun reads every level on both sides, up to 500 a side on every bar, so the wall of bids six levels down is in view](/wrun/images/diagrams/beyond-book.svg) 1. **Pine**: two rows, the touch. The faint rest is the book it never reads. 2. **wrun**: every row, bids and asks. 3. **The wall**: six levels down, a size your code can find and draw. Crypto charts, spot and perpetual. Imbalance over the nearest levels, plus the biggest bid and ask within 1% of price: ```typescript param.int("levels", 20, { min: 1, max: 500, label: "Levels per side" }); input("close", ohlcv.close); // the chart's candles input("book", book.cells, { max_cells: 1000, block_size: 10 }); // the whole book output("imbalance", line, lower, { color: "#64748b", label: "Imbalance", format: "0.00" }); output("bid_wall", line, overlay, { color: "#16a34a", label: "Bid wall", format: "price" }); output("ask_wall", line, overlay, { color: "#dc2626", label: "Ask wall", format: "price" }); let depth = new BookImbalance(20); function onStart(): void { depth = new BookImbalance(i32(p_levels())); } function onBar(): void { const n = in_book_cells(); if (n <= 0) return; // no book on this bar const cells = in_book_view(); // [price, size, side] per level const close = bar.close(); let bidWall = NaN; let bidMax = 0.0; let askWall = NaN; let askMax = 0.0; depth.begin(); for (let i = 0; i + 2 < n; i += 3) { const price = cells[i]; const qty = cells[i + 1]; const side = i32(cells[i + 2]); // +1 a bid, -1 an ask depth.add(price, qty, side); if (Math.abs(price - close) > close * 0.01) continue; if (side > 0 && qty > bidMax) { bidMax = qty; bidWall = price; } if (side < 0 && qty > askMax) { askMax = qty; askWall = price; } } depth.end(); out_imbalance(depth.imbalance()); // (bids - asks) / (bids + asks) out_bid_wall(bidWall); out_ask_wall(askWall); } ``` More: [Order flow](../functions/order-flow-kit.md#book-imbalance). ## Who actually traded **Delta from the exchange's own tags, split by price and by trade size.** ![A footprint, three bars wide: each bar is sliced by price, sell volume drawn to the left of the bar's line and buy volume to the right, each side as the exchange recorded it, with each bar's delta, buy minus sell, written underneath](/wrun/images/diagrams/beyond-footprint.svg) 1. **Each bar**, sliced by price into buckets with real bounds. 2. **Sellers**, left of the bar's line. 3. **Buyers**, right of it. 4. **Delta**, under each bar: buy minus sell. Summed bar after bar, it is CVD. `trades.volume`, `volume_profile` and `trade_volume_by_size`; sizes run in seven buckets, from under 1K to 10M and up, in USD. Big trades against small ones, as two running sums of buy minus sell split at 100K: ```typescript input("close", ohlcv.close); // the chart's candles input("sizes", trade_volume_by_size.cells, { max_cells: 7 }); output("large", line, lower, { color: "#c2410c", width: 2, label: "100K and up", format: "si" }); output("small", line, lower, { color: "#94a3b8", label: "Under 100K", format: "si" }); let large = 0.0; // buy minus sell in USD, trades of 100K and up let small = 0.0; // the same for smaller trades function onBar(): void { const n = in_sizes_cells(); const cells = in_sizes_view(); // [bucket, buy_usd, sell_usd, buy_count, sell_count] per bucket for (let i = 0; i + 4 < n; i += 5) { const net = cells[i + 1] - cells[i + 2]; // buy minus sell if (cells[i] >= 4.0) large += net; // bucket 4 starts at 100K else small += net; } out_large(large); out_small(small); } ``` When the lines part, the big trades and the small ones are on opposite sides. More: [Order flow](../functions/order-flow-kit.md#volume-profile). ## The options chain **Gamma by strike, the flip and the walls, from the live chain, in one call.** ![The options chain beside price: gamma by strike docked on the price axis, shaded where net gamma is positive and open where it is negative; the call wall above price, the put wall below it, and the gamma flip, dashed, where net gamma crosses zero](/wrun/images/diagrams/beyond-gamma.svg) 1. **Price**: the chart's candles, last close marked on the axis. 2. **Gamma by strike**, docked on the price axis: shaded where net gamma is positive, open where it is negative. 3. **Call wall**: the strike above price with the most call open interest. 4. **Gamma flip**: where the gamma curve, net gamma priced again at each price, crosses zero nearest the price (the options kit's `GammaCurve`, the flip every options card reads). 5. **Put wall**: the strike below price with the most put open interest. Any coin an options venue lists. Implied volatility and skew by tenor, one week to six months, are inputs on every bar of BTC and ETH charts. The levels and max pain, on a card: ```typescript input("close", ohlcv.close); // spot is the chart's close input("chain", options_chain.cells, { max_cells: 4000 }); output("flip", none, overlay, { label: "Gamma flip" }); output("call_wall", none, overlay, { label: "Call wall" }); output("put_wall", none, overlay, { label: "Put wall" }); output("max_pain", none, overlay, { label: "Max pain" }); render.hud("chain_card", { position: "top_right", title: "Options chain", columns: 2, tiles: [ tile.value("Call wall", "call_wall", { format: "price" }), tile.value("Gamma flip", "flip", { format: "price" }), tile.value("Put wall", "put_wall", { format: "price" }), tile.value("Max pain", "max_pain", { format: "price" }), ], }); let chain = new OptionsChain(1); let curve = new GammaCurve(1); function onStart(): void { chain = new OptionsChain(512); curve = new GammaCurve(in_chain_max_cells); } function onBar(): void { if (bar.isLast()) { // the chain arrives on the live bar const n = in_chain_cells(); if (n > 0) { const now = chainPricedAtMs(in_chain_view(), n, bar.time() * 1000.0); // when the chart priced the chain chain.load(in_chain_view(), n, now, bar.close()); curve.load(in_chain_view(), n, now, 0, bar.close()); // every live expiry } } out_flip(curve.flip()); // the gamma curve crosses zero here, nearest the price out_call_wall(chain.callWall()); // most call open interest above out_put_wall(chain.putWall()); // most put open interest below out_max_pain(chain.maxPain()); // pays option holders the least } ``` The [Greek exposure](../cookbook/greek-exposure.md) recipe docks the profile as drawn. More: [Options kit](../functions/options-kit.md). ## Off the time axis **Some answers are not lines. A pie, a curve over strikes or a heatmap gets its own pane.** ![Five panel kinds, each in a pane of its own below the chart: a pie of the bar's volume by trade size, a scatter of one value against another, a curve such as implied volatility by strike, a heatmap such as volume by hour and weekday, and tiles of big numbers with sparklines](/wrun/images/diagrams/beyond-panels.svg) 1. **Pie**: shares of one whole, such as this bar's volume by trade size. 2. **Scatter**: one dot per pair of values, x against y. 3. **Curve**: a line over any axis, such as implied volatility by strike. 4. **Heatmap**: a grid of cells, such as volume by hour and weekday. 5. **Tiles**: big numbers, each with a caption and a sparkline. This bar's volume by trade size as a pie, rebuilt on the live bar. The share of trades of 100K and up runs as a line through history: ```typescript input("close", ohlcv.close); input("sizes", trade_volume_by_size.cells, { max_cells: 7 }); output("share", line, lower, { color: "#c2410c", label: "100K and up", format: "%" }); const mix = frame("mix", { max_bytes: 1024 }); // the pie's slices panel.pie({ name: "size_mix", title: "This bar by trade size", x: "category", place: "below", frame: mix, hole: 0.5 }); const NAMES: StaticArray = ["Under 1K", "1K to 10K", "10K to 100K", "100K to 500K", "500K to 1M", "1M to 10M", "10M and up"]; const COLORS: StaticArray = ["#e2e8f0", "#cbd5e1", "#94a3b8", "#fdba74", "#fb923c", "#ea580c", "#9a3412"]; function onBar(): void { const n = in_sizes_cells(); const cells = in_sizes_view(); const live = bar.isLast(); let total = 0.0; let large = 0.0; if (live) { fb_clear(); fb_text('{"rows":['); } for (let i = 0; i + 4 < n; i += 5) { const usd = cells[i + 1] + cells[i + 2]; const k = i32(cells[i]) - 1; // buckets run 1 to 7 total += usd; if (k >= 3) large += usd; if (live) { // one slice per bucket: [name, value, color] if (i > 0) fb_text(","); fb_text("["); fb_str(NAMES[k]); fb_text(","); fb_f64(usd, 0); fb_text(","); fb_str(COLORS[k]); fb_text("]"); } } if (live) { fb_text("]}"); writeFrameBuffer(FRAME_MIX); } out_share(total > 0.0 ? (100.0 * large) / total : NaN); } ``` `fb_*` builds the frame without allocating: the sandbox refuses memory growth once the bars start. More: [Cards, frames and panels](../presentation/cards-frames-panels.md), [Volume profile and value area](../cookbook/volume-profile-value-area.md), [Volatility surface](../cookbook/iv-surface.md). ## Cards, not tables **Your code writes numbers and words. The chart draws the card.** ![Three answers on one chart: the legend names the basis line, its value and a word colored for this bar; a HUD card in the corner holds four typed tiles, a value with its change, a sparkline, a gauge and a meter; and a hover card opens where the cursor rests on the line](/wrun/images/diagrams/beyond-cards.svg) 1. **The legend** carries words as well as values, each word colored for its bar. 2. **A HUD card** sits at one of nine anchors and holds typed tiles: a value with its change, a sparkline, a gauge, a meter. 3. **A hover card** opens where the cursor rests on a line, a legend entry or a tile. The options card above is one; [Market HUD](../cookbook/market-hud.md) builds a full board. Every block kind: [What the chart shows](../presentation/overview.md). ## Settings **Declare the kind. The dialog draws the control.** - **Presets**: named sets of values; one click fills every setting they name ([Presets](../settings/presets.md)). - **Ranges, multi-selects, lists**: a slider with two handles, a pick of weekdays, an editable list of lookbacks ([Setting kinds](../settings/kinds.md)). - **Units**: an offset in percent of price or in ATRs, picked beside the number ([Sessions and units](../settings/sessions-and-units.md)). - **Pages**: settings on pages and sections, with a filter box past twelve ([Pages, sections, dividers, notes](../settings/layout.md)). ## No lookahead **`onBar()` gets one bar. There is no next bar to peek at.** ![Higher timeframes, bar by bar: a 4h candle spans four 1h bars; with lookahead on, a Pine script on history sees the new 4h close from the first of those bars, while in wrun every 1h bar sees the previous close and the new one arrives on the bar after the 4h candle closes](/wrun/images/diagrams/repainting.svg) 1. **One 4h candle** spans four 1h bars. 2. **Pine, lookahead on**: history sees the new 4h close from the first of those bars, before it happened. It is off by default; an author turns it on. 3. **wrun**: no switch. Every 1h bar sees the last closed 4h candle; the new close arrives on the bar after. The forming bar replays from the last closed bar on every update. No `varip`, no `barstate.isrealtime` ([Repainting](../core-concepts/repainting.md)). ## Bring your Pine scripts **Hover a Pine line. See the wrun line that replaces it.** ```pine pair title="Pine" map="1 2 3 4 5 6 7 8 9 10 10 11" //@version=6 indicator("MA Cross", overlay=true) fastLen = input.int(9, "Fast") slowLen = input.int(21, "Slow") fast = ta.ema(close, fastLen) slow = ta.sma(close, slowLen) plot(fast, color=color.orange) plot(slow, color=color.blue) up = ta.crossover(fast, slow) plotshape(up, shape.triangleup, location.belowbar) alertcondition(up, "Golden cross") ``` ```typescript pair title="wrun" map="1 3 4 7,2 8,2 10 10 10 11 11 - 5 6 9 9" //@lang=wrun-ts param.int("fast_len", 9, { min: 1 }); param.int("slow_len", 21, { min: 1 }); output("fast", line, overlay); output("slow", line, overlay); render.shape("cross_up_mark", { output: "low", shape: "triangle_up", where: "crossed_up" }); alert("golden_cross", { when: crossedUp }); … fast = new Ema(i32(p_fast_len())); slow = new Sma(i32(p_slow_len())); const crossed = cross.update( fastValue, slowValue); ``` In the editor, **Copy for LLM** hands any AI your code, the build's rules, the kit's API and every compiler error ([Write it with AI](write-with-ai.md)). # Execution model A wrun indicator is a function the host calls once per bar, oldest bar first, with state that lives between calls in module-level variables. This page is the mental model behind every recipe: what runs when, why the first bars of a line are empty, what "no lookahead" means when you write the code, how to know the bar's index and whether it is the newest, and where an indicator runs: in your browser, on OpenMarket's servers, on OpenMarket's alerts engine, and in the Strategy Tester. ## The bar loop ![Bar by bar: onStart() runs once; then onBar() runs once for each loaded bar, oldest first, hands its state to the next call and writes one value per bar, which the chart joins into the line; the forming bar at the right runs again as new data arrives](/wrun/images/diagrams/intro-bar-by-bar.svg) An indicator runs `onBar()` once per bar, oldest first, walking forward to the newest. Module-level variables stay alive across the whole walk, and the file defines two hooks with fixed roles (`onStart()` is optional): | Function | Called | Reads | Writes | | --- | --- | --- | --- | | `onStart()` | once, before the first bar | params via `p_()` | nothing; size your averages and buffers here | | `onBar()` | once per bar, oldest first | this bar's candle via `bar.()`, every declared input via `in_()`, params | your module-level state; every output via `out_(value)`, string slots, drawing handles, strategy orders | The hooks are plain top-level functions with no arguments that return nothing: `function onStart(): void { ... }` and `function onBar(): void { ... }`. Anything else (an argument, a missing or different return type, an arrow) is refused on the hook's own line: `onBar must be a function with no arguments that returns nothing: write function onBar(): void { ... } (the build calls it once per bar)`. Params are readable from `onStart()` on, anywhere in the file (at module scope, before it, a `p_()` reads `NaN`). Inputs and the bar's fields are readable in `onBar()` and the helpers it calls (in `onStart()` they read `NaN`). The readers return values cached for the bar, so reading one twice costs nothing. The host walks the loaded history in order. On the chart that history is exactly the candles the chart has loaded, every source is fetched over the same window, and panning back runs the indicator again over the longer window (a [per-bar script](per-bar-scripts.md) runs only the bars that just loaded). For each bar the host calls `onBar()`, then emits the bar's row with whatever `onBar()` wrote. Every bar has a row: an output `onBar()` did not write is `NaN` on that bar, and nothing is drawn there. Nothing in the file has to send the row: each `out_(value)` keeps its value for the bar (the last write wins), and the row reaches the host in one step after `onBar()` returns, so an `emitRow()` of your own does nothing. ## The bar's index, the first bar, the newest bar There are no bar-state globals. The bar's index is a module-level counter you increment in `onBar()`, and the first bar is that counter at `0` (one-time setup that needs no bar belongs in `onStart()`). The newest bar is `bar.isLast()`: true exactly when the bar being evaluated is the newest bar the host holds for this run, false on every earlier bar. Run-level renderers and declared drawings still evaluate the newest ready row on their own without it; the signal is for a handle drawing that should exist on the newest bar only, or reach past it. [Variables](core-variables.md) has the counter idioms in a compiled example, and the bar's own fields beside them. The signal is a function of the run's window, so a replay from bar 0 over the same window reproduces it: - A full run answers true on its last row only. - On the live chart it answers true on the forming bar, each time the forming bar is evaluated again. - When that bar closes, the chart evaluates it ONCE more as a closed bar, with the signal false, before the new bar is evaluated with it true. The re-run's outputs, strings, and handle drawings replace the row's. This is what keeps a chart that has been open all day identical to a fresh load: nothing the forming bar drew under `bar.isLast()` survives its close unless the closed bar draws it too. An average with a dotted projection five bars ahead, drawn on the newest bar only. The projection's far end lies past the loaded range, which a handle's absolute time coordinates allow ([Drawing objects](../presentation/drawing-objects.md)): ```typescript param("period", 20, { min: 1, max: 200 }); output("sma", line, overlay, { color: "#38bdf8", width: 2 }); handles.line({ color: "#38bdf8", width: 1, lineStyle: "dotted" }); const projection = draw.line(0); let sma = new Sma(20); let t: f64 = NaN; let prevT: f64 = NaN; function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { prevT = t; t = bar.time(); const value = sma.update(bar.close()); if (isNaN(value) || isNaN(prevT)) return; out_sma(value); // Only the newest bar carries the projection: five bars ahead is past the loaded // range, and an absolute x makes that legal. if (bar.isLast()) projection.set(t, value, t + 5.0 * (t - prevT), value); } ``` Over a full run the line is created on the last row and nowhere else; when that bar closes on the live chart, the closed-bar re-run draws no line, and the new forming bar creates it again one bar to the right. ## How many bars the run holds `bar.count()` is the number of bars the run holds while the bar is evaluated, the forming bar included. With your own bar counter it tells a bar whether a later bar exists, which a lagging line needs: a line drawn `shift` bars back can only show a bar's value once the bar `shift` bars later exists. ```typescript let index: i32 = 0; function onBar(): void { const later = index + 1 < bar.count(); // a bar after this one exists in the run out_settled(index + shift < bar.count() ? 1.0 : 0.0); // the bar shift bars later exists index += 1; } ``` - A full run (a fresh load) answers the run's bar count on every bar, so every bar sees the whole window, including bars after it. - On the live chart the forming bar answers the bars held so far, and a new revision of the forming bar evaluates only that bar again. - When a new bar opens, the chart runs every bar again from the first one with the new count, so each bar's reading stays current and a chart open all day matches a fresh load over the same bars. Reading `bar.count()` makes the sheet `wrun-6` ([Versions and contracts](../reference/versions.md)). It answers inside `onBar()` only; read in `onStart()` it stops the run by name (`wrun_bar_count_phase`). ## Everything travels by name Params, inputs, and outputs reach the code through generated readers and writers (`p_()`, `in_()`, `out_()`), one function per declared name, and the chart's own candle through `bar.()`. Underneath, the host passes values positionally, in declaration order. The editor regenerates the readers from the declarations on every compile, so reordering or renaming a declaration never rebinds a value silently: the compiler names the reader or writer that no longer exists. Raw positional reads (`getFloat(0)`) are refused by the editor's `lint` stage for the same reason ([Common errors](../faq/common-errors.md)). ## Warm-up: NaN until the window fills ![Warm-up: an average of 8 bars is NaN on the first 7 bars, so nothing is drawn there; from the bar where the window is full, the line draws](/wrun/images/diagrams/warm-up.svg) Every TA class returns `NaN` until it has seen enough bars: `Sma`, `Stdev`, and `Zscore` need `period` values, `Ema` seeds itself with a simple average of the first `period` values, `Rsi` is warm after `period + 1` samples, `Roc` after `period + 1`. `Cross.update()` returns `0` on any bar where either side is `NaN`. You have two ways to handle a value that is not ready yet, and both are correct: - Write nothing on the bar: `return` from `onBar()` before any write, after the state updates the bar still owes (the `update()` that folds the bar in, the close you remember). The bar's row then carries `NaN` in every output, and the chart draws nothing there. Use it when nothing on the bar is meaningful yet. - Write `NaN` to one output: the chart draws nothing for that output on that bar while the other outputs still draw. Use it when one line warms slower than another, or when a value legitimately has no answer (a session that has not completed yet, a ratio with a zero denominator). A warming TA value is already `NaN`, so writing it as it comes needs no test at all: the Moving Average starter does this (`out_sma(sma.update(bar.close()))`). Anything else written on a warming bar is drawn as if it were true. The chart does not skip a warm-up count for you: it hands the module every loaded bar and `onBar()` decides what to write. A bar-to-bar change with a smoothed line returns early twice over: on the first bar there is no previous close, then the change exists while its average does not, and only once both are real does it write them: ```typescript param("period", 10, { min: 2, max: 200, description: "EMA length over the bar-to-bar change" }); output("change_pct", line, lower, { unit: "%", color: "#94a3b8" }); output("smoothed", line, lower, { unit: "%", color: "#38bdf8", width: 2 }); let ema = new Ema(10); let prevClose: f64 = NaN; function onStart(): void { ema = new Ema(i32(p_period())); } function onBar(): void { const close = bar.close(); // Yesterday's close is whatever we kept from the previous call: there is no close[1] to read. const change = isNaN(prevClose) || prevClose == 0.0 ? NaN : ((close - prevClose) / prevClose) * 100.0; prevClose = close; if (isNaN(change)) return; const smoothed = ema.update(change); // The EMA is NaN until `period` changes have been folded in; those bars write nothing. if (isNaN(smoothed)) return; out_change_pct(change); out_smoothed(smoothed); } ``` ## History indexing An indicator has no history operator: `onBar()` sees exactly one bar, and indexing a number (`close[1]`) is a compile error (`Index signature is missing in type 'f64'`). Keep yesterday's value in a module-level variable when you see it (`prevClose` above), keep a window in a `StaticArray` ring buffer, and let a TA class keep the window a statistic needs. ## No lookahead A value can therefore only depend on bars at or before its own, and a mark that appears in history would have appeared live on the same bar. This is what no repaint means, and an indicator cannot break it by accident: there is nothing to peek at. The one deliberate exception is `bar.count()`: a value that reads it can change when a later bar arrives, which is why the chart runs every bar again when a bar opens ([How many bars the run holds](#how-many-bars-the-run-holds)). Higher timeframes follow from the same rule, in either of the chart's two forms ([Multi-timeframe](multi-timeframe.md)). Build the 4h view inside the module: bucket bars by `bar.time()`, and fold a bucket into its average only once the next bucket has started (the cookbook's regime filter does this). Or pin a secondary input to `interval: "4h"`: the chart fetches the 4h candles as their own series and hands each one to a chart bar only as of that bar's close, so a forming 4h candle never leaks into the 1h rows under it. The forming bar is the one exception to "one call per bar": the chart evaluates it again as new data arrives, at most about once a second per indicator, coalescing the updates in between and never dropping the latest. The chart keeps the compiled module alive, snapshots its state after the last closed bar (its memory, every module-level variable, and its drawing handles), and restores that snapshot before each new evaluation of the forming bar, so an update never counts the bar twice or stacks a second copy of what the forming bar drew. What can still change a bar you have already seen is on [Repainting](repainting.md). ## Declare the chart's candles first On the chart an indicator's rows are always the chart's own candles, and `onBar()` runs once per row. A file with no `input` line runs on them with no declaration at all: `bar.close()` and the other fields are its inputs, and the chart's close is its grid. A file whose first `input` line names another candle field (a lone `input("high", ohlcv.high);`) keeps that line, so the grid stays on that field instead of moving to the close; `bar.high()` and the other `bar` reads work either way, through the line or without one. Once a file declares an input, its first `input` line is the grid: it follows the chart's market and interval, so a market or interval pin on it is refused by name (a Polymarket `odds` input is the one source that may come first with a market of its own), and a `time` or celled source cannot be the first input (there is no feed behind the clock; a block needs a grid to be sliced by). So when the file declares anything else, declare the chart's own candles first even when the computation does not obviously use price: a file with a celled `volume_profile` input still declares `input("close", ohlcv.close)` before it, a `forming` view on a pinned input needs it, and a strategy's fills run against the chart's candles (with no input line a strategy gets `close` as its grid). The full rules, the reserved names and the order of the sheet are on [Data sources](data-sources.md). ## Where an indicator runs ![Where an indicator runs: Run draws a draft in your browser; published with Compiled or Open source code, it runs in each reader's browser, and a padlock marks both as sandboxed; published as Protected, it runs on OpenMarket's servers; alerts on a published indicator run in OpenMarket's cloud](/wrun/images/diagrams/intro-where-it-runs.svg) | Where | How it gets there | What it computes over | | --- | --- | --- | | Your browser | **Run** in the editor, or adding an indicator published with **Compiled** or **Open source** code | the chart's loaded bars and every source on [Data sources](data-sources.md), with pins served as [Multi-timeframe](multi-timeframe.md) and [Multi-source](multi-source.md) describe | | OpenMarket's servers | adding an indicator published as **Protected**, or **Run on** > **Cloud** in the editor for your own | the chart's candles; the module never downloads to the chart, which shows the result the servers stream | | OpenMarket's alerts engine | an alert set from the chart on a published indicator | the chart's own market, with the settings the overlay carries | | The Strategy Tester | an indicator that declares `strategy(...)` | the chart's own candles, in your browser | **Your browser.** **Run** compiles the file in your browser and runs the module in a sandboxed worker beside the chart. The computation never leaves the browser: the only network traffic is the data the declared sources need and a one-time download of the compiler. A draft from **Run** lasts for the session and is not saved with the layout; running again replaces it. A published indicator with **Compiled** or **Open source** code runs the same way, in each reader's browser: Compiled readers get a compiled module, never the source. **OpenMarket's servers.** An indicator published with the Publish dialog's **Code** choice **Protected** runs on OpenMarket's servers only: they compute it over the chart's candles and stream the result, and the code never leaves them; its settings dialog is the file's own, and a source, timeframe or symbol setting keeps its declared default there for now. In the editor, **Run on** offers **Cloud** only for a published Protected indicator whose published version matches the code in the tab; otherwise it says "Publish first", "Publish the current version first", or "Runs in the browser. Only a Protected Indicator runs in the cloud." Where an indicator runs is fixed by its first published version ([Publishing](../functions/publishing.md)). **OpenMarket's alerts engine.** An alert on an indicator runs in OpenMarket's cloud wherever the overlay itself computes: the alerts engine loads the published version the overlay carries and evaluates it on the chart's market and interval with the overlay's settings, over at most 600 bars of that interval. It checks on every price tick, at most once a second for each indicator, and the alert's own choice says when a fire counts ([When an alert checks and fires](../functions/alerts.md#when-an-alert-checks-and-fires)); an indicator whose runs keep failing there has its alerts paused and keeps drawing on the chart. A draft cannot carry an alert ("Publish the Indicator before adding an alert."). The engine reads another market's candles and a coarser pinned timeframe, and refuses, by name, a pin it cannot serve ("This Indicator is pinned to a different interval than the chart.") or a data source alerts cannot evaluate yet, the `oi_candles` and `volume_profile_candles` streams among them ([Alerts](../functions/alerts.md)). **The Strategy Tester.** An indicator that declares `strategy(...)` places its orders in `onBar()`, and the Strategy Tester runs it in your browser with its own simulated broker, filling orders against the chart's own candles ([Strategies overview](../strategies/overview.md)). ## Numbers only Every output is a 64-bit float, and `NaN` means "nothing here". A decision is an output too: write `1` or `0` and let the declaration turn it into a look (`color_by` picks a palette entry per bar, `shape_where` gates a mark, `when` gates a box or a segment). A file declares at least one output; without one the build stops with `a file with onBar() needs at least one output(...) statement: declare what the Indicator draws, e.g. output("value", line, overlay), and write it in onBar() with out_value(...)`. Text reaches the chart only through string slots and renderers ([Plotting](../presentation/plotting.md)). Params reach the module as numbers too: every setting is a row in the overlay's settings dialog, drawn as the control its kind names (`param.int`, `param.bool`, `param.choice`, `param.color`, ...; plain `param(...)` is a number field labelled by its `description`, else its name, and bounded by its `min` and `max`), read once before the first bar, and changing one reruns the compiled module over the loaded bars without compiling again ([Setting kinds](../settings/kinds.md)). There is no `print()`: declare a string slot named `debug`, write it with `str_debug(...)` in `onBar()`, and each non-empty line prints in the editor's Console with its bar's time ([Debugging](../faq/debugging.md)). ## Memory and speed The module runs once per loaded bar, then again each time the forming bar updates. Build what lives across bars in `onStart()` or at module scope (a `StaticArray` sized from a param's `max`). A temporary that `onBar()` makes and drops (an array, a string, an object) is fine: the module sweeps what bars dropped once about 32 KiB of it has piled up, and the build reserves 256 KiB of scratch for it before the first bar (while the module holds at most 2 MiB then). The chart's sandbox caps memory at 4 MiB and refuses a run whose memory grows once the bars start ("The Indicator allocated memory after init() ...: the sandbox forbids growth once the bars start."), so memory that grows without bound, such as a history pushed onto on every bar, is still refused, and a file that writes the four functions itself, which gets no scratch, allocates in `init()` and nothing per bar ([Collections](collections.md)). Loops bounded by a param with a declared `max` stay cheap; the compiled module itself is a few kilobytes. A run that does not finish within 20 seconds is stopped and refused by name ("The run did not finish within 20 s.") rather than hanging the chart, and the chart keeps the last result that drew. State between bars also sets what a pan-back costs. A file that keeps nothing between bars (bar values in locals, module variables assigned only in `onStart()`, scratch made inside `onBar()`) can be proven per bar, and then a pan-back computes only the bars that just loaded; a file with state between bars, which rolling math such as an average or a running total needs, runs again over the whole loaded history ([Per-bar scripts](per-bar-scripts.md) lists what the proof accepts). ## The four-function form Underneath, the chart has always called four exported functions, `init()`, `state()`, `finalize()` and `reset()`. A file with `onBar()` is built into them: the build adds the four around your hooks, with import lines for every kit name, reader and writer the file uses. For the Moving Average example (an `onStart()` that sizes the average, an `onBar()` that writes it) the added functions do this: ```typescript // What the build adds around the Moving Average's onStart() and onBar(). export function init(): void { /* reads period once */ onStart(); /* then reserves scratch for onBar()'s temporaries */ } export function state(): i32 { /* reads this bar's close */ return 1; } export function finalize(): void { /* sma starts the bar as NaN */ onBar(); /* then the row goes out */ } export function reset(): void { /* nothing: the file has no onReset() */ } ``` A file that writes the four functions itself keeps building unchanged, with the same bytes as before; every file written before the hooks existed is one of these. The Moving Average written that way: ```typescript import { input, line, ohlcv, output, overlay, param } from "./sdk/declare"; import { in_close } from "./gen/inputs"; import { emitRow, out_sma } from "./gen/outputs"; import { p_period } from "./gen/params"; import { Sma } from "./sdk/ta"; param("period", 20, { min: 1, max: 200 }); input("close", ohlcv.close); output("sma", line, overlay); let sma = new Sma(20); let value: f64 = NaN; export function init(): void { sma = new Sma(i32(p_period())); } export function state(): i32 { value = sma.update(in_close()); return isNaN(value) ? 0 : 1; } export function finalize(): void { out_sma(value); emitRow(); } export function reset(): void { sma.reset(); value = NaN; } ``` What differs from a file with `onBar()`: - **Rows.** `state()` may return `0` to emit no row at all for that bar: nothing is drawn, no output has a value there, and `finalize()` is not called. A file with `onBar()` emits a row on every bar and leaves what it did not write `NaN`. A file that needs a bar with no row at all is written with the four functions. - **Phases.** It reads in `state()` and writes in `finalize()`: params are readable in `init()` only, inputs in `state()` only, outputs, strings, frames, handles and orders writable in `finalize()` only, so a value computed in `state()` travels to `finalize()` in a module variable, and `finalize()` calls `emitRow()` last. - **Imports.** It needs its import lines: the declaring words from `./sdk/declare`, its readers and writers from `./gen/params`, `./gen/inputs`, `./gen/outputs` (and `./gen/strings`, `./gen/draw`, `./gen/strategy` when declared), the classes from the kit modules. A file with `onBar()` has nothing to import. - **Reset.** `reset()` is its required fourth export, putting every module-level variable back to its starting value. A file with `onBar()` may define `function onReset(): void { ... }` for the same job, and the build's `reset()` calls it when the host resets the run; without one, nothing is reset. The chart in your browser never resets a run this way (it restores the snapshot of the closed bars instead), so a file without `onReset()` loses nothing there. A file is one form or the other: exporting any of the four, even one, makes it the four-function form, which then declares everything itself, imports included. The reference rows for both are on [Declarations and the sheet](../reference/declarations.md). # Named streams Multi-output indicators like Bollinger bands, MACD, and the stochastic produce several lines at once. In a wrun indicator each stream is an `output` of its own, and the computation behind them is a class whose fields you read by name after one `update()`: `bands.upper`, `macd.signal`, `stoch.k`. No positional guessing: every stream is read by name. ## Introduction Some indicators produce more than one line. Bollinger bands give you an upper band, a basis, and a lower band. MACD gives a MACD line, a signal line, and a histogram. A wrun indicator declares one output per line, and a class computes all of them from one input per bar: ```text output("bb_upper", line, overlay, { color: "#2563eb" }); output("bb_basis", line, overlay, { color: "#64748b" }); output("bb_lower", line, overlay, { color: "#2563eb" }); const bands = new Bb(20, 2.0); // in onBar(): bands.update(close) out_bb_upper(bands.upper); // then read the fields by name out_bb_basis(bands.basis); out_bb_lower(bands.lower); ``` `bands.update(close)` folds one bar; `bands.upper`, `bands.basis`, and `bands.lower` are its three lines afterwards. You name what you want. There is no "is the upper band index 0 or index 2?" guesswork, and a typo like `bands.upperr` is a compile error rather than a silently wrong line. ## How it works ![Named streams: one Bb object, updated once per bar, holds three fields; the file writes each to an output of its own, and the chart draws three lines: upper, basis and lower](/wrun/images/diagrams/named-streams.svg) A multi-output computation is a class with one `update(x)` method and one typed field per stream. `update` returns the primary stream (the MACD line, the basis) so the class also reads like a single-output one, and the other streams sit on the instance. Each field is an ordinary `f64`, so it flows straight into math, other classes, conditions, and outputs: ```text const m = new Macd(12, 26, 9); m.update(close); const risingMomentum = m.hist > prevHist; // compare bars (prevHist is remembered) const smoothSignal = signalEma.update(m.signal); // feed a stream into another class ``` The kit ships every class, single-stream and multi-stream alike, and a file uses them by name with nothing to import. Two rules keep a module honest: construct in `onStart()` (allocation once), and `update()` once per bar. ## The named streams The multi-stream classes, and the fields each one carries: | Class | Fields | | --- | --- | | `Bb` | `.basis`, `.upper`, `.lower` | | `Keltner` | `.basis`, `.upper`, `.lower` | | `Donchian` | `.basis`, `.upper`, `.lower` | | `Macd` | `.macd`, `.signal`, `.hist` | | `Stoch`, `Stochastic` | `.k`, `.d` | | `Supertrend` | `.line`, `.direction` | | `Adx` | `.adx`, `.plusDi`, `.minusDi` | | `Ichimoku` | `.tenkan`, `.kijun`, `.senkouA`, `.senkouB`, `.chikou` | Every class and its conventions: [TA library](../functions/ta-library.md). A few worth calling out: - **`Stoch`** splits into the fast `%K` (`.k`) and its smoothed `%D` (`.d`). The classic crossover is `Cross.update(stoch.k, stoch.d)`. - **`Supertrend`** carries the trailing stop level as `.line` and the trend side as `.direction` (`1` or `-1`). Use `.direction` as a `color_by` index or a gate; draw `.line`. - **`Macd.hist`** is the MACD line minus the signal line, ready for a `histogram` output. ## Reading every stream at once Two shipped classes and all six of their streams as outputs. `Macd` is the fast, slow and signal EMAs folded into one object; `Bb` is the window mean and its population standard deviation. Every stream is an output of its own, so once you publish the indicator an alert set from the chart can follow any of them ([Alerts](../functions/alerts.md)). ```typescript param("fast", 12, { min: 1, max: 200, description: "MACD fast EMA" }); param("slow", 26, { min: 2, max: 400, description: "MACD slow EMA" }); param("signal", 9, { min: 1, max: 200, description: "MACD signal EMA" }); param("bb_period", 20, { min: 2, max: 400, description: "Bollinger window" }); param("bb_mult", 2, { min: 0.5, max: 4, description: "Bollinger width in standard deviations" }); output("bb_upper", line, overlay, { color: "#2563eb", width: 2, description: "Upper Bollinger band" }); output("bb_basis", line, overlay, { color: "#64748b", width: 2, description: "Bollinger basis (the moving average)" }); output("bb_lower", line, overlay, { color: "#dc2626", width: 2, description: "Lower Bollinger band" }); output("macd", line, lower, { color: "#1d4ed8", width: 2, description: "MACD line" }); output("signal", line, lower, { color: "#ea580c", width: 2, description: "Signal line" }); output("hist", histogram, lower, { color: "#15803d", description: "MACD minus signal" }); // One update() per bar; the streams are fields you read by name afterwards. let macd = new Macd(12, 26, 9); let bands = new Bb(20, 2.0); function onStart(): void { macd = new Macd(i32(p_fast()), i32(p_slow()), i32(p_signal())); bands = new Bb(i32(p_bb_period()), p_bb_mult()); } function onBar(): void { const close = bar.close(); macd.update(close); bands.update(close); // Nothing is written until the slowest stream is warm: the MACD signal line. if (isNaN(macd.signal) || isNaN(bands.basis)) return; out_bb_upper(bands.upper); out_bb_basis(bands.basis); out_bb_lower(bands.lower); out_macd(macd.macd); out_signal(macd.signal); out_hist(macd.hist); } ``` **What to expect:** the three bands start drawing once the 20-bar window fills and track together. The MACD streams warm later: the MACD line needs the slow EMA (26 bars), the signal line nine MACD values beyond that, so nothing is drawn until the 34th bar and all six lines then start in lockstep. Bars where one stream is finite and another is not are handled in the classes (`NaN` stays `NaN`), never in `onBar()`. ## A composite class as one value The class instance is one value: pass `macd` to a helper that takes a `Macd`, keep an array of them for several settings, or read a single field inline. What you cannot do is index a stream's history (`m.hist[1]`): remember the previous value in a module-level variable, exactly as for any other number (`core-variables.md`). Single-output classes like `Rsi`, `Ema`, and `Sma` return their one value from `update()` and have no stream fields, so you write them straight to an output: `out_rsi(rsi.update(close))`. Named streams are only for the multi-line indicators above. The full catalog is the [TA library](../functions/ta-library.md). # Repainting What repainting is, why it breaks backtests, and why a wrun indicator does not repaint by construction: `onBar()` sees one bar and nothing later, a higher timeframe is folded in only after its candle closes, an `interval` pin is read as of each bar's close, and the chart replays the forming bar from a snapshot of the state the closed bars left. What can still move a bar you have already seen on the chart is the window the indicator computes over and a correction to the data, and this page shows both so neither surprises you. The guarantee comes from the shape of the model, not from a flag you remember to set. ## What repainting is ![Repainting: the values on closed bars never change; only the forming bar's value moves as new data arrives, until that bar closes](/wrun/images/diagrams/repaint-forming.svg) Repainting is when a script's historical values change after the fact. The line you see today over old bars is not the line the script drew when those bars were live. A signal that looks like it fired one bar early in backtest fires one bar late in production, or never. The chart redraws itself once the future arrives, so your backtest is reading numbers that did not exist at the time. That is the whole problem in one sentence: a repainting indicator lies about the past, so anything you measure on history (win rate, drawdown, signal timing) is fiction. You cannot trust a backtest you cannot reproduce. ## Why it happens Repainting comes from reading data that was not yet available at the bar you are computing, or from a history that is not the one you ran on. Three sources, two classic and one specific to a module with state: - **An unclosed higher-timeframe candle.** A naive 4h lookup on a 1h chart hands back the forming candle's live value; history backfills the finished number the live chart never had. - **A future-leaking series.** Anything that depends on a later bar: a centered smoother, "highest of the next N bars". History resolves it; live it does not exist yet. - **State that depends on where history starts.** A running total or a bar counter begins at the first bar loaded; load more history and every value shifts, although no bar looked ahead. The tell is the same each time: the computation saw something during the backtest that it could not have seen live, or saw something live that history will not replay. ## The good news: no lookahead by construction `onBar()` receives exactly one bar: the inputs of the bar being evaluated, oldest first. There is no history array to index forward, no `[−1]`, no way to reach the next bar. A value can only depend on bars at or before its own, so a mark that appears in history would have appeared live on the same bar. An indicator cannot break this by accident; there is nothing to peek at. The causal-prefix guarantee in one sentence: at bar *t*, every value the module holds was derived only from bars at or before *t*, so the past never changes when the future arrives. `bar.count()` is the one way out, and you opt into it by name: it tells a bar how many bars the run holds, so a value that reads it (a lagging line that waits for the bar `shift` bars later) does change when a later bar arrives. The chart keeps such a file honest by running every bar again whenever a bar opens, so the live chart always matches a fresh load over the same bars ([How many bars the run holds](execution-model.md#how-many-bars-the-run-holds)). ## Higher timeframes: confirmed by the fold ![Higher timeframes, bar by bar: a 4h candle spans four 1h bars; with lookahead on, a Pine script on history sees the new 4h close from the first of those bars, while in wrun every 1h bar sees the previous close and the new one arrives on the bar after the 4h candle closes](/wrun/images/diagrams/repainting.svg) Built inside the module, a higher timeframe comes from the chart's own bars: bucket bars by `time.bar_open_sec`, remember the running bucket's close, and fold it into the 4h statistic only when a bar from the **next** bucket arrives. A 4h candle contributes exactly once, after it closed. Rerun over history and it matches what it showed live, bar for bar. No look-ahead, no flag to remember. ```typescript param("bucket_hours", 4, { min: 1, max: 168, description: "Higher-timeframe bucket, in hours" }); // The confirmed higher-timeframe close: flat across the bucket, stepping only when a candle closes. output("h4_close", line, overlay, { color: "#7c3aed", width: 2, description: "The most recent fully closed 4h candle, no look-ahead" }); // The developing value, opt-in and clearly labeled: it moves with every bar inside the bucket. output("h4_developing", line, overlay, { color: "#16a34a", width: 1, description: "The forming 4h candle's running close (repaints by design)" }); output("close", line, overlay, { color: "#94a3b8", width: 1, description: "The chart-timeframe close for comparison" }); let bucketSec: f64 = 14400.0; let bucket: f64 = NaN; // the bucket the running candle belongs to let running: f64 = NaN; // the running candle's latest close (developing) let confirmed: f64 = NaN; // the last CLOSED candle's close function onStart(): void { bucketSec = p_bucket_hours() * 3600.0; } function onBar(): void { const close = bar.close(); const b = Math.floor(bar.time() / bucketSec); if (b != bucket) { // A bar from the next bucket has arrived: the running candle is now closed, and only now is it confirmed. if (!isNaN(bucket)) confirmed = running; bucket = b; } running = close; if (isNaN(confirmed)) return; out_h4_close(confirmed); out_h4_developing(running); out_close(close); } ``` ### Read the staircase The purple `h4_close` line is flat across four 1h bars, then steps to a new level, then holds flat again. That staircase is the visual signature of a correct, confirmed higher timeframe: the value only changes when a 4h candle actually closes, and between closes there is no new confirmed information. The green `h4_developing` line tracks the grey chart close inside each bucket: that is what a repainting value looks like, and it is drawn here on purpose so you can see the difference. A cross built on the green line would not survive into production; a cross built on the purple one reproduces exactly. ## Requesting a live value is opt-in Sometimes you genuinely want the forming bucket: a live 4h close ticking in a readout. In a module that is just the running variable, as above, and it is a deliberate choice you make by reading `running` instead of `confirmed`. A developing value is fine for a display; it is the wrong thing for a signal, because it changes as the bucket fills, so a cross or threshold built on it will not reproduce on history. Reach for it only when you want to *show* the live edge, never when you want to *act* on it. A pinned input's `forming` view is the same kind of value. ## Pins are read as of close An `interval` pin reads real coarser candles, and the chart applies the same rule for you: a pinned candle reaches a chart bar only as of that bar's close, live or historical, so a forming 4h candle never leaks into the 1h rows under it ([Multi-timeframe](multi-timeframe.md)). The cost is a value that steps once per pinned candle: the same staircase. Act on a pin through its default `confirmed` view. ## The forming bar replays from a snapshot ![The forming bar replays from a snapshot: the state after the last closed bar is saved; every update of the forming bar starts from that snapshot, so nothing counts twice; when the bar closes it runs once more and becomes the new snapshot](/wrun/images/diagrams/forming-snapshot.svg) The forming bar is the one exception to "one call per bar": the chart evaluates it again as new data arrives, at most about once a second. It does not re-run history for that. It snapshots the module after the last closed bar (its memory, every module-level variable, and its drawing handles) and restores that snapshot before each new evaluation of the forming bar, so every replay starts from exactly the state the closed bars left: an accumulator cannot count the forming bar twice, and nothing the forming bar drew is stacked. When the bar closes, the chart evaluates it once more as a closed bar, then moves on to the new one. Nothing in the file has to put its state back for this: the chart restores the snapshot, every module-level variable and every TA object included, so the forming bar never depends on a reset of your own. ## What can still change a closed bar No bar changes because it looked ahead, but on the chart two things can change a bar you have already seen: - **The window.** The chart runs an indicator over exactly the bars it has loaded, and panning back runs it again over the longer window (so does a live gap longer than 250 bars). A value that depends on where history starts shifts when more history loads: a running total from the first loaded bar, a bar counter, the open of the first bar. A value over a fixed window (an SMA, a rolling sum) or reset each session stays put once its window is loaded; an EMA, which remembers every bar it has seen, moves slightly and converges. - **Corrected data.** When the chart learns that a closed bar's data changed (a late trade folded into a closed bar, a candle the venue corrected, an ETF flow revised after the US session), it runs the indicator again from its buffers, so history matches the corrected data. ```text let cvd: f64 = 0.0; // a running sum since the first LOADED bar // Pan back and the chart runs the Indicator again over the longer window: // every closed bar's cvd shifts by the delta of the bars that just loaded, // while a delta summed over a rolling window, or reset each session, keeps // its values. ``` Run-level renderers and drawings are selected from the finished rows (the newest ready row that satisfies the kind's rule wins), and they never change an output's value. ## How to stay repaint-safe A short checklist: - **Fold higher timeframes on the next bucket.** The confirmed value is the one you act on; the running value is a readout. - **Read pins confirmed.** A pinned coarse input steps as of each bar's close; its `forming` view is a readout, not a signal. - **Do not act on the still-forming bar.** Its high, low, and close are moving until it closes. Gate confirmed signals on settled data. - **Anchor what you act on.** Act on values over a rolling window or a session, not on the level of a total that starts at the first loaded bar. Stick to confirmed folds, confirmed pins and anchored windows and your backtest will mean something: what you measured on history is what the indicator would have done live. ## See also - [Multi-timeframe](multi-timeframe.md) for the full bucket-fold and `interval`-pin story, calendar buckets included. - [Execution model](execution-model.md) for the bar loop, warm-up, and where an indicator runs. # Per-bar scripts A per-bar script computes each bar from that bar alone: its candle, its inputs and the settings. When the compiler can prove that, the chart computes only the newly loaded bars on a pan-back and keeps every bar it already drew; when it cannot, every pan-back runs the indicator again over the whole loaded history. This page shows what the proof accepts, what it refuses, why rolling math such as a moving average is a different kind of script rather than a mistake, how rolling math built from finite windows still skips the whole history (it settles within W bars), how a file keeps a second mode behind one setting out of that proof (a mode guard), and where the verdict shows. There is nothing to declare: the compiler reads the code and decides. ## What a pan-back recomputes The chart runs an indicator over the bars it has loaded. Panning back loads earlier bars, and the indicator has to cover them too. Most scripts cannot reuse what they already drew: a running total, a moving average or a bar counter starts at the first loaded bar, so bars added in front can change the values after them, and the chart runs the indicator again from the new first bar to the newest. A per-bar script carries nothing from one bar to the next. A bar's value is the same whether the run started a thousand bars earlier or at that bar, so the chart runs only the bars that just loaded and keeps the rest: ```text loaded: bar 5,000 ............................. newest pan back loads: bar 1 ... bar 4,999 whole history: run bar 1 ................................... newest per-bar script: run bar 1 ... bar 4,999 keep bar 5,000 ... newest ``` The forming bar, live updates and a changed setting run as they do for any indicator ([Execution model](execution-model.md)). ## What the proof accepts The compiler proves a file per bar when everything `onBar()` reads comes from the bar at hand or from a value fixed before the first bar, and every form in the file is one of these: - **Number and boolean locals with a starting value.** `const x = bar.close() * 2.0;`, `let n = 0;` or `let up = bar.close() > bar.open();` inside `onBar()` or a helper: made when the bar starts, gone when it ends. A local declared without a value, a string and an object (`new Sma(14)` included) refuse. - **Module constants.** A top-level `const` holding a number or a boolean, from literals, arithmetic, earlier constants and the kit helpers below (`const TUPLE = 3;`, `const SPAN = TUPLE * 2 + 1;`, `const STEP = roundTo(0.125, 2);`); `Math` is refused there. A top-level table of numbers (`const WEIGHTS = [0.5, 0.3, 0.2];`), read only by index and `.length`. - **Module scalars set once in `onStart()`.** A top-level `let` holding a number or a boolean, given a constant starting value and assigned only in `onStart()` from settings, constants, `Math`, the kit helpers below and arithmetic (`depth = p_depth_pct() / 100.0;`), never from a module `let`; `onBar()` reads it and never writes it. `onStart()` holds locals and assignments only, so a choice there is a ternary, not an `if`. - **Scratch made inside `onBar()`.** A local `StaticArray` of numbers (`const sums = new StaticArray(8);`): filled, read and written by index, its `.length`, and passed to a helper that takes the same shape. - **This bar's readers.** `bar.open()`, `bar.high()`, `bar.low()`, `bar.close()`, `bar.volume()` and `bar.time()`; a feed's `in_()`; a number or boolean setting's `p_()` and `pb_()` (a list setting's reader refuses); and a celled input's count, `in__cells()`, with its view read by index through a local `const` (`const cells = in__view();`) ([Celled sources](data-sources.md#celled-sources)). - **Plain functions.** Your own functions that take numbers (or a local `StaticArray`) and return a number or a boolean; `isNaN`, `isFinite`, `NaN` and `Infinity`; the `Math` functions `abs`, `floor`, `ceil`, `round`, `trunc`, `sqrt`, `pow`, `min`, `max`, `log`, `log2`, `log10`, `exp`, `sign`, `hypot`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan` and `atan2`, and no other `Math` member (`Math.PI`, `Math.random()` and `Math.log1p()` refuse); and these kit helpers: the colour helpers `rgba`, `rgb`, `isThemeToken`, `alpha`, `mix`, `fromGradient`, `lighten`, `darken`, `red`, `green`, `blue`, `opacity`, `transparency`, `toPacked` and `fromPacked`; the session helpers `multiHas`, `unitToPrice`, `inSession`, `sessionDayOpen`, `sessionTradeDate`, `sessionWeekOpen` and `sessionGapBefore`; the size helpers `sizeUnit` and `notional`; `delta`, `deltaPct`, `roundTo`, `roundToTick` and `epochSec`; and the candle tests `candles.doji`, `hammer`, `shootingStar`, `bullishEngulfing`, `bearishEngulfing`, `insideBar`, `outsideBar` and `pinBar`. Any other kit function, `fromHex` for one, refuses. - **What the chart draws from the bar.** `out_(value)` written from the values above, and what reads only outputs or the bar's cells: lines, bands (`range`), boxes and segments, a `render.legend` entry over an output, a `render.hud` card over outputs, and a heatmap over the bar's own celled block. ## What the proof refuses Anything that carries a value from one bar into the next, or reads where the bar stands in the run, refuses the proof. The compile names the first one it meets, with its line when it has one: - **A module variable written in `onBar()`.** A flag, a counter, a running total or the previous close: `prev = bar.close();` inside `onBar()` hands the bar to the next one. - **An object.** `new Sma(...)`, `new Ema(...)`, `Cvd`, `History`, `List` and every other kit class keep earlier bars by design, wherever they are made, and a class of your own refuses too. - **A module-level array.** A `StaticArray` at the top of the file is memory every bar writes and the next bar reads (a ring buffer, a window): make scratch inside `onBar()` instead. A table that is written, filled or passed to a helper refuses the same way. - **Drawings.** A drawing handle used in code (`draw.label(...)`, `draw.line(...)`), a `handles.*` declaration and a `draw.*` declaration all live across bars. - **Text.** A string slot and its senders (`str_`, the `sb_*` builders), a string in code, and a text setting's words (`pt_()`). - **Where the bar stands.** `bar.isLast()` and `bar.count()` answer by how many bars the run holds. - **An input that reaches beyond the bar.** An input with its own `interval` or `view`, a `candles` or `intrabar` stream, a tape `history`, and a feed beside the chart's own candles that carries its last value into a bar with no reading. Carrying is the default for such a feed: declare `missing: "nan"` or `"zero"` on it to keep it per bar ([The `missing` policy](data-sources.md#alignment-and-the-missing-policy)). - **Declarations that draw or act across bars.** The renderers `render.text`, `render.label`, `render.table`, `render.shape`, `render.stats_row`, `render.bgcolor` and `render.barcolor`; frames and the levels and panels they feed; a strategy; an alert; and an output drawn at another bar (`displacement_bars`). - **A form outside the proof.** A `switch` (write `if` and `else`), an `if` in `onStart()` (a [mode guard](#one-setting-two-modes-the-mode-guard)'s dispatch aside), an arrow function, an `Array` written by index (use a `StaticArray`), a helper that returns an array, a view held in a `let`, an `onReset()` with a body, the four-function form, and a second file beside the indicator. ## Rolling math is a different kind Some math needs earlier bars by definition: - a moving average at a bar averages the bars before it; - a cumulative delta adds the bar's delta to the total of every bar before it; - a session profile folds every bar since the session opened; - swings, zones and divergences remember where price has been. These scripts are right to keep state, in a kit class or in module variables, and the per-bar proof is right to refuse them. That is not a mistake to fix, and rolling math bent into another shape to win the proof only gets harder to read. Reach for the per-bar shape when the math is per bar to begin with: a reading of the bar's own candle, book, profile or trades. Rolling math whose every piece of memory has a finite window, such as a moving average, settles within a known number of bars, and the chart uses that (next section); the rest runs again over the whole loaded history on a pan-back, as it always has. The verdict covers the whole file, so one value that never settles anywhere in it makes every pan-back recompute the history. ## Rolling math that settles within W A 20-bar moving average forgets: at any bar it reads that bar and the 19 before it, and nothing earlier. When every piece of memory in a file is an instance of a kit class with a finite window, the compiler adds the windows up into W, the number of earlier bars a fresh run needs before its values match a run from the first bar, bit for bit. On a pan-back the chart then starts a fresh run W bars before the newly loaded bars, drops those W rows, and keeps every bar it already drew: ```text loaded: bar 5,000 ............................. newest pan back loads: bar 1 ... bar 4,999 whole history: run bar 1 ................................... newest settles within W: run W bars before bar 1 ... bar 4,999 keep bar 5,000 ... newest (the W running-start rows are dropped) ``` Only finite-window kit classes qualify today: `Sma`, `Wma`, `Hma`, `Vwma`, `Alma`, `Swma`, `Linreg`, `Sum`, `Median`, `Percentile`, `Variance`, `Stdev`, `Zscore`, `Correlation`, `Cmo`, `Roc`, `Mom`, `Change`, `Cci`, `Mfi`, `Wpr`, `Stoch`, `Stochastic`, `Tr`, `Bb`, `Donchian`, `Highest`, `Lowest`, `HighestBars`, `LowestBars`, `Ichimoku`, `Rising`, `Falling`, `PivotHigh`, `PivotLow` and `Cross` from `./sdk/ta`; `Dev`, `PercentRank`, `Bbw`, `Range`, `Mode`, `Cog`, `Wvad`, `Iii`, `Efficiency`, `Ultimate`, `Vortex`, `Aroon` and `Choppiness` from `./sdk/ta-plus`; `LiquidationBurst` from `./sdk/orderflow`; and `History` from `./sdk/stats`, whose `push(...)` is its update: pushed once per bar, its size is its window, and `ago(n)` reads the value pushed `n` bars back, the fixed delay an offset draws (`delay = new History(i32(p_offset() + 1.0));` in `onStart()`, then `delay.push(average);` and `out_wma(delay.ago(i32(p_offset())));`). The smoothing classes (`Ema`, `Rma`, `Rsi`, `Atr`, `Macd`, `Adx`, `Tsi`, `Dema`, `Tema`, `Kama` and the rest) remember their start for good, so an EMA or RSI script is unchanged: its pan-back still runs the whole history. So are running totals, the other rings (`List`, `ClosedWindow`, `CandleList`), session and calendar classes, swings and zones, and a module variable written in `onBar()`. The compiler admits such a file when: - **Each instance is built at the top of the file.** `let sma = new Sma(20);` qualifies as it stands; `onStart()` may rebuild it from settings (`sma = new Sma(i32(p_period()));`), and the last top-level rebuild there is the one that counts. A constructor argument is either a number the compiler works out with its own whole-number arithmetic (a literal, a top-level constant, `+`, `-` and `*` over them, a cast: `20 - 10 * i32(1.9)` is 10, and a sum that overflows keeps the whole-history run), or one cast around settings added together, each times a positive number, plus or minus a constant (`i32(p_len())`, `i32(p_len() * 2)`, `i32(2 * p_a() + p_b() + 1)`, `i32(p_len() * 1.5)`, W rounding a fraction up). An `onStart()` local assigned once stands for its value (`const n = i32(p_len() * 3); sma = new Sma(n);`). A length that only shrinks one setting counts as that setting where the class's window is its length (every class but `Hma`, whose window is twice it): `i32(Math.floor(f64(p) / 2))` (any divisor of at least 1), `i32(Math.sqrt(f64(p)))`, `i32(Math.floor(Math.sqrt(f64(p))))` and `i32(Math.round(Math.sqrt(f64(p))))`, `p` the setting's reader (`p_len()`) or an `onStart()` local assigned once from it (`const p = i32(p_len());`). Those are the half and root lengths of a Hull average built from three `Wma`, each window counted as the full period. A cast inside the arithmetic (`i32(p_len()) * 3`), a subtracted setting, any other division or root, or a fact the chart fills rather than the settings (`chart.interval_sec()`, the tick size, the market's zone) keeps the whole-history run. - **Each instance updates exactly once per bar,** in a top-level statement of `onBar()` before any statement that can return: never under an `if`, in a loop, in a ternary branch or on the right of `&&` or `||`. An update a bar can skip would leave the window short. - **Instances are touched in `onBar()` only,** through `update(...)`, their fields and their read methods; never in a helper, never copied into another variable, passed or compared. A field or read method is free anywhere in `onBar()`, under an `if` or in a loop included: a read reaches an update only through a top-level local or directly in its argument, and the proof follows both. - **An update reads only this bar's inputs,** settings, constants, pure helpers and other instances' values, directly or through `onBar()` locals assigned in top-level statements before the first one that can return. A local may be assigned several times: the proof follows every assignment that reaches the update, in order. A local assigned under an `if` or in a loop that feeds an update, and an instance whose update reads itself (directly, through another instance, or through a local that still holds an earlier read), keep the whole-history run. - **The rest of the file passes the per-bar proof, and every input is the chart's own feed:** its candles (`bar.close()`, `input("close", ohlcv.close)`) or its bar time (`bar.time()`), with no market pin, interval or other option. Another market's candles, a book, a tape or a published feed keeps the whole-history run. W is each instance's window per constructor argument (a period's own length, twice it for `Hma`, a `History`'s size, one window per length for `Stoch`, `Stochastic`, `Ultimate` and `Ichimoku`, its displacement included), plus each class's fixed bars (one for a class that reads the bar before, such as `Change`, `Roc` or `Mfi`; two for `Tr` and `Cross`; four for `Swma`), summed over the instances, plus one bar per dependency edge: an instance whose update reads one other instance adds 1, one that reads two others adds 2. The SMA lesson (`sma-codefirst`) settles within its period: a pan-back over it at period 20 runs 20 hidden bars before the new ones. A declared `warmup(...)` or `warmup_bars` stays out of W: the sheet's `history_warmup` carries the computed windows alone, and the chart's running start is the larger of the two at the run's settings, so a declaration that matches the period costs nothing extra. ## One setting, two modes: the mode guard A built-in often offers its math on a higher timeframe too: a select picks `chart` (the chart's own bars) or a timeframe, and the timeframe path builds the higher bars from the chart's own with a `Resampler` and a `ClosedWindow`, state anchored to the calendar that never settles within a fixed number of bars. The chart path can, and a mode guard lets the compiler prove it on its own: ```typescript param.int("period", 20, { min: 1, max: 500, label: "Period" }); param.choice("timeframe", ["chart", "5m", "15m", "30m", "1h", "4h"], "chart", { label: "Timeframe" }); param.bool("wait_for_close", true, { label: "Wait for close" }); output("sma", line, overlay); let atChart: bool = true; // the guard: a module bool, any name let sma: Sma = new Sma(1); // arm A: finite kit windows only let resampler: Resampler = new Resampler(tf.CHART, true); // arm B: anything let closes: ClosedWindow = new ClosedWindow(1); function onStart(): void { atChart = p_timeframe() == 0.0; // the guard's one write, first if (atChart) { sma = new Sma(i32(p_period())); // arm A } else { resampler = new Resampler(i32(p_timeframe()), p_wait_for_close() != 0.0); // arm B closes = new ClosedWindow(i32(p_period())); } } function onBar(): void { if (atChart) { // the first statement of onBar() const v = sma.update(bar.close()); // each instance once, at the top out_sma(v); return; // arm A ends with return; } // arm B: everything after the if resampler.update(bar.time(), bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), NaN); if (resampler.closed()) closes.push(resampler.source(0, false)); out_sma(resampler.refused() ? NaN : closes.mean(i32(p_period()))); } ``` The compiler admits the guard when the file keeps to this shape; a build that breaks it names `warmup:guard:` or `warmup:mode:`: - **The guard** is a top-level `let` of type `bool` that starts `true` or `false`, written once, as the first statement of `onStart()` other than admitted abort-only checks (below), from a select compared with 0 (`atChart = p_timeframe() == 0.0;`, or `== 0`), or from several joined by `&&` ([below](#several-selects-one-guard)), and read only as the whole condition of the two dispatches: never written again, read anywhere else or shadowed by a local. - **The select** is a `param.choice(...)` whose default is its first option: a `select` with whole-number options from 0 up that include 0, default 0 and no host. `param.timeframe(...)` and `param.source(...)` pin an input for the host, a later default would leave W at the defaults meaningless, and a negative option would sink the mode window below 0, where every reader clamps it away while arm B runs, so each keeps the whole-history run (`warmup:guard:`). - **The dispatches.** `if (atChart) { ... } else { ... }` is the next statement of `onStart()`, and whatever follows it there runs in both modes. `if (atChart) { ...; return; }` is the first statement of `onBar()`, its arm ending with an unconditional `return;`: what follows that `if`, and its `else` when it has one, is arm B. A second dispatch in `onStart()` refuses. - **Arm A is proven as if it were the whole file.** The compiler keeps everything outside the two dispatches and arm A of each, drops arm B and every top-level variable, helper and class only arm B reaches, and runs the proof of this page on what is left: each instance updated once at the top of the arm, before its `return;`, and the source picked inline into a local, never through a helper. A dropped variable's initializer still runs when the module starts, so it may only read, compute and allocate: a kit class, an array, or a class of yours whose constructor sets only its own fields and that has no getter, setter, operator or base class. One that calls a helper of yours writing anything, or builds a class that could run other code, keeps the whole-history run (`warmup:mode:`), and so does a dropped class whose static fields start from such a call. - **Nothing crosses the arms.** A kit instance both arms reach, a helper both arms call that reaches one, a top-level variable written in `onBar()` before the dispatch (a bar counter) and a local of `onStart()`'s arm A that the code after the dispatch would read as another binding keep the whole-history run. A top-level number written only in `onStart()` (the source pick, a period) may be read by both. - **Setting checks may stay.** A call in `onStart()` of `abort(...)`, or of a helper that only reads settings and numbers, compares, builds its message and aborts, writing nothing, either ends the run or does nothing: it may stand before the dispatch or in arm A, and the proof sets it aside. The sheet's `history_warmup` then carries arm A's windows plus one mode window over the select, `{ terms: [{ param: "timeframe", multiplier: 1000000000 }], plus: 0, min: 0 }` (the kit exports the multiplier as `WRUN_WARMUP_MODE_UNBOUNDED`). It is a conditional proof encoding, not a bound for arm B: with the select at 0 the window adds nothing and W is arm A's; at any other option W runs past a billion bars, more than any chart holds, so the chart runs the whole history in that mode as it always did. A terminal build says which: `pan-back: new bars plus a 20-bar running start (timeframe 0 only)`. ### Several selects, one guard A built-in often keeps more than one mode behind its settings: a timeframe pick and a smoothing pick (`None`, `SMA`, `EMA`) each leave the plain line at their first option only. Join their comparisons with `&&` in the guard's one write, and arm A is the file with every select at 0: ```typescript param.int("period", 20, { min: 1, max: 500, label: "Period" }); param.choice("timeframe", ["chart", "5m", "15m", "30m", "1h", "4h"], "chart", { label: "Timeframe" }); param.choice("smoothing_type", ["None", "SMA", "EMA"], "None", { label: "Smoothing" }); param.int("smoothing_length", 9, { min: 1, max: 200, label: "Smoothing length" }); param.bool("wait_for_close", true, { label: "Wait for close" }); output("sma", line, overlay); let atChart: bool = true; // one guard for both selects let sma: Sma = new Sma(1); // arm A: the plain line let base: Sma = new Sma(1); // arm B: its own copy of the line let resampler: Resampler = new Resampler(tf.CHART, true); let closes: ClosedWindow = new ClosedWindow(1); let smaSmoothing: Sma = new Sma(1); let emaSmoothing: Ema = new Ema(1); function onStart(): void { atChart = p_timeframe() == 0.0 && p_smoothing_type() == 0.0; // every select at 0 if (atChart) { sma = new Sma(i32(p_period())); } else { base = new Sma(i32(p_period())); resampler = new Resampler(i32(p_timeframe()), p_wait_for_close() != 0.0); closes = new ClosedWindow(i32(p_period())); smaSmoothing = new Sma(i32(p_smoothing_length())); emaSmoothing = new Ema(i32(p_smoothing_length())); } } function onBar(): void { if (atChart) { const v = sma.update(bar.close()); out_sma(v); return; } // arm B reads both selects again, as often as it needs let v = base.update(bar.close()); if (p_timeframe() != 0.0) { resampler.update(bar.time(), bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), NaN); if (resampler.closed()) closes.push(resampler.source(0, false)); v = resampler.refused() ? NaN : closes.mean(i32(p_period())); } const smoothing = p_smoothing_type(); if (smoothing == 1.0) v = smaSmoothing.update(v); else if (smoothing == 2.0) v = emaSmoothing.update(v); out_sma(v); } ``` - **The write** is `&&` and nothing else between `()` and `bar.*()` from `onBar()` on (`NaN` before the first bar), and an `out_()` write reaches the row only from `onBar()`; a helper inherits the phase of its caller, so keep helpers pure and let the hooks read and write. ## Best practices - **Keep functions focused.** One thing per function: `rsiZone(rsiValue: f64): f64` returns `0`, `1`, or `2`; the output write stays in `onBar()`. - **Use descriptive names.** `isOverbought(rsiValue)`, `percentChange(oldValue, newValue)`; not `calc(a, b)` or `check(x)`. - **Prefer parameters to module state for pure math.** A function that takes everything it needs is reusable across indicators by pasting; a function that reaches into module state is tied to this file. Reserve module-state reads for predicates you pass as values. - **Turn a family of helpers into a class** when they share state: a `Window` with `sum()`, `avg()`, and `median()` (`collections.md`), a `Macd` with `update()` (`named-streams.md`). Helpers that share nothing stay functions. # Lambdas and reducers Arrow functions, function values, and the loops that do the work of the reducer methods (`map`, `filter`, `reduce`, `forEach`, `some`, `every`). A wrun indicator has arrow functions, with one rule that changes how you use them: a function cannot capture a local variable, so the "closure" is module-level state and a reducer is a plain loop over a buffer. ## Lambda syntax An arrow function has typed parameters and a typed return, in either the expression or the block form. It is a value: store it in a variable typed `(x: f64) => f64`, pass it to a function, call it. ```text const double = (x: f64): f64 => x * 2.0; const label = (side: f64): string => { return side > 0.0 ? "bid" : "ask"; }; let pick: (x: f64) => bool = above; // a named function is a value too const y = double(21.0); // 42 ``` Both forms need every type written out: an untyped parameter or a missing return type is a parse error (`Type expected.`). ## The one rule: no captured locals The JavaScript habit is a lambda that closes over the surrounding scope: `const threshold = high * 0.99; prices.filter((p) => p > threshold)`. In an indicator that exact shape, an arrow function inside `onBar()` reading a `const` of `onBar()`, is refused at compile time: ```text ERROR AS100: Not implemented: Closures ``` The compiler cannot build a function that carries a copy of another function's locals. What a function **can** read is module-level state, which is where an indicator keeps everything that matters anyway. So the pattern is: put the threshold in a module-level `let`, write the predicate as a named function (or an arrow at module scope), and pass it. ```typescript param("bars", 20, { min: 1, max: 200, description: "Bars in the window" }); output("above_count", line, lower, { color: "#16a34a", description: "Bars in the window closing above the window mean" }); output("near_high_count", line, lower, { color: "#f59e0b", description: "Bars in the window within 1% of the window high" }); const MAX_BARS = 200; const closes = new StaticArray(MAX_BARS); let n: i32 = 20; let cursor: i32 = 0; let count: i32 = 0; let mean: f64 = NaN; // module-level: the "closure" every predicate reads let nearHighLevel: f64 = NaN; // Predicates are named functions over module-level state, never over a local. function aboveMean(x: f64): bool { return x > mean; } function nearHigh(x: f64): bool { return x >= nearHighLevel; } // A reducer is a loop that takes the predicate as a value. function countWhere(xs: StaticArray, len: i32, pred: (x: f64) => bool): i32 { let hits = 0; for (let i = 0; i < len; i++) if (pred(xs[i])) hits += 1; return hits; } function windowMax(xs: StaticArray, len: i32): f64 { let m = -Infinity; for (let i = 0; i < len; i++) if (xs[i] > m) m = xs[i]; return m; } function windowMean(xs: StaticArray, len: i32): f64 { let s = 0.0; for (let i = 0; i < len; i++) s += xs[i]; return s / f64(len); } function onStart(): void { n = i32(p_bars()); } function onBar(): void { closes[cursor] = bar.close(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n) return; mean = windowMean(closes, n); nearHighLevel = windowMax(closes, n) * 0.99; out_above_count(f64(countWhere(closes, n, aboveMean))); out_near_high_count(f64(countWhere(closes, n, nearHigh))); } ``` `countWhere` is the reducer; `aboveMean` and `nearHigh` are the lambdas, reading `mean` and `nearHighLevel` from module scope instead of capturing them. The same function value can be passed to any loop that takes a `(x: f64) => bool`. ## The reducer methods `Array` has the familiar methods, and each callback is a non-capturing function with typed parameters (trailing parameters may be omitted): | Method | Callback | Returns | Allocates? | | --- | --- | --- | --- | | `map(fn)` | `(value: f64, index?: i32) => U` | a new array | yes | | `filter(fn)` | `(value: f64, index?: i32) => bool` | a new array | yes | | `reduce(fn, initial)` | `(acc: U, value: f64, index?: i32) => U` | the final accumulator | no | | `forEach(fn)` | `(value: f64, index?: i32) => void` | nothing | no | | `findIndex(fn)` | `(value: f64, index?: i32) => bool` | the first matching index, or `-1` | no | | `some(fn)` | `(value: f64, index?: i32) => bool` | `true` if any match | no | | `every(fn)` | `(value: f64, index?: i32) => bool` | `true` if all match | no | There is no `find`: use `findIndex` and read the element. `map` and `filter` return a **new** array every call. In a file with `onBar()` the module frees it once the bar drops it, so a per-bar call works, but it allocates on every bar for nothing: they belong in `onStart()` (building a lookup table once), and a file with the four functions keeps them there. On the per-bar path, write the loop over a `StaticArray` you allocated once; the window example above is the template, and `collections.md` has every numeric reducer as a method. ```text // onStart(): fine, once const doubled = periods.map((p: f64): f64 => p * 2.0); // onBar(): a loop over a preallocated buffer, no allocation let sum = 0.0; for (let i = 0; i < n; i++) sum += window[i]; ``` ## The microstructure idiom Where you would reach for a `map` and a `reduce` over order-flow rows (buy minus sell per bucket, summed), an indicator reads the bar's cells (one `[low, high, buy, sell]` row per price bucket) through the input's view and loops over them: the net delta of the bar, and the price of its largest-volume bucket (the point of control). ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); output("delta", line, lower, { color: "#2563eb", description: "Net per-bar delta: buy minus sell volume across every price bucket" }); output("poc", line, overlay, { color: "#f59e0b", description: "Price of the bucket that traded the most volume" }); function onBar(): void { const n = in_profile_cells(); if (n <= 0) return; // no block this bar const cells = in_profile_view(); // max_cells tuples of 4 f64; only the first n values are this bar's let net = 0.0; let best = -1.0; let bestPrice = NaN; for (let i = 0; i + 3 < n; i += 4) { const buy = cells[i + 2]; const sell = cells[i + 3]; net += buy - sell; // the map + reduce, as one pass if (buy + sell > best) { best = buy + sell; bestPrice = (cells[i] + cells[i + 1]) / 2.0; // the bucket's midpoint } } out_delta(net); out_poc(bestPrice); } ``` Every windowed class in the TA kit accepts any number, so `rsi.update(delta)` is a delta-RSI in one line. The celled input, its accessors, and the `max_cells` contract are in `data-sources.md`. ## Loops still exist, and you bound them `for`, `while`, and `do` are the iteration tools (`for...of` is not implemented: `Not implemented: Iterators`, so index loops it is). There is no per-loop ceiling inside the module; size every loop by a param with a declared `max`. A loop that runs away is stopped by the host's execution timeout and the evaluation is refused: it cannot hang the chart, and it cannot produce a value either. # The settings dialog Declare a setting by its kind and the dialog draws the right control: one page per thing you can declare, in the order you meet them. ## One rule A setting is one declaration users can change without editing code. `param.(name, default, options?)` names the kind of value, and the overlay's settings dialog on the chart draws the control that kind calls for: a number field, a toggle, a menu, a color picker, a market button, a session strip. The value you read once in `onStart()` drives your logic, and changing it reruns the indicator over the loaded bars without recompiling. This is how you ship a configurable indicator: an adjustable period, a threshold, a multiplier, an on/off switch, a picked market. ```typescript param.int("length", 20, { min: 2, max: 200 }); param.bool("show_bands", true); let n: i32 = 20; let bands = true; function onStart(): void { n = i32(p_length()); bands = pb_show_bands(); } ``` Every kind keeps the contract of plain `param(name, default, { required, min, max, description })`: a top-level statement, a literal default, and a generated reader, readable from `onStart()` on. Plain `param(...)` still declares a number field, and a file that uses it runs exactly as before. ## The dialog, labelled ![The settings dialog on the first page of the tour: the rail on the left, the presets strip, then the rows with their controls](/wrun/images/wrun-dialog.svg) ![The second page of the tour's dialog: a section that carries its toggle in the header and a folded section with its row count](/wrun/images/wrun-dialog-bands.svg) The tour's dialog on its two pages. On the left, the rail: one entry per `page(...)`, then a **Chart** caption with the chart's own entries. Across the top of a page, the presets strip. Below it the rows, grouped by sections: one carries its toggle in its header, one starts folded with its row count in the header. Each row is the label, a hint glyph when the declaration has one, a dot and a reset button once the value differs from its default, and the control the kind names. ## Pages on the rail `page(title)` starts a page. Pages are entries in the dialog's left rail, in order, above a **Chart** caption that holds the chart's own entries: the plot settings, visibility and price marker pages follow the pages you declare. Settings declared before the first `page(...)` land on **General**. A file with no layout word and no `group` keeps one flat list. The layout words are on [Pages, sections, dividers, notes](layout.md). ## Rows and their controls Every `param.` you declare is a row, drawn as the control its kind names ([Setting kinds](kinds.md) has all fifteen). The row's name is its `label`; without one the row shows `description`, else the name read as words (`show_bands` reads "Show Bands"). A `hint` puts words behind a small glyph after the label, shown on hover. Rows that name the same `row` word share one line of the dialog, and a row whose `when` gate is closed is dimmed, or hidden with `hide` ([Options on a setting](options.md)). The dialog adds the rest by itself. A row that differs from its default shows a dot and a reset button that names the default, and a dialog with more than twelve settings gets a filter box over every page. ## The presets strip `presets({ Name: { setting: value, ... }, ... })` ships named sets of values with the indicator. The dialog offers them as chips after **Default**; picking one fills every setting it names in one step, and editing a row afterwards shows **Custom** ([Presets](presets.md)). ## The Style page Every output you draw gets a row on the dialog's **Style** page without a declaration: visible, width, line style and color for a line; opacity beside them for an area, and for a column with a static color; visible, width and color for a mark. A spot the file binds to a setting (`color: "@basis_color"`) is that setting's row instead, so a look never has two controls ([The Style page](style-page.md)). ## Browser or cloud Most settings are numbers the module reads, and every place that runs an indicator hands them to `onStart()` the same way: your browser, OpenMarket's servers for an indicator published as **Protected**, and the alerts engine. A setting's value on the chart is the overlay's own, read once in `onStart()`: the chart runs every setting from the dialog, or from the default when none is set, and changing one reruns the indicator over the loaded bars. An alert on a published indicator runs with the settings of the overlay you set it from ([Alerts](../functions/alerts.md)). Three kinds are applied by the chart instead: `param.source` picks the field an input reads, and `param.timeframe` and `param.symbol` pin an input. For now the chart applies them only when the indicator runs in your browser. | Where the indicator runs | A number, toggle, menu, color, time, price, range, multi, list or session | A `source`, `timeframe` or `symbol` setting | | --- | --- | --- | | your browser | read in `onStart()` from the dialog | applied by the chart | | OpenMarket's servers | read in `onStart()` from the dialog | keeps the declared default; the dialog marks the row "Browser lane only for now" | | the alerts engine | the settings of the overlay you set the alert from | the alert refuses to arm while one is off its default | An indicator that runs on OpenMarket's servers has no Style page either. The lanes in full, with the picks and the 128-setting cap: [Picks, lanes, the cap](picks-and-lanes.md). ## Where to go next - [Setting kinds](kinds.md): the fifteen kinds, the control each one draws, the reader each one generates - [Options on a setting](options.md): `label`, `hint`, `step`, `row`, `when`, `slider`, `confirm`, and which kind takes which - [Pages, sections, dividers, notes](layout.md): the words that lay the dialog out - [Presets](presets.md): named sets of values and the chip strip - [The Style page](style-page.md): the rows every drawn output gets, and `"@name"` bindings - [Sessions and units](sessions-and-units.md): a window in its zone, a number with a unit picker - [Picks, lanes, the cap](picks-and-lanes.md): time and price picks, the settings the chart applies, the 128-setting cap - [What the build checks](checks.md): every refusal, on the declaration's line # Setting kinds Fifteen kinds, one row each: the declaration, the control the dialog draws, the reader your code calls. ## What it is Every kind keeps the contract of plain `param(name, default, { required, min, max, description })`: a top-level statement, a literal default, and a generated reader, readable from `onStart()` on. Plain `param(...)` still declares a number field, and a file that uses it runs exactly as before. What a menu chooses at runtime is still a number in the module: two moving-average kinds are two classes, and the `param.choice` index picks which one writes the output. ## Declare it ```typescript // a number field, a toggle, a menu, two handles on one slider, a text field param.int("length", 20, { min: 2, max: 500 }); param.text("label", "Session VWAP", { max_bytes: 64 }); param.bool("show_bands", true); param.choice("kind", ["Simple", "Exponential"], "Simple"); param.range("band_pct", [0.5, 2.0], { min: 0, max: 10 }); ``` | Kind | Declare it as | The dialog draws | | --- | --- | --- | | `int` | `param.int(name, 20, { min, max })` | a number field that steps by 1 | | `number` | `param.number(name, 2.0, { min, max, step })` | a number field that steps by `step` | | `bool` | `param.bool(name, true)` | an on/off toggle | | `choice` | `param.choice(name, ["Simple", "Exp"], "Simple")` | a menu of the labels | | `color` | `param.color(name, "#2962ff")` | a color picker | | `time` | `param.time(name, "2024-01-01 00:00")` | a date and time field with **Pick**: the next click on the chart sets it | | `price` | `param.price(name, 0.0)` | a number field with **Pick**: the next click on the chart sets the price | | `range` | `param.range(name, [0.5, 2.0], { min, max })` | one slider with two handles | | `multi` | `param.multi(name, ["Mon", "Tue"], ["Mon"])` | a chip per option up to four options, a multi-select menu past that | | `list` | `param.list(name, [5.0, 20.0], { max })` | an editable list of numbers with **Add**, up to `max` long | | `source` | `param.source(name, ohlcv.close)` | a menu of `open`, `high`, `low`, `close`, `hl2`, `hlc3`, `ohlc4`, `volume`, `hlcc4` | | `timeframe` | `param.timeframe(name, "chart")` | a menu of `chart`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w` | | `symbol` | `param.symbol(name, "BINANCE:ETHUSDT")` | a market button that opens the symbol search | | `session` | `param.session(name, "09:30-16:00", { tz })` | a day strip with the window shaded, a start and an end on the 24-hour clock, and a zone menu | | `text` | `param.text(name, "Session VWAP", { max_bytes })`, or `param.text_area(name, ...)` for several lines | a text field (a text area for `text_area`) with a "never paste keys or passwords" hint | What `onStart()` reads, per kind (the reader takes the setting's name): | Kind | `onStart()` reads | | --- | --- | | `int` | `p_length()`, a whole number | | `number` | `p_mult()` | | `bool` | `pb_show_bands()`, a `bool` | | `choice` | `p_kind()`, the picked index (0 for the first label) | | `color` | `p_basis_color()`, the color packed into one number; most files bind it to an output instead ([The Style page](style-page.md)) | | `time` | `p_since()`, epoch seconds | | `price` | `p_floor()` | | `range` | `p_band_pct_lo()` and `p_band_pct_hi()` | | `multi` | `p_days()`, a bitmask (bit 0 is the first option); `multiHas(mask, i)` tests one | | `list` | `p_lookbacks()`, an `f64[]` of the filled slots | | `source` | nothing: it declares the input too, and `in_src()` reads the picked field per bar | | `timeframe` | nothing: `{ interval: "@htf" }` on an input pins that input to the pick | | `symbol` | nothing: `{ symbol: "@pair" }` on an input pins that input to the pick | | `session` | `p_rth_start()` and `p_rth_end()` (minutes from midnight), `p_rth_tz()` (the zone's index) | | `text` | `pt_label()`, the typed words as a `string` (`p_label()` reads their UTF-8 byte count) | The defaults are literals, read from the text without running it: a number, `true` or `false`, a string, an array of literals, or for `param.source` an `ohlcv.` reference. A `param.time` default is `"YYYY-MM-DD HH:MM"` in UTC or a whole number of epoch seconds. A `param.symbol` default is `"EXCHANGE:SYMBOL"` in the chart's own ids. A `param.source` default is any word of its menu, a blend such as `hl2` included ([A blended default](picks-and-lanes.md#a-blended-default)). A `param.multi` takes at most 53 options (one bit each), and a `param.range` needs `min` and `max`. ## By the setting you need | Setting you need | wrun form | | --- | --- | | a number, a float | `param.number`, or plain `param` | | an integer | `param.int`, read whole | | a slider | `param.int` or `param.number` with `min`, `max` and `slider: true` | | an on/off toggle | `param.bool`, read with `pb_()` | | a dropdown | `param.choice`, read as the picked index | | a multi-select | `param.multi`, read as a bitmask | | a color picker | `param.color`, bound to an output with `color: "@name"` | | a palette the user picks | one `param.color` per entry, each bound into a `colors` palette by `"@name"`; a `color_by` ladder then indexes the user's colors ([Styling](../presentation/styling.md)) | | a source dropdown | `param.source`, which declares the input too; a second feed is a second input | | a timeframe field | `param.timeframe` bound to an input with `interval: "@name"`; an `interval` pin written on the input needs no setting | | a symbol field | `param.symbol` bound to an input with `symbol: "@name"`; a `symbol` + `exchange` pin written on the input needs no setting | | a session field | `param.session` and `inSession(...)` per bar; a window fixed in the file is a `Session` from `./sdk/clock` ([Clock and sessions kit](../functions/time-and-sessions-kit.md)), and the integer math underneath is on [Time and sessions](../core-concepts/time-and-sessions.md) | | a text field | `param.text` (one line) or `param.text_area` (several lines), read with `pt_()`; the words are plain text within `max_bytes` | | a label, a step, a group, a tooltip | the options `label`, `step`, `group`, `hint` ([Options on a setting](options.md)) | ## What the dialog draws ![a whole-number field that steps by one, with a hint glyph after its label](/wrun/images/wrun-settings-int.svg) ![a number field with a unit picker beside it](/wrun/images/wrun-settings-number-unit.svg) ![a bounded whole number drawn as a slider with its readout](/wrun/images/wrun-settings-slider.svg) ![a toggle and a timeframe menu sharing one line of the dialog](/wrun/images/wrun-settings-bool-row.svg) ![a menu of the labels a choice lists](/wrun/images/wrun-settings-choice.svg) ![a color picker](/wrun/images/wrun-settings-color.svg) ![a date and time field with its Pick button](/wrun/images/wrun-settings-time.svg) ![a price field with its Pick button](/wrun/images/wrun-settings-price.svg) ![one slider with two handles](/wrun/images/wrun-settings-range.svg) ![a chip per option of a multi-select](/wrun/images/wrun-settings-multi.svg) ![an editable list of numbers with an Add button](/wrun/images/wrun-settings-list.svg) ![a menu of the price fields a source can read](/wrun/images/wrun-settings-source.svg) ![a market button that opens the symbol search](/wrun/images/wrun-settings-symbol.svg) ![a day strip with the window shaded, a start and an end on the 24-hour clock, and a zone menu](/wrun/images/wrun-settings-session.svg) A row that differs from its default shows a dot and a reset button that names the default. ## Read it in onStart() Every reader works from `onStart()` on: the chart serves the settings there, before the first bar, and a reader called later, in `onBar()` or a helper, returns the same cached value. Read each setting into a module variable in `onStart()` and use the variable per bar, or read it where you use it. ```typescript function onStart(): void { const n = i32(p_length()); sma = new Sma(n); useEma = p_kind() == 1.0; bandsOn = pb_show_bands(); lowPct = p_band_pct_lo(); highPct = p_band_pct_hi(); } ``` | Kind | Readers in `./gen/params` | | --- | --- | | `int`, `number`, `price`, `time`, `choice`, `multi`, `color`, plain `param` | `p_(): f64` | | `bool` | `pb_(): bool` (and `p_()`, 1 or 0) | | `range` | `p__lo()`, `p__hi()` | | `list` | `p_(): f64[]`, the filled slots in order | | `session` | `p__start()`, `p__end()`, `p__tz()` | | `text` | `pt_(): string`, the words (and `p_()`, their UTF-8 byte count) | | a `unit` picker | `p_()` and `p__unit()`, the unit's code | | `market.tick_size()`, `market.price_precision()` | `p_market_tick_size()`, `p_market_price_precision()` | | `market.kind()`, `market.point_value()`, `market.zone()`, `market.quote_is_usd()`, `market.session_open()` | `p_market_kind()`, `p_market_point_value()`, `p_market_zone()`, `p_market_quote_is_usd()`, `p_market_session_open()` ([The market's facts](sessions-and-units.md#the-markets-facts), [Venue trade day](sessions-and-units.md#venue-trade-day)) | | `market.size_unit()`, `market.notional()` | none of their own: the readers of the facts they declare, `p_market_kind()`, `p_market_point_value()` and `p_market_zone()` ([Size units](sessions-and-units.md#size-units)) | | `source`, `timeframe`, `symbol` | none to call: the chart applies the pick | ## Text settings A text setting is a field the user types words into: a label, a note, a list of tickers. Declare it like any other setting, and read the words once, in `onStart()`, with `pt_()`. ```typescript // A moving average with a corner readout that says what you typed in the settings. param.int("length", 20, { min: 1, max: 500 }); // One line of text, at most 64 bytes. param.text("label", "Session average", { max_bytes: 64, hint: "Shown in the corner of the chart" }); // Several lines of text. The readout shows the first line. param.text_area("notes", "Buy the dip above it.\nStand aside below it.", { max_bytes: 512 }); // A preset may set a text setting like any other. presets({ Fast: { length: 9, label: "Fast average" }, Slow: { length: 50, label: "Slow average" } }); output("average", line, overlay, { color: "#2563eb" }); // Sized for the label's 64 bytes plus a space and a number. string("tag", { max_bytes: 96 }); string("note", { max_bytes: 512 }); render.table("corner", { rows: 2, cols: 1, cells: ["tag", "note"], position: "top_left" }); let average = new Sma(20); let label: string = ""; let firstNote: string = ""; // Text settings are read once, here, through pt_(). function onStart(): void { average = new Sma(i32(p_length())); label = pt_label(); firstNote = pt_notes().split("\n")[0]; } function onBar(): void { const value = average.update(bar.close()); if (isNaN(value)) return; out_average(value); sb_clear(); sb_text(label); sb_text(" "); sb_auto(value); str_tag_sb(); str_note(firstNote); } ``` - `param.text` draws a one-line field, and `param.text_area` a box for several lines. - `pt_label()` returns the typed words as a `string`. Read it in `onStart()` and keep it in a module variable. - The `tag` slot holds the label, a space and a number, so it is sized for the label's 64 bytes plus the rest. A line longer than its slot is refused, never cut. - A preset sets a text setting with its words: `Fast: { label: "Fast average" }`. ### Options | Option | What it does | Default | | --- | --- | --- | | `max_bytes` | the most UTF-8 bytes the field takes (a plain letter is 1 byte, an accented one 2, most CJK characters 3) | 256, at most 4096 | | `multiline` | keeps newlines in a `param.text` field (`param.text_area` always does) | `false` | | `label`, `hint`, `group`, `row`, `when`, `hide`, `confirm`, `required`, `description` | the words every setting takes ([Options on a setting](options.md)) | | `pt_()` reads the words. `p_()` reads their length in bytes. ### What the user can type Plain text. Before your code reads the words, the chart and every other place the indicator runs clean them the same way: - Invisible characters go: right-to-left overrides, zero-width characters and the other format marks. A "Binance" disguised with them reads as plain "Binance". - Control characters go. On a one-line field each newline becomes a space. - Words longer than `max_bytes` are refused, never cut. The dialog says "Too long: 70 of 64 bytes. Shorten the text to apply it." The words are never shown as a link or as markup, and they never fill a placeholder: a typed `{{close}}` stays those eight characters. Every text field carries the hint "Never paste keys or passwords here." The words are saved like any other setting and are never sent anywhere shared. ### Limits and refusals | Rule | What the build says | | --- | --- | | the default is a string | `param.text 'label' default must be a string literal (expected a string literal)` | | `max_bytes` is 1 to 4096 | `param.text 'label' max_bytes takes an integer from 1 to 4096, not 5000` | | the default fits `max_bytes` | `param.text 'label' default is 15 UTF-8 bytes, over its max_bytes 4` | | the default is plain text | `param.text 'label' default carries a newline, a control or an invisible character; typed text is stripped of bidi controls, zero-width characters and control characters, so a default cannot carry them` | | a text field takes no number options | `param.text 'label' takes no min option (its value is not a number field)` | | a text area is always several lines | `param.text_area 'notes' is multi-line by definition; drop multiline: false (param.text takes the flag)` | | a preset sets words | `preset 'Fast' value for 'label' takes a string literal (a text setting), not 5` | | a preset fits `max_bytes` | `preset 'Fast' value for 'label' is 70 UTF-8 bytes, over the setting's max_bytes 64` | | history is sized from numbers | `warmup term names 'label', a text setting: a window is sized from numbers, so name a numeric param (length)` | A text setting counts as one of the 128 settings. Declaring one moves the file to the `wrun-5` contract (or keeps it on a later one) when you build ([Versions and contracts](../reference/versions.md)); a place that cannot read text settings yet refuses the indicator by name instead of running it without the words. ## Fourteen kinds in one module An average of a picked price field with percent bands, an offset in a picked unit, a reference close on a picked timeframe, a ratio against a picked market, a floor line and a session filter over picked weekdays. Every setting is read in `onStart()` and kept in a module variable. Text, the fifteenth kind, has its own module under [Text settings](#text-settings). ```typescript // int: a whole number. param.int("length", 20, { min: 2, max: 500 }); // choice: a menu; the reader returns the picked index, 0 for Simple. param.choice("kind", ["Simple", "Exponential"], "Simple", { label: "Average" }); // source: declares the primary input too; in_src() reads the picked field. param.source("src", ohlcv.close); // bool: a toggle, read as a bool. param.bool("show_bands", true); // range: a low..high pair on one slider. param.range("band_pct", [0.5, 2.0], { min: 0, max: 10, step: 0.1, label: "Band width %" }); // number with a unit picker: the value and the unit's code. param.number("offset", 0.0, { min: -100, max: 100, unit: ["price", "ticks", "%", "atr"], unit_default: "%" }); // A bounded int drawn as a slider: the ATR an atr-unit offset scales by. param.int("atr_length", 14, { min: 2, max: 50, slider: true, label: "ATR length" }); // color: painted onto the basis line below, by name. param.color("basis_color", "#2962ff"); // timeframe and symbol: each pins the input that names it. param.timeframe("htf", "chart", { label: "Reference timeframe" }); input("close_htf", ohlcv.close, { interval: "@htf" }); param.symbol("pair", "BINANCE_FUTURES:ETHUSDT", { label: "Ratio against" }); input("close_pair", ohlcv.close, { symbol: "@pair" }); // list: up to four momentum lookbacks. param.list("lookbacks", [5.0, 20.0], { max: 4 }); // time and price: both can be picked on the chart. param.time("since", "2024-01-01 00:00", { label: "Start" }); param.price("floor", 0.0, { hint: "0 draws no floor" }); // session and multi: a window in its zone, and the weekdays it applies on. param.session("rth", "09:30-16:00", { tz: "America/New_York", label: "Active hours" }); param.multi("days", ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], ["Mon", "Tue", "Wed", "Thu", "Fri"]); // The tick size, written by the chart into a hidden setting. market.tick_size(); output("basis", line, overlay, { color: "@basis_color", width: 2 }); output("upper", line, overlay, { color: "#26a69a" }); output("lower", line, overlay, { color: "#ef5350" }); output("reference", line, overlay, { color: "#94a3b8", line_style: "dashed" }); output("floor", line, overlay, { color: "#f59e0b" }); output("momentum", line, lower, { color: "#8b5cf6" }); output("ratio", line, lower, { color: "#0ea5e9" }); let sma = new Sma(20); let ema = new Ema(20); let atr = new Atr(14); let rocs: Roc[] = []; let useEma = false; let bandsOn = true; let lowPct = 0.5; let highPct = 2.0; let offset = 0.0; let offsetUnit = 0; let tick = 0.0; let since = 0.0; let floorPrice = 0.0; let dayMask = 0.0; let sessionStart = 570.0; let sessionEnd = 960.0; let zone = 0; // Every setting is read here, once, and kept in module state. function onStart(): void { const n = i32(p_length()); sma = new Sma(n); ema = new Ema(n); useEma = p_kind() == 1.0; bandsOn = pb_show_bands(); lowPct = p_band_pct_lo(); highPct = p_band_pct_hi(); offset = p_offset(); offsetUnit = i32(p_offset_unit()); atr = new Atr(i32(p_atr_length())); tick = p_market_tick_size(); since = p_since(); floorPrice = p_floor(); dayMask = p_days(); sessionStart = p_rth_start(); sessionEnd = p_rth_end(); zone = i32(p_rth_tz()); const lookbacks = p_lookbacks(); rocs = []; for (let i = 0; i < lookbacks.length; i += 1) rocs.push(new Roc(i32(lookbacks[i]))); } function onBar(): void { const t = bar.time(); const close = in_src(); const reference = in_close_htf(); const pair = in_close_pair(); const simple = sma.update(close); const exponential = ema.update(close); let basis = useEma ? exponential : simple; const atrValue = atr.update(bar.high(), bar.low(), close); // The offset in the unit the dialog picked, as a price distance. if (isFinite(basis)) basis += unitToPrice(offset, offsetUnit, close, tick, atrValue); const ratio = isFinite(pair) && pair != 0.0 ? close / pair : NaN; let sum = 0.0; let count = 0; for (let i = 0; i < rocs.length; i += 1) { const r = rocs[i].update(close); if (isFinite(r)) { sum += r; count += 1; } } const momentum = count > 0 ? sum / f64(count) : NaN; // 0 = Monday, from the bar's UTC day: the bit the days setting is tested by. const weekday = i32((Math.floor(t / 86400.0) + 3.0) % 7.0); const active = inSession(t, sessionStart, sessionEnd, zone) && multiHas(dayMask, weekday); if (!isFinite(basis) || t < since) return; out_basis(basis); // A hidden line is NaN: nothing is drawn. out_upper(bandsOn ? basis * (1.0 + highPct / 100.0) : NaN); out_lower(bandsOn ? basis * (1.0 - lowPct / 100.0) : NaN); out_reference(reference); out_floor(floorPrice > 0.0 ? floorPrice : NaN); // Momentum draws inside the session window only. out_momentum(active ? momentum : NaN); out_ratio(ratio); } ``` Both averages update on every bar whatever the menu says, so the choice only picks which one writes `basis`; changing it in the settings dialog reruns the indicator over the loaded bars. The **Typed inputs tour** card in the editor's template list (`typed-inputs-tour`) is this module with a two-page layout, presets, a hover card, a HUD and legend entries declared beside it ([Plotting](../presentation/plotting.md)). ## Gotchas - A kind that takes no option refuses it by name, on the declaration's line: `param.bool 'x' takes no min option (its value is not a number field)`. - Each kind checks its own default's shape: a whole number for `param.int`, hex (`"#rrggbb"` or `"#rrggbbaa"`) for `param.color`, one of the options for `param.choice`. - A setting outside `min`..`max`, or a `param.int` setting that is not a whole number, is refused by name before the module runs: `params.length must be a whole number, got 14.5`. The default is checked the same way. `step` is only the stepper's increment: a setting between two steps (0.75 on a step of 0.5) runs as typed. - A `param.range` needs `min` and `max`, and a `param.list` needs `max`, the most items the dialog may hold. - A `param.source` default may be a blend (`hl2`, `hlc3`, `ohlc4`, `hlcc4`): every place the indicator runs blends the bar's candle the same way. - `source`, `timeframe` and `symbol` are applied by the chart, in your browser only for now; an indicator that runs on OpenMarket's servers keeps the declared default ([Picks, lanes, the cap](picks-and-lanes.md)). - Every refusal, with the words the Console prints: [What the build checks](checks.md). ## Related - [Options on a setting](options.md): the keys every kind takes, and which kind takes which - [Pages, sections, dividers, notes](layout.md): where a row lands - [Sessions and units](sessions-and-units.md): the session strip and the unit picker in full - [What the build checks](checks.md): the refusal table # Options on a setting Every kind takes one options object, every key optional, and a key the kind cannot use is refused by name, on the declaration's line. ## What it is An option is one of the dialog's words on a declaration: the row's name, its stepper, a glyph with a tooltip, which rows share a line, which toggle dims it, where it lands, and the bounds of a number field. Plain `param(...)` keeps its four keys, `required`, `min`, `max` and `description`; the dialog's words belong to the typed settings, `param.int(...)`, `param.bool(...)` and the rest. ## Declare it ```typescript // Two fields on one line of the dialog, the first with a hint. param.int("fast", 9, { min: 1, max: 200, row: "lengths", hint: "Bars in the fast average" }); param.int("slow", 21, { min: 2, max: 400, row: "lengths" }); param.color("slow_color", "#f59e0b", { label: "Color" }); param.bool("smooth", false); // Dimmed until the toggle it names is on. param.number("smoothing", 0.3, { min: 0, max: 1, step: 0.05, slider: true, when: "smooth" }); // Dimmed unless the choice holds its third option (option index 2). param.choice("band", ["none", "average", "average and bands"], "none"); param.number("band_width", 2, { min: 0, step: 0.1, when: "band=2" }); ``` | Option | What it does | | --- | --- | | `label` | the row's name in the dialog. Without one the row shows `description`, else the name read as words (`show_bands` reads "Show Bands") | | `description` | the long text of the setting, recorded in the sheet | | `min`, `max` | bounds of a number field: a setting outside them is refused by name before the module runs; required by `slider` and by `param.range`; on `param.list`, `max` is the most items the list may hold | | `step` | the stepper's increment, nothing more: a setting between two steps runs as typed, as on TradingView. A `param.int` steps by 1 unless you say otherwise | | `slider` | `true` draws a bounded `param.int` or `param.number` as a slider | | `hint` | words behind a small glyph after the label, shown on hover | | `row` | rows that name the same word share one line of the dialog | | `when` | the setting that opens the row, in one of five forms: `"name"` while it is on (any value but 0), `"!name"` while it is off, `"name=v"`, `"name!=v"`, or `"name in a,b"` while it holds one of the listed values. A toggle holds 0 or 1, a choice its option index (`when: "smoothing=2"` opens the row on the third choice). The named setting is a `param.bool`, `param.choice`, `param.int`, `param.number` or `param.multi`; the row is dimmed while the gate is closed | | `hide` | with `when`: hide the row instead of dimming it | | `group` | `"Page"` or `"Page/Section"`: where the row lands, shorthand for the layout words ([Pages, sections, dividers, notes](layout.md)) | | `unit`, `unit_default` | a unit picker beside a number ([Sessions and units](sessions-and-units.md)) | | `confirm` | marks a setting whose change is worth confirming before it applies (one that refetches); recorded in the sheet, and the dialog applies edits as you make them for now | | `visible_by` | `{ size_unit: [codes] }`: the dialog shows the row only on markets whose size unit is listed, and leaves it out elsewhere while its value still reaches `onStart()` ([Size units](sessions-and-units.md#the-dialog-and-the-lanes)) | | `style_values` | `param.choice` only: one word a choice, in the choices' order, the word the setting paints where a key takes words, such as a marks caption's `text.format` ([Marks, spans and rays](../presentation/marks-spans-rays.md)), while the choices stay the dialog's labels (`option_labels`). `param.choice("size_shown_as", ["Dollars", "Contracts or coins"], "Dollars", { style_values: ["usd", "units"] })` shows Dollars and Contracts or coins and paints `text.format: "@size_shown_as"` with `"usd"` or `"units"`. An option knob that takes a word from a setting reads the pick's word the same way: `expiries: "@expiries"` on `option_strike_flow` over `style_values: ["all", "0dte", "after_today"]` ([Knobs from a setting](../core-concepts/data-sources.md#knobs-from-a-setting)). Kept in the sheet and stripped from the literal before the AssemblyScript build, like `visible_by`: the module never reads it | | `required` | recorded in the sheet; on the chart a setting always has a value | | `tz` | `param.session` only: the zone the window is written in | ## Which kind takes which option | Option | Kinds that take it | | --- | --- | | `label`, `description`, `group`, `row`, `hint`, `when`, `hide`, `confirm`, `required`, `visible_by` | every typed kind | | `min`, `max`, `step`, `slider` | the number fields: `int`, `number`, `price`, `range` | | `max` | also `param.list`, as the most items the list may hold | | `unit`, `unit_default` | one number field: `int`, `number`, `price` (a range's two ends have no unit picker) | | `tz` | `param.session` only | | `style_values` | `param.choice` only | | `required`, `min`, `max`, `description` | plain `param`, which takes no other key | On any other kind they are refused. ## What the dialog draws ![a toggle and a timeframe menu sharing one line of the dialog](/wrun/images/wrun-settings-bool-row.svg) ![the hint glyph after a label, with its words shown on hover](/wrun/images/wrun-layout-hint.svg) ![a bounded whole number drawn as a slider with its readout](/wrun/images/wrun-settings-slider.svg) The dialog adds the rest by itself. A row that differs from its default shows a dot and a reset button that names the default, and a dialog with more than twelve settings gets a filter box over every page. ## Gotchas - `when` on a setting names the setting that opens the row, in one of the five forms above; `toggle` and `when` on a `section(...)` take the toggle's HANDLE ([Pages, sections, dividers, notes](layout.md)). - A setting the code reads only inside a branch another setting decides (an `if`, a `? :`, an `&&` or an early `return` that tests it) does nothing while that branch is closed. The build warns on its line until its `when` names that setting, so the dialog dims the row then ([What the build checks](checks.md#warnings)). - A key the kind does not take: `param.int options accept only { required, min, max, description, label, step, group, row, hint, when, hide, slider, unit, unit_default, confirm, visible_by }, not 'tooltip'`. - A size-unit list that is empty, repeats a code or names one past 3: `param.bool 'x' visible_by takes { size_unit: [codes] }, the size units of the markets where the row shows, at least one and each once: 0 units, 1 coins, 2 shares, 3 contracts`. - A typed key on plain `param`: `param options accept only { required, min, max, description }, not 'label'`. - A choice whose labels are not the words of the key it paints, and no `style_values`: `plot.marks 'trades' text.format references "@size_shown_as", which is not a param.choice over compact|price|int|usd|units`. A `style_values` list that is not one word a choice: `param.choice 'size_shown_as' style_values lists 1 word for 2 choices; give one word a choice, in the choices' order (Dollars, Contracts or coins)`. A choice whose `style_values` paint no word key and feed no option knob is refused by name too. - A number-field key on a toggle: `param.bool 'x' takes no min option (its value is not a number field)`. - A unit picker on a range: `param.range 'r' takes no unit option (a unit picker sits beside one number field, not a range)`. - `hide` without `when`: `param.int 'x' declares hide without when; hide names what happens when the when param is off, so declare when beside it`. - `when` naming a setting that cannot open a row: `param.int 'x' when names 'y', which is a param.color (when names a param.bool, param.choice, param.int, param.number or param.multi: "name", "!name", "name=v", "name!=v" or "name in a,b", e.g. when: "show_bands")`. - `when` comparing a choice with a value it does not hold: `param.int 'x' when compares the choice 'y' with 2; a choice holds its option index, 0 to 1 (a, b)`. - A slider without both bounds: `param.int 'x' declares slider without min and max (a slider needs both bounds)`. ## Related - [Setting kinds](kinds.md): the fifteen kinds the options sit on - [Pages, sections, dividers, notes](layout.md): `group` written out as layout words - [Sessions and units](sessions-and-units.md): `unit`, `unit_default` and `tz` in full - [What the build checks](checks.md): the refusal table # Pages, sections, dividers, notes The layout words are top-level statements, and source order is the layout: each word applies to the settings declared after it. ## What it is Four words lay the dialog out, top-level statements like the settings themselves: `page(title)`, `section(title, { toggle?, collapsed?, when? })`, `divider()` and `note(text)`. They are sheet-only, compiled to nothing: the module receives the same numbers whether or not the file lays its dialog out. A file with no layout word and no `group` keeps one flat list. ## Declare it - `page(title)` starts a page. Pages are entries in the dialog's left rail, in order, above a **Chart** caption that holds the chart's own entries. Settings declared before the first `page(...)` land on **General**. - `section(title, { toggle?, collapsed?, when? })` starts a section on the current page. `toggle` puts a `param.bool` in the section's header and dims its rows while the toggle is off; `collapsed: true` starts the section folded, with its row count in the header; `when` dims the section by a toggle declared elsewhere. `toggle` and `when` take the toggle's HANDLE: bind it with `const show = param.bool(...)` and pass `show`. - `divider()` draws a rule between rows. - `note(text)` puts a line of words between rows; `**bold**` is the one markup. `{ group: "Signals/Labels" }` on a setting is the one-line form: it opens the page and the section it names when they are not already open. A moving-average pair with two pages, a row of two fields, a section that carries its toggle, a folded section and a gated slider: ```typescript page("Lengths"); // Two fields on one line of the dialog, the first with a hint. param.int("fast", 9, { min: 1, max: 200, row: "lengths", hint: "Bars in the fast average" }); param.int("slow", 21, { min: 2, max: 400, row: "lengths" }); note("Keep the fast length **below** the slow one."); page("Look"); // The handle lets the section below carry this toggle in its header. const showSlow = param.bool("show_slow", true, { label: "Slow line" }); section("Slow line", { toggle: showSlow }); param.color("slow_color", "#f59e0b", { label: "Color" }); param.choice("slow_style", ["solid", "dashed", "dotted"], "dashed", { label: "Line style" }); divider(); section("Fine tuning", { collapsed: true }); param.bool("smooth", false); // Dimmed until the toggle it names is on. param.number("smoothing", 0.3, { min: 0, max: 1, step: 0.05, slider: true, when: "smooth" }); output("fast", line, overlay, { color: "#3b82f6", width: 2 }); // The color and the line style follow the two settings above, by name. output("slow", line, overlay, { color: "@slow_color", line_style: "@slow_style", width: 2 }); ``` ## What the dialog draws ![the rail of the dialog: one entry per page, then the Chart caption with the chart's own entries](/wrun/images/wrun-layout-rail.svg) ![a section header carrying its own toggle](/wrun/images/wrun-layout-section-toggle.svg) ![a folded section with its row count in the header](/wrun/images/wrun-layout-section-collapsed.svg) ![the same section open, its rows showing](/wrun/images/wrun-layout-section-open.svg) ![a rule between rows, and a note with one bold word](/wrun/images/wrun-layout-divider-note.svg) A section's toggle is drawn in the header and never as a row of its own; it stays a declared setting, so its value is saved like any other. Rows that name the same `row` word render as a pair, and dividers and notes render between rows. The pages you declare come first on the rail, then the **Style** page the dialog derives from your outputs ([The Style page](style-page.md)), then the chart's own entries under **Chart**. ## Gotchas - `toggle` and `when` on a section take the toggle's HANDLE, bound with a top-level `const`; `when` on a setting takes the gating setting's NAME, in one of the five forms on [Options on a setting](options.md). - `group` alone is enough to open pages: `{ group: "Page/Section" }` on a setting writes the same layout the words do, and only a file with no layout word and no `group` keeps one flat list. - `**bold**` is the one markup a `note` takes. - A composite (a range, a list, a session, a number with a unit) is placed once, where its declaration sits; a hidden `market.*` setting takes no place in the layout. ## Related - [The settings dialog](overview.md): the dialog with every region named - [Options on a setting](options.md): `group` and `row`, the one-line forms - [Presets](presets.md): the chip strip across the top of a page - [The Style page](style-page.md): the page the dialog derives from your outputs # Presets `presets({ Name: { setting: value, ... }, ... })` ships named sets of values with the indicator. ## What it is The dialog offers the presets as chips after **Default**; picking one fills every setting it names in one step, and editing a row afterwards shows **Custom**. Like the layout words, `presets(...)` is a top-level statement, sheet-only and compiled to nothing: the module still receives the same numbers in the same order, and `onStart()` reads them. The dialog reads the keys; `onStart()` reads the numbers. ## Declare it Write each value as you declared it: a number within the setting's bounds, `true` or `false`, a choice's label, a color string, a time in either spelling, a market as `"EXCHANGE:SYMBOL"`, a text setting's words within its `max_bytes`. A range, list, session or unit is set through its parts (`band_pct_lo`, `rth_start`, `offset_unit`, by the dialog's words for a session zone or a unit). A value the setting cannot take is refused on the `presets` line. ```typescript page("Signal"); param.int("period", 14, { min: 2, max: 200, label: "Length" }); param.choice("kind", ["Simple", "Exponential"], "Simple"); const show = param.bool("show_band", true); section("Band", { toggle: show }); param.range("band_pct", [0.5, 2.0], { min: 0, max: 10, step: 0.1, label: "Band width %" }); param.color("band_color", "#94a3b8"); // The range is set through its two ends. presets({ Tight: { band_pct_lo: 0.2, band_pct_hi: 1 } }); ``` A moving-average pair ships two presets, each naming a different mix of its settings; picking one fills every setting it names: ```typescript presets({ Scalp: { fast: 5, slow: 13, show_slow: true }, Swing: { fast: 20, slow: 50, slow_style: "solid" } }); ``` The sheet records `presets` as `[{name, values: {param: number | boolean | string}}]`, as declared; the chart turns each value into the setting's own form when a preset is picked. ## What the dialog draws ![the presets strip across the top of a page: a Default chip, then one chip per preset](/wrun/images/wrun-layout-presets.svg) ![the strip after an edit: the Custom chip lit](/wrun/images/wrun-layout-presets-custom.svg) ![a changed row with its dot and the reset arrow that names the default](/wrun/images/wrun-layout-changed-reset.svg) The strip holds a **Default** chip, one chip per preset, and a **Custom** chip once the values leave every preset. A row that differs from its default shows a dot and a reset button that names the default. ## Gotchas - A preset names a composite's members, never the composite: `preset 'A' sets 'band', which is not a declared param on the sheet (a composite is set by its members, e.g. band_lo)`. - A value the setting cannot take is refused on the `presets` line: `preset 'A' value for 'mode' takes one of its options as a string (fast, slow), not "Zed"`. - A choice is set by its label, a market by `"EXCHANGE:SYMBOL"`, a time in either spelling, a session zone or a unit by the dialog's words for it. - A text setting takes words that fit its `max_bytes`: `preset 'Fast' value for 'label' takes a string literal (a text setting), not 5` and `preset 'Fast' value for 'label' is 70 UTF-8 bytes, over the setting's max_bytes 64`. ## Related - [The settings dialog](overview.md): where the strip sits on a page - [Setting kinds](kinds.md): the value each kind takes - [Sessions and units](sessions-and-units.md): the parts a session and a unit are set through - [What the build checks](checks.md): the refusal table # The Style page Every output you draw gets a row on the dialog's **Style** page without a declaration. ## What it is The Style page draws visible, width, line style and color for a line; opacity beside them for an area, and for a column with a static color; visible, width and color for a mark. A per-bar ladder keeps its spot: an output colored by `color_by` has no color row, one widened by `width_by` no width row, and a `color_by` palette stays the way to switch looks per bar. The user's changes repaint the output and are saved with the overlay; the file's values stay the defaults. A spot the file binds to a setting (`color: "@basis_color"`, `line_style: "@style"`) is that setting's row instead, so a look never has two controls. Every `render.hud` card of the indicator adds a Look row (unless its `look` is bound to a setting), a Position row and a Show row, and every heatmap whose colour scale reads the data a Sensitivity row (below). ## Declare it A color the user should pick is a `param.color` bound by name; a line style is a `param.choice` over `solid`, `dashed`, `dotted`: ```typescript param.color("fast_color", "#3b82f6", { label: "Fast" }); param.choice("style", ["solid", "dashed", "dotted"], "solid", { label: "Line style" }); output("fast", line, overlay, { color: "@fast_color", line_style: "@style", width: 2 }); ``` A `colors` palette takes a setting per entry (`colors: ["@up", "@down"]`), so a `color_by` ladder's colors can be the user's too. The same reference reaches a band, a fill, a box, a segment and a docked profile: ```typescript param.color("band_ink", "#94a3b8", { label: "Band" }); param.choice("side", ["right", "left"], "right", { label: "Profile side" }); param.number("width", 0.12, { min: 0.05, max: 0.5, label: "Profile width" }); param.bool("show_poc", false, { label: "Point of control" }); range("band_hi", "band_lo", { color: "@band_ink", edge_line_style: "@style" }); box("zone", { top: hi, bottom: lo, color: "@band_ink", borderStyle: "@style" }); plot.levels({ name: "profile", frame: profile_rows, dock: "@side", color: "@band_ink", width_frac: "@width", poc: "@show_poc" }); ``` A guide's axis tag look binds to a `param.choice` the same way. Its choices are the dialog's words, and `style_values` names the look each one draws: ```typescript param.choice("rail_labels", ["Tags", "Band and words"], "Tags", { label: "Rail labels", style_values: ["quiet", "words"] }); // Both edges of the move follow the one setting: a soft capsule, or the price on the axis and the label in words. output("move_high", line, overlay, { role: "guide", label: "Move high", axis_label: true, axis_look: "@rail_labels" }); output("move_low", line, overlay, { role: "guide", label: "Move low", axis_label: true, axis_look: "@rail_labels" }); ``` An output's other colour words bind the same way: a split line's `up_color` and `down_color`, an area's `fill_color`, and the entries of a candle group's `border_colors` and `wick_colors` each take a `param.color`, so one pair of inks can drive several looks at once. ```typescript param.color("up_ink", "#22c55e", { label: "Up" }); param.color("down_ink", "#ef4444", { label: "Down" }); param.color("fill_ink", "#f59e0b", { label: "Fill" }); // One pair of inks drives the split line and the candle group's borders and wicks; the fill ink drives the area's edge and fill. output("osc", line, lower, { split: "slope", up_color: "@up_ink", down_color: "@down_ink" }); output("cvd", area, lower, { color: "@fill_ink", fill_color: "@fill_ink", fill_opacity: 0.3 }); output("ha_open", candle, overlay, { colors: ["@up_ink", "@down_ink"], border_colors: ["@up_ink", "@down_ink"], wick_colors: ["@up_ink", "@down_ink"] }); output("ha_high", candle, overlay); output("ha_low", candle, overlay); output("ha_close", candle, overlay); ``` A string that starts with `@` is a reference to a setting by name. The build writes the setting's default in its place before it compiles, so the source compiles to the same module as one that wrote the default literally, and the sheet records which setting controls the spot. The places that paint are below; two more pin an input ([Picks, lanes, the cap](picks-and-lanes.md)). | Where | Names | What the chart does | | --- | --- | --- | | `color: "@name"` on an output, a text or label renderer, or a legend entry; an entry of a `colors` palette | a `param.color` | paints with the picked color | | `line_style: "@name"` on an output | a `param.choice` over `solid`, `dashed`, `dotted` | draws the picked style | | `axis_look: "@name"` on a guide output (`role: "guide"`, `axis_label: true`) | a `param.choice` whose every word, its `style_values` or else its choices, is `pill`, `quiet` or `words` | draws the guide's axis tag in the picked look; the choices stay the dialog's labels | | an output's other colour words: `fill_color`, an entry of `fill_colors`, `fill_gradient` or `gradient`, `up_color`, `down_color`, an entry of `border_colors` or `wick_colors` | a `param.color` | paints the fill, the stroke, the split or the candle part with the picked color | | `color`, an entry of `colors` or `gradient`, `edge_line_style` on a `range`; `color`, an entry of `colors` on a `fill` | a `param.color`; a `param.choice` over the three line styles | paints the band or the fill, dashes its edges | | `color`, `borderColor`, an entry of `colors` or `borderColors`, `borderStyle` on a `box`; `color`, `lineStyle` on a `segment` | a `param.color`; a `param.choice` over the three line styles | paints the per-bar shape, dashes its border or stroke | | a style key of `plot.levels` (`color`, a `series[].color`, a `gradient` stop, `dock`, `width_frac`, `poc`, `thickness_px`, `font_size`, `label_place` and the rest) | a colour key takes a `param.color`; a word key a `param.choice` whose every choice is a legal word of that key; a number key a `param.number` or `param.int` (an integer key `param.int` only) whose `min..max` lies inside the key's range; a boolean key a `param.bool` | redraws the docked profile with the pick; a structural key (`name`, `frame`, `panel`, `beside`, `offset`, `unit`, a series name) refuses a reference | | every colour word of a `panel.*` declaration (a series' `color` and `fill_color`, `positive_color`, `negative_color`, the `fill_*_color` pair, `palette` entries and the rest, [Panel words](../presentation/cards-frames-panels.md#panel-words)) | a `param.color` | paints the panel with the picked color; a title or a series name keeps an `@` as text | | `look` on a `render.hud` card | a `param.choice` whose every choice is a look | draws the card in the picked look; the card gets no Look row ([Looks](../presentation/hud-and-hover-cards.md#looks)) | One setting may control several spots. A data-only output (`none`) has nothing to paint and refuses a reference (a `barcolor` output, which paints the candles, takes one), and so do a `draw.*` object, a `handles.*` default, a tile or block and a HUD card's colours: write a literal there. Width, opacity and visibility need no setting: the Style page draws a row for them per output, and a look with no setting bound to it stays the declaration's (`color`, `width`, `opacity` and `line_style` on the output are set in the file). Every other setting is compute-affecting by construction: it reaches `onStart()`, and the indicator reruns over the loaded bars when it changes; a toggle that hides a line does so by writing `NaN` to it while it is off. ## A setting at an alpha A colour drawn translucent keeps its translucency when the user picks a new colour: write the alpha after the setting's name, a decimal from 0 to 1. ```typescript param.color("bull", "#22c55e", { label: "Bull" }); // The zone's edges at 60 percent and its interior at 20, all from one setting. output("zone_hi", line, overlay, { color: "@bull/0.6" }); output("zone_lo", line, overlay, { color: "@bull/0.6" }); range("zone_hi", "zone_lo", { color: "@bull/0.2" }); ``` The build writes the setting's default at that alpha in the reference's place, the colour's own alpha replaced, and records the alpha beside the spot, so the chart paints every pick at 20 percent there. The default takes the form the spot holds: `rgba(34, 197, 94, 0.2)` where the colour takes `rgba()` (an output's `color` and `colors`, a text, label, shape, bgcolor or barcolor renderer's colours, a legend entry, a range's colours and gradient, a fill's `color`, a box's `color` and `borderColor`, a segment's `color`, a mini-chart grid's colours), and `#22c55e33` where it takes a colour word (an area's `fill_color`, a gradient stop, the candle and split colours, a fill's or a box's ladder, a stats row, a docked profile or a price canvas, a `plot.levels` colour, a panel's colours). A panel series colour is the one spot that binds without an alpha: the chart reads it as `#rrggbb`, `#rrggbbaa` or a theme token and refuses the panel on the `rgba()` a recolour at an alpha writes, so write the plain reference there (a translucent default is `#rrggbbaa`). ## The Look row Every `render.hud` card of the indicator gets a Look row, a list of the twelve looks with "As made" first (the author's own `look`, or the [default look](../presentation/hud-and-hover-cards.md#the-default-look) when the declaration has none). The pick is the viewer's, saved with the overlay and never written into the sheet; it sits between the author's `look` and the words declared beside it, so a declared `corner_radius` still wins over the picked look's radius. A second HUD in the same indicator keeps its own row ([HUD cards](../presentation/hud-and-hover-cards.md#looks)). A card whose `look` the file bound to a setting (`look: "@card_look"`) gets no Look row: the setting's own row is the look's one control. ## The Position row Under each card's Look row, a Position row says where the viewer moved the card on the chart ("From the script" until they move it), with a Reset that puts it back where `position` and `offset` place it. Like the Look pick, the place is the viewer's, saved with the overlay and never written into the sheet ([Moving a card](../presentation/hud-and-hover-cards.md#moving-a-card)). ## The Show row Beside each card's Look and Position rows, a Show row brings back a card the viewer hid with the cross on its title row. Like the Look pick and the place, it is the viewer's, saved with the overlay and never written into the sheet, and the file has nothing to declare for it ([Collapsing and hiding a card](../presentation/hud-and-hover-cards.md#collapsing-and-hiding-a-card)). ## The Sensitivity row Every `plot.heatmap` whose colour scale reads the data gets a Sensitivity row: a slider from Subtle to Vivid for how quickly the colours saturate. Untouched, it sits where the declaration's `auto_quantile` puts it (0.98 when absent) and draws exactly that; toward Vivid the top of the scale comes down so smaller values reach the bright end, toward Subtle full colour is kept for the largest. The chart recolours while the slider moves, with no rerun. Like the Look pick, the setting is the viewer's, saved with the overlay and never written into the sheet. A heatmap with both ends declared, or a one-sided one (`size`, `bid`, `ask`, `total`, `buy`, `sell`) with `max` declared, has no row; one whose `auto_quantile` is bound to a setting (`auto_quantile: "@contrast"`) shows that setting's row instead ([Heatmaps](../presentation/price-canvases.md#heatmaps)). ## What the dialog draws ![the Style page: one section per drawn output with its visible, width, line style and color rows](/wrun/images/wrun-style-rows.svg) The Style page follows the pages you declare on the rail, one section per output titled by its `label`, each with its own reset. ## Gotchas - The Style page is drawn where the indicator runs in the browser; an indicator that runs on OpenMarket's servers keeps the looks the file declares. - An alpha where it cannot land: on a panel series colour, `panel.bars 'b' series[0].color references "@bull/0.5", but a panel series colour binds without an alpha`; on a line style, `an alpha belongs to a colour reference`; and `"@bull/1.5"` or `"@bull/.4"`, `whose alpha is not a decimal from 0 to 1`. - A reference to the wrong kind: `output 'h' color references "@k", which is not a param.color`; on a `plot.levels` key, a `param.choice` with a word the key refuses, a number setting whose range leaves the key's (`width_frac: "@w"` with `max: 0.9`), a colour setting on a boolean key (`poc: "@ink"`) and a reference on a structural key (`panel: "@p"`) are each refused by name. - A reference where no setting can paint (a `draw.*` object, a `handles.*` default, a tile): the Console names the declaration and asks for a colour literal there. - A `param.color` read in `onStart()` through `p_()` is the color packed into one number; most files bind it to an output instead. ## Related - [Setting kinds](kinds.md): `param.color` and `param.choice`, the two kinds that paint (`param.number`, `param.int` and `param.bool` join them on a docked profile) - [Picks, lanes, the cap](picks-and-lanes.md): the two references that pin an input, and the lanes - [Styling](../presentation/styling.md): every look an output takes, and which looks have no form - [Plotting](../presentation/plotting.md): the outputs the rows are derived from # Sessions and units `param.session` declares a window on the 24-hour clock in its zone, and `unit` on a number puts a unit picker in the field. ## What it is `param.session(name, "HH:MM-HH:MM", { tz })` declares a window on the 24-hour clock and the zone it is written in. A window may wrap midnight (`"22:00-04:00"`). Per bar, `inSession(...)` says whether the bar's open sits inside the window, with daylight saving applied per bar from the zone's own rule. `unit: ["price", "ticks", "%", "atr"]` on a number puts a unit picker in the field, listing the units in your order; `unit_default` names the one picked at first (the first listed when absent). `unitToPrice(...)` then turns the number into a price distance per bar. ## Declare it ```typescript // session: a window in its zone. param.session("rth", "09:30-16:00", { tz: "America/New_York", label: "Active hours" }); // number with a unit picker: the value and the unit's code. param.number("offset", 0.0, { min: -100, max: 100, unit: ["price", "ticks", "%", "atr"], unit_default: "%" }); // A bounded int drawn as a slider: the ATR an atr-unit offset scales by. param.int("atr_length", 14, { min: 2, max: 50, slider: true, label: "ATR length" }); // The tick size, written by the chart into a hidden setting. market.tick_size(); ``` `tz` is `param.session` only: the zone the window is written in, one of these, each with its own daylight-saving rule: | Index | `tz` | Standard offset | Daylight saving (one hour ahead) | | --- | --- | --- | --- | | 0 | `UTC` (the default) | UTC+0 | none | | 1 | `America/New_York` | UTC-5 | second Sunday of March to first Sunday of November | | 2 | `America/Chicago` | UTC-6 | second Sunday of March to first Sunday of November | | 3 | `Europe/London` | UTC+0 | last Sunday of March to last Sunday of October | | 4 | `Europe/Berlin` | UTC+1 | last Sunday of March to last Sunday of October | | 5 | `Asia/Tokyo` | UTC+9 | none | | 6 | `Asia/Hong_Kong` | UTC+8 | none | | 7 | `Asia/Singapore` | UTC+8 | none | | 8 | `Australia/Sydney` | UTC+10 | first Sunday of October to first Sunday of April | | 9 | `Asia/Kolkata` | UTC+5:30 | none | | 10 | `America/Los_Angeles` | UTC-8 | second Sunday of March to first Sunday of November | | 11 | `America/Toronto` | UTC-5 | second Sunday of March to first Sunday of November | | 12 | `America/Mexico_City` | UTC-6 | none | | 13 | `America/Sao_Paulo` | UTC-3 | none | | 14 | `America/Argentina/Buenos_Aires` | UTC-3 | none | | 15 | `Europe/Paris` | UTC+1 | last Sunday of March to last Sunday of October | | 16 | `Europe/Amsterdam` | UTC+1 | last Sunday of March to last Sunday of October | | 17 | `Europe/Zurich` | UTC+1 | last Sunday of March to last Sunday of October | | 18 | `Europe/Madrid` | UTC+1 | last Sunday of March to last Sunday of October | | 19 | `Europe/Rome` | UTC+1 | last Sunday of March to last Sunday of October | | 20 | `Europe/Stockholm` | UTC+1 | last Sunday of March to last Sunday of October | | 21 | `Europe/Oslo` | UTC+1 | last Sunday of March to last Sunday of October | | 22 | `Europe/Copenhagen` | UTC+1 | last Sunday of March to last Sunday of October | | 23 | `Europe/Warsaw` | UTC+1 | last Sunday of March to last Sunday of October | | 24 | `Europe/Helsinki` | UTC+2 | last Sunday of March to last Sunday of October | | 25 | `Europe/Athens` | UTC+2 | last Sunday of March to last Sunday of October | | 26 | `Europe/Istanbul` | UTC+3 | none | | 27 | `Europe/Moscow` | UTC+3 | none | | 28 | `Asia/Jerusalem` | UTC+2 | Friday before the last Sunday of March to last Sunday of October | | 29 | `Asia/Riyadh` | UTC+3 | none | | 30 | `Asia/Dubai` | UTC+4 | none | | 31 | `Africa/Johannesburg` | UTC+2 | none | | 32 | `Asia/Karachi` | UTC+5 | none | | 33 | `Asia/Bangkok` | UTC+7 | none | | 34 | `Asia/Jakarta` | UTC+7 | none | | 35 | `Asia/Ho_Chi_Minh` | UTC+7 | none | | 36 | `Asia/Kuala_Lumpur` | UTC+8 | none | | 37 | `Asia/Shanghai` | UTC+8 | none | | 38 | `Asia/Taipei` | UTC+8 | none | | 39 | `Asia/Manila` | UTC+8 | none | | 40 | `Asia/Seoul` | UTC+9 | none | | 41 | `Pacific/Auckland` | UTC+12 | last Sunday of September to first Sunday of April | The dialog shows each zone by its city (`SESSION_TZ_LABELS`: `New York`, `Kolkata`, `Sao Paulo`, ...). The list only grows at its end: a saved setting stores the index `p__tz()` reads, so the first nine never move and a new zone is appended. A `tz` outside the list refuses the build and names every id. `unit` and `unit_default` belong to one number field (`int`, `number`, `price`): a range's two ends have no unit picker. `market.tick_size()` declares the tick size as a hidden setting the host writes before `onStart()`; `market.price_precision()` does the same for the price decimals, and `market.zone()` for the market's own time zone as an index into this same list ([Chart context](#chart-context) says who fills what). ## What the dialog draws ![a day strip with the window shaded, a start and an end on the 24-hour clock, and a zone menu](/wrun/images/wrun-settings-session.svg) ![a number field with a unit picker beside it](/wrun/images/wrun-settings-number-unit.svg) ## Read it in onStart() A session is three readers: `p__start()` and `p__end()` (minutes from midnight) and `p__tz()` (the zone's index). The index is what `p__tz()` reads and what `inSession` takes; `SESSION_TZ_IDS` and `SESSION_TZ_LABELS` hold the ids and the dialog's words in the same order. The rules are compiled into the module, so a session reads the same in your browser, on OpenMarket's servers and in an alert. The bar's open is `bar.time()` ([Time and sessions](../core-concepts/time-and-sessions.md)). A unit pick reaches the module as a code that never changes with the order you list: `price` 0, `ticks` 1, `%` 2, `atr` 3, read through `p__unit()` beside `p_()`. The tick size is read through `p_market_tick_size()`, the price decimals through `p_market_price_precision()`. ```typescript function onStart(): void { offset = p_offset(); offsetUnit = i32(p_offset_unit()); atr = new Atr(i32(p_atr_length())); tick = p_market_tick_size(); sessionStart = p_rth_start(); sessionEnd = p_rth_end(); zone = i32(p_rth_tz()); } ``` Per bar, `inSession(barOpenSec, startMin, endMin, zone)` answers whether the bar's open sits inside the window, and `unitToPrice(value, unit, close, tick, atr)` turns the number into a price distance: `ticks` multiplies by the tick size, `%` takes that percent of `close`, `atr` multiplies by the ATR you pass, and `price` is the value as it is. ```typescript const atrValue = atr.update(bar.high(), bar.low(), close); // The offset in the unit the dialog picked, as a price distance. if (isFinite(basis)) basis += unitToPrice(offset, offsetUnit, close, tick, atrValue); active = inSession(t, sessionStart, sessionEnd, zone) && multiHas(dayMask, weekday); ``` ## Chart context Numbers about the chart and its market reach your file before the first bar: the bar interval, the price decimals, the tick size, the chart's colours, and the market's kind, point value, time zone, quote currency ([The market's facts](#the-markets-facts)) and the minute its trade day opens ([Venue trade day](#venue-trade-day)). Declare the ones you need at the top level and read them in `onStart()`. Wherever the indicator runs, it gets the numbers that place can know, and 0 for the rest. ```typescript // A close line with a corner readout of the three facts the host writes before the first bar. chart.interval_sec(); market.price_precision(); market.tick_size(); output("close_line", line, overlay, { color: "#94a3b8" }); string("facts", { max_bytes: 96 }); render.table("corner", { rows: 1, cols: 1, cells: ["facts"], position: "top_left" }); let intervalSec: f64 = 0; let decimals: i32 = 0; let tick: f64 = 0; function onStart(): void { intervalSec = p_chart_interval_sec(); decimals = i32(p_market_price_precision()); tick = p_market_tick_size(); } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; out_close_line(close); sb_clear(); sb_text("bar "); // 0 means the host did not fill the fact. if (intervalSec > 0) sb_duration(intervalSec); else sb_text("unknown"); sb_text(", close "); sb_f64(close, decimals); sb_text(tick > 0 ? ", tick known" : ", tick unknown"); str_facts_sb(); } ``` On a 15-minute BTC chart the readout says `bar 15m`, the close at the chart's own decimals, and `tick unknown`. ### Who fills what | Declare | Read with | On the chart | On OpenMarket's servers and in alerts | Where there is no chart | | --- | --- | --- | --- | --- | | `chart.interval_sec()` | `p_chart_interval_sec()` | the bar interval in seconds (a 15-minute chart reads 900) | the chart's number, carried with the indicator | the interval of the bars it runs on | | `market.price_precision()` | `p_market_price_precision()` | the chart's price decimals | the chart's number | the most decimals the market's candle prices carry, at most 10; 0 when it reads no candles of that market | | `market.tick_size()` | `p_market_tick_size()` | the market's tick where the market publishes one (CME markets), else 0 | the chart's number | 0, until market data carries tick sizes | | `chart.bg_color()` | `i32(p_chart_bg_color())` | the background colour, packed | the chart's number | 0 | | `chart.fg_color()` | `i32(p_chart_fg_color())` | the text colour, packed | the chart's number | 0 | | `market.kind()` | `i32(p_market_kind())` | what the chart's market trades | the chart's number | what the market directory says the market trades | | `market.point_value()` | `p_market_point_value()` | the money one point of price is worth on one contract | the chart's number | 1 for a market priced per unit (a coin, a perpetual, a stock), 0 on a CME futures market, whose multiplier is not known there | | `market.zone()` | `i32(p_market_zone())` | the market's exchange time zone | the chart's number | New York for US stocks, indices and forex, Chicago for CME, London for the London metals, else 0 (UTC) | | `market.quote_is_usd()` | `i32(p_market_quote_is_usd())` | whether prices are in US dollars | the chart's number | from the market's quote currency | | `market.session_open()` | `p_market_session_open()` | the minute the market's trade day opens on its clock | yes: the hosted worker, the registry and Enterprise select the wrun8 pair (`@openmarket/contracts` 5.24.0, 2026-10-13) | 1020 on CME futures (17:00 Chicago) and on forex (17:00 New York), else 0 (midnight) | - Read 0 as "unknown". `unitToPrice` leaves a ticks value as it is when the tick is 0, and a `Bucket` refuses its span when the interval is 0. The zone and the session open are the exceptions: the zone's 0 is UTC and the session open's 0 is midnight, also where either is unknown. - These are hidden settings: the settings dialog never shows them, and the number the host writes always wins over anything passed under the same name. - Each one counts toward the 128 settings. ### The interval and the colours ```typescript // The bar interval and the chart's two colours, written by the chart into hidden settings. chart.interval_sec(); chart.bg_color(); chart.fg_color(); ``` - `chart.interval_sec()` is the chart's bar interval in seconds, read through `p_chart_interval_sec()` and available from the first bar (a 15-minute chart reads 900); 0 only when the interval is unknown. - `chart.bg_color()` is the chart's background, a custom background included, and `chart.fg_color()` is the chart's text colour, each as the packed colour the colours kit uses (`(r << 24) | (g << 16) | (b << 8) | a` as a signed 32-bit integer, so white reads `-1`). Read them with `i32(p_chart_bg_color())` and `i32(p_chart_fg_color())`; 0 means unavailable. ```typescript function onStart(): void { intervalSec = p_chart_interval_sec(); bg = i32(p_chart_bg_color()); fg = i32(p_chart_fg_color()); } ``` The text colour is the theme's, not the background's: on a custom background it may not contrast with the background. Choose ink from the background's brightness instead: `red(bg)`, `green(bg)` and `blue(bg)` read its channels, and [Read a color back](../functions/colors-kit.md#read-a-color-back) draws dark words on a light chart and light words on a dark one. Treat `fg_color` as the theme's hint. ### The market's facts ```typescript // What the market trades, its point value, its time zone and its quote, written by the host into hidden settings. market.kind(); market.point_value(); market.zone(); market.quote_is_usd(); ``` Each is a number, and 0 means the host does not know: | Declare | Reads | Values | | --- | --- | --- | | `market.kind()` | `i32(p_market_kind())` | 1 crypto, 2 a stock or an ETF, 3 forex, 4 a metal, 5 an index, 6 an economic series; 0 unknown, or none of these (a prediction market, an oil contract) | | `market.point_value()` | `p_market_point_value()` | the money one whole point of price is worth on one contract: a futures multiplier (50 on the E-mini S&P), 1 on a market priced per unit (a coin, a perpetual, a stock); 0 unknown | | `market.zone()` | `i32(p_market_zone())` | the market's exchange time zone as its index in the zone list above (1 New York, the clock of US stocks and forex, 2 Chicago, 3 London); 0 is UTC, also where the zone is unknown | | `market.quote_is_usd()` | `i32(p_market_quote_is_usd())` | 1 when prices are in US dollars, 2 in another currency or coin (USDT and USDC included: BTCUSDT is priced in USDT), 0 unknown | | `market.session_open()` | `p_market_session_open()` | the minute of the day, on the market's clock, at which its trade day opens: 1020 (17:00) on CME futures and on forex, 0 (midnight) on every other market and where it is unknown ([Venue trade day](#venue-trade-day)) | - A futures market reports what it trades: an index future reads 5, a gold future 4. - A stock that trades around the clock on a crypto venue reads 2 and its venue's zone, UTC. - The codes never change: a new kind is added at the end of the list. - The zone is an index, not an offset: pass it to `inSession(...)` or `new Clock(SESSION_TZ_IDS[zone])` and each bar gets its own daylight-saving offset. - `market.size_unit()` and `market.notional()` declare the facts the size helpers read, so one file counts and prices a size on every market ([Size units](#size-units)). ```typescript // A listed stock's regular hours on its own exchange clock: the close drawn only between 09:30 and 16:00 there, every bar on a market that trades around the clock. market.kind(); market.zone(); market.point_value(); market.quote_is_usd(); output("session_close", line, overlay, { color: "#2962ff" }); output("point_value_usd", line, lower, { color: "#94a3b8" }); let kind: i32 = 0; let zone: i32 = 0; let pointValue: f64 = 0; let inDollars = false; function onStart(): void { kind = i32(p_market_kind()); // 0 is UTC, also where the host does not know the zone. zone = i32(p_market_zone()); pointValue = p_market_point_value(); inDollars = i32(p_market_quote_is_usd()) == 1; } function onBar(): void { const close = bar.close(); // A stock (kind 2) on an exchange clock keeps its hours, 09:30 (minute 570) to 16:00 (minute 960); // zone 0 is a venue that trades around the clock (a stock perpetual), or an unknown zone. const open = kind != 2 || zone == 0 || inSession(bar.time(), 570, 960, zone); out_session_close(open ? close : NaN); // A one-point move on one contract, in dollars where the market is priced in them. out_point_value_usd(inDollars && pointValue > 0 ? pointValue : NaN); } ``` On a US stock the line breaks outside New York's regular hours, daylight saving included, and the lower pane reads 1. On BTCUSDT, and on a stock perpetual that trades around the clock, the line runs through every bar; on BTCUSDT the lower pane stays empty, since the price is in USDT. ## Venue trade day A CME futures trade date does not start at midnight UTC: it opens at 17:00 Chicago the evening before the date it is stamped with, and its week opens on Sunday at 17:00. A forex trade date (gold and silver on `FX_OTC` included) opens the same way at 17:00 New York, and its week opens on Sunday at 17:00 New York. Declare `market.session_open()` beside `market.zone()`, read both in `onStart()`, and the same four helpers place any bar in its trade day, so a daily or weekly anchor lands where the exchange's does. ```typescript // The market's clock and the minute its trade day opens, written by the host into hidden settings. market.zone(); market.session_open(); ``` | Helper | Answers | | --- | --- | | `sessionDayOpen(t, zone, openMin)` | the time, in epoch seconds, at which the trade day holding `t` opened | | `sessionTradeDate(t, zone, openMin)` | that trade day's date as days since 1970-01-01 (times 86400 is its 00:00 UTC stamp) | | `sessionWeekOpen(t, zone, openMin)` | the time the trading week holding `t` opened: the open of its Monday trade date | | `sessionGapBefore(prevT, t, zone, openMin)` | `true` when the bar at `t` sits in another trade day than the bar at `prevT` | `t` is a bar's open time (`bar.time()`), `zone` is `i32(p_market_zone())` and `openMin` is `p_market_session_open()`. - An open past 12:00 stamps the next date: on CME a bar from 17:00 Chicago on belongs to tomorrow's trade date, so Monday's trade date, and the week, open on Sunday at 17:00. - Where the trade day opens at midnight on UTC (crypto), the helpers return the UTC day and the UTC week from Monday: the same numbers as `Math.floor(t / 86400) * 86400`, to the bit. - Daylight saving follows the zone: the CME open stays at 17:00 on the Chicago clock in summer and in winter, and the forex open at 17:00 on the New York clock (21:00 UTC in summer, 22:00 UTC in winter). - There is no holiday calendar: a weekday holiday's session keeps its own date. - `sessionGapBefore` is `true` on the first bar of each trade day: after the daily break and the weekend on CME, at 17:00 New York on forex, after every UTC midnight on a market that trades around the clock. It is `false` when `prevT` is `NaN`, as on the first bar. A session VWAP that restarts at the exchange's trade day: 17:00 Chicago on CME, 17:00 New York on forex, midnight UTC on crypto. ```typescript market.zone(); market.session_open(); output("session_vwap", line, overlay, { color: "#f59e0b" }); let zone: i32 = 0; let openMin: f64 = 0; let dayOpen: f64 = NaN; let pv: f64 = 0; let vol: f64 = 0; function onStart(): void { zone = i32(p_market_zone()); openMin = p_market_session_open(); } function onBar(): void { const open = sessionDayOpen(bar.time(), zone, openMin); if (open != dayOpen) { // A new trade day: the sums restart. dayOpen = open; pv = 0; vol = 0; } const typical = (bar.high() + bar.low() + bar.close()) / 3; pv += typical * bar.volume(); vol += bar.volume(); out_session_vwap(vol > 0 ? pv / vol : NaN); } ``` On E-mini S&P futures (ES) with hourly bars, around the switch to daylight time on 2026-03-08 (Chicago is UTC-6 before it, UTC-5 after): | Bar opens (Chicago) | Trade date | Trade day opened | Week opened | New trade day | | --- | --- | --- | --- | --- | | Fri 03-06 14:00 | 2026-03-06 | Thu 03-05 17:00 | Sun 03-01 17:00 | | | Sun 03-08 17:00 | 2026-03-09 | Sun 03-08 17:00 | Sun 03-08 17:00 | yes, after the weekend | | Mon 03-09 10:00 | 2026-03-09 | Sun 03-08 17:00 | Sun 03-08 17:00 | no | | Tue 03-10 15:00 | 2026-03-10 | Mon 03-09 17:00 | Sun 03-08 17:00 | no | | Tue 03-10 17:00 | 2026-03-11 | Tue 03-10 17:00 | Sun 03-08 17:00 | yes, after the daily break | On BTCUSDT the same file restarts at 00:00 UTC every day. ## Size units A bar's volume and a trade's size count coins on a crypto pair, shares on a stock and contracts on a futures market. Declare `market.size_unit()` and two helpers name the unit and turn any size into money, so one file labels and prices a size right on every market without checking the exchange. ```typescript // The facts the size helpers read, written by the host into hidden settings. market.size_unit(); market.notional(); ``` Neither word adds a setting of its own. `market.size_unit()` declares `market.kind()`, `market.point_value()` and `market.zone()`; `market.notional()` declares `market.point_value()` and `market.zone()`. A fact two words name is declared once. Read the facts in `onStart()` and pass them per bar: | Helper | Answers | | --- | --- | | `sizeUnit(kind, pointValue, zone)` | the unit the market counts its size in, as a code below | | `notional(qty, price, pointValue, zone)` | what `qty` of that size is worth at `price`, in the market's quote currency: `qty * price * pointValue`, or `NaN` on a CME market whose multiplier is not known | `kind` is `i32(p_market_kind())`, `pointValue` is `p_market_point_value()` and `zone` is `i32(p_market_zone())`. | Code | Label | The market | | --- | --- | --- | | 0 | units | none of the rules below holds: forex, a metal, an index, an economic series, a market the host does not know | | 1 | coins | a crypto kind | | 2 | shares | a stock or an ETF | | 3 | contracts | a futures market | The first rule that holds decides the code: 1. **Contracts** when the point value is a contract multiplier, a positive number other than 1 (50 on ES, 5 on MES), or the zone is Chicago (2), the clock only CME futures keep. 2. **Coins** when the kind is crypto (1). 3. **Shares** when the kind is a stock or an ETF (2). 4. **Units**, code 0, otherwise. - The contracts rule comes first: CME bitcoin futures trade a coin (kind 1) and still count contracts. - `notional` never prints a wrong number. On the Chicago zone a point value of 0 or 1 is a multiplier the host does not hold (a CME option on the chart, every CME market where there is no chart), so it returns `NaN` and a money view stays empty. The cost: a CME contract whose multiplier really is 1 reads `NaN` too. - Off the Chicago zone a point value of 0 means the host does not know it, and `notional` multiplies by 1. - The codes never change: a new unit is added at the end of the list. The kit exports the codes and their labels as `WRUN_MARKET_SIZE_UNITS` and `WRUN_MARKET_SIZE_UNIT_LABELS`, so the chart shows the same words. | Market | kind, point value, zone | `sizeUnit` | A size in money | | --- | --- | --- | --- | | ES (E-mini S&P 500 futures) | 5, 50, 2 | 3, contracts | 2 contracts at 6000: `notional(2, 6000, 50, 2)` is 600000 | | ES where the host does not hold its multiplier | 5, 0, 2 | 3, contracts | `notional(2, 6000, 0, 2)` is `NaN` | | BTCUSDT perpetual | 1, 1, 0 | 1, coins | 0.5 BTC at 60000: `notional(0.5, 60000, 1, 0)` is 30000 (USDT) | | AAPL | 2, 1, 1 | 2, shares | 100 shares at 230: `notional(100, 230, 1, 1)` is 23000 | A volume pane in money on every market, with the unit its size counts in: ```typescript market.size_unit(); output("volume_money", histogram, lower, { color: "#26a69a" }); output("size_unit", none, lower); let unit: i32 = 0; let pointValue: f64 = 0; let zone: i32 = 0; function onStart(): void { pointValue = p_market_point_value(); zone = i32(p_market_zone()); unit = sizeUnit(i32(p_market_kind()), pointValue, zone); } function onBar(): void { out_volume_money(notional(bar.volume(), bar.close(), pointValue, zone)); out_size_unit(f64(unit)); } ``` On ES a bar of 2 contracts at 6000 reads 600000 and `size_unit` reads 3; on BTCUSDT a bar of 0.5 BTC at 60000 reads 30000 and `size_unit` reads 1. Where the host does not hold ES's multiplier the money pane stays empty and `size_unit` still reads 3. ### The dialog and the lanes Three words hand the size unit to the host, for what the module cannot change by itself: which rows the settings dialog and the chart show, the unit a volume lane is read in, and which markets fetch an input at all. None reaches the module: the build keeps them in the sheet and compiles the same bytes without them. | Word | On | What the host does | | --- | --- | --- | | `visible_by: { size_unit: [codes] }` | a typed setting (`param.`) or an `output(...)` | shows the row only on markets whose size unit is listed. Elsewhere the settings dialog leaves the setting out (its value still reaches `onStart()`), and the chart mounts nothing for the output: no plot, no legend entry, no stats row that reads it. The module still computes every output. | | `currency: "Auto"` | a `trades.*` or `volume_profile.cells` input | reads the lane in contracts (what `"Coin"` reads) on a market whose size unit is contracts (3), and in dollars (`"USD"`) on every other market. | | `needed_by: { size_unit: [codes] }` | a secondary scalar feed `input(...)` (scaffold 72) or a secondary `tape.cells` input (scaffold 95) | fetches the input's lane only on markets whose size unit is listed. Elsewhere nothing is asked for it and the input reads its fill on every bar (`NaN`, `0` under `missing: "zero"`, `NaN` under `"carry"`; a tape reads zero prints), never holding the run. Without the word the input is needed everywhere. | ```typescript // Liquidations exist on crypto venues: no toggle and no row on futures. param.bool("show_liq", true, { label: "Liq", visible_by: { size_unit: [0, 1, 2] } }); output("liq", histogram, lower, { visible_by: { size_unit: [0, 1, 2] } }); // One profile lane beside the candles: contracts on futures, dollars everywhere else. input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192, ticks_per_bar: 5, currency: "Auto" }); // The liquidations lane only where the row can show: never asked on futures. input("liq", liquidations.liquidations, { side: "BUY", missing: "nan", needed_by: { size_unit: [0, 1, 2] } }); ``` On ES the dialog has no Liq toggle, the chart draws no Liq row, no liquidations are fetched and the profile counts contracts; on BTCUSDT all three show and the profile is in dollars. - The codes are the size units above, 0 units, 1 coins, 2 shares and 3 contracts: at least one, each once. A setting's derived rows (a range's two ends, a session's three parts, a unit picker) hide with it. - `visible_by` belongs to typed settings and outputs. On `input(...)`, plain `param(...)`, a stats row or any other declaration it is refused by name; a stats row hides with the output it reads. - `needed_by` belongs to a secondary scalar feed input, a published feed (`series.value`) included, and to a secondary `tape.cells` input: on the first input (its rows are the grid every market needs), a `time.*` input, every other celled `.cells` input and a metric composition it is refused by name. Two tapes with different floors can split the markets between them, a dollar floor on coins and shares and a contracts floor on futures ([Large prints](../core-concepts/data-sources.md#large-prints-tape)): each keeps its own floor, judged on every run. Give a row that only reads such an input the same list as its `visible_by`, so a market that hides the row never fetches its data. An `is_new_period` view on a pin equal to the chart's interval still reads 1 there: it asks nothing on any market. - `"Auto"` follows the market the indicator runs on. On an input pinned to another market it is refused: name the unit, `"USD"` or `"Coin"`. - Every host resolves `"Auto"` the same way, where it plans the lane's fetch: it takes the market's size unit from the facts it holds (the point value and the zone decide contracts) and reads `"Coin"` on 3, `"USD"` on anything else, a host that knows no facts included. The kit exports the three rules for hosts: `wrunLaneCurrency(currency, sizeUnit)`, `wrunVisibleOnMarket(visibleBy, sizeUnit, setting)` and `wrunNeededOnMarket(neededBy, sizeUnit, setting)`, where `setting` is `wrunKeyedSettingReader(params, sizeUnit, read)` (below). **Keyed by a choice.** A typed setting's `visible_by` and a tape's `needed_by` may name one `param.choice` of the file beside `size_unit`, with the option indexes it holds under. The two keys hold together: `visible_by: { size_unit: [1], min_unit: [1] }` shows the row on coin markets while `min_unit` picks its second choice ([A tape picked by a setting](../core-concepts/data-sources.md#large-prints-tape)). - `size_unit` stays required, and one choice at most stands beside it. - The choice keys its own row by the size unit alone. Where that row is hidden it reads its default: a stock chart that saved Coins reads Dollars. The module still receives the saved value. - An undeclared name, a setting that is no `param.choice`, an index the choice lacks, a second choice, a choice keyed by another choice and the row itself are refused by name. - An output's `visible_by` and a scalar feed's `needed_by` keep the size unit alone. | Host | `currency: "Auto"` | `visible_by` | `needed_by` | | --- | --- | --- | --- | | The chart | resolved on the chart's market | the dialog and the chart's rows follow it | the lane is fetched only where the chart's market is listed; a tape off the list reads zero prints | | OpenMarket's servers and alerts | resolved from the market facts the chart sends (point value and zone; missing facts read dollars); the servers select the wrun10 pair, wrun9 since 2026-10-13 | admitted: the servers compute every output and the chart hides the rows | the lane is fetched only where the facts the chart sends (kind, point value and zone) list the market's size unit (wrun10, selected 2026-10-14); Enterprise requests still ask the lane on every market until that executor fills skipped inputs; a tape's `needed_by` is refused by name (`source.tape.needed_by`) until a head admits it | | Where there is no chart | resolved from the venue tables: only CME futures read contracts there, and no CME rows are read there, so every lane served reads dollars | nothing changes: metric reads, watches and previews read every output | the input reads its fill where the market's size unit is not listed (the market's facts decide it); a tape off the list is never subscribed and reads zero prints | | A host on an older kit | before scaffold 69: refused by name | before scaffold 69: the row shows on every market | before scaffold 72: the sheet check drops the word and the lane is asked on every market, so the input reads the lane's data there too; only the build refuses it by name, as an unknown input option. Before scaffold 95 the sheet check refuses it on a tape by name | ## Gotchas - A tick size or an ATR of 0 means unavailable, and `unitToPrice` then leaves the value as it is. - A unit picker on a range is refused: `param.range 'r' takes no unit option (a unit picker sits beside one number field, not a range)`. - A session counts as three settings and a `unit` list as one more toward the 128-setting cap ([Picks, lanes, the cap](picks-and-lanes.md)). - A preset sets a session or a unit through its parts (`rth_start`, `offset_unit`, by the dialog's words for a session zone or a unit) ([Presets](presets.md)). - A window fixed in the file needs no setting: it is a `Session` ([Clock and sessions kit](../functions/time-and-sessions-kit.md)). - `market.size_unit()` and `market.notional()` are declarations: they take no arguments and stand at the top level. Per bar, call `sizeUnit(...)` and `notional(...)` with the facts read in `onStart()`. - `visible_by` hides a row; it never stops a value. A package that has no number to show on a market writes `NaN` there itself, and the hidden row keeps the dialog and the chart free of an empty line. ## Related - [Setting kinds](kinds.md): every kind and its readers - [Options on a setting](options.md): `unit`, `unit_default` and `tz` among the other keys - [Time and sessions](../core-concepts/time-and-sessions.md): the integer math underneath a session - [Clock and sessions kit](../functions/time-and-sessions-kit.md): a window fixed in the file # Picks, lanes, the cap Two kinds are picked on the chart, three are applied by the chart rather than read by the module, and a sheet holds at most 128 settings. ## What it is `param.time` draws a date and time field with **Pick**: the next click on the chart sets it. `param.price` draws a number field with **Pick**: the next click on the chart sets the price. Three kinds are applied by the chart instead of being read by the module: `param.source` picks the field an input reads, and `param.timeframe` and `param.symbol` pin an input. OpenMarket's cloud accepts at most 128 settings per indicator. ## Declare it ```typescript // time and price: both can be picked on the chart. param.time("since", "2024-01-01 00:00", { label: "Start" }); param.price("floor", 0.0, { hint: "0 draws no floor" }); // source: declares the primary input too; in_src() reads the picked field. param.source("src", ohlcv.close); // timeframe and symbol: each pins the input that names it. param.timeframe("htf", "chart", { label: "Reference timeframe" }); input("close_htf", ohlcv.close, { interval: "@htf" }); param.symbol("pair", "BINANCE_FUTURES:ETHUSDT", { label: "Ratio against" }); input("close_pair", ohlcv.close, { symbol: "@pair" }); ``` A `param.time` default is `"YYYY-MM-DD HH:MM"` in UTC or a whole number of epoch seconds. A `param.symbol` default is `"EXCHANGE:SYMBOL"` in the chart's own ids. A `param.source` default is any word of its menu: `open`, `high`, `low`, `close`, `hl2`, `hlc3`, `ohlc4`, `volume` or `hlcc4` ([A blended default](#a-blended-default)). ### A blended default `hl2`, `hlc3`, `ohlc4` and `hlcc4` are blends of the candle, not prices stored on it: wherever the indicator runs, the bar's own candle is blended the same way, so a blend is as good a default as `close`. | Word | The bar's | | --- | --- | | `hl2` | `(high + low) / 2` | | `hlc3` | `(high + low + close) / 3` | | `ohlc4` | `(open + high + low + close) / 4` | | `hlcc4` | `(high + low + close + close) / 4` | A blend is missing on a bar where a price it reads is missing. A plain input may read one too: `input("mid", ohlcv.hl2)`. ```typescript // An EMA of the typical price by default: hlc3, a blend of each bar's candle, and any other word of the menu in the dialog. param.source("src", ohlcv.hlc3, { label: "Price" }); param.int("length", 21, { min: 2, max: 500 }); output("ema", line, overlay, { color: "#f59e0b", width: 2 }); let ema = new Ema(21); function onStart(): void { ema = new Ema(i32(p_length())); } function onBar(): void { out_ema(ema.update(in_src())); } ``` A string that starts with `@` on an input is a reference to a setting by name; the build writes the setting's default in its place before it compiles, and the sheet records which setting controls the pin: | Where | Names | What the chart does | | --- | --- | --- | | `interval: "@name"` on an input | a `param.timeframe` | pins the input to the picked timeframe; `chart` removes the pin | | `symbol: "@name"` on an input | a `param.symbol` | pins the input to the picked market, exchange included unless the input names one | | `ticks_per_bar: "@name"` on a `volume_profile.cells` input | a `param.int` whose `min..max` lies inside 1..500 | asks for the profile at the setting's bucket size and fetches again when it changes; the chart and the alerts engine both apply it ([Order flow](../functions/order-flow-kit.md#what-the-chart-serves)) | The pin rules still hold: a timeframe pick must be coarser than the chart and a whole multiple of it, which is why a default of `"chart"` runs on every interval ([Multi-timeframe](../core-concepts/multi-timeframe.md)). A `symbol` pin that starts with `@` but names no setting is the venue's own spelling and stays the literal (Hyperliquid spot markets are `"@107"`; a `param.symbol` default may carry one, `"HYPERLIQUID:@107"`). A pin the user need not change is written on the input itself, on an input after the first: both halves together for a market, `interval` on its own. The chart honors it, and a pin it cannot serve is refused by name when the indicator runs; on a 1h chart this one reads BTC's closed 4h candles ([Multi-timeframe](../core-concepts/multi-timeframe.md#the-interval-pin-a-real-coarser-feed) and [Multi-source](../core-concepts/multi-source.md#multi-symbol) have the pin rules): ```typescript input("btc_4h", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", interval: "FOUR_HOURS" }); ``` ## What the chart draws ![the dialog dimmed while a pick is armed, with a hint naming the setting the next click on the chart sets](/wrun/images/wrun-pick-mode.svg) A time or price row's **Pick** button lets the pointer through the dialog, dims it and shows a hint, "Click the chart to set {label}". The next click on the chart sets the row: the bar's time in epoch seconds for a time, the price under the pointer for a price. A press that travels is a pan, not a pick, and Escape disarms. ## Read it in onStart() `p_since()` reads the time as epoch seconds and `p_floor()` the price. `source`, `timeframe` and `symbol` have no reader to call: the chart applies the pick, and the input bound to the setting reads the picked field, timeframe or market per bar. ```typescript function onStart(): void { since = p_since(); floorPrice = p_floor(); } function onBar(): void { const t = bar.time(); const close = in_src(); const reference = in_close_htf(); const pair = in_close_pair(); if (!isFinite(basis) || t < since) return; } ``` ## Where a setting applies Most settings are numbers the module reads, and every place that runs an indicator hands them to `onStart()` the same way: your browser, OpenMarket's servers for an indicator published as **Protected**, and the alerts engine. Three kinds are applied by the chart instead: `param.source` picks the field an input reads, and `param.timeframe` and `param.symbol` pin an input. For now the chart applies them only when the indicator runs in your browser: - an indicator that runs on OpenMarket's servers keeps the declared default, and its dialog marks the row "Browser lane only for now"; - an alert refuses to arm while one of them is off its default ("Alerts cannot use the Reference timeframe setting yet. Set it back to its default to arm."); - a `param.source` default runs everywhere, a blend included: every place blends the bar's candle the same way. An indicator that runs on OpenMarket's servers has no Style page either ([The Style page](style-page.md)). An alert on a published indicator runs with the settings of the overlay you set it from ([Alerts](../functions/alerts.md)). ## The 128-setting cap OpenMarket's cloud accepts at most 128 settings per indicator, so the build refuses a file whose settings expand past 128, on the declaration that crosses the line. Most kinds count once: | Declaration | Counts as | | --- | --- | | `int`, `number`, `bool`, `choice`, `color`, `time`, `price`, `multi`, `source`, `timeframe`, `symbol`, plain `param`, each `market.*` | 1 | | a `unit` list on a number | 1 more | | `range` | 2 | | `session` | 3 | | `list` | `max` + 1 | A list is the kind that grows: `param.list("lookbacks", [5.0, 20.0], { max: 4 })` draws an editable list of numbers with **Add**, up to `max` long, and counts `max` slots and the count. A list whose `max` alone crosses the cap is refused on its own line: `param.list 'l' max 200 would put 201 params on the sheet (max slots and the count); hosted lanes cap params at 128, so max is at most 127`. ## Gotchas - A source default off the menu: `unknown field ohlcv.vwap for param.source 's' (known: open, high, low, close, hl2, hlc3, ohlc4, volume, hlcc4)`. - More than 128 settings: `the sheet would carry 129 params after expansion (a range derives two, a list max + 1, a session three, a unit list one more); hosted lanes cap params at 128`. - In a preset, a time is written in either spelling, a price as a number within its bounds, and a market as `"EXCHANGE:SYMBOL"` ([Presets](presets.md)). ## Related - [Setting kinds](kinds.md): the five kinds on this page among the fifteen - [The Style page](style-page.md): the two references that paint - [Multi-timeframe](../core-concepts/multi-timeframe.md): why a timeframe pick must be coarser than the chart - [What the build checks](checks.md): the refusal table # What the build checks The declarations are read from the text without running it, and **Run** checks them before the compiler runs. ## What it is Declarations are literals: the extractor reads them from the text without running it, and each kind checks its own default's shape, a whole number for `param.int`, hex for `param.color`, one of the options for `param.choice`. Every kind takes one options object, every key optional, and a key the kind cannot use is refused by name. The Console shows each refusal on the declaration's line: ```text param.bool 'x' takes no min option (its value is not a number field) ``` ![A toggle declared with a min option: its line underlined in the editor, the declarations row in the Console with the refusal, the error count in the status bar, and Run blocked](/wrun/images/checks-declaration.png) - Line 7 is underlined as you type: the extractor reads the declaration before anything compiles. - The Console row is tagged `declarations` and starts with the line number; the message names the kind, the setting and the option. - The status bar counts the error, and Run answers "Cannot run: 1 error(s) must be fixed first." ## The refusal table | Mistake | What the Console says | | --- | --- | | a key the kind does not take | `param.int options accept only { required, min, max, description, label, step, group, row, hint, when, hide, slider, unit, unit_default, confirm, visible_by }, not 'tooltip'` | | a typed key on plain `param` | `param options accept only { required, min, max, description }, not 'label'` | | a number-field key on a toggle | `param.bool 'x' takes no min option (its value is not a number field)` | | a unit picker on a range | `param.range 'r' takes no unit option (a unit picker sits beside one number field, not a range)` | | `hide` without `when` | `param.int 'x' declares hide without when; hide names what happens when the when param is off, so declare when beside it` | | `when` naming a setting that cannot open a row | `param.int 'x' when names 'y', which is a param.color (when names a param.bool, param.choice, param.int, param.number or param.multi: "name", "!name", "name=v", "name!=v" or "name in a,b", e.g. when: "show_bands")` | | `when` comparing a choice with a value it does not hold | `param.int 'x' when compares the choice 'y' with 2; a choice holds its option index, 0 to 1 (a, b)` | | `when` spelling no gate | `param.int 'x' when 'y == 1' names no setting: when takes "name", "!name", "name=v", "name!=v" or "name in a,b", naming the setting that opens the row (e.g. when: "show_bands")` | | a slider without both bounds | `param.int 'x' declares slider without min and max (a slider needs both bounds)` | | a fractional `param.int` default | `param.int 'x' default must be an integer literal, not 1.5` | | a choice default that is not an option | `param.choice 'm' default "c" is not one of its options (known: a, b)` | | a color that is not hex | `param.color 'c' default takes "#rrggbb" or "#rrggbbaa", not 'red'` | | a range without bounds | `param.range 'r' needs min and max (the two-handle slider's bounds), e.g. param.range("r", [1, 2], { min: 0, max: 100 })` | | a list without `max` | `param.list 'l' needs max (the most items the dialog may hold), e.g. param.list("l", [1,2], { max: 8 })` | | a list whose `max` alone crosses 128 | `param.list 'l' max 200 would put 201 params on the sheet (max slots and the count); hosted lanes cap params at 128, so max is at most 127` | | a source default off the menu | `unknown field ohlcv.vwap for param.source 's' (known: open, high, low, close, hl2, hlc3, ohlc4, volume, hlcc4)` | | a reference to the wrong kind | `output 'h' color references "@k", which is not a param.color` | | a reference where no setting can paint | `draw.line 'ln' color references "@c", but a param paints an output, a renderer or a legend entry only; write a colour literal here` | | a preset naming a composite | `preset 'A' sets 'band', which is not a declared param on the sheet (a composite is set by its members, e.g. band_lo)` | | a preset value the setting cannot take | `preset 'A' value for 'mode' takes one of its options as a string (fast, slow), not "Zed"` | | a name a composite already derives | `param 'band_lo' collides with the name param.range 'band' derives; rename one` | | more than 128 settings | `the sheet would carry 129 params after expansion (a range derives two, a list max + 1, a session three, a unit list one more); hosted lanes cap params at 128` | | a default above `max` | `Param 'length' (default): default above max` | | `min` above `max` | `Param 'length' (min): min must be <= max` | | a computed default (`param("n", base * 2)`) | `param 'n' default must be a numeric literal, not 'base * 2'; write the number, e.g. param("n", 14)` | | a string default on a number field (`param("mode", "ema")`) | `param 'mode' default must be a numeric literal, not '"ema"'; write the number, e.g. param("mode", 14)` | | a name built from a variable | `param names must be string literals (expected a string literal)` | The rows by the page that explains them: the option rows on [Options on a setting](options.md), the default rows on [Setting kinds](kinds.md), the reference rows on [The Style page](style-page.md), the preset rows on [Presets](presets.md), the source default and the cap on [Picks, lanes, the cap](picks-and-lanes.md). ## Warnings Three findings warn on the declaration's line and never block **Run**: each names a setting that sits in the dialog and does nothing. | Finding | What the Console says | | --- | --- | | a setting no code reads | `param 'x' is never read, so changing the setting changes nothing: read it with p_x() where the code needs it, or remove the declaration` (in a file with `onBar()`, the form in [Common errors](../faq/common-errors.md#is-never-read-so-changing-the-setting-changes-nothing)) | | a setting read only inside branches another setting decides, with no `when` naming it | `param 'x' is read only inside branches 'mode' decides (line 12), so its row changes nothing while 'mode' closes them: give it a when naming 'mode' ...` | | a paint target on an output key its plot does not draw | `param 'dash' paints hist.line_style, which a histogram output does not draw, so the setting moves nothing there: remove the target, or paint a key the output draws` | A branch decides a read when the read sits in an `if` arm, a `? :` arm, the right side of an `&&` or `||`, or the rest of a block after an `if` that returns, and the test reads the other setting against constants. A setting read on both sides of one test (an `if` and its `else`, a chart path and a higher timeframe path) needs no `when`, and neither does a row whose section's `toggle` or `when` already names the setting. A bar or histogram column takes no line style or smooth target, and neither does a shape, scatter or candle. A column's `width` paints: it is a share of the bar slot, so a Width setting bound there resizes the columns. An official OpenMarket indicator cannot be published with any of the three, so every setting it ships is live. ## Reserved names A setting cannot take a name the chart keeps for itself: `symbol`, `exchange`, `interval`, `transformations`, `ticksPerBar`, `currency`, `runMode`, `devViewerTier`, `errorMessage`, `splineVisibility`, `customScriptId`, `subType`, `scriptSource`, `catalogSource`, `wrunRef`, `wrunRegistryRef`, `wrunRunTarget`, `wrunAlertOutputs`, `wrunDraftRef`, `isProtectedScript`, `codeVisibility`, `hasGuide`, `scriptAuthor`, or any name that starts with `__style__` ("param 'symbol' uses a reserved name ...; rename it"). Every other name is free, `smooth`, `width` and `opacity` included. ## Common errors Each message with its symptom, its cause and its fix, beside the rest of the build's refusals: [Common errors](../faq/common-errors.md). The full grammar, every key and its legal values: [Declarations and the sheet](../reference/declarations.md#the-declaration-grammar). ## Related - [Setting kinds](kinds.md): the default each kind takes - [Options on a setting](options.md): which kind takes which option - [Presets](presets.md): the values a preset may name - [Common errors](../faq/common-errors.md): symptom, cause and fix per message # Style anything ![The desk on two chart cells: on the left, BTCUSDT 5m with the GEX by expiry board docked against the price axis, cells in the chart's up and down colours with signed dollars, the at-the-money row outlined, the per-strike bars left of the board and the dashed gamma flip level with its label; on the right, BTCUSDT 1h with the eight tiles, the Deribit GEX curve with its spot marker, point callouts and caption, and the rolling CVD histogram at the bottom](/wrun/images/style-anything/overview.png) Every part a wrun indicator draws can be styled. A line, a column, a docked profile, a card in a corner, a label, a strike board and a pane each take their look as words in the declaration, and the chart draws what the words say; the code only writes numbers. This page walks one real indicator part by part, an options desk: a strike matrix docked on the price axis, a dashboard of tiles, a gamma curve and a cumulative volume delta. Each part shows its picture, the lines of the desk that style it, the words that matter most, and the page that lists every word. Nothing has to be styled: a HUD card with no `look` and a line, bars, histogram, scatter or heatmap panel with no look words draw the chart's house look ([The house look](#the-house-look)). The two files are cookbook recipes and template cards of their own: [Strike Matrix](../cookbook/strike-matrix.md) is the left cell (the board, the per-strike bars and the levels, under **On price**) and [Options Dashboard](../cookbook/options-dashboard.md) the right (the tiles, the gamma curve and the rolling CVD, under **Beyond the time axis**); each compiles as written, on a chart of a coin with a listed options chain. The whole desk is eight declarations, two files on two chart cells; the frames, outputs and slots they read come first: ```typescript const board = frame("board", { max_bytes: 32768 }); const gexRows = frame("gex_rows", { max_bytes: 16384 }); const tileRows = frame("tile_rows", { max_bytes: 4096 }); const gexCurve = frame("curve_rows", { max_bytes: 16384 }); output("t_prev", none, overlay); output("t_last", none, overlay); output("flip_price", none, overlay); output("cvd_sign", none, lower); string("flip_text", { max_bytes: 32 }); plot.matrix({ name: "gex_board", frame: board, dock: "right", column_width: 66, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "usd", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.accent", label: "Exposure by expiry", tooltip: "{{column}}: {{value:usd}} at {{price}}" }); plot.levels({ name: "gex_by_strike", frame: gexRows, dock: "right", width_px: 100, baseline: "center", labels: false, opacity: 0.95, thickness_px: 10, format: "usd", signed: true, hover: true, offset: [340, 0] }); // offset: the board's width (4 columns of 66 px plus the price column), so the bars sit left of it instead of under it draw.line("flip_line", { x1: "t_prev", y1: "flip_price", x2: "t_last", y2: "flip_price", color: "theme.text", width: 1, line_style: "dashed", extend: "both" }); handles.label({ anchor: "right", align: "right", style: "knockout", font_weight: "medium" }); panel.tiles({ name: "tiles", title: "Options, Deribit", x: "category", place: "below", frame: tileRows, columns: 4, accent: "auto", positive_color: "theme.up", negative_color: "theme.down", format: "usd", signed: true, hover_card: true, height_frac: 0.18 }); panel.line({ name: "gex_curve", title: "Deribit GEX (Hypothetical Spot)", x: "number", place: "below", frame: gexCurve, series: [{ name: "Net GEX", color: "theme.text", width: 2 }], smooth: true, fill_mode: "signed", fill_positive_color: "theme.up", fill_negative_color: "theme.down", fill_fade: true, x_format: "usd", x_decimals: 1, format: "usd", signed: true, decimals: 0, x_title: "Spot", y_zero: true, legend_style: "none", hover_card: true, height_frac: 0.25, maximize: true, stats_row: true }); output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors: ["theme.down", "theme.up"], width: 0.7, label: "Agg. Rolling CVD", format: "si", description: "Rolling cumulative volume delta: aggressive buys minus sells over the window" }); pane("cvd", { height_frac: 0.12, format: "si" }); // the Indicator's home pane: it carries the Indicator's name, so no title here ``` ## The map | Part | What you see | The words that matter most | Full page | | --- | --- | --- | --- | | Side charts | a small chart of its own below the candles: the gamma curve | `chrome`, `legend_style`, `smooth`, `glow`, `fill_mode`, `markers`, `badge`, `height_frac` | [Frames, panels and compact widgets](cards-frames-panels.md#frames-panels-and-compact-widgets) | | Levels and profiles | bars docked on the price axis, one per strike | `dock`, `width_px`, `baseline`, `thickness_px`, `offset`, `hover`, `poc`, `opacity` | [Docked profiles](cards-frames-panels.md#docked-profiles) | | Cards and HUDs | the dashboard: eight tiles below the chart | `columns`, `accent`, `positive_color`, `negative_color`, `format`, `look`, `chrome`, `background_color` | [Panel words](cards-frames-panels.md#panel-words), [HUD cards](hud-and-hover-cards.md#hud-cards) | | Labels and drawings | a line across the chart at the gamma flip, its label just left of the strike bars | `style`, `align`, `valign`, `font_weight`, `line_style`, `extend`, `sticky_right`, `axis_label` | [Drawing objects](drawing-objects.md) | | Lines over time | the rolling CVD as columns, one number per bar | `color_by`, `colors`, `width`, `label`, `format`, `split`, `fill_color`, `glow` | [Styling](styling.md), [Plotting](plotting.md) | | Price canvases | the strike matrix: a row per strike, a column per expiry | `palette`, `center`, `scale`, `column_width`, `highlight_color`, `grid_lines`, `format`, `font_weight` | [Price canvases](price-canvases.md) | | Panes | the tiles, the curve and the CVD stacked under the chart | `height_frac`, `format`, `title`, `place`, `scale`, `invert`, `padding`, `min` | [Panes](plotting.md#panes) | | Theme and the Style page | the same desk on a light chart, with the user's own colours | `theme.*` tokens, `"@name"`, `param.color`, `param.choice`, `contrast_guard`, `stack_handles` | [Theme colours](styling.md#theme-colours), [The Style page](../settings/style-page.md) | ## Side charts A side chart is a small chart of its own, in a pane below the candles or in the strip beside them. The desk's gamma curve is a `panel.line` over a decimal x, the hypothetical spot; its dashboard of tiles is a `panel.tiles` (the next part). Reach for one when the picture is not one value per bar: a curve over strikes, a count per weekday, a board of numbers. The module writes the rows as a frame; the look is the declaration's words, and the per-run chrome (the markers and the caption) rides in the frame beside the rows. ![The gamma curve panel: a smooth line in the chart's text colour over a dollar spot axis, its fill fading downward, the dashed Spot marker with its label, two point callouts pinned on the curve at the trough and the peak, and the caption under the title](/wrun/images/style-anything/side-charts.png) ```typescript const gexCurve = frame("curve_rows", { max_bytes: 16384 }); // The gamma curve: a smooth line in the chart's text ink over hypothetical spot, filled in the up colour above zero // and the down colour below, both axes in dollars; the spot marker and the point callouts (the flip, the peak, the // trough) are written per run into the frame. The one series needs no legend chip: the title names it and the hover // card reads it. panel.line({ name: "gex_curve", title: "Deribit GEX (Hypothetical Spot)", x: "number", place: "below", frame: gexCurve, series: [{ name: "Net GEX", color: "theme.text", width: 2 }], smooth: true, fill_mode: "signed", fill_positive_color: "theme.up", fill_negative_color: "theme.down", fill_fade: true, x_format: "usd", x_decimals: 1, format: "usd", signed: true, decimals: 0, x_title: "Spot", y_zero: true, legend_style: "none", hover_card: true, height_frac: 0.25, maximize: true, stats_row: true }); ``` The frame the module writes beside the rows, with the chrome of this run: the spot marker, three point callouts pinned on the curve and the caption (the flip callout is written only when the curve crosses zero): ```json { "rows": [ [76726.8, 65600], [76932.9, 787123], [93776.5, 398200000] ], "markers": [ { "x": "spot", "label": "Spot", "wash": true }, { "x": 76820.4, "valign": "point", "series": "Net GEX", "label": "Gamma flip", "color": "theme.text", "show_value": true }, { "x": 93776.5, "valign": "point", "series": "Net GEX", "label": "+$398.2M @ $93776", "color": "theme.up" }, { "x": 76726.8, "valign": "point", "series": "Net GEX", "label": "+$65.6K @ $76726", "color": "theme.down" } ], "caption": "live chain, all expiries" } ``` The words that matter: - `chrome` picks the frame: `"hairlines"` (horizontal value hairlines only, with no frame and no vertical lines; the default, [The default look](cards-frames-panels.md#the-default-look)), `"box"`, `"grid"` or `"none"`; the rich words of a line (`smooth`, `glow`, `animate`, the fills, `markers`) are refused only on a line that declares `"box"`. - `legend_style` (`"none"`, `"title"`, `"pane"`, `"chips"`; absent, the regular legend) and `legend_latest` put the series names and their last values on the panel; `hover_card` is the readout under the pointer. - `height_frac` is the pane's share of the chart; `place: "side"` with `width_px` and `height_px` moves the panel into the strip beside the price pane. - `fill_mode: "signed"` with `fill_positive_color` and `fill_negative_color` shades a line around zero and `fill_fade` fades the fill away from the line; `stroke_fade` fades the stroke away from a pivot; `markers` rule off an x of note. - `badge` puts a chip on the panel's title row (`text`, a `color` that defaults to `theme.accent`, a `text_color` that defaults to whichever of light or dark reads on the fill); a marker with `valign: "point"` is a callout pinned to the curve, at the value of the declared `series` it names (the first series by default) or at an exact `y`. Both are frame keys too, so the module can rewrite the chip and point at the peak it found on every run. - `x_title`, `y_title`, `x_format` with `x_decimals`, `y_zero` and `y_min`, `y_max` dress the axes; `maximize` and `stats_row` add the fullscreen button and the strip. Every panel word, kind by kind, is on [Panel words](cards-frames-panels.md#panel-words); the strip beside the chart is on [The strip beside the chart](price-canvases.md#the-strip-beside-the-chart). ## Levels and profiles A docked profile is one bar per price along the price axis, drawn from a frame the module writes. On the desk it is net gamma by strike: zero sits mid-dock, positives grow one way and negatives the other, each row in its own colour from the frame, a hover card per row. Reach for it when a number lives at a price rather than at a time: open interest by strike, volume by price, a liquidation map. `plot.profile` draws the same shape from the chart's own volume cells with no frame. Two canvases docked on the same side overprint and no word stacks them: `offset: [340, 0]`, the board's width, pushes the bars inward so they sit left of the board instead of under it. ![The per-strike net GEX bars in a narrow column left of the board: teal bars growing one way from the centre baseline and violet bars the other, one per strike, the dashed flip level running through them](/wrun/images/style-anything/levels.png) ```typescript const gexRows = frame("gex_rows", { max_bytes: 16384 }); // the bars: net GEX per strike, the board's row sums // The per-strike net GEX bars beside the board: zero mid-dock, positives one way and negatives the other, each row // in its own colour from the frame, a hover card per row, pushed inward past the board (both dock right), 100 px wide. plot.levels({ name: "gex_by_strike", frame: gexRows, dock: "right", width_px: 100, baseline: "center", labels: false, opacity: 0.95, thickness_px: 10, format: "usd", signed: true, hover: true, offset: [340, 0] }); // offset: the board's width (4 columns of 66 px plus the price column), so the bars sit left of it instead of under it ``` The frame carries one price, one value, one colour and one hover hint per row: ```json { "prices": [84000, 84250, 84500], "values": [-1200000, 350000, 2400000], "colors": ["theme.down", "theme.up", "theme.up"], "tooltips": [ "C +$1.2M | P -$2.4M", "C +$0.9M | P -$0.5M", "C +$2.6M | P -$0.2M" ] } ``` The words that matter: - `dock` and a fixed `width_px` (or `width_frac`) place the profile; `offset` and `beside` nest one profile inside another. - `baseline: "center"` grows positive rows one way and negative the other; `series` splits a row into stacked segments, each with its colour. - `thickness_px` caps a bar's height and `step` gives every row a price band of its own (a strike ladder). - `labels`, `label_place`, `format` with `signed`, `text_color` and `font_size` print the rows; `hover` opens the chart's card on a row, with the frame's `tooltips` as its hint. - `poc`, `poc_color`, `poc_width`, `poc_line_style`, `poc_extend` and `poc_label` draw the point of control; the `value_area_*` words rule off the value area and `outside_opacity` fades the rows beyond it. - `opacity`, `gradient`, `border_color`, `shape: "outline"` and `behind_candles` change how the bars paint. Every word, with its range, is on [Docked profiles](cards-frames-panels.md#docked-profiles); a profile over the chart's own cells is on [Profiles anchored in time](price-canvases.md#profiles-anchored-in-time). ## Cards and HUDs A dashboard is a panel of tiles below the chart, or a card pinned at one of the nine anchors that never moves with price. The desk's eight tiles are a `panel.tiles`: a label, a value, a caption and a colour per tile, written per run into the frame; the panel prints signed dollars, a tile's own format word or text wins, and the accent tints a numeric tile by its sign. Reach for a tiles panel when the numbers need room; for a readout that floats over the candles, a `render.hud` card picks a whole `look` at once, and a status card (`draw.card`), a ladder, a feed and a meter take the same surface and chrome words. ![The eight tiles in two rows of four: live net GEX in teal, the gamma flip and max pain in the text colour, the dealer regime in teal, the P/C ratio and net VEX in teal, the 25D skew and the dealer delta in rose, each with a caption under its value](/wrun/images/style-anything/cards.png) ```typescript const tileRows = frame("tile_rows", { max_bytes: 4096 }); // Eight tiles in two rows of four: the panel prints signed dollars, a tile's own format word or text wins, and the // accent tints a numeric tile by its sign (the chart's up colour above zero, its down colour below); a tile with its own // colour keeps it. The tiles, the curve and the CVD pane take 0.55 of the chart, so the candles keep the rest. panel.tiles({ name: "tiles", title: "Options, Deribit", x: "category", place: "below", frame: tileRows, columns: 4, accent: "auto", positive_color: "theme.up", negative_color: "theme.down", format: "usd", signed: true, hover_card: true, height_frac: 0.18 }); ``` The rows as the module writes them, `[label, value, caption, color, spark, format]` with `null` to skip an element; the neutral values carry `theme.text`, so they read on the light chart too: ```json { "rows": [ ["Live net GEX", 235182438, "@ $85.2K | chart", null, null, "usd"], ["Gamma flip", "$87,526", "+2.7% from spot", "theme.text"], ["Max pain", "$79,000", "-7.3% from spot", "theme.text"], ["Dealer regime", "Positive Gamma", "Dips bought, rallies sold", "theme.up"], ["P/C ratio", "0.63", "Calls favored", "theme.up"], ["25D skew", "+0.1pp", "Puts bid (downside)", "theme.down"], ["Dealer delta", "-62.1K", "Net short delta, in coins", "theme.down"] ] } ``` The words that matter: - A tiles panel: `columns` (1 to 8), `accent` (`"auto"` tints a numeric tile by its sign, `"neutral"` leaves it), `positive_color` and `negative_color`, `format` with `signed`, `decimals` and `unit` for every value it prints, `hover_card`, `height_frac` and `title`; a row's own `color`, `spark` and `format` win over the panel's. - A HUD card: absent `look`, the default look ([The default look](hud-and-hover-cards.md#the-default-look)); `look` is one of twelve presets (`glass`, `terminal`, `cockpit`, `phosphor` and the rest) and any word beside it wins; `chrome` the frame (`"card"`, `"none"`, `"brackets"`, `"rules"`, `"tag"`, `"title_bar"`, `"window"`, `"cover"`); `texture: "scanlines"` the finish. - The surface: `background_color` with `background_opacity`, or `background_gradient` with `gradient_direction`; `border_color`, `border_width`, `border_style`; `corner_radius`, `padding`, `shadow`, `opacity`. - The type and the accent: `font_family`, `text_color`, `title_text_color`, `title_case`, `label_case`, `text_glow`; `accent_color`, or `accent_color_by` with `accent_colors` so the whole card follows an output per bar. - Size and place: `width`, `offset`, `z`, `safe_area`, `mobile`; each tile's `draw`, `color` or `color_by` with `colors`, `headline`, `font_size`, `height`. The tiles words are on [Panel words](cards-frames-panels.md#panel-words) and the rows on [Panel rows, kind by kind](cards-frames-panels.md#panel-rows-kind-by-kind); every HUD word is on [HUD cards](hud-and-hover-cards.md#hud-cards) and the twelve looks on [Looks](hud-and-hover-cards.md#looks); the card, ladder, feed and meter words on [Status cards](cards-frames-panels.md#status-cards) and [Ladder, feed and meter](cards-frames-panels.md#ladder-feed-and-meter). ## Labels and drawings A drawing is one object placed from the newest bar. The desk draws each of its levels as a dashed line across the whole pane and a knockout label that ends just left of the strike bars, so it never covers a cell of the board; the gamma flip is the pair below, and the largest GEX strike, max pain and the put wall repeat it in their own colours. The line is a `draw.line`; the label is a handle the live bar places in pixels from the price axis at the level's price, its text a slot the live bar writes. Reach for `draw.*` when one declaration is one object; for a mark on every signal bar use `render.text` or `render.shape`, and for an object the module moves and deletes later, a handle. Every look word is optional, and absent keeps the object's usual look. ![The gamma flip level: a violet dashed line across the price pane with its knockout label, #3 $88K | GF $87.5K, ending at the last candle, the line running on through the board's cells](/wrun/images/style-anything/labels.png) ```typescript output("t_prev", none, overlay); output("t_last", none, overlay); output("flip_price", none, overlay); string("flip_text", { max_bytes: 48 }); // "#1 $86K | Flip · all expiries $85.7K" // The gamma flip: one dashed line across the whole pane, placed from the newest bar. draw.line("flip_line", { x1: "t_prev", y1: "flip_price", x2: "t_last", y2: "flip_price", color: "theme.text", width: 1, line_style: "dashed", extend: "both" }); // Its knockout label: a label handle placed in pixels from the price axis (x) at the level's price (y), right-aligned // so its right edge sits just left of the bars. handles.label({ anchor: "right", align: "right", style: "knockout", font_weight: "medium" }); const tags: LabelHandle[] = [draw.label(0), draw.label(1), draw.label(2), draw.label(3)]; // the wall, the flip, max pain, the put wall; handle objects allocate once // On the live bar, with the text built in the line buffer; inset is the board's and the bars' width in pixels. tags[1].set(inset, flipPrice).text(str_flip_text_sb).color(theme.TEXT); ``` The words that matter: - A line: `width`, `line_style`, `extend` (`"none"`, `"left"`, `"right"`, `"both"`), `arrow`, `glow` with `glow_color`, `sticky_right`, `axis_label` and `opacity`. - A label: `style` from eight words (`plain`, `box`, `knockout`, `emblem`, `pill`, `badge`, `callout`, `price_label`; `knockout` hides what is behind the text), `align` (which edge of the text sits on x), `valign`, `background_color`, `border_color`, `border_width`, `corner_radius`, `padding`, `font_weight`, `font_family`, `emblem_shape` with `emblem_color`, `max_width` and `angle`. - A label handle: `handles.label(...)` takes the label words as the defaults every label handle starts from; `anchor: "right"` measures its x in pixels from the price axis while its y stays a price, and the setters (`set`, `text`, `color`) place, word and paint each one per run. - A box: `color` is the fill, then `border_*`, `shape: "ellipse"`, `gradient` with `gradient_direction`, and `text` with its `text_color`, `font_size`, `align`, `valign` and `padding`. - A renderer mark takes the same label `style` words plus `label_position`, `size`, `size_by` and a `color_by` ladder; `tooltip` is a template shown on any of them. The drawings are on [Run-level drawings](drawing-objects.md#run-level-drawings), every setter a handle takes on [Every look a handle takes](drawing-objects.md#every-look-a-handle-takes), the pixel anchors on [Pane pixel placement](cards-frames-panels.md#pane-pixel-placement), and the renderer marks on [Labels, tooltips, badges](labels-and-tooltips.md). ## Lines over time A line over time is an output: one number per bar that the chart draws as a line, an area, columns or marks. The desk's rolling CVD is a `histogram` coloured by a sign ladder, columns in the chart's down colour below zero and its up colour above, in a pane of its own that prints K and M on its axis. Reach for the output words first: they are the cheapest look, and every drawn output can carry an alert once the indicator is published. ![The rolling CVD histogram in its pane: violet columns below zero on the left turning green above zero on the right, the legend reading the indicator's name and the last value, the axis tag in green](/wrun/images/style-anything/lines.png) ```typescript input("buy", trades.volume, { side: "BUY", missing: "zero", description: "Aggressive buy volume" }); input("sell", trades.volume, { side: "SELL", missing: "zero", description: "Aggressive sell volume" }); output("cvd_sign", none, lower, { description: "0 while the rolling CVD is negative, 1 while positive: the histogram's palette index" }); output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors: ["theme.down", "theme.up"], width: 0.7, label: "Agg. Rolling CVD", format: "si", description: "Rolling cumulative volume delta: aggressive buys minus sells over the window" }); pane("cvd", { height_frac: 0.12, format: "si" }); // the Indicator's home pane: it carries the Indicator's name, so no title here ``` The words that matter: - The static look: `color`, `width`, `opacity`, `line_style`, `glow`, `z`; the per-bar ladders `color_by` with `colors` (or `color_packed_by`) and `width_by` with `widths`; `label` and `format` for the legend and the axis tag. - A line's shape: `smooth`, `step`, `gradient`, and `split` with `up_color`, `down_color`, `split_level`, `split_fill`, `split_base`. - An area's fill: `fill_color`, `fill_opacity`, `fill_gradient` with `gradient_mode`, or `fill_color_by` with `fill_colors`. - Columns: `width` as a share of the bar slot, `base`, `grading`, `stack`; a candle group: `candle_style`, `border_colors`, `wick_colors`, `border_width`. - Marks: `shape`, `location`, `char`, `fill`, `fill_opacity`; a level: `role: "guide"` with `align`, `pill_style`, `font_size`, `axis_label`, `axis_look`. Every output word is on [Styling](styling.md); the looks each plot kind takes are the table on [Lines, areas, columns, dots, marks](plotting.md#lines-areas-columns-dots-marks) and [Candles](plotting.md#candles); a band between two lines is a `range()` or a `fill()` ([Decisions to looks](styling.md#decisions-to-looks)). ## Price canvases A price canvas is drawn on the price chart from cells the chart already serves or from a frame the module writes. The desk's strike matrix is a `plot.matrix`: one row per strike on the price axis, one column per expiry, each cell tinted on a diverging scale around zero. Heatmaps, footprints, TPO letters and anchored profiles are the other four. Reach for a canvas when the picture is a grid over price: a cell per bar and price row, or a cell per strike and expiry. The board sits on its strikes' prices, so strikes outside the candles' own range stay clipped until you zoom the price axis out by dragging it, as the original's author did; no word widens the range. ![The GEX by expiry board docked against the price axis: the expiries 0DTE, 06OCT, 07OCT and 08OCT across the header, the strikes down the price column, every cell a signed dollar amount tinted teal for calls and violet for puts by size, the at-the-money row outlined in amber](/wrun/images/style-anything/canvases.png) ```typescript const board = frame("board", { max_bytes: 32768 }); // the matrix: one row per strike, one column per expiry // The strike by expiry board against the price axis: a diverging palette centred on zero, puts in the chart's down // colour and calls in its up colour, the tint by the square root of the cell's size, signed dollars in every cell, the // at-the-money row outlined in amber. plot.matrix({ name: "gex_board", frame: board, dock: "right", column_width: 66, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "usd", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.accent", label: "Exposure by expiry", tooltip: "{{column}}: {{value:usd}} at {{price}}" }); ``` The frame the module sends is `{ prices, cells, cols, title, highlight }`: the strikes ascending, one cell row per strike with `null` where an expiry lists no open interest, the column names (`"0DTE"`, `"05OCT"`, ...), the board's title and the at-the-money row to outline. The words that matter: - The scale: `palette` with `min`, `max`, `center`, `auto_quantile` and `scale` (`"linear"`, `"sqrt"`, `"log"`); `opacity` over every fill. - The grid: `column_width`, `row_max_px`, `header`, `price_column`, `cell_padding`, `grid_color`, `grid_width`, `grid_style`, `grid_lines`, the `border_*` words and `highlight_color`. - The type and numbers: `font_size`, `font_family`, `font_weight`, `align`, `text_color`, `header_text_color`, `format` with `decimals`, `signed` and `unit`; `tooltip` and `label` for the readout. - A heatmap adds `row_height`, `floor`, `cell_gap`, `behind_candles` and `labels`; a footprint `mode`, the `imbalance_*` words, `hide_zero`, `cell_metric`; a TPO `display`, `color_mode`, `letter_minutes` and `single_prints_color`; an anchored profile `span`, `mode`, `naked` and `extend`. Every canvas, word by word, is on [Price canvases](price-canvases.md); the matrix on [Strike matrices](price-canvases.md#strike-matrices). ## Panes A pane is a scale of the indicator's own: below the chart for a number with its own range, or over the candles on a hidden scale with `place: "price"`. The desk's right cell stacks three under the chart: the tiles at 0.18 of the chart, the curve at 0.25 with a maximize button and a stats row, and the indicator's own CVD pane at 0.12, mounted last beside the time axis; the three take 0.55, so the candles keep the rest, and the home pane carries the indicator's name, so it takes no title. Reach for a pane when a small-magnitude series would hug the axis floor on the price pane, or when two studies need scales of their own. ![The right cell top to bottom: the candles, the BTC Options tiles panel, the Deribit GEX curve panel with the Spot marker, callouts and caption, and the Options Dashboard CVD pane next to the time axis](/wrun/images/style-anything/panes.png) ```typescript const tileRows = frame("tile_rows", { max_bytes: 4096 }); const gexCurve = frame("curve_rows", { max_bytes: 16384 }); output("regime_sign", none, overlay); output("cvd_sign", none, lower); string("regime_text", { max_bytes: 48 }); output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors: ["theme.down", "theme.up"], width: 0.7, label: "Agg. Rolling CVD", format: "si", description: "Rolling cumulative volume delta: aggressive buys minus sells over the window" }); pane("cvd", { height_frac: 0.12, format: "si" }); // the Indicator's home pane: it carries the Indicator's name, so no title here render.legend("regime_entry", { text: "regime_text", color_by: "regime_sign", colors: ["theme.down", "theme.up"] }); panel.tiles({ name: "tiles", title: "Options, Deribit", x: "category", place: "below", frame: tileRows, columns: 4, accent: "auto", positive_color: "theme.up", negative_color: "theme.down", format: "usd", signed: true, hover_card: true, height_frac: 0.18 }); panel.line({ name: "gex_curve", title: "Deribit GEX (Hypothetical Spot)", x: "number", place: "below", frame: gexCurve, series: [{ name: "Net GEX", color: "theme.text", width: 2 }], smooth: true, fill_mode: "signed", fill_positive_color: "theme.up", fill_negative_color: "theme.down", fill_fade: true, x_format: "usd", x_decimals: 1, format: "usd", signed: true, decimals: 0, x_title: "Spot", y_zero: true, legend_style: "none", hover_card: true, height_frac: 0.25, maximize: true, stats_row: true }); ``` The words that matter: - `title` heads the pane's legend, and `{{name}}` reads a setting; the indicator's home pane carries its name instead. - `place: "below"` stacks the pane under the chart in declaration order; `place: "price"` draws its outputs over the candles on a hidden scale. - `height_frac` is the pane's share of the chart, on a pane and on a panel alike; `padding: [top, bottom]` sets the autoscale margins; `min` and `max` hold either end. - `scale` is `"linear"`, `"log"`, `"percent"` or `"indexed"`, and `invert: true` flips the axis. - `format`, `decimals`, `signed` and `unit` print the axis ticks; `pane: ""` on an output puts it in the pane. Every pane word is on [Panes](plotting.md#panes). ## Theme and the Style page Every colour word takes a theme token beside a hex colour, and a token follows the chart: the board's zero cell takes `theme.bg`, the legend entry `theme.muted` and the neutral tile values `theme.text`, so the desk reads on a dark and a light chart alike, re-resolved on a theme switch with no rerun, while every hex colour stays as written on both. A `"@name"` in place of a colour, a line style or a docked profile's key hands that spot to a setting, and the dialog's Style page draws the user's own controls for every drawn output without a declaration. Two chart-level flags finish the set. ![The same eight tiles on a dark chart and on a light chart side by side: the panel surface follows the theme, the neutral values read white on dark and black on light, and the teal and rose values keep their colours](/wrun/images/style-anything/theme.png) ```typescript string("spot_text", { max_bytes: 32 }); const board = frame("board", { max_bytes: 32768 }); const tileRows = frame("tile_rows", { max_bytes: 4096 }); // The words that follow the chart's theme: theme.muted on the legend entry; theme.down and theme.up at the palette's // ends around theme.bg (the board's zero cell takes the chart background, dark or light); theme.up and theme.down on // the tiles' signed values, theme.text on the neutral ones in the frame. render.legend("spot_entry", { text: "spot_text", color: "theme.muted" }); plot.matrix({ name: "gex_board", frame: board, dock: "right", column_width: 66, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "usd", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.accent", label: "Exposure by expiry", tooltip: "{{column}}: {{value:usd}} at {{price}}" }); panel.tiles({ name: "tiles", title: "Options, Deribit", x: "category", place: "below", frame: tileRows, columns: 4, accent: "auto", positive_color: "theme.up", negative_color: "theme.down", format: "usd", signed: true, hover_card: true, height_frac: 0.18 }); ``` The point callouts in the curve's frame take a theme word per run (the peak `theme.up`, the trough `theme.down`, the flip `theme.text`), and the legend entry's `color_by` reads `theme.down` or `theme.up` off the regime's sign, so the words follow the chart's own up and down colours. The words that matter: - The seven tokens: `theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid`, `theme.accent`; every colour key on this page takes one, and so does a colour string inside a frame. - `"@name"` binds a spot to a setting: a `param.color` behind a colour, a `param.choice` behind a line style or a docked profile's word key, a `param.number`, `param.int` or `param.bool` behind a profile's number or switch. - `label`, `format`, `legend` and `visible` on an output shape its row on the Style page; every HUD gets a Look, a Position and a Show row of its own. - `chart.contrast_guard(false)` keeps the author's colours as written on a light chart; `chart.stack_handles(true)` stacks the indicator's corner groups under other indicators' groups. The tokens are on [Theme colours](styling.md#theme-colours), the bindings and the rows on [The Style page](../settings/style-page.md), and the packed form a module writes on [Colors kit](../functions/colors-kit.md#theme-tokens). ## The house look A HUD card with no `look`, a line, bars, histogram or scatter panel with no `chrome` and a heatmap with no `palette` draw the chart's house look ([HUD cards](hud-and-hover-cards.md#the-default-look), [panels](cards-frames-panels.md#the-default-look)). Its rules, to keep when you style a part yourself: - Sentence case: titles, labels and captions, never all capitals. - Horizontal hairlines only: a plot gets no frame and no vertical lines. - One accent, one use: the selected or now marker. - Colour means sign: up and down, or the series itself. - Legends are words and numbers: no swatches, chips or dots. - Theme words over hex: `theme.text`, `theme.muted`, `theme.up`, `theme.down` and `theme.bg` follow the chart, so a part reads on a dark and a light chart alike. ```typescript const gexCurve = frame("curve_rows", { max_bytes: 16384 }); output("net_gex", none); output("net_gex_chg", none); output("cvd_sign", none, lower); // Colour for sign only, in theme words: the down colour below zero, the up colour above. output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors: ["theme.down", "theme.up"], label: "Rolling CVD", format: "si" }); pane("cvd", { height_frac: 0.12, format: "si" }); // No chrome and no legend_style: value hairlines and the regular legend; the series in the text colour. panel.line({ name: "gex_curve", title: "Net GEX by spot", x: "number", place: "below", frame: gexCurve, format: "usd", series: [{ name: "Net GEX", color: "theme.text" }] }); // No look: the default look, its change in the up or down colour. render.hud("desk", { position: "top_right", title: "Options desk", tiles: [tile.value("Net GEX", "net_gex", { format: "usd", delta: "net_gex_chg", headline: true })] }); ``` ### When to reach for a look Reach for a `look`, a frame word or colours of your own when the card or panel is a branded or themed dashboard that should stand apart from the chart. Everywhere else, leave the words out and keep to the rules above. ## Every word The deep pages list every word with its range and what refuses: - [Plotting](plotting.md) and [Styling](styling.md): outputs, panes, ranges, fills, boxes and segments - [Drawing objects](drawing-objects.md) and [Labels, tooltips, badges](labels-and-tooltips.md): drawings, handles and renderer marks - [Cards, frames and panels](cards-frames-panels.md): tables, cards, panels, docked profiles, ladders, feeds and meters - [HUD and hover cards](hud-and-hover-cards.md) and [Legend](legend.md): the three surfaces that read the newest values - [Price canvases](price-canvases.md): heatmaps, footprints, TPO letters, anchored profiles and strike matrices # What the chart shows Three surfaces read the indicator's newest values and are drawn by the chart from declarations alone: the legend entry, a HUD card at one of the nine anchors, and the card that opens when the cursor rests on a legend entry, a HUD tile or a line. ## What it is The three share one vocabulary of blocks and one rule for text: a template in double braces, the alert placeholder style. The blocks are seven kinds, `value`, `rows`, `spark`, `gauge`, `meter`, `pill` and `chips`; on a HUD card they are the `tile.*` constructors, on a hover card the same constructors under the `block.*` name ([Blocks and tiles](hud-and-hover-cards.md#blocks-and-tiles)). Every tile and block reads the newest row, so a data-only output written per bar is the way to carry a delta or a regime onto the card. The declarations are erased before the compiler and ride the sheet alone: the module writes numbers and words per bar and never mentions a tile. | Home | What it shows | Declared with | | --- | --- | --- | | the legend entry | each output's `label` and its value in the output's `format`; words after the indicator's name; a slot's words or an output's value as an extra entry | `label`, `format`, `legend` on the output; `legend({ title })`; `render.legend` | | the hover card | the blocks the cursor opens on a legend entry, a HUD tile or a line; without one, the output's `tooltip`, else its label and value | `hover(handle, [block.*])`, or `hover: [...]` on an output, a `render.text` or a `render.label` | | the HUD card | a card of typed tiles at one of the nine anchors, one or two columns | `render.hud(name, { position, title?, columns?, tiles })` | ## Declare it - `legend({ title })`: the words after the indicator's name, `(14)` style; `{{length}}` reads a setting by name ([Legend](legend.md)). - `render.legend(name, { text?, value?, format?, color?, color_by?, colors? })`: an entry in the legend, a string slot's words (`text`) or an output's formatted value (`value`), in a static `color` or colored per bar by a ladder ([Legend](legend.md)). - `render.hud(name, { position, title?, columns?, tiles })`: a card at one of the nine anchors, one or two columns, its tiles from the kit ([HUD cards](hud-and-hover-cards.md#hud-cards)). - `hover: [...]` on an output, `render.text` or `render.label`, or `hover(handle, [...])` at the top level: the card the cursor opens ([Hover cards](hud-and-hover-cards.md#hover-cards)). `badges` names another output, a ladder whose labels become chips on the card. A basis line with a titled legend, a regime word in the legend, a four-tile HUD and a hover card with four block kinds: ```typescript param.int("length", 20, { min: 2, max: 500 }); param.int("rsi_length", 14, { min: 2, max: 200, label: "RSI length" }); // label, format and tooltip shape the legend entry; the handle names the output for hover() below. const basis = output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); // Data-only: the delta a tile shows beside the basis, and the regime ladder (0 under, 1 over). output("basis_chg", none); output("state", none); string("regime", { max_bytes: 16 }); // The legend reads " (20)" from the length setting; the entry below it is the slot's word, colored by the ladder. legend({ title: "({{length}})" }); render.legend("regime_entry", { text: "regime", color_by: "state", colors: ["#ef5350", "#26a69a"] }); // A card of four tiles in the top-right corner. render.hud("board", { position: "top_right", title: "Basis", columns: 2, tiles: [tile.value("Basis", "basis", { format: "price", delta: "basis_chg" }), tile.spark("RSI", "rsi", { bars: 32 }), tile.gauge("RSI level", "rsi", { min: 0, max: 100, format: "int" }), tile.pill("Regime", "regime", { color_by: "state", colors: ["#ef5350", "#26a69a"] })] }); // The card the basis line opens on hover: a lead value, rows, a meter, chips. hover(basis, [block.value("Basis", "basis", { format: "price", delta: "basis_chg" }), block.rows([["RSI", "rsi", "0.0"], ["Regime", "regime"]]), block.meter("RSI", "rsi", { min: 0, max: 100, marks: [30, 70] }), block.chips("regime")]); let sma = new Sma(20); let rsi = new Rsi(14); let basisValue: f64 = NaN; let prevBasis: f64 = NaN; function onStart(): void { sma = new Sma(i32(p_length())); rsi = new Rsi(i32(p_rsi_length())); } function onBar(): void { const close = bar.close(); prevBasis = basisValue; basisValue = sma.update(close); const rsiValue = rsi.update(close); if (isNaN(basisValue) || isNaN(rsiValue)) return; out_basis(basisValue); out_basis_chg(basisValue - prevBasis); out_rsi(rsiValue); const over = close > basisValue; out_state(over ? 1.0 : 0.0); sb_clear(); sb_text(over ? "over" : "under"); str_regime_sb(); } ``` ## What the chart draws ![the legend row: the name with its title suffix, then two labelled values](/wrun/images/wrun-legend.svg) ![a card of four tiles in the top-right corner: a value with its change, a sparkline, a dial and a chip](/wrun/images/wrun-hud.svg) ![the card a tile opens under the cursor: a value block with its delta](/wrun/images/wrun-hover-card.svg) The module above writes five numbers and one word per bar: the legend reads "Basis 20", then "Basis 64,120.5", "RSI 61.3" and the regime word in the ladder's color; the card in the corner shows the basis with its change, a sparkline, a dial and the regime chip; resting the cursor on the basis line, its legend entry or its tile opens the hover card. Which home answers which question: | You want | Use | Not | | --- | --- | --- | | a word or a value in the legend | `label` and `format` on the output, `render.legend` for a slot's words | a text renderer in the corner | | an answer when the cursor rests on a line or a tile | `tooltip` on the output, or a `hover` block list | a table the user has to read across | | a corner readout that does not move with price | a `render.hud` tile, or a one-cell `render.table` with a `position` | a label, which sits at its `x` and `y` | | a dashboard | `render.hud` with typed tiles, or `render.table` for a grid of words | many labels | ## Gotchas What a card cannot do: - A block takes its kind's options and nothing else, and a spark's `color` or a pill's `colors` is a literal: a setting paints an output, a renderer or a legend entry only ([Blocks and tiles](hud-and-hover-cards.md#blocks-and-tiles)). - A block or tile takes no `size`: the pixel size is a `render.text` and `render.label` option, and renderer text has no alignment option ([Labels, tooltips, badges](labels-and-tooltips.md)). - A presentation name used twice is refused. - The legend, the HUD and the hover card are drawn where the indicator runs in the browser. ## Related - [Style anything](style-anything.md): every part a wrun indicator draws can be styled, one real indicator part by part - [Legend](legend.md), [Hover cards](hud-and-hover-cards.md#hover-cards), [HUD cards](hud-and-hover-cards.md#hud-cards), [Labels, tooltips, badges](labels-and-tooltips.md), [Styling](styling.md), [Blocks and tiles](hud-and-hover-cards.md#blocks-and-tiles) - [Plotting](plotting.md): the outputs and renderers that draw on the time axis - [The settings dialog](../settings/overview.md): the dialog the same file lays out # Plotting A wrun indicator draws by declaring, not by calling: it declares `output(name, plot, panel, options)` once at the top of the file and writes one number per bar, and the chart draws that number as a line, a column, a mark, or a tint from the declaration. That is why the module never touches a color, and why every drawn output is a value an alert can follow once the indicator is published ([Alerts](../functions/alerts.md)). This page maps everything you might want to draw to its wrun form, and compiles the forms that exist. ## The map | You want | wrun form | Notes | | --- | --- | --- | | a plotted series | `output(name, line \| bar \| scatter \| candle, panel)` | the plot kind is the declaration, not a runtime argument | | a line | `output(name, line, panel, { color, width, line_style, opacity, glow, step, smooth, gradient, split })` | a filled line is `area`; `glow` is a soft halo in pixels ([Styling](styling.md)); `smooth` bends it into curves, `step` draws it as horizontal and vertical segments, `gradient` shades the stroke by height, `split` colours it above and below a level or by slope | | columns | `output(name, bar, panel, { width, base, grading, stack })` | one value per bar; `width` is a share of the bar slot (1 = columns touch), `base` the level they grow from, `grading` fades them by magnitude, `stack` stacks them on their siblings | | a histogram | `output(name, histogram, panel, { color_by, colors, corner })` | columns grow from zero (or from `base`); a sign ladder colors them; `corner` rounds them, in pixels | | candles | four consecutive `candle` outputs (open, high, low, close), or a box and a segment per bar | the chart draws the four as one candle; `candle_style` on the first output draws them hollow, as OHLC bars or as high-low bars; see below | | a mark on some bars | `output(name, shape, panel, { shape, shape_where, location, char, fill, fill_opacity, glow })` or `render.shape` | either picks the mark from ten shapes (`char` draws one character); `location` sits it above or below the bar or at the pane's edge | | several marks or a pie per bar | none: one thing per bar per renderer | a one-summary pie is a `panel.pie` snapshot; a per-level picture is a `plot.levels` frame ([Cards, frames and panels](cards-frames-panels.md)) | | text at a price | `render.text(name, { y, text, color, size, style?, align?, valign?, font_weight?, font_family? })` | one mark per bar whose slot was written; a `style` other than plain text draws each as a tag (`price_label`, `pill`, `callout`, `badge`, `box`, `knockout`, `emblem`) | | a price tag | `render.label(name, { x, y, text, style: "price_label" })` for one tag at the newest bar, or `render.text` with the same `style` for a tag per bar | a label's `style` is also `plain`, `pill`, `callout`, `badge`, `box`, `knockout` or `emblem` | | a corner readout | `render.label(name, { position, text, offset? })` pinned to one of the nine anchors, a one-cell `render.table(name, { rows: 1, cols: 1, cells, position })`, or a `render.hud` card with one tile | fixed position at one of nine anchors; the newest bar that wrote the slot wins | | an output on its own scale over the candles | `pane(name, { place: "price" })` and `output(name, plot, overlay, { pane: name })` | open interest or a cumulative delta drawn over price on a hidden scale of its own ([Panes](#panes)) | | several panes below the chart | `pane(name, { title, height_frac, scale, min, max, format })` and `output(name, plot, lower, { pane: name })` | up to four named panes, stacked in declaration order ([Panes](#panes)) | | a table | `render.table(name, { rows, cols, cells, position })` for a grid of words, styled by the same literal (widths, fills, lines, per-cell colours that follow an output; [Styled tables](cards-frames-panels.md#styled-tables)); `render.hud(name, { position, tiles })` for a card of typed tiles | cells are string slots; tiles read outputs and slots | | a rectangle | `box(...)` per bar, `draw.box` for one object, or a box handle | [Drawing objects](drawing-objects.md) | | a grid of mini charts pinned to the viewport | none | a dashboard is a `render.table` or a `render.hud` card; a snapshot panel below the chart is a `panel.*` frame ([Cards, frames and panels](cards-frames-panels.md)) | | a statistics-strip row | `render.stats_row(name, { output, title, format, polarity })` | a strip row over an output | | a heatmap, a curve over a category or an index, tiles | `panel.heatmap`, `panel.line` over a category or index x, `panel.tiles` | a frame snapshot in its own pane below the chart ([Cards, frames and panels](cards-frames-panels.md)) | | a horizontal level | `output(name, line, panel, { role: "guide", align?, pill_style?, font_size?, axis_label?, axis_look? })` written to the constant every bar | one full-width line at the output's last value, out of the legend; `align` puts its label on the line, `axis_label: true` on the axis (`axis_look` the tag's look); or a segment `from: 0, to: 1` | | a background tint | `render.bgcolor(name, { where, color, color_by, colors, width?, line_style? })` | a tint per bar where the gate is nonzero; with `width` a vertical line per gated bar instead of a band | | colored candles | `render.barcolor(name, { where, color, color_by, colors })` | the bar's own candle tinted where the gate is nonzero | | a fill between two lines | `range("a", "b", { color })` between two drawn outputs for a band with edges, `fill("a", "b", { color, opacity })` for the interior only, or a `box` per bar | the chart draws the range as a band with its two edges and the fill as shading with none ([Styling](styling.md)) | | a name and a description | the output `name` and `description` | names are unique per family by construction | ## Outputs `output(name, plot, panel, options)` returns a handle a `box` or `segment` can name; a bare statement discards it. - `plot`: `line`, `bar`, `area`, `histogram`, `candle`, `shape`, `scatter`, or `none` for a data-only output (computed, never drawn: the building block for gates, palettes, and shape coordinates). - `panel`: `overlay` (the price pane) or `lower` (its own pane). Put small-magnitude series (oscillators, percentages, counts) in `lower`; a z-score on the price axis hugs the axis floor. - Static style: `color`, `width`, `opacity` (0..1), `line_style` (`"solid"`, `"dashed"`, `"dotted"`), `glow` (a halo in pixels on a line, an area, columns, candles or marks), `z` (the paint order inside the pane, an integer -10..10), `description` (documents the output). A colour is `"#rrggbb"`, `"#rrggbbaa"` or a theme token such as `"theme.up"` ([Styling](styling.md#theme-colours)). - Numbers: `format` (`price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd`, `auto`), `decimals` (0..8), `signed` and `unit` (printed after the value; unbounded on an output, as it always was) shape the legend, the hover card and the axis tag; `decimals` and `signed` need `format`, and a `unit` prints only beside one ([Styling](styling.md#placement-per-output)). - Per-bar color: `color_by: ""` plus `colors` (at least two entries). Each bar's value indexes the palette (floored); a finite value outside the palette takes entry 0, and a non-finite one draws the static color. `color_packed_by: ""` reads a packed colour the module computes per bar instead (never beside `color_by`). A `shape` output takes either ladder too: each mark in its bar's colour. - Per-bar width: `width_by` plus `widths` (1..10 entries, each 0.5..20), the same ladder for line width. On `bar` and `histogram` outputs `width` and `widths` are a share of the bar slot (`widths` entries from 0.05): 1 means the columns touch, 0.5 half the slot, 2 overlap. - Gated marks: `plot: shape` with `shape_where: ""` draws a mark at the output's value only on bars where the gate is nonzero. - Axis tags: `axis_label: true` tags this output's last value on the price axis (absent, only the first mounted output is tagged); `axis_name: true` adds the indicator's name to that tag (plus the output's label when several outputs are tagged); `price_line: true` draws a dotted line across the pane at the last value. The three are refused on a data-only output. On a guide, `axis_look` picks the tag's look: `"pill"` (the default), `"quiet"` or `"words"` ([Lines, areas, columns, dots, marks](#lines-areas-columns-dots-marks)). - `pane: ""` puts the output in a named pane, declared with `pane(...)` below; absent, a `lower` output lands in the default pane. - `displacement_bars` (an integer in -500..500) makes the chart draw the series shifted left or right without changing its values; past the loaded edge it extrapolates at the bar spacing. `displacement_bars_by: { param: "", scale?: 1, offset?: 0 }` reads the shift from a setting instead: `round(scale * value + offset)` bars, clamped to -500..500, which wins over `displacement_bars` while the setting is a finite number. An output cannot color, widen, or gate itself: the palette index and the gate must be different outputs. The rest of the vocabulary is on the [Styling](styling.md) page. The legend shows each output's `label`, or its name read as words when there is none (`bb_upper` reads "Bb upper"), and its value in the output's `format`; `legend: false` keeps an output out of the legend, and `legend({ title: "..." })` adds words after the indicator's name in the legend ([Legend](legend.md)). ## Panes `pane(name, options)` declares a pane of the indicator's own, at most four per indicator, and `pane: ""` on an output puts the output in it. The name `"lower"` styles the default pane; any other name is a new pane below the chart, stacked in declaration order, the default pane first unless it is declared later. These time-series panes sit at the bottom of the indicator's stack, next to the time axis; the indicator's panels (`panel.line`, `panel.bars` and the rest, on [Cards, frames and panels](cards-frames-panels.md#panel-words)) stack above them. A declared pane with nothing drawn in it is refused, and so is a pane beside a declared overlay, with one exception: beside `display({ overlay: "offchart" })` the indicator lives in the default pane, so `pane("lower", { format: "0.00" })` formats that pane's axis (`format`, `decimals`, `signed` and `unit` only; any other pane or word is refused). The options, every one optional: ```typescript pane("rsi", { title: "RSI {{period}}", height_frac: 0.2, min: 0, max: 100 }); pane("oi", { place: "price", scale: "log", format: "si" }); output("rsi", line, lower, { pane: "rsi", color: "#7c3aed" }); output("oi", line, overlay, { pane: "oi", color: "#f59e0b" }); ``` - `title` (1..40 characters, `{{param}}` reads a setting): the pane's legend title. An indicator that homes below the chart (no drawn output on the price pane) keeps its own name on the pane holding its first drawn output, so that pane takes no title. - `place`: `"below"` (the default) or `"price"`. A pane placed on price draws its outputs over the candles on a hidden scale of their own (open interest or a cumulative delta on price); its outputs declare `overlay`, a pane placed below takes `lower` outputs, and the pair must match. - `height_frac` (0.05..0.6): the pane's share of the chart height, refused on a pane placed on price. Absent, a pane below an on-price indicator takes 0.22 and an indicator that homes below keeps the chart's default pane size. - `scale`: `"linear"` (the default), `"log"`, `"percent"` or `"indexed"`; `invert: true` flips the axis; `padding: [top, bottom]` (each 0..0.4) sets the autoscale margins; `min` and `max` hold either end of the autoscale (RSI: `min: 0, max: 100`, `min` below `max`; a log scale refuses `min` at or below 0). Dragging the axis by hand still works. - `format`, `decimals`, `signed`, `unit`: the pane's axis ticks, the same four words an output takes (`decimals`, `signed` and `unit` need `format`). Absent, a lower pane prints K, M and B from 1,000 and its own precision below that. An inverted pane turns a loss into something that hangs: write a drawdown as a positive percent and flip the axis, so zero sits at the top of the pane and the deepest loss reaches lowest, with the running peak drawn over price above it. The pane keeps a title because the indicator homes on the price pane. ```typescript output("peak", line, overlay, { color: "theme.muted", line_style: "dotted" }); pane("dd", { title: "Drawdown", height_frac: 0.18, invert: true, min: 0, padding: [0.02, 0.1], format: "%", decimals: 1 }); output("drawdown", area, lower, { pane: "dd", color: "#ef4444", fill_color: "#ef4444", fill_opacity: 0.25 }); ``` Ranges, fills, boxes, segments and renderers follow the pane of the output they anchor to, and a card, feed or meter with `panel: "lower"` sits in the indicator's lower pane too. ## Lines, areas, columns, dots, marks A line is a `line` output; a filled line is `area`. Columns are `bar`, and a `histogram` is columns grown from zero, colored per bar through a `color_by` ladder over a sign output (`value >= 0 ? 1 : 0`); `base` grows the columns from another level instead (`colors[0]` at or above it, `colors[1]` below). Dots are `scatter`. A mark on some bars is a `shape` output plus a `shape_where` gate: write the price every bar and let the gate decide which bars draw. A level such as 70 is a guide: a `line` output with `role: "guide"` written to `70` on every bar, drawn as one full-width line at its last finite value, kept out of the legend and inside the pane's autoscale (an alert can still follow it). `align` (`"left"`, `"center"`, `"right"`) puts the output's label on the line, `pill_style` (`"filled"`, the default, or `"outlined"`) and `font_size` (6..64) dress that label, and `axis_label: true` puts the value and the label on the axis instead (never both). `axis_look` dresses that axis tag: `"pill"` (the default) is the price pill with the label in a flag beside it, `"quiet"` one soft capsule holding the label and the price, `"words"` the price on the axis with the label in words just above the line; it needs `role: "guide"` and `axis_label: true`, and a setting can pick it (`axis_look: "@name"`, [The Style page](../settings/style-page.md)). A chart that does not know the word draws the pill. A guide takes no `color_by`, `color_packed_by`, `width_by` or `price_line`. The looks a line, an area, a column and a mark take beyond colour and width (the words are opt-in; absent, the output draws as it always has): | Plot | Words | What they draw | | --- | --- | --- | | `line` | `step: true` | horizontal then vertical segments (trailing stops, funding steps); refused beside `smooth` | | `line`, `area` | `smooth: true` | the line (and an area's edge) bent into curves | | `line` | `gradient: [...]` | the stroke shaded by height, 2 to 8 colours listed from the top of the pane to the bottom; never beside `color_by`, `color_packed_by` or `split` | | `line` | `split: "level" \| "slope"`, `up_color`, `down_color`, `split_level?`, `split_fill?`, `split_base?` | `"level"`: `up_color` above `split_level` (default 0), `down_color` below, and `split_fill: true` shades down to `split_base` (default `split_level`); `"slope"`: `up_color` while rising, `down_color` while falling; both colours are required with `split` | | `area` | `fill_color`, `fill_opacity`, `fill_gradient: [...]`, `gradient_mode` | the fill's own colour (default the line colour) at `fill_opacity` (0.4 on a flat fill, 1 on gradient stops), or 2 to 8 stops top to bottom laid over `"pane"` (the default), `"fill"` or `"line"`; `fill_color` and `fill_gradient` exclude each other | | `area` | `fill_color_by` + `fill_colors`, or `fill_color_packed_by` | the fill coloured per bar by its own ladder (name the line's `color_by` output to follow the line); `fill_opacity` and `opacity` multiply each colour | | `bar`, `histogram` | `width`, `base`, `grading: "linear" \| "square"`, `stack: ""` | `width` as a share of the bar slot; `base` the level the columns grow from; `grading` fades each column by its magnitude within the visible range; bars sharing a `stack` name stack in declaration order, positives above 0 and negatives below (never beside `base`, and every member on one pane) | | `shape`, `scatter` | `shape`, `location`, `char`, `font_family`, `fill`, `fill_opacity` | `shape` picks the mark (`circle`, the default, `cross`, `triangle_up`, `triangle_down`, `diamond`, `arrow_up`, `arrow_down`, `flag`, `square`, `char`); `location` is `"absolute"` (the default), `"above_bar"`, `"below_bar"`, `"top"` or `"bottom"`; `shape: "char"` with `char` (one character) draws that character in `font_family` (`ui`, `mono`, `serif`, `rounded`); `fill: false` draws the outline only and `fill_opacity` fades the interior, neither on a `char` mark | | every drawn plot | `glow`, `opacity`, `z` | a halo in pixels; the opacity, which now fades every colour the output draws (ladders, packed colours, a column's sign pair, a candle's colours, marks, gradient stops); the paint order inside the pane | `triangle_down` points down (apex at the bottom), `triangle_up` up. ```typescript param("fast", 9, { min: 1, max: 200 }); param("slow", 21, { min: 2, max: 400 }); output("fast", line, overlay, { color: "#2563eb", width: 2, description: "Fast average, a line" }); output("slow", area, overlay, { color: "#94a3b8", opacity: 0.3, description: "Slow average, drawn as an area" }); output("cross_mark", shape, overlay, { color: "#16a34a", shape_where: "crossed", description: "A mark on the low of each bullish-cross bar" }); output("crossed", none, overlay, { description: "1 on the bar the fast average crosses above the slow: the mark's gate" }); output("volume", bar, lower, { color: "#4ecdc4", description: "Volume as bars" }); output("delta", histogram, lower, { color_by: "delta_sign", colors: ["#ef5350", "#26a69a"], description: "Fast minus slow as columns, colored by sign" }); output("delta_sign", none, lower, { description: "0 negative, 1 positive: the histogram's palette index" }); output("spread", scatter, lower, { color: "#f97316", description: "Close minus fast, as dots" }); output("rsi", line, lower, { color: "#7c3aed", width: 2, description: "RSI" }); output("overbought", line, lower, { color: "#ff0000", width: 1, line_style: "dashed", description: "The 70 level, written on every bar" }); let fast = new Sma(9); let slow = new Sma(21); let rsi = new Rsi(14); const cross = new Cross(); function onStart(): void { fast = new Sma(i32(p_fast())); slow = new Sma(i32(p_slow())); rsi = new Rsi(14); } function onBar(): void { const close = bar.close(); const low = bar.low(); const volume = bar.volume(); const fastValue = fast.update(close); const slowValue = slow.update(close); const rsiValue = rsi.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; const delta = fastValue - slowValue; out_fast(fastValue); out_slow(slowValue); out_cross_mark(low); out_crossed(crossed == 1 ? 1.0 : 0.0); out_volume(volume); out_delta(delta); out_delta_sign(delta >= 0.0 ? 1.0 : 0.0); out_spread(close - fastValue); out_rsi(rsiValue); out_overbought(70.0); } ``` `cross_mark` is written on every bar (the bar's low) and drawn only where `crossed` is `1`. The gate is itself an output, so a declared `alert` can fire on it ([Alerts](../functions/alerts.md)). A two-line fill colored by sign (a momentum fill) is this `delta` histogram, or a `range()` between the two lines with a two-entry `colors` sign palette ([Styling](styling.md)). The other looks in the table, one coherent look per declaration. An area's fill can fade: list the stops top to bottom and lay them over the fill's own extent, so the colour is strongest at the line and gone at the floor; `axis_name` puts the indicator's name on the axis tag beside the value. ```typescript // Cumulative delta as an area: amber at the line, nothing at the pane floor, the indicator's name on the axis tag. output("cvd", area, lower, { color: "#f59e0b", width: 2, smooth: true, fill_gradient: ["#f59e0b", "#f59e0b00"], gradient_mode: "fill", fill_opacity: 0.9, axis_label: true, axis_name: true, format: "si" }); ``` When the line already follows a ladder, the fill can follow the same one: name the ladder output again on `fill_color_by` and give `fill_colors` a rung per colour, so the edge and the fill switch together. ```typescript // RSI as an area: oversold, neutral and overbought are the three rungs of one ladder, read by the edge and by the fill. output("rsi", area, lower, { color_by: "zone", colors: ["theme.up", "theme.muted", "theme.down"], fill_color_by: "zone", fill_colors: ["theme.up", "theme.muted", "theme.down"], fill_opacity: 0.3, smooth: true }); output("zone", none, lower, { description: "0 under 30, 1 between, 2 over 70: the index both ladders read" }); ``` A split line colours itself around a level or by slope, and `split_fill` shades between the line and `split_base`, so an oscillator reads as a two-tone area that reaches the floor instead of stopping at the split level. ```typescript // A money flow oscillator on a 0..100 pane: green above 50, red below, the shading hanging from the line down to 0. output("mfi", line, lower, { width: 2, smooth: true, split: "level", split_level: 50, up_color: "theme.up", down_color: "theme.down", split_fill: true, split_base: 0 }); ``` Columns that share a `stack` name pile up in declaration order, so two volumes become one column per bar, the second share on top of the first; `grading` fades the small columns. ```typescript // Buy and sell volume piled into one column per bar. output("buy_volume", bar, lower, { color: "theme.up", width: 0.8, stack: "volume", grading: "linear" }); output("sell_volume", bar, lower, { color: "theme.down", width: 0.8, stack: "volume", grading: "linear" }); ``` A mark can be softened and lit: `fill_opacity` thins its interior and `glow` puts a halo around it (`render.shape` takes the same two words), which keeps a signal visible without hiding the candle under it. ```typescript // A faded diamond with a halo above each signal bar. output("signal_mark", shape, overlay, { shape: "diamond", shape_where: "fired", location: "above_bar", color: "#f59e0b", fill_opacity: 0.4, glow: 6 }); output("fired", none, overlay, { description: "1 on the bars that fire the signal: the mark's gate" }); ``` A mark can also be a character: `shape: "char"` with `char` draws that one character in `font_family`, here under each bar that crosses a displaced average whose shift follows a setting through `displacement_bars_by` ([Outputs](#outputs)). ```typescript param.int("shift", 5, { min: -50, max: 50, label: "Shift (bars)" }); // A displaced average, and a character mark under each bar that crosses it. output("dma", line, overlay, { color: "#38bdf8", width: 2, displacement_bars_by: { param: "shift" } }); output("cross_mark", shape, overlay, { shape: "char", char: "✕", font_family: "mono", shape_where: "crossed", location: "below_bar", color: "theme.text" }); output("crossed", none, overlay, { description: "1 on the bar the close crosses the displaced average: the mark's gate" }); ``` Columns can grow from a level other than zero, and a guide's on-line label can be an outlined pill rather than a filled one: RSI as columns from 50, the sign pair colouring them above and below it, with the 70 level labelled on the left. ```typescript // RSI as columns grown from 50, and the 70 level as a guide with an outlined pill. output("rsi_bars", histogram, lower, { base: 50, colors: ["theme.up", "theme.down"], width: 0.6, grading: "square" }); output("overbought", line, lower, { role: "guide", align: "left", pill_style: "outlined", font_size: 10, color: "theme.muted", line_style: "dashed" }); ``` A level that names itself on the price axis can wear a quieter tag than the pill: the two edges of a move, each a guide written to its price on every bar, tagged with its label and price in one soft capsule. ```typescript // The move's two edges as levels, each tagged on the axis with its label and price in one soft capsule. output("move_high", line, overlay, { role: "guide", label: "Move high", axis_label: true, axis_look: "quiet", color: "theme.muted" }); output("move_low", line, overlay, { role: "guide", label: "Move low", axis_label: true, axis_look: "quiet", color: "theme.muted" }); ``` ## Candles An output is one number per bar, so a candle takes four: declare four consecutive `candle` outputs in the order open, high, low, close, and the chart draws them as one candle, colored by the first output's `colors` (bullish, then bearish) or its `color_by` ladder. A `candle` output that does not start four consecutive candle outputs is refused when the chart draws it ("candle output '' must start four consecutive candle outputs (open, high, low, close)"). A derived candle series (Heikin Ashi, a synthetic bar) works either way. As four candle outputs: ```typescript output("ha_open", candle, overlay, { colors: ["#4caf50", "#f44336"] }); output("ha_high", candle, overlay); output("ha_low", candle, overlay); output("ha_close", candle, overlay); ``` The group's first output carries the candle look, and the other three refuse these words by name: `candle_style` is `"candle"` (the default), `"hollow"` (up candles outlined), `"ohlc"` (OHLC bars) or `"high_low"` (high-low bars); `border_colors` and `wick_colors` take one colour for both directions or `[up, down]` (absent, border and wick follow the body colour); `border_width` is 0..10 (default 1); `opacity` fades every candle colour, and `glow` puts a halo on the candles. The legend lists a candle group as one entry reading its open, high, low and close ([Legend](../presentation/legend.md)). Hollow candles over the chart's own: the first output carries the look, the borders and the wicks take colours of their own, and `opacity` lets the real bars show through the group. ```typescript // Heikin Ashi drawn hollow: up candles outlined, down candles filled, one grey wick colour for both. output("ha_open", candle, overlay, { colors: ["theme.up", "theme.down"], candle_style: "hollow", border_colors: ["theme.up", "theme.down"], wick_colors: ["theme.muted"], border_width: 1.5, opacity: 0.85 }); output("ha_high", candle, overlay); output("ha_low", candle, overlay); output("ha_close", candle, overlay); ``` Or as a body box and a wick segment per bar, which draws the candle from the same four numbers and gives each part its own color: ```typescript const haOpen = output("ha_open", none, overlay, { description: "Heikin Ashi open" }); const haHigh = output("ha_high", none, overlay, { description: "Heikin Ashi high" }); const haLow = output("ha_low", none, overlay, { description: "Heikin Ashi low" }); const haClose = output("ha_close", none, overlay, { description: "Heikin Ashi close" }); const bullish = output("bullish", none, overlay, { description: "1 when the smoothed close is above the smoothed open" }); const bearish = output("bearish", none, overlay, { description: "1 otherwise" }); // The body: one box per bar between open and close, one declaration per color. box("body_up", { top: haClose, bottom: haOpen, when: bullish, color: "#4caf50", opacity: 0.9, borderWidth: 0 }); box("body_down", { top: haOpen, bottom: haClose, when: bearish, color: "#f44336", opacity: 0.9, borderWidth: 0 }); // The wick: a vertical segment from the high to the low on the same bar. segment("wick", { yFrom: haHigh, yTo: haLow, color: "#9ca3af", width: 1 }); let prevOpen: f64 = NaN; let prevClose: f64 = NaN; function onBar(): void { const o = bar.open(); const h = bar.high(); const l = bar.low(); const c = bar.close(); const close = (o + h + l + c) / 4.0; // The first bar seeds the open from the raw bar; after that it is the previous smoothed midpoint. const open = isNaN(prevOpen) ? (o + c) / 2.0 : (prevOpen + prevClose) / 2.0; const high = Math.max(h, Math.max(open, close)); const low = Math.min(l, Math.min(open, close)); prevOpen = open; prevClose = close; out_ha_open(open); out_ha_high(high); out_ha_low(low); out_ha_close(close); out_bullish(close >= open ? 1.0 : 0.0); out_bearish(close < open ? 1.0 : 0.0); } ``` The four `none` outputs draw nothing on their own; the chart shows only the boxes and wicks. A data-only output is not offered as an alert condition, so write a drawn output (or declare an `alert` over the gate) for anything you want to alert on ([Alerts](../functions/alerts.md)). The recursion the sample writes by hand ships as `HeikinAshi` in `./sdk/ta-plus`: `update(open, high, low, close)` fills the fields `open`, `high`, `low`, `close` and works over another market's candles too ([Extra indicators](../functions/extra-indicators.md)). ## Text, labels, tables, strips, tints Text does not travel as an output. A `string("name", { max_bytes })` declaration adds a byte-capped slot the module writes once per bar in `onBar()` through its generated senders (nothing to import): build a line with `sb_clear()`, `sb_text("...")`, `sb_int(n)`, `sb_f64(x, decimals)` and send it with `str__sb()`, or send a whole string with `str_("...")`. Renderers then place the text: | Renderer | Draws | | --- | --- | | `render.text(name, { y, text, color?, size?, style?, align?, valign?, font_weight?, font_family?, size_by?, color_by? + colors? \| color_packed_by?, panel? })` | one text mark per bar whose slot was written, at (bar, `y`); plain text is placed by `align` and `valign`, sized per bar by `size_by`, coloured per bar by its ladder; a tag `style` (`price_label`, `pill`, `callout`, `badge`, `box`, `knockout`, `emblem`) takes the tag words instead: `label_position`, `background_color` (or `background_color_by` + `background_colors`), `border_color`, `corner_radius`, `emblem_shape`, `emblem_color` | | `render.label(name, { x, y, text, color?, size?, style?, align?, valign?, ...look })`, or `render.label(name, { position, text, offset?, ...look })` | ONE label at (`x`, `y`), `x` an output in epoch seconds, or pinned to one of the nine anchors by `position` and nudged by `offset` (`[x, y]` px, each -200..200, pointing inward from the anchored edges: a positive `x` moves a right-anchored label left, a positive `y` moves a bottom-anchored label up); the newest bar that wrote a nonempty slot (with finite `x` and `y`, when placed by them) wins; the look words are `background_color`, `border_color`, `corner_radius`, `padding` (0..64, default 4), `font_weight`, `font_family`, `emblem_shape`, `emblem_color`, `size_by` | | `render.table(name, { rows, cols, cells, position?, ...look, styles? })` | a grid of string slots (`rows * cols` names, row-major); the newest bar where every cell was written wins; the look keys (width, column widths, fills, lines, font, alignment, header rows) and `styles` (one entry per styled cell) are on [Styled tables](cards-frames-panels.md#styled-tables) | | `render.shape(name, { output, shape, where?, color?, color_by?, colors?, width?, location?, glow?, char?, font_family?, fill?, fill_opacity?, tooltip? })` | a shaped mark per bar at the output's value where the gate is nonzero, in `color`, or in the `colors` entry a `color_by` output picks per bar; `width` (px, any positive number; the engine clamps what it paints) is the mark size, `location` sits it `"absolute"`, `"above_bar"`, `"below_bar"`, `"top"` or `"bottom"`, `glow` adds a halo, `shape: "char"` with `char` draws one character in `font_family`, `fill: false` draws the outline only, `fill_opacity` fades the interior, `tooltip` is a template shown on the mark | | `render.stats_row(name, { output, title?, format?, polarity?, color?, colors?, color_by?, color_packed_by?, priority?, visible? })` | a row in the statistics strip under the price pane, one cell per bar; `colors` is `[bull, bear]` on a diverging row or the ladder `color_by` indexes; `priority` 1..3 (default 2) keeps a row's text longest as bars narrow; `visible: false` draws no row at all | | `render.bgcolor(name, { where, color?, color_by?, colors?, width?, line_style? })` | a background tint per bar where the gate is nonzero, static or by ladder; with `width` (0.5..10 px) a vertical line per gated bar through the pane instead of a tint, dashed by `line_style` | | `render.barcolor(name, { where, color?, color_by?, colors? })` | the bar's own candle (body and wick) tinted where the gate is nonzero, static or by ladder; untinted bars keep the chart's candle colors | `size` is an integer pixel count, 6..64 (`10` reads as small text, `16` as large). A shape's `color_by` + `colors` ladder follows the `bgcolor` rules: the output's value is floored into `colors`, a finite index outside the palette takes entry 0, a non-finite value draws no mark (the static `color` never substitutes), and either half without the other is refused. `position` on a table is one of nine anchors (`top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`). `format` and `polarity` on a stats row ride to the chart verbatim (`si`, `signedSi`, `percent`, `price`, `raw`; `magnitude`, `diverging`, `none`). `visible` on a stats row (default `true`) takes `true`, `false` or an `"@"` reference to a `param.bool`: the setting's default draws, the setting switches the row from the settings dialog, and while it is off the row draws nothing at all, not even an empty strip line. One setting may switch several rows. The strip's own look is one sheet key beside its rows, `stats_strip`: `grading` (the population each cell's heat is ranked against: `rolling`, the default, `daily`, `weekly`, `visible` or `whole`), `label_side` (`left` or `right`, the edge the label gutter sits on) and `theme` (`candle`, the chart's candle colours, or `teal_rose`, `viridis`, `inferno`, `blue_red`, `mono`). A `param.choice` paints a key through `style_targets` (`{ "path": ["stats_strip", "grading"] }`) and `style_values` over that key's words, with its default's word written in the key; the key exists only beside a stats row. A row's `color` bound to a `param.color` paints the pick, the default included; mark the target `"unset_at_default": true` and the chart removes the colour while the setting holds its default, so the strip's theme colours the row until the user picks one. Declaring a string slot or a renderer switches the derived sheet to the second runtime contract; the numeric outputs compute exactly as before. `style` on a text or label renderer picks its look, the same eight words on both: `plain` (text alone, placed by `align` and `valign`), `price_label` (the price tag), `pill` (a rounded chip at the value), `callout` (a leader line to its bar), `badge` (a dot in the label's color), `box` (a rounded box, the handle label's default), `knockout` (a box in the chart's background colour that hides what is behind the text) and `emblem` (a small mark before the text, its shape `emblem_shape`: `dot`, `square`, `diamond`, `triangle_up`, `triangle_down`). A tag look takes `label_position`, `background_color`, `border_color` and `corner_radius`; plain text takes `align` and `valign`; the two sets never mix on one renderer. `font_weight` (`normal`, `medium`, `bold`) and `font_family` (`ui`, `mono`, `serif`, `rounded`) apply to both. The label styles, the `tooltip` template and `badges` are on [Labels, tooltips, badges](labels-and-tooltips.md). A corner readout is a `render.label` with `position` (below), a one-cell table or a HUD card ([HUD and hover cards](hud-and-hover-cards.md#hud-cards)). A per-bar readout, a live label, a dashboard, a strip row, a background tint, and a candle tint together: ```typescript param("period", 20, { min: 1, max: 200 }); param("stretch", 2, { min: 0.1, max: 20, description: "Percent from the average that counts as stretched" }); output("average", line, overlay, { color: "#38bdf8", width: 2, description: "Simple average" }); output("bar_time", none, overlay, { description: "Bar open in epoch seconds, the label's x" }); output("stretch_pct", none, overlay, { description: "Close distance from the average, percent" }); output("stretched", none, overlay, { description: "1 while the close is stretched from the average" }); output("volume", none, overlay, { description: "Volume, shown in the strip" }); string("readout", { max_bytes: 32 }); string("tag", { max_bytes: 32 }); string("stretch_label", { max_bytes: 16 }); string("stretch_text", { max_bytes: 16 }); // A text mark on every stretched bar (the slot is left unwritten on quiet bars). render.text("stretch_mark", { y: "average", text: "readout", color: "#f59e0b", size: 10 }); // One label riding the newest bar, at the average. render.label("average_tag", { x: "bar_time", y: "average", text: "tag", color: "#38bdf8", size: 11 }); // A fixed-position 1x2 dashboard: the newest bar where both cells were written wins. render.table("stats", { rows: 1, cols: 2, cells: ["stretch_label", "stretch_text"], position: "top_right" }); // Volume as a statistics-strip row. render.stats_row("volume_row", { output: "volume", title: "Volume", format: "si", polarity: "magnitude" }); // A background tint on stretched bars. render.bgcolor("stretch_tint", { where: "stretched", color: "#f59e0b22" }); // The stretched bars' own candles, body and wick, in the same amber. render.barcolor("stretch_candles", { where: "stretched", color: "#f59e0b" }); let sma = new Sma(20); let threshold: f64 = 2.0; function onStart(): void { sma = new Sma(i32(p_period())); threshold = p_stretch(); } function onBar(): void { const close = bar.close(); const volume = bar.volume(); const barTime = bar.time(); const value = sma.update(close); if (isNaN(value)) return; const stretch = value == 0.0 ? NaN : ((close - value) / value) * 100.0; const stretched = Math.abs(stretch) >= threshold; out_average(value); out_bar_time(barTime); out_stretch_pct(stretch); out_stretched(stretched ? 1.0 : 0.0); out_volume(volume); if (stretched) { sb_clear(); sb_f64(stretch, 1); sb_text("%"); str_readout_sb(); } sb_clear(); sb_text("SMA "); sb_f64(value, 2); str_tag_sb(); str_stretch_label("stretch"); sb_clear(); sb_f64(stretch, 2); sb_text("%"); str_stretch_text_sb(); } ``` Leaving `readout` unwritten on quiet bars is the whole gating story for `render.text`: a slot not written that bar is absent, and an absent slot draws nothing. A price tag on every signal bar is the same renderer with `style: "price_label"`: each written bar's text sits at `y` as a price tag. A label the module moves, re-words, or deletes on a later bar is a label handle ([Drawing objects](drawing-objects.md)). ### Mark size `width` on a `render.shape` sets the mark's size in pixels, any positive number; left out, the chart draws its own default size. Two sizes of one mark grade a signal at a glance: ```typescript // Volume spikes marked under the bar: a large dot over three times the average volume, a small one over twice. param.int("length", 20, { min: 2, max: 200, label: "Average length" }); output("low", none, overlay, { description: "The bar low, where the marks sit" }); output("big", none, overlay, { description: "1 when volume is over three times its average" }); output("small", none, overlay, { description: "1 when volume is over twice its average but not three times" }); render.shape("big_spike", { output: "low", shape: "circle", where: "big", color: "#f97316", width: 12 }); render.shape("spike", { output: "low", shape: "circle", where: "small", color: "#f97316", width: 6 }); let average = new Sma(20); function onStart(): void { average = new Sma(i32(p_length())); } function onBar(): void { const volume = bar.volume(); const mean = average.update(volume); if (isNaN(mean) || mean <= 0.0) return; const ratio = volume / mean; out_low(bar.low()); out_big(ratio > 3.0 ? 1.0 : 0.0); out_small(ratio > 2.0 && ratio <= 3.0 ? 1.0 : 0.0); } ``` - **One renderer per size.** `width` is fixed in the declaration, so a large and a small dot are two `render.shape` lines over the same output, each with its own gate. - **Gates that never overlap.** `small` is 1 only between two and three times the average, so a bar never carries both marks. ## Fixed-position text Text that sits at a viewport anchor and does not move with price is a `render.label` pinned by `position` over a string slot the module rewrites on every bar, so the newest bar decides the text: `render.label("status", { position: "top_right", text: "status_text", offset: [12, 8], style: "box", background_color: "theme.bg" })`. With `position` the label needs no `x` and `y` (declaring them beside it is refused: a corner label is nudged by `offset`, not placed by coordinates, and each number of the offset points inward from the anchored edges), and its `style` is one of `plain`, `box`, `knockout`, `pill`, `badge` or `emblem` (`price_label` and `callout` belong to a label at a price). The other corner readouts are a one-cell `render.table` at that anchor (`render.table("status", { rows: 1, cols: 1, cells: ["status_text"], position: "top_right" })`) and a `render.hud` card with a `tile.pill` or `tile.value` at the same anchor ([HUD and hover cards](hud-and-hover-cards.md#hud-cards)). A label the module owns and moves is a handle ([Drawing objects](drawing-objects.md)). ## Legend, HUD and hover Three surfaces read the indicator's newest values and are drawn by the chart from declarations alone: the legend entry, a HUD card at one of the nine anchors, and the card that opens when the cursor rests on a legend entry, a HUD tile or a line. They share one vocabulary of blocks, and the rest of this section documents them: `legend({ title })`, `label`, `format` and `render.legend` on [Legend](legend.md); `hover(handle, [block.*])` and `badges` on [Hover cards](hud-and-hover-cards.md#hover-cards); `render.hud(name, { position, title?, columns?, tiles, look?, ... })` on [HUD cards](hud-and-hover-cards.md#hud-cards), with its surface and type words and the twelve looks a card can wear; every `block.*` and `tile.*` constructor, the colour, drawing, headline and height words of a tile, on [Blocks and tiles](hud-and-hover-cards.md#blocks-and-tiles); the three together, with a complete module, on [What the chart shows](overview.md). ## Ranges and panels A rectangle between two times and two prices: per bar it is a `box` between two outputs over a bar-offset span; for one object placed from the newest bar it is `draw.box` with four coordinate outputs, two of them epoch seconds from the `time` source; for a rectangle the module keeps, grows, and deletes it is a box handle ([Drawing objects](drawing-objects.md)). A heatmap, a curve over a category or an index, tiles, and a one-summary pie are frame-backed panels: `panel.heatmap`, `panel.line` over a category or index x, `panel.tiles` and `panel.pie`, each a JSON snapshot the module writes and the chart draws in its own pane below the price chart ([Cards, frames and panels](cards-frames-panels.md)). Viewport-pinned panels of raw bars and a variable number of marks per bar have no renderer: every output is one number per bar on the chart's time axis. For a dashboard use `render.table` over string slots; for a per-level picture use a `plot.levels` frame docked on the price axis, or the chart's own footprint view beside the wrun indicator. ## The name requirement A wrun indicator's outputs are unique by construction (a duplicate `output("sma", ...)` is refused in the editor's Console, `duplicate output name 'sma'`), the name is the legend entry (read as words), and `description` is the optional long text. Names follow one grammar across outputs, boxes, segments, renderers, and drawings, and share one namespace: a renderer cannot reuse an output's name. ## When to use which | You want | Use | Not | | --- | --- | --- | | a value someone could alert on | a drawn output, or a declared `alert` over a gate | a box or a label (decorations are never alert targets) | | a mark on some bars only | `plot: shape` with `shape_where`, or `render.shape` with `where` | a text renderer on every bar | | a live readout at the newest bar | `render.label` from a string slot | `render.text` (one mark per bar) | | text on every signal bar | `render.text` from a slot written on those bars | one label per signal | | a corner readout that does not move with price | a `render.label` with a `position`, a one-cell `render.table` with a `position`, or a `render.hud` tile | a label placed by `x` and `y` | | a dashboard | `render.hud` with typed tiles (and a `look`), or `render.table` for a grid of words | many labels | | a word or a value in the legend | `label` and `format` on the output, `render.legend` for a slot's words | a text renderer in the corner | | an answer when the cursor rests on a line or a tile | `tooltip` on the output, or a `hover` block list | a table the user has to read across | | a label the module moves or deletes later | a label handle (`draw.label(id)`) | a renderer, which cannot be moved | | a per-bar tint behind the bars | `render.bgcolor` | recoloring a line | | trend or regime colored candles | `render.barcolor` | a background tint fighting the candle for contrast | | a level | a `line` output with `role: "guide"` written to the constant | a drawing | | an oscillator and a second study in panes of their own | two `pane(...)` declarations and `pane` on their outputs | one crowded lower pane | # Styling How outputs draw. The rule that keeps a wrun indicator honest: outputs are numbers, some numbers are decisions, and declarations map decisions to looks. Styling lives in the `output(...)` options and in the `range()`, `box()` and `segment()` declarations at the top of the file, never in the module's code: the chart reads the declaration and draws it, and **Run** records it in the sheet it derives. A static look is one option per output; a look that changes per bar is a ladder, a data-only output whose floored value indexes a palette. What the user may change comes from the same declarations: a `param.color` bound to an output by name, and [the Style page](../settings/style-page.md) the dialog derives from the outputs. This page is the wrun vocabulary for each look (size, tooltips, z-order, palettes, gradients), and which looks have no form. Every part a wrun indicator draws can be styled; for a part-by-part walk through one real indicator, start with [Style anything](style-anything.md) and come back here for the vocabulary. ## Placement, per output - `plot`: `line`, `bar`, `area`, `histogram`, `candle`, `shape`, `scatter`, or `none` for a data-only output: computed, never drawn, the building block for gates and palettes below. On the chart `bar` and `histogram` both draw as columns and `shape` and `scatter` as marks; `candle` takes four consecutive outputs (open, high, low, close) that draw as one candle ([Plotting](plotting.md)). - `panel`: `overlay` (the price chart) or `lower` (a pane below it). Put small-magnitude series (probabilities, oscillators) in `lower`; an odds-scale line on the price axis hugs the axis floor. The `lower` outputs of an indicator that also draws on price share one pane below the chart unless `pane: ""` sends them to a pane declared with `pane(name, { title, place, height_frac, scale, invert, padding, min, max, format })`: up to four named panes, below the chart or, with `place: "price"`, over the candles on a hidden scale of their own ([Panes](plotting.md#panes)). - `z`: the paint order inside a pane, an integer -10..10 on an output, a `range`, a `fill` or a `box`. Absent, the engine's layer applies: tints 0, fills 1, lines, columns, bands, marks and boxes 2, text 3; ties keep declaration order. - Numbers: `format` names how the output's value prints in the legend, the hover card and its axis tag: `price` (the chart's price digits, or a lower pane's own step digits on its axis), `%` (the value with a percent sign), `si` (K, M, B, T at one decimal from 1,000, `5.4K`, and at most two decimals under 1,000 with trailing zeros dropped, `4`, `4.5`, `980`), `int`, `0`, `0.0`, `0.00`, `0.000` (fixed digits), `usd` (`$` with two decimals under 1,000, else `$1.2K`, `$1.2M`, `$1.2B`, `$1.2T` at one decimal, the sign before the `$`) and `auto` (six significant digits with `,` thousands). `decimals` (0..8) overrides the word's digits, `signed: true` puts a `+` on positives, and `unit` prints after the value once `format` is declared (an output's `unit` is not bounded, as it never was; keep it short, a host may cut a long one); `decimals` and `signed` without `format` are refused ("decimals needs format"). A `unit` on its own is recorded in the sheet as before and never printed. Without `format` the chart formats numbers itself: a lower pane prints K, M and B from 1,000 and its own precision below that, a value on the price pane prints at the chart's price precision. A pane's axis ticks take the same four words on `pane(...)`. ## Static style, per output One option per output, read from the declaration: ```typescript output("overbought", line, lower, { color: "#ff0000", width: 1, line_style: "dashed", description: "The 70 level, written on every bar" }); output("delta", histogram, lower, { color_by: "delta_sign", colors: ["#ef5350", "#26a69a"], description: "Fast minus slow as columns, colored by sign" }); // Red while the close is under the average, green (and three times as wide) while it is over. output("mid", line, overlay, { color_by: "regime", colors: ["#ef4444", "#22c55e"], width_by: "regime", widths: [1, 3] }); // The band between the two edges: dotted edge lines and a slate interior. range("band_hi", "band_lo", { color: "#94a3b8", edge_width: 1, edge_line_style: "dotted" }); // A curved line split around zero, shaded below it; a fill between the two edges with no edge lines of its own. output("osc", line, lower, { smooth: true, split: "level", up_color: "theme.up", down_color: "theme.down", split_fill: true }); fill("band_hi", "band_lo", { color: "theme.accent", opacity: 0.15 }); // The 70 level as a guide: one full-width line, labelled on the line, out of the legend. output("upper", line, lower, { role: "guide", align: "right", color: "theme.muted" }); ``` | Look | Option | What it draws | | --- | --- | --- | | a color | `color`, or a `colors` palette | the line, column or mark color | | a halo | `glow` | a soft halo in pixels on a line, an area, columns, candles, marks and scatter dots, and on a `render.shape` mark | | rounded columns | `corner` | rounded column corners on a histogram, in pixels | | transparency | `opacity` | 0..1 on an output, fading every colour it draws: a ladder's rungs, a packed colour, a column's sign pair, a candle's body, border and wick, marks and gradient stops; per box, per fill, per handle and per card too | | thickness | `width` | the line width; `widths` the per-bar ladder, 1..10 entries, each 0.5..20; on columns a share of the bar slot, `widths` entries from 0.05 (1 = the columns touch) | | a dash | `line_style` | `solid`, `dashed`, `dotted`; lines and areas take the dash, columns do not | | curves | `smooth` | a line, or an area's edge, bent into curves | | steps | `step` | a line as horizontal then vertical segments (a trailing stop, a funding step); never beside `smooth` | | a stroke shaded by height | `gradient` on a line | 2 to 8 colours from the top of the pane to the bottom; never beside `color_by` or `split` | | two colours around a level or by slope | `split`, `up_color`, `down_color`, `split_level`, `split_fill`, `split_base` | `"level"`: `up_color` above `split_level` (default 0) and `down_color` below, `split_fill` shading down to `split_base`; `"slope"`: `up_color` while rising, `down_color` while falling | | an area's fill | `fill_color`, `fill_opacity`, `fill_gradient`, `gradient_mode`, `fill_color_by` plus `fill_colors`, `fill_color_packed_by` | the fill's own colour (default the line's) at `fill_opacity` (0.4 flat, 1 on stops), or stops top to bottom over the pane, the fill or each column, or a colour per bar from its own ladder | | a fill between two lines | `fill(a, b, { color, opacity, opacity_by, color_by, colors, color_packed_by, z, behind_candles })` | the interior only, no edge lines, between two drawn outputs on one pane, its opacity per bar from an output with `opacity_by`; `behind_candles: true` paints it under the candles on the price pane | | a band's edges | `edge_width`, `edge_line_style` on a `range()` | both edge lines at an integer width 0..10 (`0` = no edge lines), solid, dashed or dotted | | a faded band | `gradient` on a `range()` | 2 to 8 colors, listed top to bottom, shading the interior vertically instead of a flat tint | | where the stops lie | `gradientMode` | `"pane"` (the pane height, the default), `"fill"` (the band's own vertical extent) or `"line"` (per column, from `upper` down to `lower`) | | a band's legend row | `legend`, `label` on a `range()` | `legend: false` drops the row; `label` names it | | columns from a level | `base` | columns grow from `base` instead of zero, `colors[0]` at or above it and `colors[1]` below | | columns faded by size | `grading` | `"linear"` or `"square"`: each column's alpha follows its magnitude within the visible range | | stacked columns | `stack` | bars sharing a stack name stack in declaration order, positives above zero and negatives below | | a candle's style | `candle_style`, `border_colors`, `wick_colors`, `border_width` on a candle group's first output | `"candle"`, `"hollow"`, `"ohlc"` or `"high_low"`; border and wick colours as `[both]` or `[up, down]`; the border width 0..10 | | the mark | `shape`, `location`, `char`, `font_family`, `fill`, `fill_opacity` | the shape (ten words, `char` one character in `font_family`); `"absolute"`, `"above_bar"`, `"below_bar"`, `"top"` or `"bottom"`; the outline only, or a faded interior | | a level | `role: "guide"`, `align`, `pill_style`, `font_size`, `axis_label`, `axis_look` | one full-width line at the output's last value, out of the legend; a label on the line (`"left"`, `"center"`, `"right"`; `"filled"` or `"outlined"`; 6..64 px) or on the axis, that tag a `"pill"` (the default), a `"quiet"` capsule or `"words"` | | paint order | `z`, `behind_candles` on a fill | `z` orders the layers inside the pane: an integer -10..10 on an output, a range, a fill or a box; absent, the engine's layer (tints, fills, lines and columns and bands and marks and boxes, text) in declaration order. `behind_candles: true` puts a fill under the candles instead | | a theme colour | `"theme.up"`, `"theme.down"`, `"theme.text"`, `"theme.muted"`, `"theme.bg"`, `"theme.grid"`, `"theme.accent"` | the chart's own colour, resolved when it paints and again on a theme switch ([Theme colours](#theme-colours)) | | a color per bar | `color_by` plus `colors`, or `color_packed_by` | each bar's value indexes the palette, or carries a packed colour | | a width per bar | `width_by` plus `widths` | the same ladder for line width | | an inset strip's colours | `color`, `colors`, `color_by`, `opacity` on `out.inset` | `colors` without `color_by` is a sign pair (up at or above zero, down below); with `color_by` the bar's ladder colour | | a HUD's look | `look` on `render.hud` | one of twelve presets, every word of which a declared word overrides ([HUD cards](hud-and-hover-cards.md#looks)) | `color` (or a `colors` palette), `width`, `opacity` (0..1), `line_style` (`solid`, `dashed`, `dotted`; lines and areas take the dash, columns do not), `glow` (a soft halo in pixels on a line, an area, columns, candles, marks and scatter dots), `corner` (rounded column corners, in pixels), and `description`, which documents the output in the sheet. A colour is `"#rrggbb"`, `"#rrggbbaa"` (the alpha in the last byte), a CSS colour name as before, or a theme token (below); `opacity` multiplies every colour the output draws, a ladder's rungs, a packed colour, a column's sign pair, a candle's border and wick and a gradient's stops included. The legend's and the Style page's words for an output come from `label` (the name read as words when absent) and its numbers from `format`, `decimals`, `signed` and `unit` (above); `legend: false` keeps an output out of the legend, `visible: false` starts it hidden, `visible_by: { size_unit: [codes] }` mounts it only on the markets whose size unit is listed ([Size units](../settings/sessions-and-units.md#the-dialog-and-the-lanes)), `price_line: true` draws a dotted line across the pane at its last value, `axis_label: true` tags that value on the price axis and `axis_name: true` adds the indicator's name to the tag ([Plotting](plotting.md)); on a guide, `axis_look` picks that tag's look. The looks a plot kind takes beyond these (`step`, `smooth`, `gradient` and `split` on lines; `fill_color`, `fill_opacity`, `fill_gradient` and the fill ladder on areas; `base`, `grading`, `stack` and `width` as a share of the bar slot on columns; `candle_style`, `border_colors`, `wick_colors` and `border_width` on a candle group; `shape`, `location`, `char`, `fill` and `fill_opacity` on marks; `role: "guide"` for a level) are the table on [Plotting](plotting.md#lines-areas-columns-dots-marks). The per-look reading of this vocabulary, with the decision rule, is [Decisions to looks](#decisions-to-looks). ## Theme colours Every colour word accepts a theme token beside the hex forms: `theme.up` and `theme.down` (the chart's candle colours), `theme.text` (the axis text), `theme.muted` (that text at 55 percent), `theme.bg` (the background), `theme.grid` (the grid lines) and `theme.accent` (the app's accent). The chart resolves a token when it paints and again when the theme switches, with no rerun, so a `"theme.text"` label reads on a dark and a light chart alike. A token rides every colour key of this page (outputs, ranges, fills, boxes, segments, renderers, drawings, handles, cards, HUDs, docked levels and panels), the colour strings inside a frame, and a packed colour the module writes (`toPacked(theme.UP)` from `./sdk/color`, [Colors kit](../functions/colors-kit.md#theme-colours)). A `param.color` default or preset stays a hex colour ("a colour param takes #rrggbb or #rrggbbaa; put the token on the colour key"), and a `theme.` word outside the seven is refused by name. Two chart-level flags ride beside the tokens: `chart.contrast_guard(false)` keeps the author's colours as written on a light chart (the chart otherwise darkens colours that would vanish there), and `chart.stack_handles(true)` stacks this indicator's corner-anchored handle groups below other indicators' groups instead of overprinting them ([Drawing objects](drawing-objects.md)). ## The Style page Every output you draw gets a row on the dialog's **Style** page without a declaration, and a spot the file binds to a setting (`color: "@basis_color"`, `line_style: "@style"`) is that setting's row instead, so a look never has two controls. The rows, the bindings and the browser-or-cloud rule are on [The Style page](../settings/style-page.md). ## Decisions to looks - Per-bar coloring: emit the decision as a data-only output (`none`), then on the styled output set `color_by: ""` plus a `colors` palette (at least 2 entries). Each bar's floored value indexes the palette; a finite value outside the palette takes entry 0, and a non-finite one draws the output's static color (entry 0 when the output declares no `color`). An output cannot color itself: the index expression is its own output. - Per-bar width: the color ladder's sibling. On the styled output set `width_by: ""` plus a `widths` ladder (1..10 entries, each 0.5..20); each bar's value indexes the ladder (floor; a finite out-of-range index takes entry 0). A non-finite value on either ladder draws that bar in the static style. Both halves or neither, each refused by name without the other. An output cannot set its own width. - Gated markers: a `shape` output with `shape_where: ""` renders only where the gate is nonzero. An output cannot gate itself. - Banded ranges: `range(upper, lower, options?)` names two DIFFERENT drawn outputs (by name, as strings; a `none` output is refused: "range references '', which is not a rendered output"). The chart draws a band: both edge lines at `edge_width` (an integer 0..10; `0` draws the band with no edge lines) and `edge_line_style` (`solid`, `dashed` or `dotted`), with a tinted interior in `color`. A `colors` palette plus `color_by` (a data-only output) tints the band per bar (floor; a finite out-of-range value takes entry 0); `color_by` requires `colors`. `colors` WITHOUT `color_by` is the band's sign palette (a momentum fill): entry 0 where `upper` plots above `lower`, entry 1 where it plots below. `gradient` (2 to 8 colors, listed top to bottom) shades the interior vertically instead of a flat tint, laid over `gradientMode`: `"pane"` (the pane height, the default), `"fill"` (the band's own vertical extent) or `"line"` (per column, from `upper` down to `lower`). `smooth` is a boolean smoothing hint. `legend: false` drops the band's own legend row and `label` names it (default: the upper edge's label); `z` sets its paint order. Declare as many ranges as needed; the same pair may repeat with different options. - Fills: `fill(a, b, options?)` shades the interior between two drawn outputs on one pane and draws no edge lines, so each line keeps its own look. Options: `color`, `opacity` (0..1, default 0.25), the `color_by` plus `colors` ladder or `color_packed_by` for a colour per bar (a non-finite rung draws no fill that bar), `opacity_by` for an opacity per bar, `z`, and `behind_candles`. `opacity_by` names a declared output whose value on each bar is that bar's opacity (0..1), with any colour mode; a non-finite value keeps `opacity`. `behind_candles: true` paints the interior under the candles on the price pane while the two lines stay above them; both sides must then draw on the price pane: no `pane` word, not the `lower` panel, in an indicator that sits on price. The two sides must be different drawn outputs on the same pane; `colors` without `color_by`, `color_by` without `colors`, `color_packed_by` beside `color_by`, an `opacity_by` that names no declared output, and `behind_candles` with a side on the lower pane or on a named pane, or in an indicator that lives in its own pane below the chart, are refused. A setting reaches a fill's opacity through `opacity_by`: the file writes the setting, scaled to 0..1, into a data-only output on every bar, and the fill reads it there. ```typescript param.int("cloudOpacity", 40, { min: 0, max: 100, label: "Cloud opacity" }); output("cloud_alpha", none); // the cloud's opacity on each bar, 0..1 fill("span_a", "span_b", { color_by: "cloud_side", colors: ["#22c55e", "#ef4444"], opacity_by: "cloud_alpha" }); // in onBar(): out_cloud_alpha(p_cloudOpacity() / 100.0); ``` A band can sit under the candles: `behind_candles: true` paints the interior beneath the bars, and the two averages still draw over them. ```typescript // SMA 20 and SMA 30 on the price pane, the band between them under the candles. output("fast", line, overlay, { color: "#22c55e" }); output("slow", line, overlay, { color: "#ef4444" }); fill("fast", "slow", { color: "#FFFF00", opacity: 0.45, behind_candles: true }); const sma20 = new Sma(20); const sma30 = new Sma(30); // in onBar(): out_fast(sma20.update(bar.close())); out_slow(sma30.update(bar.close())); ``` A packed colour skips the palette: the module writes a colour per bar into a data-only output (`toPacked` from the colour kit, [Colors](../functions/colors-kit.md)) and the drawn output names it with `color_packed_by`; an area's fill reads the same number through `fill_color_packed_by`, so a heat that shifts smoothly needs no rungs. ```typescript // A heat area painted per bar from a colour the module computes: the edge and the fill both read it. output("heat", area, lower, { color_packed_by: "heat_color", fill_color_packed_by: "heat_color", fill_opacity: 0.35, width: 2 }); output("heat_color", none, lower, { description: "A packed colour per bar, written with toPacked(...) in onBar()" }); ``` A per-bar box takes the same two ladders for its fill and its border, under camelCase keys in the declaration (`colorBy`, `borderColorBy`, `borderColorPackedBy`, `borderStyle`), with output handles for the `By` keys ([Boxes](drawing-objects.md#boxes)): a zone can follow the regime with a dashed border while a second box, drawn only where the band squeezes, takes its fill and border from one packed heat colour. ```typescript const hi = output("band_hi", line, overlay); const lo = output("band_lo", line, overlay); const regime = output("regime", none, overlay); const heat = output("heat_color", none, overlay); const squeezed = output("squeezed", none, overlay); // The zone behind the last three bars: fill and border by the regime ladder, dashed, painted behind the lines. box("zone", { top: hi, bottom: lo, from: -3, to: 0, colorBy: regime, colors: ["#ef444433", "#22c55e33"], borderColorBy: regime, borderColors: ["#ef4444", "#22c55e"], borderStyle: "dashed", z: -1 }); // The squeeze box: fill and border from one packed colour, where the gate is nonzero. box("squeeze", { top: hi, bottom: lo, when: squeezed, colorPackedBy: heat, borderColorPackedBy: heat, opacity: 0.3, borderWidth: 2 }); ``` Every reference is checked as you type and when you press **Run**: `color_by`, `width_by`, `shape_where`, and each `range()` side must name a declared (and, where required, drawn) output, and none may name its own output. A refusal points at the declaration in the editor's Console and names the field (for example "Output 'mid' (color_by): ..."). Styling dresses per-output SERIES. When the indicator should also put text, tables, shaped marks, or free-standing objects (lines, boxes, polylines, labels) on the chart, that is the renderer and drawing vocabulary: `render.*` and `draw.*` declarations over named outputs and string slots ([Plotting](plotting.md), [Drawing objects](drawing-objects.md)). Shapes that repeat on EVERY bar (a zone behind the last few bars, a projection ray from each bar) are the `box()` and `segment()` declarations over output handles ([Boxes](drawing-objects.md#boxes), [Segments](drawing-objects.md#segments)). ## Tags, the legend and the candle tint Four looks belong to the indicator as a whole: whether it keeps a price axis of its own, which plots tag their value on the price axis, the order its plots join the legend, and the pane it lives in. One top-level `display({ ... })` declares them, at most once: | Key | What the chart does | Absent | | --- | --- | --- | | `axis: false` | no price axis of its own: an indicator on the price pane rides the chart's scale | its own axis | | `price_display: "per_output"` | every plot tags its value on the price axis unless its `show_price_display` is `false`; a mark tags only when its `show_price_display` is `true` | the first output alone tags | | `overlay: "offchart"` | the indicator lives in its own pane below the chart; `pane("lower", { format: "0.00" })` formats that pane's axis | the outputs' panels decide | | `mount_order: "first_value"` | plots join the legend, and paint within one layer, in the order they first draw a value | declaration order, every range after every output | Five words sit on the plots themselves: | Word | On | What it does | | --- | --- | --- | | `show_price_display` | an output, a `range`, a `render.shape` | the plot's tag on the price axis, read under `price_display: "per_output"`: `false` drops it, `true` forces one | | `show_price_display_by` | an output | a declared output whose value on the last bar switches the tag: nonzero on, zero off, `NaN` keeps `show_price_display` | | `omit_if_empty` | an output, a `range` | `true`: a run that never drew it leaves it out, with no legend row and no tag (a plot drawn under an `if`) | | `fill: false` | a `range` | the two edge lines and no interior | | `barcolor: true` | a `none` output | the candles take its colour: each bar's value (floored) picks an entry of `colors`, or `color_packed_by` names a packed colour; a `NaN` or out-of-range value leaves the candle as it is; one per indicator | Every colour bound to a setting also takes it at an alpha: `"@/0.45"` paints the setting's colour at 45 percent, and a recolour keeps the 45; a panel series colour binds without one ([The Style page](../settings/style-page.md#a-setting-at-an-alpha)). ```typescript // No price axis of its own, a tag per plot, and plots listed in the order they first draw a value. display({ axis: false, price_display: "per_output", mount_order: "first_value" }); param.int("length", 20, { min: 2, max: 200, label: "Length" }); param.color("bull", "#22c55e", { label: "Bull" }); param.color("bear", "#ef4444", { label: "Bear" }); param.bool("tag_basis", true, { label: "Tag the basis" }); // The basis tags its value while the setting is on; the edges never tag. output("basis", line, overlay, { color: "@bull", show_price_display_by: "basis_tag" }); output("upper", line, overlay, { color: "@bull/0.5", show_price_display: false }); output("lower", line, overlay, { color: "@bear/0.5", show_price_display: false }); output("basis_tag", none); // A mark on each breakout: a run with none leaves it out of the legend. output("breakout", shape, overlay, { shape: "triangle_up", location: "below_bar", color: "@bull", omit_if_empty: true }); // The two edges as lines with no interior, untagged. range("upper", "lower", { fill: false, show_price_display: false }); // The candles in the trend's colour at 45 percent: 0 below the basis, 1 above. output("tint", none, overlay, { barcolor: true, colors: ["@bear/0.45", "@bull/0.45"] }); let sma = new Sma(20); let stdev = new Stdev(20); let tag: f64 = 1.0; function onStart(): void { sma = new Sma(i32(p_length())); stdev = new Stdev(i32(p_length())); tag = pb_tag_basis() ? 1.0 : 0.0; } function onBar(): void { const close = bar.close(); const mid = sma.update(close); const sd = stdev.update(close); if (isNaN(mid) || isNaN(sd)) return; const hi = mid + 2.0 * sd; out_basis(mid); out_upper(hi); out_lower(mid - 2.0 * sd); out_basis_tag(tag); if (close > hi) out_breakout(bar.low()); out_tint(close > mid ? 1.0 : 0.0); } ``` Refused by name: a tag word on a `none` output ("show_price_display needs a drawn output"), `omit_if_empty` on one ("omit_if_empty needs an output that draws a value"), `barcolor` on a drawn output, without `colors` or `color_packed_by`, beside `color_by` (its own value is the index) or on a second output, a `range` with `fill: false` and a `gradient`, a `show_price_display_by` that names no output, a second `display(...)` and a word `display` does not take (`overlay: "onchart"`). ## Text size, tooltips, alignment, z-order, palettes The styling vocabulary, item by item: | You want | wrun form | | --- | --- | | text size | `size`, an integer pixel count 6..64, on `render.text` and `render.label`, or `size_by` for a size per bar from an output; `font_size` on a guide's label, a box's text and a card | | type | `font_weight` (`normal`, `medium`, `bold`) and `font_family` (`ui`, the app font; `mono`; `serif`; `rounded`, each a system stack, nothing downloads) on renderer text, labels, box text, cards, HUDs and docked levels | | a tooltip on a plot | `tooltip` on the output, a template over its own value and any output or string slot: `"{{label}} {{value:price}} · {{state}}"`; shown on the legend entry and when the cursor nears the line ([Labels, tooltips, badges](labels-and-tooltips.md)) | | a tooltip on a cell, label, mark or drawing | `tooltip` on `render.text`, `render.label`, `render.shape`, `draw.line`, `draw.box`, `draw.polyline` and `draw.label` (one template per declaration, shown on its marks or object); a handle's `tooltip(send)` setter; a `hover` block list on an output or a label for a full card ([HUD and hover cards](hud-and-hover-cards.md#hover-cards)); a table cell's `tooltip` in its `styles` entry, a string slot ([Styled tables](cards-frames-panels.md#styled-tables)) | | price tags, callouts, pills | `style` on `render.text` and `render.label`, eight words on both: `plain`, `price_label` (the price tag on the axis), `pill` (a rounded chip at the value), `callout` (a leader line to its bar), `badge` (a dot in the label's color), `box`, `knockout` (a box in the background colour) and `emblem` (a mark before the text); a tag look takes `label_position`, `background_color`, `border_color` and `corner_radius` ([Labels, tooltips, badges](labels-and-tooltips.md)) | | text alignment | `align` (`left`, `center`, `right`) and `valign` (`top`, `middle`, `bottom`) on plain `render.text` and `render.label`, on a handle or declared label, and on a box's text; the nine anchors (`top_left` ... `bottom_right`) are a table's, a HUD's or a corner `render.label`'s `position` ([Drawing objects](drawing-objects.md)) | | z-order | `z` (-10..10) on an output, a range, a fill or a box, else the engine's layer in declaration order; a handle's `zorder` setter on lines, boxes, labels and polylines | | a palette | a `colors` literal array on the output, box, range, fill, bgcolor, barcolor, stats row or shape renderer; bucket the driving value into its index ([Colors](../functions/colors-kit.md)); an entry may be a `param.color` by name; `color_packed_by` names an output that carries a packed colour per bar instead | | per-element glow, opacity, gradients | `glow` per output, per renderer mark and per handle (`glow_color` picks its colour); `opacity` per output (every colour it draws), per box and per handle; a `color_by` ladder per bar; a line's `gradient` by height, an area's `fill_gradient`, a `range()` band's vertical `gradient`, a box handle's `gradient`; `corner` rounds histogram columns, `corner_radius` the corners of labels, boxes, cards and HUDs | | a setting behind a look | `"@"` in place of a colour, a `colors` or `gradient` entry, or a line style on an output, a `range`, a `fill`, a `box`, a `segment`, a legend entry or a docked `plot.levels` key; `"@/"` for the setting's colour at an alpha; a `param.color` on every colour word of a panel ([Panel words](cards-frames-panels.md#panel-words)); a `param.choice` over the looks on a HUD card's `look` ([Looks](hud-and-hover-cards.md#looks)) ([The Style page](../settings/style-page.md)) | | a table's fill, frame, lines and widths | the look keys on `render.table`: fills with opacity and gradients, a frame, the lines between cells, column widths, merged cells ([Styled tables](cards-frames-panels.md#styled-tables)) | Value-driven styling, computing the style from the data per element, is the ladder: normalize the driving value, floor it into a bucket, write the bucket to a `none` output, and index a palette with it. The palette is finite, so the gradient is stepped, and the decision stays a number you can read at the Console prompt or hand to a declared alert. ## A worked example Bollinger-style bands with a regime-colored (and regime-widened) midline and a banded range. The declarations carry every look; the module computes four numbers per bar and never mentions a color: ```typescript param("period", 20, { min: 2, max: 400 }); param("band_width", 2, { min: 0.5, max: 4, description: "Stdev multiples" }); // Red while the close is under the average, green (and three times as wide) while it is over. output("mid", line, overlay, { color_by: "regime", colors: ["#ef4444", "#22c55e"], width_by: "regime", widths: [1, 3] }); output("band_hi", line, overlay, { color: "#94a3b8", opacity: 0.6 }); output("band_lo", line, overlay, { color: "#94a3b8", opacity: 0.6 }); output("regime", none, overlay, { description: "0 below the average, 1 above: the palette and width index" }); // The band between the two edges: dotted edge lines and a slate interior. range("band_hi", "band_lo", { color: "#94a3b8", edge_width: 1, edge_line_style: "dotted" }); let sma = new Sma(20); let stdev = new Stdev(20); let mult: f64 = 2.0; function onStart(): void { const period = i32(p_period()); sma = new Sma(period); stdev = new Stdev(period); mult = p_band_width(); } function onBar(): void { const close = bar.close(); const mid = sma.update(close); const sd = stdev.update(close); const regime = close > mid ? 1.0 : 0.0; if (isNaN(mid) || isNaN(sd)) return; out_mid(mid); out_band_hi(mid + mult * sd); out_band_lo(mid - mult * sd); out_regime(regime); } ``` The `regime` output computes on every bar but never draws; it exists so the palette (and the `widths` ladder) on `mid` has a decision to index. The band is one `range()` over the two drawn edges, so the chart shades it without a box per bar. The two params are number fields in the overlay's settings dialog (a `param.int` would step by whole numbers, and `param.number` with a `step` by that step), and changing one reruns the compiled module without recompiling it; the three lines each get a Style row. The `output(...)` options carry `color`, `colors`, `width`, `opacity`, `line_style`, `glow`, `corner`, `z`, `color_by`, `color_packed_by`, `shape_where`, `width_by`, `widths`, `displacement_bars`, `displacement_bars_by`, `unit`, `description`, the plot-kind looks of [Plotting](plotting.md#lines-areas-columns-dots-marks) (`step`, `smooth`, `gradient`, `split` and its four companions, `fill_color`, `fill_opacity`, `fill_gradient`, `gradient_mode`, `fill_color_by`, `fill_colors`, `fill_color_packed_by`, `base`, `grading`, `stack`, `candle_style`, `border_colors`, `wick_colors`, `border_width`, `shape`, `location`, `char`, `font_family`, `fill`, `role`, `align`, `pill_style`, `font_size`, `axis_look`, `pane`), the presentation keys `label`, `format`, `decimals`, `signed`, `legend`, `visible`, `price_line`, `axis_label`, `axis_name`, `tooltip`, `hover`, `badges`, `hint`, and the chart words `show_price_display`, `show_price_display_by`, `omit_if_empty` and `barcolor` ([Tags, the legend and the candle tint](#tags-the-legend-and-the-candle-tint)); ranges declare as `range(upper, lower, options?)`, fills as `fill(a, b, options?)`, panes as `pane(name, options?)`, boxes and segments as `box(name, options)` / `segment(name, options)` over output handles, and declaration order sets the indexes ([Declarations and the sheet](../reference/declarations.md)). ## Where the rules live Every styling reference is validated as you type and when you press **Run**, and every refusal names the declaration and the field in the editor's Console; the messages are in [Common errors](../faq/common-errors.md). The module never draws: the chart reads the declarations, so the look is exactly what they describe, whatever the module computes. # Drawing objects A wrun indicator has three forms of drawing. A `box` or a `segment` is declared once over two outputs and evaluated on every bar; a run-level drawing declaration (`draw.label` and its kin) is placed from the newest bar's outputs; and a **handle** is an object the module creates under an integer id and moves, restyles, or deletes on a later bar. This page is the vocabulary, the form each kind of object takes, and the rules each form runs under. ## The objects | You want | wrun form | Lifecycle | | --- | --- | --- | | a line | `segment(name, { yFrom, yTo, from, to })` per bar; `draw.line(id).set(x1, y1, x2, y2)` as a handle | per bar, or a handle the module owns | | a box | `box(name, { top, bottom, from, to, when })` per bar; `draw.box(id).set(left, top, right, bottom)` as a handle | per bar, or a handle the module owns | | a label | `draw.label(id).set(x, y).text(str__sb)` as a handle; `render.label(name, { x, y, text })` for one label the newest bar wins | a handle, or one label | | a polyline | `draw.polyline(id).setPoints(points, count)` as a handle; `draw.polyline(name, { points })` declared over output pairs | a handle of up to 100,000 points, or 64 output pairs from the newest bar | | a fill between two lines | `draw.line(id).fillTo(otherId, color)` between two line handles; `fill("a", "b", { color })` between two drawn outputs ([Styling](styling.md)); a `box` per bar between two outputs | a handle the module owns, per output, or per bar | | a table | `render.table(name, { rows, cols, cells, position })` over string slots | the newest complete row wins | | a mark (a dot, a square, a diamond) | `draw.label(id).set(x, y).mark().style(LabelStyle.Emblem).emblem(Emblem.Diamond).size(10)` as a handle; `draw.box(id).shape(BoxShape.Ellipse)` for an ellipse | a label with no text, or an ellipse inscribed in a box | | many marks, boxes or segments on every bar or every event | `plot.marks`, `plot.spans` or `plot.rays`: up to 64 records a bar, each written on its own bar; a timed span or ray runs between two times, from before that bar ([Marks, spans and rays](marks-spans-rays.md)) | per bar, never moved; no ids and no live-object cap | | a tooltip on an object | `tooltip: "slope {{slope:0.00}}"` on a declared drawing; `handle.tooltip(str__sb)` on a handle | shown when the cursor rests on the object | | to restyle, move, or delete an object later | the handle's setters (`set`, `setXy2`, `setRightBottom`, `color`, `fill`, `fillTo`, `width`, `style`, `extend`, `size`, `glow`, `arrow`, `cornerRadius`, `gradient`, `text`, ...) and `delete()` | a setter stamps the bar it ran on; `delete()` frees the id | Every piece is a decoration over numbers the module already computes: outputs are the values, and boxes, segments, drawings, and handles never change an output's value ([Execution model](../core-concepts/execution-model.md)). Two forms are both called `draw`: `draw.line(name, {...})` as a top-level statement declares a run-level drawing, and `draw.line(id)` returns a handle; a name or an options object as the first argument is what makes the call a declaration. A handle does everything a run-level declaration does (create it under `bar.isLast()`). ## Boxes A box is declared once and evaluated on every bar. On bar `i` it spans bars `i + from` to `i + to` (inclusive) and prices `min(top, bottom)` to `max(top, bottom)`. Nothing is drawn on a bar where any referenced output is `NaN`, or where the optional `when` gate is `0` or `NaN`. Coordinates are output HANDLES: `output(...)` returns one, so bind it with a top-level `const` and pass the const. `from` and `to` are bar offsets (negative = past, positive = ahead; literals in -500..500, whole or fractional, or a handle whose per-bar value is truncated to the offset; default `0`). A fraction places the edge inside its bar at that share of the bar's interval: `from: -0.5, to: 0.5` draws a box one bar wide centred on the bar, and `from: -0.15, to: 0.15` a narrow stick through it. Options: `when` (a gate handle), `panel` (`"overlay"` or `"lower"`, default: the panel of `top`'s output), `color`, `borderColor`, `opacity` (0..1, default 0.2), `borderWidth` (0..10, default 1; `0` for no border), `borderStyle` (`"solid"`, `"dashed"`, `"dotted"`), `z` (the paint order, -10..10). The fill takes the opacity, so `color` must be a hex, `rgb()`, `hsl()` or theme-token color; a named color is refused. A colour per bar comes from a ladder on either part: `colorBy` (an output handle whose floored value picks the entry) plus `colors` (1..64 colours) for the fill, `borderColorBy` plus `borderColors` for the border, or `colorPackedBy` / `borderColorPackedBy` naming an output that carries a packed colour per bar. A finite out-of-range rung clamps to entry 0, a non-finite rung (or a packed value that does not decode) draws no box on that bar, and a rung colour's own alpha multiplies `opacity`. A ladder half without the other, a packed key beside its `By` key, or a name that is not a declared output is refused. `color`, `borderColor` and `borderStyle` also take a `"@"` setting ([The Style page](../settings/style-page.md)). Every referenced output may be data-only (`none`), which is the usual shape: compute the coordinates, never draw them as lines. A box or a segment adds no data to the module (the referenced outputs already reach the chart), and **Run** records its options in the sheet under snake_case names (`x_from`, `border_color`, `border_style`, `color_by`, `y_from`, and so on). The last five bars' range, tinted only while the range is expanding: ```typescript param("bars", 5, { min: 2, max: 50, description: "Bars in the trailing range" }); input("high", ohlcv.high); const rangeHi = output("range_hi", none); const rangeLo = output("range_lo", none); const expanding = output("expanding", none); // Behind the last five bars, tinted only while the range is wider than it was one bar ago. box("range_zone", { top: rangeHi, bottom: rangeLo, from: -4, to: 0, when: expanding, color: "#f59e0b", opacity: 0.15, borderColor: "#f59e0b", borderWidth: 1 }); const MAX_BARS = 50; const highs = new StaticArray(MAX_BARS); const lows = new StaticArray(MAX_BARS); let n: i32 = 5; let cursor: i32 = 0; let count: i32 = 0; let prevWidth: f64 = NaN; let width: f64 = NaN; function onStart(): void { n = i32(p_bars()); } function onBar(): void { highs[cursor] = bar.high(); lows[cursor] = bar.low(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n) return; let hi = -Infinity; let lo = Infinity; for (let i = 0; i < n; i++) { if (highs[i] > hi) hi = highs[i]; if (lows[i] < lo) lo = lows[i]; } prevWidth = width; width = hi - lo; out_range_hi(hi); out_range_lo(lo); out_expanding(!isNaN(prevWidth) && width > prevWidth ? 1.0 : 0.0); } ``` Two shapes that fall out of the per-bar rule: - A shaded channel between two lines is a box on every bar with `from` and `to` left at `0`: each bar contributes a one-bar-wide slice, and the slices tile into a band. The [anchored VWAP recipe](../cookbook/anchored-vwap.md) shades its band this way. - A zone that lives until price breaks it is the same one-bar box gated by a `when` output that stays `1` while the zone is alive: the band starts at the pivot and stops on the bar that mitigates it (the [zone tracker](../cookbook/zone-tracker.md)). That is one form of "create the box at the pivot, delete it when mitigated"; the other is a box handle, below, which is the same object from creation to deletion. A fill between two lines has two forms, both drawn by the chart: `range("upper", "lower", { color })` over two DRAWN outputs draws a band with edge lines, a sign palette or a vertical gradient ([Styling](styling.md#decisions-to-looks)), and the one-bar box above, whose `color` and `opacity` are the fill's. The box reads outputs, not lines, so either side may be data-only, and a conditional fill (shading only some bars) is a `when` gate on the box. A hand-written sheet's `fills` list has no declaration form. Two boxes gated by opposite outputs, one color each; the delta sits near zero, so it and its fills live in a `lower` pane (a box follows its `top` output's panel) instead of flattening the price scale under the candles: ```typescript param("period", 20, { min: 2, max: 400 }); const delta = output("delta", line, lower, { color: "#e2e8f0", width: 1, description: "Close minus its average" }); const zero = output("zero", line, lower, { color: "#64748b", width: 1, description: "Zero baseline" }); const below = output("below", none, lower, { description: "1 while the delta is negative" }); const above = output("above", none, lower, { description: "1 while the delta is positive or zero" }); // Two fills, one per sign: each bar contributes one slice between the delta and zero, // in the delta's own pane (each box takes the panel of its `top` output). box("fill_up", { top: delta, bottom: zero, when: above, color: "#22c55e", opacity: 0.15, borderWidth: 0 }); box("fill_down", { top: zero, bottom: delta, when: below, color: "#ef4444", opacity: 0.15, borderWidth: 0 }); let sma = new Sma(20); function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { const close = bar.close(); const avg = sma.update(close); const value = isNaN(avg) ? NaN : close - avg; if (isNaN(value)) return; out_delta(value); out_zero(0.0); out_below(value < 0.0 ? 1.0 : 0.0); out_above(value >= 0.0 ? 1.0 : 0.0); } ``` Both boundary series here are outputs the chart draws; the module could also leave one of them `none` and the box would still tile, because a box reads outputs, not lines (a `range()` needs both sides drawn). ## Segments A segment is the straight line from `(i + from, yFrom)` to `(i + to, yTo)`, evaluated on every bar `i` with the same offset, gate, and `NaN` rules as a box. Options: `when`, `panel`, `color`, `width` (0.5..20, default 1), `lineStyle` (`"solid"`, `"dashed"`, `"dotted"`). Absent `color` and `panel` follow `yFrom`'s output; `color` and `lineStyle` take a `"@"` setting. A dotted projection from each bar's average toward where the slope points, its length decided per bar by an output-valued offset: ```typescript param("period", 20, { min: 2, max: 200 }); const anchor = output("anchor", line, overlay, { color: "#38bdf8" }); const target = output("target", none); const reach = output("reach", none); // From this bar's average to the projected level, `reach` bars ahead: the offset is an output, // so each bar decides its own length. segment("projection", { yFrom: anchor, yTo: target, from: 0, to: reach, color: "#38bdf8", width: 1, lineStyle: "dotted" }); let ema = new Ema(20); let value: f64 = NaN; let prev: f64 = NaN; function onStart(): void { ema = new Ema(i32(p_period())); } function onBar(): void { prev = value; value = ema.update(bar.close()); if (isNaN(value)) return; const slope = isNaN(prev) ? 0.0 : value - prev; const bars = slope == 0.0 ? 0.0 : 5.0; out_anchor(value); out_target(value + slope * bars); out_reach(bars); } ``` Horizontal levels are segments with `yFrom` and `yTo` on the same output and `from: 0, to: 1`: each bar draws its level to the next bar, and the pieces chain into one line that steps when the level changes (the [key levels recipe](../cookbook/key-levels.md)). Offsets past the loaded range clamp to its edge, so a segment cannot reach into empty space to the right of the newest bar; a handle's absolute coordinates can. ### A box and a segment together A moving average with a one-percent band drawn as a zone behind the last five bars while the average rises, plus a dotted ray from each bar's average to the band top three bars ahead. Both shapes take their color and panel from the outputs they reference: ```typescript param("period", 20, { min: 1, max: 200 }); const mid = output("mid", line, overlay, { color: "#38bdf8" }); const bandHi = output("band_hi", none); const bandLo = output("band_lo", none); const rising = output("rising", none); box("band_zone", { top: bandHi, bottom: bandLo, from: -4, to: 0, when: rising, opacity: 0.15, borderWidth: 0 }); segment("mid_ray", { yFrom: mid, yTo: bandHi, from: 0, to: 3, lineStyle: "dotted" }); let sma = new Sma(20); let value: f64 = NaN; let prev: f64 = NaN; function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { prev = value; value = sma.update(bar.close()); if (isNaN(value)) return; out_mid(value); out_band_hi(value * 1.01); out_band_lo(value * 0.99); out_rising(!isNaN(prev) && value > prev ? 1.0 : 0.0); } ``` ## Run-level drawings `draw.line`, `draw.box`, `draw.polyline`, and `draw.label` with a name as the first argument are the declared kind of object: one per declaration, its coordinates read from outputs on the NEWEST bar only. Every coordinate finite there means the object exists; any `NaN` there means no object, regardless of earlier bars. It is "draw from the last bar" as a declaration: the chart evaluates the newest bar on its own, and re-evaluates it as live data arrives. - `draw.line(name, { x1, y1, x2, y2, color?, width?, line_style?, extend?, arrow?, glow?, glow_color?, sticky_right?, axis_label?, opacity?, tooltip? })` - `draw.box(name, { left, top, right, bottom, color?, border_color?, opacity?, border_width?, border_style?, corner_radius?, extend?, shape?, gradient?, gradient_direction?, glow?, glow_color?, text?, text_color?, font_size?, font_weight?, font_family?, align?, valign?, padding?, tooltip? })`: `color` is the fill, painted at `opacity` (default 0.2), and the border too unless `border_color` is set (default `#38bdf8`, the box handle default); it takes any colour string, as it always has: a hex, `rgb()`, `hsl()` or theme-token fill takes the opacity, a named colour paints as given (only `handles.box` insists on an alpha-rewritable fill); `text` names a string slot drawn inside the box - `draw.polyline(name, { points, color?, width?, line_style?, opacity?, fill_color?, closed?, smooth?, arrow?, glow?, glow_color?, tooltip? })`, where `points` is a flat `["x0", "y0", "x1", "y1", ...]` list of output-name pairs, at most 64 pairs - `draw.label(name, { x, y, text, color?, style?, align?, valign?, background_color?, border_color?, border_width?, corner_radius?, font_weight?, font_family?, padding?, max_width?, angle?, glow?, glow_color?, emblem_shape?, emblem_color?, sticky_right?, axis_label?, opacity?, tooltip? })`, `text` a string slot X coordinates are epoch SECONDS, not milliseconds: `bar.time()` feeds them, and a point in the past is that time minus a bar count times the interval in seconds. Drawings reference outputs by NAME (strings), unlike per-bar boxes and segments, which take handles. The style words are the handle defaults' words (the table under [Handles](#handles)), spelled snake_case, and every one is optional: absent keeps the object's look as it has always been. `tooltip` is a template over the newest bar (`{{name}}`, `{{name:format}}`, `{{label}}`, `{{value}}`) shown when the cursor rests on the object. A `\n` inside a slot's text starts a new line on a label and on box text. Every declared kind at once: a high and a low line, a zone box between them, a three-point path, and a label, all placed from the newest bar, plus a per-bar horizontal level for contrast. The drawings reach two bars ahead by adding two intervals to the bar time. ```typescript param("lookback", 20, { min: 2, max: 500, description: "Bars in the zone's range" }); output("close_line", line, overlay, { color: "#2563eb", width: 2, description: "Close, the anchor line" }); const level = output("level", none, overlay, { description: "The lookback high, a stepping level" }); output("zone_high", none, overlay, { description: "Lookback high: the top line and the box top" }); output("zone_low", none, overlay, { description: "Lookback low: the bottom line and the box bottom" }); output("zone_mid", none, overlay, { description: "The midpoint, the path's middle point" }); output("t0", none, overlay, { description: "This bar's open time, epoch seconds" }); output("t1", none, overlay, { description: "One bar ahead" }); output("t2", none, overlay, { description: "Two bars ahead" }); string("note", { max_bytes: 32 }); // Per bar: the lookback high carried one bar to the right, chaining into a stepped level line. segment("level_line", { yFrom: level, yTo: level, from: 0, to: 1, color: "#94a3b8", width: 1, lineStyle: "dashed" }); // Run level, placed from the newest bar: two lines, a box, a path, and a label. draw.line("top_line", { x1: "t0", y1: "zone_high", x2: "t2", y2: "zone_high", color: "#2563eb", width: 2 }); draw.line("bottom_line", { x1: "t0", y1: "zone_low", x2: "t2", y2: "zone_low", color: "#dc2626", width: 2 }); draw.box("zone", { left: "t0", top: "zone_high", right: "t2", bottom: "zone_low", color: "#dbeafe" }); draw.polyline("path", { points: ["t0", "zone_low", "t1", "zone_mid", "t2", "zone_high"], color: "#f97316", width: 2 }); draw.label("last", { x: "t1", y: "close_line", text: "note", color: "#111827" }); const MAX_BARS = 500; const highs = new StaticArray(MAX_BARS); const lows = new StaticArray(MAX_BARS); let n: i32 = 20; let cursor: i32 = 0; let count: i32 = 0; let t: f64 = NaN; let prevT: f64 = NaN; let intervalSec: f64 = NaN; function onStart(): void { n = i32(p_lookback()); } function onBar(): void { const close = bar.close(); prevT = t; t = bar.time(); // The interval is the spacing between consecutive bar opens; NaN on the first bar. if (!isNaN(prevT)) intervalSec = t - prevT; highs[cursor] = bar.high(); lows[cursor] = bar.low(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n || isNaN(intervalSec)) return; let hi = -Infinity; let lo = Infinity; for (let i = 0; i < n; i++) { if (highs[i] > hi) hi = highs[i]; if (lows[i] < lo) lo = lows[i]; } out_close_line(close); out_level(hi); out_zone_high(hi); out_zone_low(lo); out_zone_mid((hi + lo) / 2.0); out_t0(t); out_t1(t + intervalSec); out_t2(t + 2.0 * intervalSec); sb_clear(); sb_text("last "); sb_f64(close, 2); str_note_sb(); } ``` After this runs you see one stepped level line (per bar), two lines, one box, one path, and one label (all from the newest bar). A declared drawing that should be REMOVED emits `NaN` through one of its coordinate outputs on the newest bar; a handle, below, has a `delete()`. ## Handles A handle is an object the module owns: it creates it, keeps its identity from bar to bar, moves or restyles it later, and deletes it. Four kinds: `line`, `box`, `label`, `polyline`. **Handles are for a few objects, long-lived or rare**: a level that moves, a label that rewords, the zones still live, a path built point by point, and the objects that come a few times across a chart (a finished session's box, a broken zone, a line between two swings). Anything drawn on most bars (a print, a flagged candle, a level set on its own bar) belongs in a `plot.marks`, `plot.spans` or `plot.rays` section ([Marks, spans and rays](marks-spans-rays.md)): the chart draws a section in one batch, with no ids, no deletes and no live-object cap, and a timed span or ray reaches back to any time your script stored. A pool of handles recycled across bars to draw per-bar objects spends an id per object, runs into the live caps below and deletes what it can no longer keep; a section does none of that. The other way round costs too: a section spends its slots on every bar, record or not, so for tens of objects a chart handles paint cheaper. Measured on the chart with Session Map, Supply and Demand Zones and CVD Divergence rewritten onto timed spans and rays: each drew slower than its handles, so all three stayed on handles. **Declare the kinds you draw** at the top of the file, once per kind, with the defaults every new handle of that kind starts from: `handles.line({ panel, color, width, line_style, extend })`, `handles.box({ panel, color, border_color, opacity, border_width })`, `handles.label({ text, panel, color, size, align })`, and `handles.polyline({ panel, color, width, line_style })`. There is no name (handles are ids the module picks) and every option is optional; `handles.box()` enables boxes with the defaults. A label's `text` names the string slot its text is read from (a label that only draws a mark needs none). A label's `align` (`left`, `center` or `right`) is the text edge that sits on its x; omitted centres the text, and (x, y) stays the point either way. The legacy spellings `borderColor`, `borderWidth` and `lineStyle` still work beside the snake_case ones (both spellings of one key at once are refused), and every look below is a default here too: `glow`, `glow_color`, `sticky_right`, `axis_label`, `arrow`, `opacity` on a line; `border_style`, `corner_radius`, `extend`, `shape`, `gradient`, `gradient_direction`, `text_color`, `font_size`, `font_weight`, `font_family`, `align`, `valign`, `padding` on a box; `style`, `background_color`, `border_color`, `border_width`, `corner_radius`, `font_weight`, `font_family`, `valign`, `padding`, `max_width`, `angle`, `emblem_shape`, `emblem_color` on a label; `fill_color`, `closed`, `smooth` on a polyline. `safe_area: true` on any kind keeps its pane-anchored handles clear of the chart's chrome (the legend, the pane action bar, the price-axis tags). Declaring any kind, or calling `bar.isLast()`, switches the derived sheet to the third runtime contract (`abi_version: "wrun-3"`); the numeric outputs compute exactly as before. **Make the objects once**, at module level or in `onStart()`: `draw.line(id)`, `draw.box(id)`, `draw.label(id)`, `draw.polyline(id)`. An id is any integer from `0` up, in ONE space across the four kinds: while a box holds id `3`, a label cannot. An object made per bar would allocate on every bar for nothing. **Draw in `onBar()`**, beside the outputs. The rules, each refused by name when broken: | Call | On an id nobody holds | On a live id of the same kind | | --- | --- | --- | | `set(...)` (`setPoints` on a polyline) | creates the handle: `createdBar` is this bar, the style is the kind's defaults | moves it: this bar becomes its `mutatedBar` | | the partial setters `setXy1`, `setXy2`, `setLeftTop`, `setRightBottom` | refused (nothing to remember the other corner from) | moves one end; the object re-sends the remembered rest | | `color`, `fill`, `fillTo`, `width`, `style`, `extend`, `opacity`, `size`, `border`, `zorder` and every other look setter below | refused (the handle does not exist) | restyles it; this bar becomes its `mutatedBar` | | `delete()` | a no-op | removes it; the id is free for a later bar (a new handle, a new creation bar) | | `set(...)` on an id a handle of ANOTHER kind holds | | refused: delete that handle first | Coordinates are absolute: `x` in epoch seconds (`bar.time()`), `y` in price. Nothing clamps: a box that should end one bar past the newest bar sets its right edge to `t + interval`, and the chart draws it there. Every coordinate must be finite. Colors on a setter are `rgba(r, g, b, a)` values (`rgb(r, g, b)` for opaque) or a theme token from `./sdk/color` (`theme.UP`, `theme.DOWN`, `theme.TEXT`, `theme.MUTED`, `theme.BG`, `theme.GRID`, `theme.ACCENT`, with `alpha(theme.BG, 0.85)` for a translucent one), which the chart resolves when it paints ([Colors kit](../functions/colors-kit.md#theme-colours)); `style` on a line takes `LineStyle.Solid`, `Dashed`, `Dotted`; `extend` takes `Extend.None`, `Left`, `Right`, `Both`. The core setters by kind: `width` and `style` on lines and polylines, `extend` and `fillTo` on lines, `border` and `fill` on boxes, `size` and `fill` on labels, `opacity` and `zorder` on all four kinds. A `width` of `0.5` draws a hairline, and a polyline sent one point draws a dot. A label's text comes from a string slot: build the line with `sb_*`, then `tag.set(x, y).text(str__sb)` sends the slot and draws the label with the bytes the slot holds on that bar (a `\n` in the text starts a new line). Call it again on a later bar to move or re-word the label. `tag.align(ALIGN_RIGHT)` (or `style.align(tag, ALIGN_RIGHT)`) makes the text end at x instead of centring on it; `ALIGN_LEFT` starts it there and `ALIGN_DEFAULT` restores centred text, clearing a declared `align` default. `tag.set(x, y).mark()` draws a label with no text (no slot is read): with `style(LabelStyle.Emblem)` and an `emblem(...)` it is a dot, a square, a diamond or a triangle, `size` pixels across, at (x, y). ### Every look a handle takes Each setter below restyles a live handle like `color` does (a setter on an id nobody holds is refused). Word arguments are the enums of `./gen/draw`: `Arrow { None, Start, End, Both }`, `AxisLabel { None, Price, Text }`, `BoxShape { Default, Rect, Ellipse }`, `GradientDirection { None, Vertical, Horizontal }`, `FontWeight { Default, Normal, Medium, Bold }`, `FontFamily { Default, Ui, Mono, Serif, Rounded }`, `LabelStyle { Default, Box, Plain, Knockout, Emblem, Pill, Badge, Callout }`, `Emblem { Default, Dot, Square, Diamond, TriangleUp, TriangleDown }`, and the `VALIGN_DEFAULT`, `VALIGN_TOP`, `VALIGN_MIDDLE`, `VALIGN_BOTTOM` constants beside `ALIGN_*`. A `Default` word clears the setter back to the declared default. | Setter | Kinds | What it does | | --- | --- | --- | | `glow(px)`, `glowColor(c)` | line, box, label, polyline | a halo of 0..32 px around the stroke, border or text, in `glowColor` (default the object's own colour); `glow(0)` removes it | | `opacity(f)`, `zorder(n)` | line, box, label, polyline | the object's opacity 0..1 (a box's fill opacity) and its paint order | | `tooltip(send)`, `tooltipString(s, send)`, `clearTooltip()` | line, box, label, polyline | the tooltip text from a string slot sender (`tooltipString` sends `s` through it first), read on this bar; `clearTooltip()` removes it | | `arrow(Arrow)` | line, polyline | an arrowhead at the start, the end or both (`Arrow.None` removes them) | | `stickyRight(on)` | line, label | the object keeps its right end (a line) or its point (a label) beside the price axis as the chart scrolls | | `axisLabel(AxisLabel)` | line, label | a pill on the price axis at the line's right endpoint price (`Price`) or the label's y (`Price`, or `Text` for the label's first line) | | `fitTo(group)`, `padding(px)` | box | the box sizes itself to the union of every label in `group` (1..65535), grown by `padding` (0..64, default 6); `fitTo(0)` releases it; anchor and extend are ignored while fitted | | `borderStyle(LineStyle)`, `cornerRadius(px)`, `extend(Extend)`, `shape(BoxShape)` | box | a dashed or dotted border, rounded corners (0..32), the box stretched to the pane's left or right edge, or the ellipse inscribed in the box | | `gradient(start, end, GradientDirection)`, `clearGradient()` | box, polyline | a two-colour fill laid top to bottom or left to right in place of the flat fill, over the box or over the bounding box of the polygon a polyline encloses | | `text(send)`, `textString(s, send)`, `clearText()`, `textColor(c)`, `fontSize(px)`, `align(i32)`, `valign(i32)`, `padding(px)` | box | text inside the box from a string slot, in `textColor` at `fontSize` (6..64, default 12), aligned by `ALIGN_*` and `VALIGN_*` inside `padding` | | `fontWeight(FontWeight)`, `fontFamily(FontFamily)` | label, box | the text's weight and family (`Ui` is the app font, `Mono`, `Serif` and `Rounded` system stacks) | | `style(LabelStyle)` | label | the label's look: `Box` (the default rounded box), `Plain` (text alone), `Knockout` (a box in the background colour that hides what is behind the text), `Emblem` (a mark before the text), `Pill`, `Badge`, `Callout` | | `emblem(Emblem)`, `emblemColor(c)` | label | the emblem's shape (`TriangleDown` points down) and colour (default the text colour) | | `border(c)`, `borderWidth(px)`, `cornerRadius(px)` | label | the box's border colour and width (0..10) and its corner radius (0..32, default 4) | | `valign(i32)`, `padding(px)`, `maxWidth(px)`, `angle(deg)` | label | the box placed above, on or below y; its padding (0..64, default 6); text wrapped at `maxWidth` (0..2000, 0 = no wrap); the whole label rotated -90..90 degrees about (x, y) | | `group(id)`, `mark()` | label | the group a `fitTo` box measures (0 = none); a label with no text | | `fill(c)`, `closed(on)`, `smooth(on)` | polyline | the polygon fill colour; the path closed back to its first point (and filled when `fill` is set); the path curved through its points | `line.extend(Extend.Right).fillTo(otherId, c)` keeps working: the shading between two lines follows their extensions. Two chart-level flags belong beside the handle looks: `chart.contrast_guard(false)` keeps the author's colours as written on a light chart, and `chart.stack_handles(true)` stacks this indicator's corner-anchored groups below other indicators' groups at the same corner instead of overprinting them ([Styling](styling.md#theme-colours)). Both flags are statements beside the declarations they govern. Readouts pinned to the top-right corner as knockout labels (a theme-background box behind the text), kept in the author's colours on a light chart and stacked under other indicators' corner groups instead of over them: ```typescript string("tag", { max_bytes: 16 }); handles.label({ text: "tag", anchor: "top_right", color: "#fde68a", size: 11, style: "knockout", padding: 6 }); chart.contrast_guard(false); chart.stack_handles(true); ``` Every look in the table is also a default on a `handles.` declaration and a key on a declared drawing, spelled snake_case, but for a polyline's gradient, which only the handle sets while the module runs (`handles.polyline` and a declared polyline take no `gradient`). Swing tags on a busy chart: the emblem look puts a diamond before the text, the box sits above its point inside 6 px of padding, and a long note wraps at 120 px instead of running across the candles. ```typescript string("tag", { max_bytes: 24 }); handles.label({ text: "tag", color: "#e5e7eb", size: 11, style: "emblem", emblem_shape: "diamond", emblem_color: "#f59e0b", valign: "top", padding: 6, max_width: 120 }); ``` A level the viewer should never lose: the line's right end rides beside the price axis as the chart scrolls, its price pilled onto the axis, under a 4 px halo in its own colour. ```typescript handles.line({ color: "#38bdf8", width: 1, line_style: "dashed", sticky_right: true, axis_label: "price", glow: 4, glow_color: "#38bdf8" }); ``` A zone that explains itself: a declared box with its note printed inside, a dashed border in the fill's colour and the text in the top-left corner inside 8 px of padding. ```typescript output("t0", none, overlay, { description: "The zone's first bar, epoch seconds" }); output("t1", none, overlay, { description: "Two bars past the newest bar" }); output("zone_hi", none, overlay, { description: "The zone's top" }); output("zone_lo", none, overlay, { description: "The zone's bottom" }); string("note", { max_bytes: 32 }); draw.box("supply", { left: "t0", top: "zone_hi", right: "t1", bottom: "zone_lo", color: "#ef4444", border_color: "#ef4444", border_style: "dashed", text: "note", text_color: "#fecaca", align: "left", valign: "top", padding: 8 }); ``` A pattern outline that reads as a shape rather than a line: a closed, curved path filled at 20% in its own colour, the stroke under a 6 px halo. ```typescript output("t0", none, overlay, { description: "This bar's open time, epoch seconds" }); output("t1", none, overlay, { description: "One bar ahead" }); output("t2", none, overlay, { description: "Two bars ahead" }); output("lo", none, overlay, { description: "The pattern's low" }); output("mid", none, overlay, { description: "The pattern's midpoint" }); output("hi", none, overlay, { description: "The pattern's high" }); draw.polyline("wedge", { points: ["t0", "lo", "t1", "mid", "t2", "hi"], color: "#f97316", width: 2, fill_color: "#f9731633", closed: true, smooth: true, glow: 6, glow_color: "#f97316" }); ``` A measured move: a dotted arrow from the breakout to its target, drawn half transparent so it reads as a projection, with the target's caption standing upright beside the arrowhead, the text ending at the point. ```typescript output("t0", none, overlay, { description: "The breakout bar, epoch seconds" }); output("t1", none, overlay, { description: "The target bar, ahead of the newest bar" }); output("y0", none, overlay, { description: "The breakout price" }); output("y1", none, overlay, { description: "The target price" }); string("target", { max_bytes: 24 }); draw.line("move", { x1: "t0", y1: "y0", x2: "t1", y2: "y1", color: "#a78bfa", width: 2, line_style: "dotted", arrow: "end", opacity: 0.6 }); draw.label("target_tag", { x: "t1", y: "y1", text: "target", color: "#a78bfa", style: "plain", angle: 90, align: "right" }); ``` `render.text` and `render.label` take the label words too (`style`, `emblem_shape`, `emblem_color`, and `align` and `valign` on plain text) plus three ladders of their own, each naming a declared numeric output: `background_color_by` with `background_colors` picks the tag's fill per bar, `color_packed_by` reads a packed text colour per bar, `size_by` the text size per bar. A tag to the right of every bar whose slot was written, its fill from a regime ladder, inked and sized per bar: ```typescript output("close_line", line, overlay, { color: "#2563eb", width: 2, description: "Close, the tag's anchor" }); output("regime", none, overlay, { description: "0 quiet, 1 trending, 2 stretched: picks the tag's fill" }); output("ink", none, overlay, { description: "The text colour per bar, packed with toPacked()" }); output("strength", none, overlay, { description: "The text size per bar, 8..14 px" }); string("readout", { max_bytes: 16 }); render.text("state_tag", { y: "close_line", text: "readout", style: "box", label_position: "right", background_color_by: "regime", background_colors: ["#334155", "#1d4ed8", "#b91c1c"], color_packed_by: "ink", size_by: "strength" }); ``` Session zones: a box that grows with every bar of its session, a label on it, four zones kept on the chart with the oldest deleted to make room, and the open zone stretched one bar past the newest bar: ```typescript param("bars", 12, { min: 2, max: 500, description: "Bars per zone" }); input("high", ohlcv.high); output("zone_hi", line, overlay, { color: "#38bdf8", description: "The open zone's high so far" }); output("zone_lo", line, overlay, { color: "#38bdf8", description: "The open zone's low so far" }); string("tag", { max_bytes: 16 }); // Enable box and label handles; every new box and label starts from these defaults. handles.box({ color: "#38bdf8", opacity: 0.2, borderWidth: 1 }); handles.label({ text: "tag", color: "#e5e7eb", size: 11 }); // Four zones stay on the chart. Handle objects are made once; ids are one space across kinds. const KEEP = 4; const zones: BoxHandle[] = [draw.box(0), draw.box(1), draw.box(2), draw.box(3)]; const tags: LabelHandle[] = [draw.label(4), draw.label(5), draw.label(6), draw.label(7)]; let bars: i32 = 12; let count: i32 = 0; let slot: i32 = 0; let serial: i32 = 0; let t: f64 = NaN; let prevT: f64 = NaN; let start: f64 = NaN; let hi: f64 = NaN; let lo: f64 = NaN; function onStart(): void { bars = i32(p_bars()); } function onBar(): void { prevT = t; t = bar.time(); if (count == 0) { start = t; hi = bar.high(); lo = bar.low(); } else { hi = Math.max(hi, bar.high()); lo = Math.min(lo, bar.low()); } count += 1; out_zone_hi(hi); out_zone_lo(lo); const zone = zones[slot]; const tag = tags[slot]; if (count == 1) { // The zone's first bar: set(...) on an id nobody holds creates the box; fill(...) tints it. serial += 1; zone.set(start, hi, t, lo).fill(rgba(56, 189, 248, 51)); } else { // Every later bar grows the same box: the id is what makes it the same box. zone.setLeftTop(start, hi).setRightBottom(t, lo); } sb_clear(); sb_text("zone "); sb_int(serial); tag.set(start, hi).text(str_tag_sb); // On the newest bar only, stretch the open zone one bar past the loaded range. if (bar.isLast() && !isNaN(prevT)) zone.setRightBottom(t + (t - prevT), lo); if (count >= bars) { // The zone is complete: move to the next slot and delete the zone that slot held. count = 0; slot = (slot + 1) % KEEP; zones[slot].delete(); tags[slot].delete(); } } ``` Run over thirty hourly bars with twelve bars per zone, this leaves three boxes and three labels: the first created on bar 0 and last moved on bar 11, the second on bars 12 and 23, the open one created on bar 24, moved on bar 29, and reaching one hour past bar 29. The `delete()` calls on the first three zone changes hit ids nobody holds and do nothing; the fourth removes the oldest zone, and its id is created again on the next bar with a new creation bar. ### Restyle later A setter on a later bar is a mutation of the same object, and the bar it ran on is recorded as the handle's last-mutation bar. The prior high as a line that extends with every bar, turns red and thick on the bar the close breaks it, stays for a while, and is deleted, freeing the id for the next level: ```typescript param("lookback", 20, { min: 2, max: 200, description: "Bars in the prior high" }); param("hold", 10, { min: 1, max: 100, description: "Bars a broken line stays before it is deleted" }); output("level", line, overlay, { color: "#94a3b8", description: "The prior high the line sits on" }); output("broke", none, overlay, { description: "1 on the bar the close breaks the line" }); handles.line({ color: "#94a3b8", width: 1, lineStyle: "dashed" }); const MAX_LOOKBACK = 200; const highs = new StaticArray(MAX_LOOKBACK); const stop = draw.line(0); let n: i32 = 20; let hold: i32 = 10; let cursor: i32 = 0; let count: i32 = 0; let level: f64 = NaN; let levelT: f64 = NaN; let fresh: bool = false; let heldBars: i32 = -1; function onStart(): void { n = i32(p_lookback()); hold = i32(p_hold()); } function onBar(): void { const t = bar.time(); const close = bar.close(); // The highest high of the previous n bars, this bar excluded. let prior: f64 = NaN; if (count >= n) { prior = -Infinity; for (let i = 0; i < n; i++) if (highs[i] > prior) prior = highs[i]; } highs[cursor] = bar.high(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (isNaN(prior)) return; // A new level while no broken line is being held: the line restarts here. if (heldBars < 0 && prior != level) { level = prior; levelT = t; fresh = true; } out_level(level); if (fresh) { // Create the line (or re-create it on the same id after a delete). stop.set(levelT, level, t, level); fresh = false; } else if (heldBars < 0) { // Extend the same line to this bar: a mutation, so its mutated bar moves with it. stop.setXy2(t, level); } if (heldBars < 0 && close > level) { // The break: recolor and thicken the existing line, then hold it for a while. heldBars = 0; stop.color(rgba(239, 68, 68, 255)).width(2); } else if (heldBars >= 0) { heldBars += 1; if (heldBars >= hold) { // Delete the held line; the next bar creates a fresh one on the same id. stop.delete(); heldBars = -1; level = NaN; } } out_broke(heldBars == 0 ? 1.0 : 0.0); } ``` ### Fill between two lines `line.fillTo(otherId, color)` shades the area between this line and another line handle, the way a cloud fills between its two spans. The color is an `rgba(...)` value whose alpha is the fill's opacity, and `fillTo(-1, color)` removes the fill. The fill follows both lines as they move, so set it once and keep moving the lines; it stops showing when the other line is deleted. Handle coordinates are absolute times, so both lines, and the fill between them, can reach past the newest bar: that is how a cloud projected ahead of price is drawn. ```text const spanA = draw.line(0); // made once, at module level const spanB = draw.line(1); // onBar(), under bar.isLast(): spanA.set(t, a0, tAhead, a1); spanB.set(t, b0, tAhead, b1); spanA.fillTo(1, rgba(34, 197, 94, 51)); // a green fill, 20% opaque ``` The other line must be live when `fillTo` runs. A fill toward the line's own id, toward an id no handle holds, or toward a box, label or polyline is refused by name, and `fillTo` exists on lines only. When either line is extended (`extend(Extend.Right)`, say), the shading follows the extended segments to the canvas edge instead of stopping at the drawn points. ### Paths built point by point A polyline handle takes its points from a buffer the module owns: `x0, y0, x1, y1, ...` in a `StaticArray`, and `setPoints(points, count)` sends the first `count` pairs (1..100,000; a run's live polylines hold 524,288 points in all). Re-send as the path grows; the host copies the points, so the buffer is yours to shift. `closed(true)` joins the last point back to the first, `fill(c)` fills the polygon under the stroke, `smooth(true)` curves the path through its points, and `arrow(Arrow.End)` puts a head on the last segment; a path sent with one point draws a dot. `gradient(start, end, GradientDirection.Horizontal)` fills the polygon from `start` at its left edge to `end` at its right, painted over the bounding box of its points (`Vertical` runs top to bottom), so a zone can fade out along its length in one polygon: `gradient(alpha(ink, 0.2), alpha(ink, 0.0), GradientDirection.Horizontal)` falls in a straight line to nothing at the far end. `clearGradient()` brings the flat `fill` colour back. A zigzag through the last twelve confirmed swings: ```typescript param("strength", 3, { min: 1, max: 20, description: "Bars on each side that confirm a swing" }); input("high", ohlcv.high); output("swing", none, overlay, { description: "The newest confirmed swing price" }); handles.polyline({ color: "#f97316", width: 2 }); const KEEP = 12; const MAX_STRENGTH = 20; const WINDOW = 2 * MAX_STRENGTH + 1; const highs = new StaticArray(WINDOW); const lows = new StaticArray(WINDOW); const times = new StaticArray(WINDOW); // The path's points, x0, y0, x1, y1, ... in one buffer the host reads count pairs from. const points = new StaticArray(2 * KEEP); const path = draw.polyline(0); let k: i32 = 3; let window: i32 = 7; let cursor: i32 = 0; let filled: i32 = 0; let stored: i32 = 0; let lastDir: i32 = 0; let swing: f64 = NaN; let changed: bool = false; function append(x: f64, y: f64): void { if (stored == KEEP) { // Full: drop the oldest point, keep the newest KEEP - 1. for (let i = 0; i < 2 * (KEEP - 1); i++) points[i] = points[i + 2]; stored -= 1; } points[2 * stored] = x; points[2 * stored + 1] = y; stored += 1; changed = true; } function onStart(): void { k = i32(p_strength()); window = 2 * k + 1; } function onBar(): void { highs[cursor] = bar.high(); lows[cursor] = bar.low(); times[cursor] = bar.time(); cursor = (cursor + 1) % window; if (filled < window) filled += 1; changed = false; if (filled < window) return; // The candidate is the bar k bars back, the center of the window. const center = (cursor + k) % window; let isHigh = true; let isLow = true; for (let i = 0; i < window; i++) { if (i == center) continue; if (highs[i] >= highs[center]) isHigh = false; if (lows[i] <= lows[center]) isLow = false; } // Swings alternate: a high after a high is skipped. if (isHigh && lastDir != 1) { lastDir = 1; swing = highs[center]; append(times[center], swing); } else if (isLow && lastDir != -1) { lastDir = -1; swing = lows[center]; append(times[center], swing); } out_swing(swing); // A new swing: re-emit the whole path under the same id. if (changed && stored >= 2) path.setPoints(points, stored); } ``` ### Declare every kind you draw **Run** records the `handles.*` declarations in the sheet it derives as a `handles` map, one entry per kind with the defaults every new handle of that kind starts from, under their snake_case names. A kind you did not declare refuses its draw calls by name when the indicator runs, so an indicator that draws boxes and labels declares exactly those two, and a `handles.label` whose labels carry text needs a `string(...)` declaration. Field ranges are on the [Limits](../reference/limits.md) page. ### What the chart receives After a run the chart holds one record per LIVE handle, in creation order: its kind, the bar it was created on, the bar it was last mutated on, and its final geometry and style (`createdBar`, `mutatedBar`, `props`). A deleted handle is simply absent. On the live chart the newest bar is re-evaluated as updates arrive (coalesced, at most about once a second): the chart puts the module AND its handles back to the state after the last closed bar and re-runs the bar, so an update never stacks a second copy of what the forming bar drew; when the bar closes, the chart re-runs it once more as a closed bar (with `bar.isLast()` false) before the new bar starts, so a chart that has been open all day shows exactly what a fresh load shows ([Execution model](../core-concepts/execution-model.md)). ## Limits | Family | Cap | | --- | --- | | `box` declarations | 16 per indicator, each drawn once per bar | | `segment` declarations | 16 per indicator, each drawn once per bar | | renderers | 64 per indicator | | declared drawings | 64 per indicator; a declared polyline of at most 64 points | | live handles | 1000 per kind, 1500 in total; a polyline handle of at most 100,000 points and 524,288 across the live polylines; 4096 draw calls per bar | | drawings on the chart | 2,000 per run; a run that would draw more keeps the newest 2,000, and the indicator's legend row says "Drawings capped" | | string slots | 64, each at most 4096 bytes; 64 KiB of strings per row, 2 MiB per run for strings and frames together | | bar offsets | literals in -500..500, whole or fractional; a box or segment offset clamps to the loaded range; a handle's absolute coordinates never clamp | Handles run under the 1000-per-kind ceiling, so a module that keeps drawing deletes stale objects to stay under it; a tracker that evicts its oldest zone with `delete()` stays under it by construction, and a module that draws something on every bar or every event writes a section instead ([Marks, spans and rays](marks-spans-rays.md)). The caps on declared shapes are on declarations, not objects: a repeating pattern is one `box` gated per bar, a batched section, or one handle per live occurrence. ## What you cannot do - Move a declared shape later: only the forming bar is re-evaluated, where the chart replaces that one bar's shapes on each live update, never stacks them. Anything that must move, restyle, or vanish on a later bar is a handle. - Draw an unbounded number of things. The caps above are the whole budget; a handle-drawing indicator deletes what it no longer needs. - Reach more than 500 bars away with a literal offset on a box or segment; pass an output handle for a data-driven reach, and it still clamps to the loaded range. A handle takes an absolute time instead and never clamps. - Fill a box with a named color: the fill takes the opacity, so `color` must be hex, `rgb()`, `hsl()` or a theme token. - Reuse a name across families: outputs, boxes, segments, renderers, and declared drawings share one namespace (handles are ids and have no name). - Let an output color, widen, or gate itself. - Put text in an output, or a string in a param. - Draw from `onStart()`: handle calls belong in `onBar()`, beside the outputs. - Pin a label to the pane's right edge by coordinates alone: a line handle extends past its points with `extend(Extend.Right)`, a line or a label keeps beside the price axis with `stickyRight(true)` (or `sticky_right` on the declaration), and otherwise a label sits where its coordinates say unless it takes a pane `anchor` ([Cards, frames and panels](cards-frames-panels.md#pane-pixel-placement)). - Draw a composite tool (a retracement ladder, a long-and-short box, a rotated text card) in one call: build it from handles, extended lines with `fillTo`, boxes with text, `extend` and a gradient, labels with the `Callout`, `Knockout` and `Plain` looks and an `angle`. # Cards, frames and panels Tables, cards, panels and widgets show one snapshot of your indicator rather than one value per bar: a styled table in a corner, a status card, a small chart in its own pane, a ladder, a feed or a meter. Each is a declaration over outputs, string slots or frames the module already writes, and each selects one snapshot per run: levels docked on the price axis, a heatmap, a table or tiles in their own pane below the chart, and the widgets on the price pane. The per-bar vocabulary lives on other pages: marks, tints and fills on [Plotting](plotting.md), coordinate drawings and handles on [Drawing objects](drawing-objects.md), the canvases drawn from cells (heatmaps, footprints, letter profiles, strike matrices) on [Price canvases](price-canvases.md). Every colour word on this page takes `"#rrggbb"`, `"#rrggbbaa"` or a theme token (`theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid`, `theme.accent`); a token follows the chart's theme and re-resolves on a theme switch without a rerun. A number prints through one `format` word (`price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd`, `auto`) with `decimals` (0..8), `signed` and `unit` (0..8 characters) beside it ([Styling](styling.md)). ## Marks, tints and fills The three per-bar visuals that sit beside a card, in one line each: - A shaped mark on some bars is `render.shape(name, { output, shape, where?, color?, color_by?, colors?, width?, location?, glow?, fill?, fill_opacity?, char?, font_family?, tooltip? })`, one of ten shapes (`circle`, `cross`, `triangle_up`, `triangle_down` with its apex down, `diamond`, `arrow_up`, `arrow_down`, `flag`, `square`, and `char`, one character in `font_family`) drawn at the output's value where the gate is nonzero, so the mark sits where the output points (`low` for below the bar, `high` for above, a level for an absolute price), or where `location` puts it (`"above_bar"`, `"below_bar"`, `"top"`, `"bottom"`) without a second output; `width` (px, any positive number) sizes it, `glow` halos it, `fill: false` keeps the outline only, `fill_opacity` fades the interior and `tooltip` is a template shown on the mark: [Plotting](plotting.md#text-labels-tables-strips-tints). - A tinted candle is `render.barcolor(name, { where, color?, color_by?, colors? })`, body and wick, and a tint behind the bar is `render.bgcolor` with the same options; the two stack (a regime background under trend-colored candles). With `width` (0.5..10 px) and `line_style` a `bgcolor` draws one vertical line per gated bar instead of a band: [Plotting](plotting.md#text-labels-tables-strips-tints). - A fill between two lines is a `range()` over two drawn outputs (`edge_width: 0` keeps the band and drops the edge lines), a `fill("upper", "lower", { color?, opacity?, opacity_by?, color_by?, colors?, color_packed_by?, z?, behind_candles? })` that tints the interior only on one pane (under the candles with `behind_candles: true`), or a one-bar `box` on every bar, gated by `when` for a conditional fill: [Plotting](plotting.md#lines-areas-columns-dots-marks), [Styling](styling.md) and [Drawing objects](drawing-objects.md#boxes). ## Styled tables `render.table(name, { rows, cols, cells, position?, ...look, styles? })` draws a grid of words in a corner of the chart, and you style it in the same declaration: column widths, fills with opacity and gradients, a frame apart from the lines between cells, bold type, merged cells and rounded corners. Each cell is a string slot your file writes in `onBar()`, and the table shows the newest bar where every cell was written. ```typescript // A styled board in the top right corner: a title across both columns, then a trend row and a close row. output("close_line", line, overlay, { color: "#94a3b8", description: "The close, drawn so the table has a chart" }); output("trend_state", none); string("title", { max_bytes: 24 }); string("under_title", { max_bytes: 1 }); string("trend_label", { max_bytes: 16 }); string("trend_word", { max_bytes: 16 }); string("close_label", { max_bytes: 16 }); string("close_text", { max_bytes: 32 }); // The title spans both columns of row one, over the cell under_title holds. The label column is held at 90px and // the value column is measured. Dotted lines sit between the rows; a solid, rounded frame sits around the table. render.table("board", { rows: 3, cols: 2, cells: ["title", "under_title", "trend_label", "trend_word", "close_label", "close_text"], position: "top_right", width: 220, column_widths: [90, 0], cell_padding: 6, font_size: 11, align: "right", text_color: "#e2e8f0", background_gradient: ["#0f172a", "#1e293b"], background_opacity: 0.9, border_color: "#475569", border_width: 1, corner_radius: 8, grid_color: "#334155", grid_width: 1, grid_style: "dotted", grid_lines: "rows", styles: [ { cell: "title", colspan: 2, align: "center", font_weight: "bold", gradient: ["#1d4ed8", "#0f172a"], gradient_direction: "horizontal" }, { cell: "trend_label", align: "left" }, { cell: "close_label", align: "left" }, { cell: "trend_word", font_weight: "bold", color_by: "trend_state", colors: ["#7f1d1d", "#14532d"], opacity: 0.5 }, ], }); let average = new Sma(20); function onBar(): void { const close = bar.close(); if (isNaN(close)) return; const mean = average.update(close); const up = !isNaN(mean) && close > mean; out_close_line(close); out_trend_state(up ? 1.0 : 0.0); str_title("Trend board"); // A covered cell is never drawn, but the table waits for a bar that wrote every cell, so write it empty. str_under_title(""); str_trend_label("Trend"); str_trend_word(up ? "up" : "down"); str_close_label("Close"); sb_clear(); sb_auto(close); str_close_text_sb(); } ``` - **The title spans both columns.** `colspan: 2` on the `title` cell covers the cell to its right. That cell keeps a slot of its own, `under_title`, written empty every bar: a covered cell is never drawn, but the table still waits for a bar that wrote all six cells. - **Two gradients.** The table blends top to bottom at 90% opacity; the title cell has its own gradient, left to right. - **A frame and a grid.** `border_*` is the line around the table, here solid with rounded corners. `grid_*` is the lines between cells, here dotted and between rows only. - **A cell that follows the data.** The trend cell's fill is picked by the `trend_state` output every bar: 0 is the first colour, 1 the second. ### Table options Every key is optional except `rows`, `cols` and `cells`. | Key | What it sets | Values | | --- | --- | --- | | `rows`, `cols`, `cells` | the grid, and one slot name per cell, row by row | at most 32 rows and 32 columns; `rows * cols` names (one string slot each, 64 at most) | | `position`, `offset` | the corner, and a nudge from it | one of the nine anchors, `top_left` to `bottom_right`; `[x, y]` in px, each within 200 | | `width`, `column_widths` | the table's width, and each column's | px, up to 4096; one width per column, `0` fits the words, and spare width goes to the `0` columns | | `header_rows`, `header_row`, `header_column` | which rows and column are headers | `header_rows` up to `rows`; `header_row` is the one-row switch; `header_column` makes the first column a header | | `font_size`, `font_family`, `font_weight` | the type | 6 to 64 px; a font name; `"normal"` or `"bold"` | | `cell_padding`, `align`, `valign` | the space and the alignment in every cell | 0 to 64 px; `"left"`, `"center"`, `"right"`; `"top"`, `"middle"`, `"bottom"` | | `text_color`, `header_text_color` | the text colour | a colour | | `background_color`, `header_background_color`, `background_opacity` | the fills, and how solid they are | a colour; opacity 0 to 1 | | `background_gradient`, `gradient_direction` | a fill that blends from colour to colour | 2 to 8 colours; `"vertical"` (the default) or `"horizontal"` | | `border_color`, `border_width`, `border_style`, `corner_radius` | the frame around the table | width 0 to 10; `"solid"`, `"dashed"` or `"dotted"`; corners 0 to 32 px | | `grid_color`, `grid_width`, `grid_style`, `grid_lines` | the lines between cells | width 0 to 10; the three styles; `"all"`, `"rows"`, `"cols"` or `"none"` | | `position_by` + `positions`, `font_size_by` | a corner or a type size an output picks per bar | a list of anchors; an output holding the size | | `rows_by` | how many rows paint: a table whose rows come and go | a data-only output; its value on the table's bar, rounded down and held to 0..`rows`, is the count of rows painted from the top, the rest left out | | `styles` | one entry per styled cell, named by its slot | `{ cell, ... }` with the cell keys below | The cell keys, inside a `styles` entry: | Key | What it sets | | --- | --- | | `colspan`, `rowspan` | how many columns to the right, and rows below, the cell covers | | `color`, `opacity` | the cell's fill, and how solid it is | | `gradient`, `gradient_direction` | the cell's own gradient (2 to 8 colours), and its own direction | | `text_color`, `font_size`, `font_weight` | the cell's type | | `align`, `valign` | the cell's alignment | | `tooltip` | the cell's hover text: a string slot, its words on the table's bar | A table sized for its longest form can paint fewer rows, and a cell can explain itself on hover: ```typescript output("rows_shown", none); // 3 while the extra rows are on, else 2 string("label", { max_bytes: 16 }); string("value", { max_bytes: 16 }); string("note", { max_bytes: 96 }); // ... one slot per cell of rows 2 and 3 ... render.table("board", { rows: 3, cols: 2, cells: ["label", "value", "a2", "b2", "a3", "b3"], rows_by: "rows_shown", styles: [{ cell: "value", tooltip: "note" }] }); ``` ### Colours that follow the data Every colour key takes a ladder, the way `render.bgcolor` does. Name an output with `_by`, and its value on the table's bar picks an entry of `s`: `color_by: "trend_state", colors: ["#7f1d1d", "#14532d"]`. The value is rounded down, a value outside the list picks the first entry, and `NaN` keeps the static colour. An output that holds a packed colour is named with `_packed_by` instead. A colour reads one ladder, never both. Colours in a table are literals. A `param.color` paints an output, a renderer's static colour or a legend entry, never a table. A second board, with a header row and a tinted trend cell, in one literal: ```typescript output("close_line", line, overlay, { color: "#94a3b8", description: "The close, drawn so the table has a chart" }); output("trend_state", none); string("tf_label", { max_bytes: 16 }); string("trend_word", { max_bytes: 16 }); string("close_label", { max_bytes: 16 }); string("close_text", { max_bytes: 32 }); // A 2 x 2 board: a bold label column held at 80px, numbers right aligned, hairline row separators, // and the trend cell tinted by the trend output every bar (index 0 = down, 1 = up). render.table("board", { rows: 2, cols: 2, cells: ["tf_label", "trend_word", "close_label", "close_text"], position: "top_right", width: 220, column_widths: [80, 0], header_rows: 1, cell_padding: 5, font_size: 11, align: "right", background_color: "#0f172a", background_opacity: 0.92, text_color: "#e2e8f0", header_background_color: "#1e293b", border_color: "#334155", border_width: 1, grid_color: "#1e293b", grid_width: 1, grid_lines: "rows", styles: [{ cell: "tf_label", align: "left", font_weight: "bold" }, { cell: "close_label", align: "left" }, { cell: "trend_word", color_by: "trend_state", colors: ["#7f1d1d", "#14532d"], opacity: 0.35 }] }); let average = new Sma(20); function onBar(): void { const close = bar.close(); if (isNaN(close)) return; const mean = average.update(close); out_close_line(close); const up = !isNaN(mean) && close > mean; out_trend_state(up ? 1.0 : 0.0); str_tf_label("Trend"); str_trend_word(up ? "up" : "down"); str_close_label("Close"); sb_clear(); sb_auto(close); str_close_text_sb(); } ``` ### Limits and refusals | Rule | What the build says | | --- | --- | | one width per column | `render.table 'board' column_widths lists 1 widths for 2 columns (one per column; 0 = measured)` | | a span stays inside the grid | `table 'board' cell 'title' spans 3 columns from column 1 of 2` | | a slot that spans must fit at every cell that lists it, so a covered cell needs its own slot | `table 'board' cell 'title' spans 2 columns from column 2 of 2` | | a style names one of the table's cells | `render.table 'board' styles names cell 'ghost', which is not one of its cells (title, under_title, trend_label, trend_word, close_label, close_text)` | | `rows_by` names a data-only output | `render.table 'board' rows_by names 'close_line', which is a drawn output; rows_by takes a data-only output (plot none) holding how many rows paint` | | a cell's `tooltip` names a string slot | `render.table 'board' styles cell 'title' tooltip names 'ghost', which is not a declared string slot (the cell's hover text is the slot's text)` | | a ladder comes as a pair | `table 'board' cell 'trend_word' declares color_by without colors (both or neither)` | | colours are literals | `render.table 'board' text_color references a param, but a param paints an output, a renderer's static colour or a legend entry, never a table; write a colour literal here` | | a gradient has 2 to 8 colours | `gradient must list at least 2 color stops` | | opacity is 0 to 1 | `opacity must be <= 1` | | corners are 0 to 32 px | `corner_radius must be <= 32` | | words come from the list | `option 'grid_lines' takes "all", "rows", "cols", "none" (a string literal), not 'diagonal'` | The words in a cell are plain text: never a link, never markup. A table declared without the look keys draws the chart's plain table. The chart draws tables with its own table engine, so a styled table shows in screenshots like every other plot. For inline bars and sparklines in a table under the chart, declare a `panel.table` over a frame instead (Frames, panels and compact widgets, below); it takes the same look words, and up to 128 rows by 12 columns. ## Status cards `draw.card(name, { title, anchor?, offset?, z?, state_by?, rows, headline?, ...look })` declares a run-level status card in `drawings[]`, available from `abi_version: "wrun-2"`. Names share the output, renderer, drawing, box and segment namespace. A sheet accepts at most 8 cards within its 64-drawing limit; each card has 1 to 12 rows, or 0 to 12 when it has a headline. A pane holds 32 cards, feeds and meters across every indicator. `title` takes 1 to 40 characters, 80 when it holds a `{{template}}`; each row's `label` takes 1 to 24, 64 with a template. A template reads a declared output as `{{name}}` (its declared format, else six significant digits) or `{{name:format}}`, a string slot as `{{name}}`, and the chart's names as `{{symbol}}`, `{{exchange}}` and `{{timeframe}}`; an unknown name stays as written, and a templated output joins the card's complete-row rule below. `anchor` uses the same nine positions as label renderers: `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`. Defaults are `top_right`, `offset: [0, 0]` and `z: 0`. Each offset is an integer from -4096 to 4096; `z` is an integer. Each row has an optional `value`: a literal string of 0 to 64 characters, `{ text: "slot_name" }`, or `{ output: "output_name", format?, decimals?, signed?, unit? }`. Output references always name declared numeric outputs; `text` always names a declared string slot. Slot contents retain their declared byte limit. The format words are the shared ten plus `pct` (the value times 100, two decimals and `%`); without one a value prints at six significant digits. `si` prints K, M, B, T at one decimal from 1,000 (`5.4K`) and at most two decimals under 1,000 with trailing zeros dropped (`4`, `4.5`, `980`). `usd` prints a `$` with two decimals under 1,000 and `$1.2K`, `$1.2M`, `$1.2B`, `$1.2T` above; `auto` prints six significant digits with `,` thousands; `price` prints at the chart's price digits; `decimals` overrides the word's digits, `signed` puts a `+` on positives, `unit` is appended as written. A row that declares `usd`, `auto`, `int` or `pct` with no `decimals`, `signed` or `unit` keeps the text it always printed (`$1234567.00`, six significant digits with no thousands separators, the rounded integer, the value times 100 at two decimals), so an older card reads exactly as before; the shared text above applies to the other words and to any row that declares a companion. A row's `color` is a colour word or an object containing both `color_by` and `colors`, with at least two colour words. The output's floored value picks a palette entry; a finite index outside the palette selects entry 0. `countdown_to: { output: "deadline" }` carries the numeric output as raw epoch milliseconds, without converting it to seconds. `clock: true` asks the chart to show its clock. Both may appear beside a value. A `headline` is one big number above the rows: `{ output | text, format?, decimals?, signed?, unit?, color?, font_size?, font_weight?, align? }`, exactly one of `output` or `text`, the format and colour words as a row's, `font_size` 6..64 (default 24), `font_weight` `"bold"` unless declared, `align` `"left"`, `"center"` or `"right"`. `rule` draws a hairline between the headline and the rows (default on when both exist) in `rule_color` (default the label ink at 0.4 alpha). The look, every key optional, absent keeping today's card: | Keys | What they set | | --- | --- | | `chrome` | `"state"` (the default: the state word, the stripe, the border in the state colour) or `"plain"` (no state word, no stripe, no border, a muted title, controls on hover); any key below declared beside it wins | | `show_state`, `state_colors`, `stripe`, `controls` | the state word; four colours for ok, armed, fired and error (exclusive with `accent_color`); the 3 px stripe; the hide and collapse glyphs `"always"`, `"hover"` or `"none"` (with `"none"` the glyphs stay hidden at rest, and hovering the card still shows them, so a viewer can always hide or collapse it) | | `accent_color`, `title_text_color`, `title_font_size`, `title_font_weight` | the accent (default the state ink), the title's ink (default the accent), size and weight | | `background_color`, `background_opacity`, `background_gradient`, `gradient_direction` | the surface (default the theme card surface), its alpha (0..1), 2..8 stops `"vertical"` or `"horizontal"` | | `border_color`, `border_width`, `border_style`, `corner_radius`, `padding` | the border (default the accent, 0..10 px, `"solid"`, `"dashed"` or `"dotted"`), the corners (0..32 px, default 6), the inset (0..24 px, default 6) | | `width`, `opacity` | a fixed width (80..1200 px; absent measures the text under a 40% cap, a declared width drops the cap and clamps to the pane width minus 16), the whole card's alpha | | `font_size`, `font_family`, `font_weight`, `text_color`, `label_text_color` | the type (6..64 px, default 12; `"ui"`, `"mono"`, `"serif"` or `"rounded"`; `"normal"`, `"medium"` or `"bold"`), the value ink (default the theme text) and the label ink (default the theme muted ink) | | `above_drawings` | paint over every handle and user drawing, still under the legend (default under them) | | `safe_area` | start the offset past the chart's own chrome: the legend stack at `top_left`, the pane action bar at `top_center` and `top_right`, the price-axis tags on the right anchors (default the pane's 8 px edge) | | `panel` | `"overlay"` (the price pane) or `"lower"` (the indicator's own lower pane; an indicator with none keeps the card on price) | The newest ready bar with every referenced numeric output finite and every referenced slot present wins. Empty strings count as present. If no bar is complete, the newest ready bar still supplies the card: missing values become `""`, missing colours and countdowns are omitted, and missing state reads `ok`. With no ready bar the selection is `{ kind: "card", name, card: null }`. `state_by` maps exactly `0` to `ok`, `1` to `armed`, `2` to `fired`, and `3` to `error`; other values read `ok`. `rows` stays a literal object array, including the nested value, colour and countdown objects. References are literal names, never handles; variables, spreads and expressions are refused. **Run** reads these options and removes the declaration before AssemblyScript typechecks the file; no card accessor is needed. This declaration assumes the named outputs and string slot have already been declared: ```typescript draw.card("session_pnl", { title: "{{symbol}} session", anchor: "top_left", safe_area: true, chrome: "plain", headline: { output: "pnl", format: "usd", signed: true, color: { color_by: "pnl_side", colors: ["theme.down", "theme.up"] } }, rows: [ { label: "Trades", value: { output: "trades", format: "int" } }, { label: "Win rate", value: { output: "win_rate_pct", format: "%", decimals: 1 } }, { label: "Status", value: { text: "status_text" } }, { label: "Next close", countdown_to: { output: "close_at_ms" } }, ], background_color: "#0f141bf2", corner_radius: 10, width: 220, }); ``` `draw.feed` and `draw.meter` take the same look, placement and `panel` words, plus a `title`; a feed also takes `time_format`, a meter `bar_height` and `track_color`, and a ladder its own list (Frames, panels and compact widgets, below). Cards share the selection's 8 MiB expanded-result budget. Accounting is 16 bytes per card and per card row, 8 per carried number (the two offsets, `z`, and each countdown), plus the UTF-8 bytes of every carried string: kind, name, title, headline, state, anchor, row labels, resolved values and colours. Exceeding the budget refuses with `wrun_render_result_too_large`. ## Everything rolls back correctly Markers, tints and bands are per-bar records over outputs, so they follow the engine's forming-bar rule: the chart snapshots the module after the last closed bar and replays the revised forming bar from that snapshot as live updates arrive, and that bar's marks, tints, and slices are replaced, never stacked. Cards replace their selected snapshot on each run. Handle drawings roll back the same way: the chart keeps the handles beside the module state, puts both back before each replay, and re-runs the closed bar once more when it closes, so a handle the forming bar created or moved is never duplicated by an update ([Execution model](../core-concepts/execution-model.md)). ## Every primitive in one module A marker on each bullish and bearish cross, a background tint by the sign of the delta, a shaded band, and a two-cell dashboard, over one moving-average pair. ```typescript param("fast", 9, { min: 1, max: 200 }); param("slow", 21, { min: 2, max: 400 }); const fast = output("fast", line, overlay, { color: "#2563eb", width: 2, description: "Fast average" }); const slow = output("slow", line, overlay, { color: "#94a3b8", width: 1, description: "Slow average" }); output("high", none, overlay, { description: "The bar high: where a bearish mark sits" }); output("low", none, overlay, { description: "The bar low: where a bullish mark sits" }); output("bullish", none, overlay, { description: "1 on a bullish-cross bar" }); output("bearish", none, overlay, { description: "1 on a bearish-cross bar" }); output("delta_bucket", none, overlay, { description: "0 fast below slow, 1 fast above: the tint ladder index" }); string("regime_text", { max_bytes: 8 }); string("delta_text", { max_bytes: 16 }); // Markers: an arrow below the bar on a bullish cross, one above it on a bearish cross. render.shape("buy_mark", { output: "low", shape: "arrow_up", where: "bullish" }); render.shape("sell_mark", { output: "high", shape: "arrow_down", where: "bearish" }); // Bar color: a background tint by regime; index 0 is red, index 1 green, on every bar. render.bgcolor("regime_tint", { where: "fast", color_by: "delta_bucket", colors: ["#ef444418", "#22c55e18"] }); // Fill between: a slice per bar between the two averages. box("ribbon", { top: fast, bottom: slow, color: "#2563eb", opacity: 0.1, borderWidth: 0 }); // A 1x2 dashboard: regime word, delta value. render.table("dashboard", { rows: 1, cols: 2, cells: ["regime_text", "delta_text"], position: "top_right" }); let fastSma = new Sma(9); let slowSma = new Sma(21); const cross = new Cross(); function onStart(): void { fastSma = new Sma(i32(p_fast())); slowSma = new Sma(i32(p_slow())); } function onBar(): void { const close = bar.close(); const fastValue = fastSma.update(close); const slowValue = slowSma.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; const above = fastValue >= slowValue; out_fast(fastValue); out_slow(slowValue); out_high(bar.high()); out_low(bar.low()); out_bullish(crossed == 1 ? 1.0 : 0.0); out_bearish(crossed == -1 ? 1.0 : 0.0); out_delta_bucket(above ? 1.0 : 0.0); str_regime_text(above ? "long" : "short"); sb_clear(); sb_f64(fastValue - slowValue, 2); sb_text(" delta"); str_delta_text_sb(); } ``` `regime_tint` gates on `fast`, which is finite on every ready bar, so the tint appears everywhere and the ladder picks the color; gate on a `0`/`1` output instead to tint only some bars. The 8-digit hex colors carry the tint's alpha. ## Frames, panels and compact widgets Use `wrun-4` frames for one JSON snapshot that survives the whole run. Declare `frame("book")`, then write it from `onBar()`: a frame rebuilt on every bar or live tick is built in the generated frame buffer with `fb_clear()`, `fb_text(s)`, `fb_str(s)`, `fb_int(n)`, `fb_f64(x, decimals)` and `fb_num(x)` and sent with `writeFrameBuffer(FRAME_BOOK)`, allocation-free; a small frame the module already holds as a string goes through `writeFrame(FRAME_BOOK, json)`. Each frame holds its last write, up to 96 KiB; up to eight frames share a 2 MiB transport budget with strings. | Declaration | Snapshot | | --- | --- | | `plot.levels({ name, frame, dock, width_frac?, poc?, labels?, color?, span?, ...style })` | `{ prices, values, colors?, ...fields }`; 1..512 monotonic prices and equally sized values, null for gaps; with `span: "time"`, `{ spans: [{ start, end, prices, values, colors?, labels_text?, series?, value_area?, poc_price?, poc_label_text? }] }`, 1..64 spans and at most 4096 rows in all | | `panel.bars`, `panel.line`, `panel.scatter`, `panel.histogram`, `panel.pie`, `panel.heatmap`, `panel.table`, `panel.tiles` | `{ rows, ...chrome }`; kind-specific tuples, at most 2000 rows (a table 128), empty allowed; a chrome field beside `rows` overrides the declared word for that run; a table's `markets` names the market each row is about | | `plot.matrix({ name, frame, dock?, columns?, ...style })` | `{ prices, cells, cols?, title?, highlight?, range? }`; 1..128 prices, one cell row per price of 1..12 columns, at most 1536 cells ([Price canvases](price-canvases.md)) | | `draw.ladder({ name, frame, side, divider?, title?, ...style })` | `{ rows, divider?, title? }`; 1..256 price/value/fraction/color rows | | `draw.feed({ name, frame, anchor?, offset?, z?, title?, time_format?, ...style })` | `{ lines, title?, markets? }`; 1..50 millisecond-time/text/color rows, and the market each line is about | | `draw.minicharts({ name, frame, anchor?, x?, y?, columns?, panel_width?, panel_height?, gap?, ... })` | `{ title?, panels }`; 1..12 labelled panels of 0..100 candles | Levels default to a width fraction of 0.12. Every colour in a declaration or a frame takes `#rrggbb`, `#rrggbbaa` or a theme token (`theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid`, `theme.accent`), resolved by the chart at paint time and again on a theme switch. The levels style words (placement, bars, labels, the point of control, hover and the frame fields they read) are on [Docked profiles](cards-frames-panels.md#docked-profiles). Panels declare name, title, x (`time`, `index`, `number`, `category`), place (`below`, `side`) and frame. Bars, line and table also declare series (1..8, a table 1..12), each `{ name, color? }` plus its own look. Histograms and heatmaps use category x; a `number` x takes decimal row keys (a price grid) on a line, bars or scatter. An unwritten frame leaves its consumer absent; a malformed written frame refuses with `wrun_frame_invalid`. ### Panel words Every word is optional and scoped by kind: a word on a kind it does not list refuses by name ("`` is only valid for "). Absent words keep the chart's look, except `font_family`, whose default `"ui"` is the app font (the four words are `"ui"`, `"mono"`, `"serif"`, `"rounded"`). | Kind | Words | | --- | --- | | every kind | `height_frac` (0.05..0.9, the pane's share of the chart), `maximize` (the legend's fullscreen button), `font_family`, `format` with `decimals` (0..8), `signed` and `unit` (1..8 characters) for every value the panel prints | | line, bars, histogram, scatter, pie | `chrome` (`"hairlines"`, `"box"`, `"grid"` or `"none"`, absent `"hairlines"`: horizontal value hairlines only; pie `"box"` or `"none"`, absent `"box"`), `hover_card` (a readout under the pointer, default on; not on pie or table), `legend_style` (`"none"`, `"title"`, `"pane"`, `"chips"` on a line; bars drop `"chips"`; scatter and pie take `"none"` or `"title"`), `x_title`, `y_title` (1..40), `y_min`, `y_max` (the value axis), `y_zero` (line and scatter), `x_min`, `x_max` (a line with x `index` or `number`, scatter) | | line, bars, histogram, scatter | `badge` (`{ text: 1..24, color?, text_color? }`): a chip on the panel's title row, filled `theme.accent` unless `color` says otherwise, its text in whichever of light or dark reads on the fill unless `text_color` picks one | | line | `stats_row` (with `maximize`), `smooth`, `points`, `labels` (each series' last value at its end), `glow`, `animate`, `legend_latest` (with `legend_style: "chips"`), `fill_mode` (`"flat"` or `"signed"`), `fill_positive_color`, `fill_negative_color`, `fill_fade`, `stroke_fade` (`{ pivot: number | "spot", edge_opacity?, left_color?, right_color? }`), `markers` (0..8 of `{ x: number | string | "spot", label?, color?, badge?, wash?, valign?: "top" | "middle" | "point", y?, series?, show_value?, line_style?, width? }`; `valign: "point"` makes the marker a callout pinned at a point on the curve instead of a line down the pane, `y` fixing the value or `series` naming the declared series whose value at `x` anchors it, the first series by default; `y` and `series` need `"point"`, and `series` must be a declared series), `x_format`, `x_decimals`, `x_unit` (with x `index` or `number`), `positive_color`, `negative_color` | | a line series | `fill`, `fill_color`, `style` (`"line"`, `"bars"`, `"step"`), `smooth`, `points`, `labels`, `width` (0.5..20), `line_style`, `legend` | | bars | `color_mode` (`"series"` or `"sign"`), `positive_color`, `negative_color`, `x_format`, `x_decimals`, `x_unit` (with x `index` or `number`); a series `legend` | | histogram | `color`, `labels` (each bin's count), `bins` (2..200 slots reserved on the axis) | | scatter | `color`, `guides` (0..8 of `{ axis: "x" | "y", value, label?, color?, line_style?, width? }`), `quadrants` (`{ x, y, colors: [4], labels?: [4] }`), `trails`, `trail_width` (0.5..6), `trail_fade`, `label_overlap` (`"hide"`, `"leader"`, `"show"`; with `labels`) | | pie | `hole_total`, `hole_caption` (1..24; both need `hole > 0`), `slice_gap` (0..8 px), `border_color`, `border_width` (0..10) | | heatmap | `scale` (`"palette"` or `"signed"`), `palette` (2..8 colours), `min`, `max`, `highlight` (`{ row?, col? }`), `row_title`, `col_title` (1..24), `positive_color`, `negative_color` | | tiles | `columns` (1..8), `accent` (`"auto"` or `"neutral"`), `positive_color`, `negative_color` | | table | the styled-table words (`position`, `offset`, `width`, `column_widths`, `cell_padding`, `font_size`, `font_weight`, `align`, `valign`, `text_color`, `header_text_color`, `background_color`, `background_opacity`, `background_gradient`, `gradient_direction`, `header_background_color`, `border_color`, `border_width`, `border_style`, `grid_color`, `grid_width`, `grid_style`, `grid_lines`, `header_column`) with the same ranges; a series `align`, `format`, `decimals`, `signed`, `unit` (the column's) | A colour word of a panel declaration may name a setting instead of a colour: `"@"` for a declared `param.color` binds every colour word above: a series' `color` and `fill_color`, `positive_color` and `negative_color`, the `fill_*_color` pair, a heatmap's `palette` entries, a histogram's or a scatter's `color`, the badge, marker, guide and quadrant colours, the stroke fade's inks and the pie and table colours. The build writes the setting's default in its place, so the sheet reads as if you had written that colour, and the chart paints the trader's pick there before every run; the setting's row is the colour's one control ([The Style page](../settings/style-page.md)). A reference to anything but a `param.color` is refused by name (`panel.bars 'flow' positive_color references "@side", which is not a param.color`), and an `@` in a title or a series name stays text. A colour inside a frame's rows (a pie slice, a scatter dot, a tile, a table cell) is run data: the module reads its `param.color` and writes the colour into the row. ```typescript param.color("bid_ink", "#22c55e", { label: "Bids" }); param.color("ask_ink", "#ef4444", { label: "Asks" }); panel.line({ name: "depth_curve", title: "Cumulative depth", x: "number", place: "below", frame: depth, series: [{ name: "Bids", color: "@bid_ink", fill: true, fill_color: "@bid_ink" }, { name: "Asks", color: "@ask_ink" }] }); ``` The rich words of a line (`smooth`, `points`, `glow`, `animate`, the fills, the stroke fade, `markers`, `stats_row`, `legend_latest`, `hover_card`, `legend_style: "chips"`, a series `fill_color`, `style: "step"`, `smooth`, `points` or `labels`) are refused only on a line that declares `chrome: "box"`. A line, bars, histogram or scatter panel that declares no chrome draws `"hairlines"`, horizontal value hairlines only with no frame and no vertical lines, on every x, stacked or not; a pie draws `"box"`. A time line with any chrome but `"box"` spaces its points by time and labels the axis in the chart's display timezone. A rich line panel (any chrome but `"box"`, so every line that declares none) keeps its own value axis on the left, so the pane's right-hand value strip stays blank: the strip belongs to series that share the chart's time axis, and a curve over strikes or distances does not. An indicator's panels also stack above its time-series panes: the panes that read the time axis sit at the bottom, next to the time axis, and the panels sit above them, each group in declaration order. ### Panel frames Beside `rows`, a frame may carry per-run chrome: `title` (1..40) and `caption` (1..64) on every kind; `badge` (`{ text, color?, text_color? }`) on line, bars, histogram and scatter; `markers`, `x_min`, `x_max`, `y_min`, `y_max` on a line; `y_min`, `y_max` on bars and histogram; `x_labels` on a line or bars whose x is `"number"` (below); `x_min`, `x_max`, `y_min`, `y_max`, `guides`, `quadrants` on scatter; `min`, `max`, `highlight` and `summary` (0..5 of `{ label, values }`, the values following the columns) on a heatmap; `hole_text` and `hole_caption` (1..24) on a pie; `markets` (one entry per row, [Rows that open a market](#rows-that-open-a-market)) on a table. A frame field overrides the declared word of the same name for that run, `markers` replaces the declared list and `badge` replaces the declared chip (a frame without the key leaves the declared chip standing); any other key beside `rows` refuses by name. Frame markers take the same words as declared ones, `valign: "point"` with `y` or `series` included, so a module can point at the peak it just found. `x_labels` gives each row of a line or bars panel on x `"number"` its own text under the x axis: a list of strings, one per row in row order, `""` for a row without a label, each at most 24 characters. The chart prints a row's label in place of its number, so an axis of days to expiry can read `15 Jan`, `22 Jan`, `15 Jan '27`. It names rows and overrides no declared word. A list of another length than the rows, a label over 24 characters, or the key on a panel whose x is not `"number"` refuses the whole frame, as a bad row does (`x_labels must hold one text per row (3), "" for a row without a label`; `x_labels is only valid for a line or bars with x 'number'`), so no half-labelled axis is ever drawn. `fbExpiryLabel(expiryMs, nowMs, zone)` writes an option expiry's label into the frame buffer, the text `TextBuilder.expiry` spells: the expiry's trade date on the market's clock (`zone` is `i32(p_market_zone())`) as `15 Jan`, or `15 Jan '27` when its year is not the year of now's trade date, at most ten characters that need no escaping. It writes no quotes, so open and close the string around it: ```typescript fb_text('],"x_labels":['); for (let i = 0; i < count; i += 1) { if (i > 0) fb_text(","); fb_text('"'); fbExpiryLabel(expiries[i], nowMs, zone); fb_text('"'); } fb_text("]}"); ``` The frames module carries the writer only when a source names `fbExpiryLabel`, so every other package keeps its bytes. Rows take colour words wherever they took a hex colour: a scatter row's colour, a pie slice's, a tiles row's, a table cell's. A bars value may be `{ value, color? }` to colour one bar. A tiles row may end with its own format word (`[label, value, caption?, color?, spark?, format?]`, with null to skip an element). A table cell may be a styled object with `text`, `value` (printed through the column's or the table's format when text is absent), `color`, `bar`, `spark`, `background_color`, `opacity`, `gradient`, `text_color`, `font_size`, `font_weight`, `align`, `valign`, `colspan` and `rowspan`; a table takes 128 rows and 12 columns, the other kinds 2000 rows. ### Rows that open a market A table row or a feed line can name the market it is about, so that a click on it opens that market's chart in a new chart tab (upcoming: no chart opens a row's market yet): a flow table whose rows open their option contracts, a tape whose lines open the contract that printed, a list of tickers that open their stock charts. The chart you are on stays as it is. The frame carries `markets` beside `rows` (a table) or `lines` (a feed), one entry per row or line in the order written, each `null` (a row about no market, a total) or one of two forms, in symbol codes: | Entry | Names | | --- | --- | | `{ "contract": [root_code, expiry_ms, side_cp, strike] }` | one US listed option contract: the option root's code (1 to 6 characters, as listed: `SPXW`, `BRKB`), the expiry in epoch milliseconds, `+1` a call and `-1` a put, the strike (above 0 and below 100000) | | `{ "ticker": code }` | one stock or ETF by its ticker's code (1 to 10 characters) | The contract is the one the US listed options cells carry: the same four values lead each `option_contract_flow` and `option_contract_state` tuple and sit at cells 2 to 5 of an `option_prints` tuple (after `offset_ms` and `print_key`), so a row built from a cell names its contract as it reads it; `encodeSymbol("SPY")` spells a code ([Data sources](../core-concepts/data-sources.md#us-listed-options-opra)). The generated frame buffer writes an entry with `fb_contract(root_code, expiry_ms, side_cp, strike)` and `fb_ticker(code)`: ```typescript // Two rows of a flow table, each naming its market: a contract, then a ticker. fb_clear(); fb_text('{"rows":[["SPY 450C","1.2M"],["QQQ","block"]],"markets":['); fb_contract(encodeSymbol("SPY"), expiryMs, 1.0, 450.0); fb_text(","); fb_ticker(encodeSymbol("QQQ")); fb_text("]}"); writeFrameBuffer(FRAME_FLOW); ``` The frame that code writes, the contract expiring 18 December 2026 (`expiryMs` 1797627600000) and the two tickers as their codes (`SPY` 42,899, `QQQ` 40,041): ```json { "rows": [["SPY 450C", "1.2M"], ["QQQ", "block"]], "markets": [{ "contract": [42899, 1797627600000, 1, 450] }, { "ticker": 40041 }] } ``` A list whose length is not the row or line count, an entry in neither form, and `markets` on any panel kind but a table refuse the frame by name. Once that ships, the chart opens the market on its own rules: a contract chart applies its own data access, and a row with `null` takes no click. A Protected indicator's table and feed, run on OpenMarket's servers, draw their rows without their markets for now. ### Side placement and windows `place: "side"` marks a panel as side content. On a chart it mounts below the candles like every other panel, in a pane of its own with the same options. What it adds is a **window**: the chart offers an Indicator with side content a cell of its own, where the candles are hidden and the Indicator's panels, tables and lower pane fill the whole height. The window keeps the market and timeframe of its cell; that market is still the file's first input and its clock, so the Indicator runs exactly as it does on a chart. How a reader opens one: - The window icon beside the Indicator's name in the legend. It shows while the sheet places any panel `side`; once the reader has seen or used it, it moves in with the row's hover buttons. - The legend menu: **Open as window** (a new cell beside the chart, which keeps its Indicator), **Show as window here** (this cell becomes the window) and, on a window, **Show chart**. - **Add as window** in the Indicators picker, on a package page and in search. In a window the header carries the Indicator's name, its settings and its menu; the market chip still switches the market and the Indicator runs again. Drawing tools, price alerts and replay are off there. An Indicator with nothing to show beside the candles (price-pane plots only) gets a "Nothing to show as a window" card with Show chart. Removing the Indicator from a window that was opened into its own cell closes that cell and the layout returns to what it was; a chart turned into a window in place comes back as a chart. The window sizes the panes itself: tables take the height their rows need (together at most half the window), the other panels and the lower pane share the rest. `width_px` (160..480) and `height_px` (80..800) are accepted only with `place: "side"` and are reserved for a strip beside the price pane that panels do not use today; the strip beside the price axis is for `dock: "side"` matrices ([Price canvases](price-canvases.md)). A window also remembers and answers: - The pointer on a window's index or category panes (a curve over strikes, a bars panel): a guide snaps to the nearest key with a dot per series, a readout shows the values there, and the legend values follow the key; leaving the pane shows the last row again. `tooltipEnabled: false` removes the card only. - The split a reader drags between a window's panes is remembered across reloads for that Indicator; it resets when the Indicator's set of panes changes. - Closing a window cell can be undone: Ctrl+Z / Cmd+Z brings the cell back where it was, with the Indicator. - A draft you are editing can open as a window: press Open as window beside Run in the editor; every later Run lands in that window, and stopping the draft or closing its tab closes the cell. A draft window is not saved: after a reload the cell is an empty chart. `draw.meter({ name, label, fraction: { output }, ramp, text?, anchor?, offset?, z? })` reads the last ready numeric fraction. Ramp has 2..5 colour words; text is a short literal or `{ slot }`. A card row's `spark: { output, window }` carries its last 2..64 ready values, oldest first. A ladder, feed or meter takes a `title` (1..40 characters; a ladder or feed frame may carry its own `"title"` per run, and a meter title takes the card templates), the card surface and chrome words (the background, border, `corner_radius`, `padding`, `width`, `opacity`, the type words, `chrome`, `stripe`, `controls`, `accent_color`, `above_drawings`, `safe_area` and `panel`, with the card's ranges) and an `offset` of -4096..4096 px. A ladder also takes `width_frac` (0.02..0.5, default 0.14), `offset: [x, 0]` (x 0..4096 px inward from the axis), `opacity`, `color` (the row default), `labels`, `format`, `decimals`, `signed`, `unit` (the value text), `text_color`, `font_size`, `font_family`, `font_weight` and `divider_color`; its frame carries 1..256 rows with colour words. A feed takes `time_format` (`"HH:mm:ss"`, `"HH:mm"`, `"MM-dd HH:mm"` or `"none"`); a meter takes `bar_height` (2..40 px) and `track_color`, and its ramp takes colour words. `draw.minicharts({ name, frame, ... })` pins a grid of up to 12 small candle charts to the pane, the grid a multi-timeframe matrix draws. Its options: `anchor` (default `top_right`) and `x`, `y` pixel offsets from it (-2000..2000, default -16 and 48), `z`, `columns` 1..4 (2), `panel_width` 72..320 (128), `panel_height` 48..220 (72), `gap` 0..48 (8), the colours `background_color`, `border_color`, `text_color`, `bull_color`, `bear_color` and `wick_color`, `candle_style` (`candles`, `hollow`, `bars`, `line`, `area`), two moving averages (`ma_fast_length`, `ma_slow_length`, each drawn only when given, with `ma_fast_color`, `ma_slow_color`, `ma_width` 0.5..5 and the `show_fast_ma` / `show_slow_ma` switches) and `show_change` / `show_volume` for the change badge and the volume strip, which the chart computes from the candles. Every option takes a literal. The colours, the switches, the average lengths, `ma_width` and `candle_style` also take an `"@"` reference, so a setting changes that option: a `param.color` for a colour, a `param.bool` for a switch, a `param.int` with `min` 1 or more for a length, a `param.number` or `param.int` within 0.5 to 5 for `ma_width`, a `param.choice` over the style words for `candle_style`. The setting's default draws until it is changed, and one setting may drive several options. The frame carries the title and each panel's label and candles, `[time_ms, open, high, low, close, volume]` oldest first, volume `null` for none. Build it with the grid's writers: `mc_begin(title)` clears the frame buffer and opens the grid, `mc_panel(label)` opens a panel, `mc_bar(openSec, open, high, low, close, volume)` appends a candle (its open in epoch seconds), `mc_candles(label, list, bars, formingSec, open, high, low, close, volume)` writes a whole panel from a `CandleList` of closed candles plus the forming candle (`NaN` for none; it is drawn last when it opens after the newest closed one, `bars` candles at most), and `writeMiniCharts(FRAME_GRID)` sends it. `mc_leg(label, list, bars, in_x_view(), in_x_cells(), bar.time())` reads that forming candle off a `candles` input declared with `view: "forming"`, the timeframe's live candle on the live bar. A title of `{{symbol}}` reads as the chart's market. A grid with no reference gets settings of its own: the look's colours, candle style, averages and switches ("Panel background", "Bull candle", "Fast MA length", "Candle style", "Show volume", ...), each defaulting to the value written here; write colours as `"#rrggbb"` or `"#rrggbbaa"`. `out.inset("vol", { dock: "bottom", height_px: 28, shape: "histogram" })` declares an ordinary numeric output in a compact strip. Every ready row appears in its history. Insets work on every ABI. An inset also takes `color`, `colors` (`[up, down]` by sign, or a ladder beside `color_by`) and `opacity`. The build extracts these object declarations before AssemblyScript type checking. `frame()` returns its slot index; generated `FRAME_` constants provide the same index. The frame builder exists only when frames are declared. Its UTF-8 scratch is one `StaticArray` sized to the largest declared `max_bytes`, reserved during module initialization and reused by every `fb_*` append and by `writeFrame`, so repeated frame writes never grow guest memory; the string handed to `writeFrame` is the caller's own allocation, which is why a frame rebuilt per bar builds through `fb_*` instead. `fb_text` appends raw JSON text (punctuation, keys, words), `fb_str` a quoted and escaped JSON string, `fb_int` an integer, `fb_f64` a number with a fixed decimal count, `fb_num` a double's shortest spelling; `fb_f64` and `fb_num` write `null` for a non-finite value, JSON's gap. Both senders pass the bytes the frame requires, so an oversized frame refuses host-side by the slot's `max_bytes`, never truncated. The caps an author meets are on [Limits](../reference/limits.md). ### Pane pixel placement Line, box, label and polyline handle declarations accept `anchor` as the default for newly created handles: `handles.line({ anchor: "top_left" })`. Absent means chart coordinates. The nine pane spots are `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`; both coordinates become CSS pixel offsets. `top` and `bottom` change only y; x remains chart time. `left` and `right` change only x; y remains chart price. Offsets start at the pane's content rectangle with no extra inset. Left and top measure inward to the right and down; right and bottom measure inward to the left and up. Centre offsets are signed, and negative offsets are allowed everywhere. The renderer scales pixels once by device pixel ratio and clips every drawing to its own pane. Time culling applies only when x remains chart time. `safe_area: true` on a handle declaration (`handles.box({ anchor: "top_right", safe_area: true })`) starts the offsets past the chart's own chrome instead: the legend stack at the top left, the pane action bar at the top centre and right, the price-axis tags on the right. After a handle's `set`, call `.anchor(ANCHOR_TOP_LEFT)` or `style.anchor(handle, ANCHOR_TOP_LEFT)` with an `ANCHOR_*` constant. `ANCHOR_CHART` restores chart coordinates and clears a declared default until the handle is recreated. These helpers go through `style` with prop 7, integer values 0..13. Invalid values refuse as `wrun_draw_style_out_of_range`. Label handles also take `align`: which edge of the text sits on x, with (x, y) staying the anchor point. `handles.label({ align: "left" })` is the default for new labels; `left` starts the text at x, `right` ends it there, `center` or an omitted word centres it as before. After a label's `text`, call `.align(ALIGN_RIGHT)` or `style.align(label, ALIGN_RIGHT)` with an `ALIGN_*` constant; `ALIGN_DEFAULT` restores centred text and clears a declared default. These use prop 8, integer values 0..3, on labels and box text (a box takes `align`, `valign` and `padding` too); other kinds refuse as `wrun_draw_prop_unsupported`. ## Docked profiles `plot.levels({ name, frame, dock, ... })` draws a profile docked on the price axis from a frame the module writes each run: one bar per price, its length the row's value. The required words and today's optional ones (`width_frac`, `poc`, `labels`, `color`) keep their meaning; everything below is opt-in, erased before the file compiles, and takes `"@"` on any style key so the Style page can change it without a rerun of your code ([The Style page](../settings/style-page.md)). Where the profile sits: | Word | Value | What it does | | --- | --- | --- | | `panel` | `"overlay"` (default), `"lower"` | on the price pane, or on the indicator's own lower pane, where the frame's prices read on that pane's value scale (an RSI or CVD profile beside the oscillator); `"lower"` needs a lower pane | | `behind_candles` | boolean (default false) | the bar fills draw under the candles; labels, the POC, the value-area lines, borders and the outline stay above; refused on `"lower"`, beside `gradient`, or with `shape: "outline"` | | `span` | `"pane"` (default), `"time"` | docked on the pane edge, or one profile per time span the frame carries, each laid out between its own start and end ([Profiles in time spans](#profiles-in-time-spans)) | | `offset` | `[x, 0]`, x 0..4096 px | inward from the pane edge, or from the neighbour named by `beside` | | `beside` | another declared level's name | dock right inside that level (open interest beside gamma); refused when it names itself, an undeclared level, a level on another panel or dock side, a level with `span: "time"`, or closes a cycle | | `width_px` | 16..600 px | a fixed dock width instead of `width_frac`; refused beside it | | `scale`, `scale_max` | `"own"` (default), `"shared"`, `"fixed"`; a number > 0 | `"shared"` scales every `"shared"` level of the indicator by the largest row among them; `"fixed"` fills the dock at `scale_max` (required there, refused otherwise) and clamps longer rows; the frame's `scale_max` overrides it per run | | `thickness_px` | 2..40 px | the tallest a bar may be, centred on its price | | `step` | number > 0 (price units) | every row spans its price plus and minus half a step (a strike ladder) | `offset`, `beside`, `width_px`, `scale: "shared"` and `step` place the pane dock only. A level with `span: "time"` that declares one is refused by name ([Profiles in time spans](#profiles-in-time-spans)). How the bars paint: | Word | Value | What it does | | --- | --- | --- | | `color`, `opacity` | a colour word; 0..1 (default 0.65) | the bar colour and the alpha every bar colour's own alpha is multiplied by; `opacity: 1` paints the exact colour | | `baseline` | `"edge"` (default), `"center"` | `"center"` puts zero mid-dock: positive values grow one way, negative the other (a net gamma profile); under `"edge"` a negative row draws nothing | | `series` | 1..8 of `{ name, color }`, unique names | one row split into stacked segments (calls and puts), fed by the frame's `series` arrays | | `gradient`, `gradient_direction` | 2..8 colour words; `"horizontal"` (default) or `"vertical"` | fading bars: horizontal runs from the bar's root to its tip; a row or segment with its own colour keeps it and takes the stops' alpha profile; refused beside `behind_candles` | | `border_color`, `border_width`, `border_style` | a colour word; 0..10 px (1 when a colour is set, else 0); `"solid"`, `"dashed"`, `"dotted"` | an outline on every bar and segment | | `shape` | `"bars"` (default), `"outline"` | `"outline"` draws no fills, one stepped line along the bar tips per side, broken at null rows | | `outside_opacity` | 0..1 (default 0.5) | how far rows outside the frame's value area fade | | `value_area_color`, `value_area_width`, `value_area_line_style`, `value_area_labels` | a colour word (default the level colour); 0..10 px (default 1, 0 draws no lines); `"dashed"` unless declared; boolean | the two lines across the dock at the value area's low and high prices, and the `VAH` and `VAL` tags beside them | Labels, the point of control and hover: | Word | Value | What it does | | --- | --- | --- | | `labels` | boolean | the row labels; a frame with `labels_text` turns them on unless the declaration says `false` | | `format`, `decimals`, `signed`, `unit` | the shared number words | how a row without its own text (and its hover value) prints; without a format word the value prints as written | | `text_color`, `font_size`, `font_weight`, `font_family` | a colour word (default the row colour at full alpha); 6..64 px (default 10); the weight word; `"ui"`, `"mono"`, `"serif"`, `"rounded"` (default the chart axis font) | the label type | | `label_place` | `"outside"` (default), `"inside"`, `"axis"` | beyond the bar tip, inside the bar at its tip, or inside at its root | | `tag_place` | `"inner"` (default), `"axis"` | where the `POC`, `VAH` and `VAL` tags sit: at the dock's inner end, away from the pane edge it hangs on, or at its edge on the axis side, where the chart's own profiles put them; under `span: "time"`, at a span's root or at its other end. Only the tags move: the row labels and the lines stay put | | `hover` | boolean (default false) | hovering a row opens the chart's hover card: the price, the value, one line per series, the row's tooltip | | `poc`, `poc_color`, `poc_width`, `poc_line_style`, `poc_extend`, `poc_label` | boolean; a colour word (default the POC row colour); 1..10 px; the line style; `"dock"` (default) or `"pane"` (across the whole pane); boolean | the point of control line (the largest row unless the frame names `poc_price`) and its tag (`POC` and the price, or the frame's `poc_label_text` printed as written) | The frame carries the data and may carry per-run chrome beside `prices`, `values` and `colors`: | Field | Value | What it does | | --- | --- | --- | | `prices`, `values`, `colors` | 1..512 strictly ordered numbers; as many numbers or null (a gap that keeps its band); colour strings (`#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`, a theme token; anything else falls back to the level colour) | the rows | | `labels_text` | one string of 0..24 characters or null per row | that text on the row; `""` leaves the row bare; null prints the formatted value | | `series` | one array of numbers or null per declared series, each the length of `prices` | the segments, stacking outward from the baseline in series order; `values` still names the row for its label and hover; never beside `colors` | | `lows`, `highs` | one number or null per row, both arrays together, `low` below `high` | a row's own price band; a null pair falls back to `step`, else to the neighbours' midpoints | | `tooltips` | one string of 0..64 characters or null per row | the hover card's hint | | `value_area` | `[low, high]` prices | the value area: rows outside dim, two lines across the dock | | `poc_price`, `poc_label_text` | a number; 1..24 characters | the price the POC line marks; the whole tag, printed as written (turns the tag on) | | `scale_max` | a number > 0 | the fixed scale for this run; `scale: "fixed"` only | | `spans` | the time-anchored shape | with `span: "time"`, in place of the fields above; each span may carry its own `labels_text`, `series`, `value_area`, `poc_price` and `poc_label_text` ([Profiles in time spans](#profiles-in-time-spans)) | A frame whose shape disagrees with the declaration (a `series` count that differs on the frame or on one span, `colors` beside `series`, a `scale_max` on a level whose scale is not `"fixed"`, a `spans` frame on `span: "pane"`) refuses the run as `wrun_frame_invalid`. A two-sided profile of calls and puts, net at the baseline, with a value area and a tagged point of control: ```typescript param.choice("side", ["right", "left"], "right"); param.color("call_ink", "#38bdf8"); param.color("put_ink", "#a78bfa"); const gexFrame = frame("gex_levels", { max_bytes: 32768 }); plot.levels({ name: "gex", frame: gexFrame, dock: "@side", baseline: "center", width_frac: 0.18, series: [{ name: "Calls", color: "@call_ink" }, { name: "Puts", color: "@put_ink" }], labels: true, format: "usd", label_place: "inside", poc: true, poc_extend: "pane", poc_label: true, hover: true, outside_opacity: 0.4 }); ``` ```json { "prices": [62000, 62500, 63000, 63500], "values": [41000, -18500, 25000, 9000], "series": [ [52000, 11000, 30000, 12000], [-11000, -29500, -5000, -3000] ], "labels_text": ["C 52.0K / P 11.0K", null, "", null], "tooltips": ["Calls 1,240 OI / Puts 860 OI", null, null, null], "value_area": [62000, 63000], "poc_price": 62000, "poc_label_text": "Max pain" } ``` A session volume profile the module bins itself, docked right: rows six pixels thick, the value area marked by dotted amber lines with their `VAH` and `VAL` tags, rows outside it faded, and the point of control drawn across the dock. ```typescript const sessionFrame = frame("session_rows", { max_bytes: 16384 }); plot.levels({ name: "session_profile", frame: sessionFrame, dock: "right", width_frac: 0.2, color: "#38bdf8", thickness_px: 6, outside_opacity: 0.35, value_area_color: "#f59e0b", value_area_width: 1.5, value_area_line_style: "dotted", value_area_labels: true, poc: true, }); ``` The same profile with its `VAH`, `VAL` and `POC` tags on the axis side of the dock, where the chart's own profiles put them. The bars, the row labels and the lines stay where they were: ```typescript const sessionFrame = frame("session_rows", { max_bytes: 16384 }); plot.levels({ name: "session_profile", frame: sessionFrame, dock: "right", width_frac: 0.2, color: "#38bdf8", value_area_labels: true, poc: true, poc_label: true, tag_place: "axis" }); ``` Open interest by price with every bar outlined in a dotted hairline, the fills at half strength, and a strong dashed point of control across the whole pane with its tag on: the look for a profile that sits under other overlays and still has to read. ```typescript const oiRows = frame("oi_rows", { max_bytes: 16384 }); plot.levels({ name: "oi_profile", frame: oiRows, dock: "left", width_frac: 0.15, color: "#a78bfa", opacity: 0.5, border_color: "#c4b5fd", border_width: 1, border_style: "dotted", poc: true, poc_color: "#f472b6", poc_width: 3, poc_line_style: "dashed", poc_extend: "pane", poc_label: true, }); ``` A liquidation map docked right inside that open interest profile, on a fixed scale so a new cluster never rescales the dock, each row spanning the price band its frame gives it instead of the midpoints between neighbours. ```typescript const oiRows = frame("oi_rows", { max_bytes: 16384 }); const liqRows = frame("liq_rows", { max_bytes: 16384 }); plot.levels({ name: "oi_profile", frame: oiRows, dock: "left", width_frac: 0.15, color: "#a78bfa", format: "si" }); plot.levels({ name: "liq_map", frame: liqRows, dock: "left", beside: "oi_profile", width_frac: 0.08, color: "#f97316", scale: "fixed", scale_max: 50000000, format: "usd", hover: true, }); ``` ```json { "prices": [61250, 61750, 62250, 62750], "values": [12500000, 48000000, 9000000, 31000000], "lows": [61000, 61500, 62000, 62500], "highs": [61500, 62000, 62500, 63000], "scale_max": 60000000 } ``` ### Profiles in time spans With `span: "time"` the frame carries `spans`, one profile each ([Price canvases](price-canvases.md#profiles-anchored-in-time) has the frame's shape and caps). The chart lays each span out between its own start and end, so five words of the pane dock do not apply. Every other word applies to each span: | Under `span: "time"` | Words | | --- | --- | | apply to each span | `dock` (the span's edge the rows grow from), `width_frac` (the share of the span's width), `panel`, `behind_candles`, `color`, `opacity`, `baseline`, `series`, `thickness_px`, `scale: "own"` or `"fixed"` with `scale_max`, `gradient`, `gradient_direction`, `border_color`, `border_width`, `border_style`, `shape`, `labels`, `label_place`, `format`, `decimals`, `signed`, `unit`, `text_color`, `font_size`, `font_weight`, `font_family`, `hover`, `poc` and the `poc_*` words, `outside_opacity`, the `value_area_*` words, `tag_place` | | pane dock only | `offset`, `width_px`, `beside`, `scale: "shared"` and `step`, each refused by name; and the pane frame's fields `lows` and `highs` (the row bands), `tooltips` and the per-run `scale_max`, which a span never carries | A refusal names the word, for example `level 'oi' span 'time' takes no width_px: each span is laid out between its own start and end`, then the list of pane dock words. A level on the pane dock cannot sit `beside` a level with `span: "time"` either. Each span may carry its own levels beside its rows, under the pane frame's rules and caps: | Field | Value | What it does | | --- | --- | --- | | `spans[i].labels_text` | one string of 0..24 characters or null per row of that span | that text on the row; `""` leaves the row bare; null prints the formatted value | | `spans[i].series` | one array of numbers or null per declared series, each the length of that span's `prices`; on every span or on none when the level declares `series` (none: each span draws its rows whole; a mixed frame refuses as `every span carries series or none does`), refused when it declares none; never beside that span's `colors` | that span's segments | | `spans[i].value_area` | `[low, high]` prices, low below high | that span's value area: its rows outside dim, two lines across it and the `VAH` and `VAL` tags | | `spans[i].poc_price` | a number | the price that span's POC line marks | | `spans[i].poc_label_text` | 1..24 characters | that span's whole POC tag, printed as written: write the price into it when you want it shown | A span without its own `labels_text`, `value_area`, `poc_price` or `poc_label_text` falls back to the level's own: the formatted values, no value area, the POC on the span's largest row, and the `POC` tag with its price. The chart matches a span's own levels to its rows by the span's `start` and `end`, so give every span its own pair: a repeated pair keeps the last span's levels. The row bands (`lows`, `highs`), `tooltips` and `scale_max` are pane frame fields. A span that carries one, or any other key outside the list above, refuses the run as `wrun_frame_invalid` naming the span and the key (`spans.1: unknown span key 'lows'`). So does a span's `series` that disagrees with the declared series, or sits beside that span's `colors`, and a frame where some spans carry `series` and others do not (`spans.1.series: every span carries series or none does`). Open interest per session, calls one way and puts the other from each session's start. Each finished session marks its own point of control and value area, and the tags sit at the session's far end: ```typescript const oiSpans = frame("oi_spans", { max_bytes: 65536 }); plot.levels({ name: "oi_sessions", frame: oiSpans, dock: "left", span: "time", width_frac: 0.45, baseline: "center", series: [ { name: "Calls", color: "#38bdf8" }, { name: "Puts", color: "#a78bfa" }, ], labels: true, format: "si", poc: true, poc_label: true, value_area_labels: true, outside_opacity: 0.4, tag_place: "axis", hover: true, }); ``` The first span names its own levels, its tag text carrying the price; the second, the open session, falls back to the POC on its largest row and draws no value area. Both carry their segments, as a level declaring `series` needs on every span: ```json { "spans": [ { "start": 1727740800, "end": 1727827200, "prices": [61000, 61500, 62000], "values": [1200, 3400, -800], "series": [ [2000, 4100, 600], [-800, -700, -1400] ], "labels_text": [null, "C 4.1K / P 0.7K", null], "value_area": [61000, 61500], "poc_price": 61500, "poc_label_text": "OI POC 61.5K" }, { "start": 1727827200, "end": 1727913600, "prices": [61500, 62000, 62500], "values": [900, null, 2600], "series": [ [1500, null, 3000], [-600, null, -400] ] } ] } ``` ### Session profiles from cells The chart can also draw a profile itself from `volume_profile` cells, one per session, through `plot.profile` ([Price canvases](price-canvases.md#profiles-anchored-in-time)); it styles the same parts in its own words. Here each row splits buy and sell volume, rows outside the value area take a faded pair of colours, the point of control is thick, the three levels stay drawn until price trades through them, and hovering a cell reads it out. ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); plot.profile({ name: "session_vp", cells: "profile", span: "session", session: "1d", mode: "split_bar", buy_color: "#34d399", sell_color: "#f87171", row_height: 25, value_area: 0.7, outside_buy_color: "#34d39955", outside_sell_color: "#f8717155", poc: true, poc_width: 3, naked: true, level_labels: true, cell_hover: true, }); ``` The caps a profile meets (four levels, 512 rows, 64 spans and 4096 rows across them, 96 KiB per frame) are on [Limits](../reference/limits.md). ## Panel rows, kind by kind A panel draws a small chart of its own in a pane below the chart (`place: "below"`), or as side content (`"side"`) that mounts below on a chart and fills a window ([Side placement and windows](#side-placement-and-windows)). The file writes the panel's rows into a frame, usually once, on the newest bar, and each kind reads its rows in its own shape: | Panel | One row | Options of its own | | --- | --- | --- | | `panel.bars`, `panel.line` | `[key, v1, ..., vN]`: one value per series, `null` for a gap | `series` (1 to 8, required), `stacked`; bars also `orientation` (`"vertical"` or `"horizontal"`) | | `panel.scatter` | `[key, x, y, size?, color?, label?]`: a dot at (`x`, `y`), the label at most 24 characters | none | | `panel.histogram` | `[label, count]`: a bin's label (1 to 24 characters) and its count | `bins` (2 to 200), `orientation`; `x: "category"` only | | `panel.pie` | `[name, value, color?]`: one slice, at most 24 | `hole` (0 to 0.8) | | `panel.heatmap` | `[x key, y key, value]`: one cell, `null` for an empty one | `x: "category"` only | | `panel.table` | one cell per series and no key: words (at most 64 characters), a number, or a styled cell `{ text?, value?, color?, bar?, spark?, background_color?, opacity?, gradient?, text_color?, font_size?, font_weight?, align?, valign?, colspan?, rowspan? }`; at most 128 rows | `series` (1 to 12, required) | | `panel.tiles` | `[label, value, caption?, color?, spark?]`: one tile, at most 24 | none | Every panel also takes `name`, `title`, `x`, `place` and `frame`, and the look words of its kind (Frames, panels and compact widgets, above). `x` says what a key is: `"time"` an epoch second, `"index"` a whole number, `"number"` a decimal (a price grid), `"category"` a word of 1 to 64 characters. A panel holds at most 2,000 rows unless the table says fewer (128), and an empty `rows` list draws an empty panel. A color is a colour word: a hex literal such as `"#16a34a"`, `"#rrggbbaa"` or a theme token. Volume by weekday as stacked bars, one bar per day of the week: ```typescript // Volume by weekday in a pane below the chart: one bar per day of the week, up-bar and down-bar volume stacked. output("weekday", none, overlay, { description: "The bar's weekday, 0 Sunday to 6 Saturday, UTC" }); const days = frame("days", { max_bytes: 1024 }); panel.bars({ name: "by_weekday", title: "Volume by weekday (UTC)", x: "category", place: "below", frame: days, stacked: true, series: [{ name: "Up bars", color: "#16a34a" }, { name: "Down bars", color: "#dc2626" }] }); const NAMES: StaticArray = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const upVolume = new StaticArray(7); const downVolume = new StaticArray(7); let clock = new Clock(); function onBar(): void { const close = bar.close(); if (isNaN(close)) return; clock.update(bar.time()); const day = clock.weekday(); if (close >= bar.open()) upVolume[day] += bar.volume(); else downVolume[day] += bar.volume(); out_weekday(f64(day)); if (!bar.isLast()) return; // One row per weekday: [category, up volume, down volume], one value per series. fb_clear(); fb_text('{"rows":['); for (let i = 0; i < 7; i++) { if (i > 0) fb_text(","); fb_text("["); fb_str(NAMES[i]); fb_text(","); fb_f64(upVolume[i], 0); fb_text(","); fb_f64(downVolume[i], 0); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_DAYS); } ``` - **One value per series.** `["Mon", up, down]` carries the two declared series in their order; `stacked: true` puts them in one bar. - **Written once, on the newest bar.** The sums grow on every bar, and the frame is built on `bar.isLast()` with the `fb_*` writers, which never allocate. - **The last write wins.** The panel shows what the newest bar wrote; a frame never written leaves the panel off the chart, and a row in the wrong shape stops the run with `wrun_frame_invalid`. The looks below take the words of the Panel words table, kind by kind; every declaration assumes `onBar()` writes the named frame. ### The default look A line, bars, histogram or scatter panel that declares no `chrome` draws `"hairlines"`: horizontal value hairlines only, with no frame and no vertical lines. A heatmap that declares no `palette` ramps from the chart background to the text colour, black to white on a dark chart. The legend is the regular one, and a caption draws in sentence case; `legend_style: "chips"`, `glow`, `badge` and `y_title` draw only when declared. A declared word wins: on a line, bars, histogram or scatter panel `chrome` is `"hairlines"`, `"box"`, `"grid"` or `"none"`, and a declared `palette` replaces the ramp. The rules behind the look are on [The house look](style-anything.md#the-house-look). ```typescript const funding = frame("funding", { max_bytes: 4096 }); const hours = frame("hours", { max_bytes: 16384 }); const basis = frame("basis", { max_bytes: 4096 }); // No chrome: value hairlines only, and the regular legend. panel.bars({ name: "funding_by_venue", title: "8h funding by venue", x: "category", place: "below", frame: funding, format: "0.000", unit: "%", series: [{ name: "Funding", color: "theme.text" }] }); // No palette: the cells ramp from the chart background to the text colour. panel.heatmap({ name: "funding_heat", title: "Funding by venue and hour", x: "category", place: "below", frame: hours, format: "0.000", unit: "%" }); // A declared chrome wins: the box frame, by name. panel.line({ name: "basis_by_expiry", title: "Basis by expiry", x: "category", place: "below", frame: basis, chrome: "box", series: [{ name: "Basis", color: "theme.text" }] }); ``` ### Line panels A gamma exposure curve: net dealer gamma by strike, filled green where it is positive and red where it is negative, the fill fading away from the line, the spot strike marked with a badge that prints the value there, a chip on the title row naming the regime, a callout pinned to the curve at the peak strike, and a stats row for the maximised view. Reach for the signed fill whenever a curve's sign is the story. The `badge` word is the chip: its text, an optional fill (`theme.accent` when absent) and an optional text colour (light or dark, whichever reads on the fill, when absent). A marker with `valign: "point"` is the callout: instead of a line down the pane it draws a dot on the curve with a short leader to its label, anchored where the named `series` crosses `x` (the first series when `series` is absent), or at an exact value when `y` is given. ```typescript const gexRows = frame("gex_rows", { max_bytes: 16384 }); panel.line({ name: "gex_curve", title: "Gamma exposure by strike", x: "number", place: "below", frame: gexRows, height_frac: 0.3, chrome: "grid", maximize: true, stats_row: true, y_zero: true, fill_mode: "signed", fill_positive_color: "#22c55e", fill_negative_color: "#ef4444", fill_fade: true, badge: { text: "LONG GAMMA", color: "#22c55e", text_color: "#0b0d12" }, markers: [ { x: "spot", label: "Spot", badge: true, show_value: true }, { x: 64000, label: "Peak", valign: "point", series: "Net gamma", color: "#22c55e" }, ], series: [{ name: "Net gamma", color: "#e2e8f0", width: 2, smooth: true }], }); ``` The frame carries the rows and, per run, the chrome that moves: a caption naming the expiry window, a fixed value axis so the curve does not rescale on every tick, the badge (a frame badge replaces the declared chip for that run, so the regime flips to "SHORT GAMMA" in red when the module finds dealers short), and the markers. The frame's list replaces the declared one, so the spot marker is written again beside the flip strike, which the module finds where the curve crosses zero and washes down the pane in its colour, and two callouts pin the peak and the trough: the peak reads its height off the `Net gamma` series, the trough is pinned at an exact `y`. ```json { "title": "Gamma exposure by strike", "caption": "Dealer gamma per 1% move, 0 to 7 days to expiry", "y_min": -4000000, "y_max": 6000000, "badge": { "text": "SHORT GAMMA", "color": "#ef4444", "text_color": "#f4f4f4" }, "markers": [ { "x": "spot", "label": "Spot", "badge": true, "show_value": true }, { "x": 63500, "label": "Flip", "color": "#f59e0b", "line_style": "dashed", "valign": "middle", "wash": true }, { "x": 64000, "label": "Peak", "valign": "point", "series": "Net gamma", "color": "#22c55e", "show_value": true }, { "x": 61000, "label": "Trough", "valign": "point", "y": -2500000, "color": "#ef4444" } ], "rows": [ [60000, -1200000], [61000, -2500000], [62000, -800000], [63000, 1500000], [64000, 3900000], [65000, 2200000] ] } ``` A cumulative depth curve, bids and asks by distance from the mid price: both axes titled, the x axis printed as a percentage with two decimals, the value axis pinned from 0 to 500 so the two sides share one scale across runs, and chips in the legend showing each side's latest value. ```typescript const depth = frame("depth", { max_bytes: 16384 }); panel.line({ name: "depth_curve", title: "Cumulative depth", x: "number", place: "below", frame: depth, x_title: "Distance from mid", y_title: "Size (BTC)", x_format: "auto", x_decimals: 2, x_unit: "%", y_min: 0, y_max: 500, legend_style: "chips", legend_latest: true, format: "0.0", series: [ { name: "Bids", color: "#22c55e" }, { name: "Asks", color: "#ef4444" }, ], }); ``` A liquidation density curve around spot, glowing and animated as it updates, its stroke fading toward the edges, red for the longs below spot and green for the shorts above, with a tint under the line in the same ink. Reach for the fade when the pivot is the point and the tails are context. ```typescript const liqs = frame("liqs", { max_bytes: 16384 }); panel.line({ name: "liq_density", title: "Liquidation density", x: "number", place: "below", frame: liqs, glow: true, animate: true, stroke_fade: { pivot: "spot", edge_opacity: 0.15, left_color: "#ef4444", right_color: "#22c55e" }, series: [{ name: "Liquidations", color: "#f59e0b", width: 1.5, fill: true, fill_color: "#f59e0b33" }], }); ``` A curve on a number axis can name each row. The frame's `x_labels` holds one text per row, in the rows' order (`""` for a row without a label, at most 24 characters each), and the chart prints a row's label under the x axis in place of its number, so a curve over days to expiry reads each expiry's date. The key is valid on a line or bars panel with `x: "number"` only, and a list of another length than the rows refuses the whole frame. ```json { "rows": [ [7, 52.4], [35, 49.8], [98, 48.1] ], "x_labels": ["16 Oct", "20 Nov", "22 Jan '27"] } ``` ### Bars Funding by venue as bars coloured by sign, the axis pinned from -0.05% to 0.05% so venues compare across runs, and a readout under the pointer. ```typescript const funding = frame("funding", { max_bytes: 4096 }); panel.bars({ name: "funding_by_venue", title: "8h funding by venue", x: "category", place: "below", frame: funding, color_mode: "sign", positive_color: "#22c55e", negative_color: "#ef4444", y_title: "Funding", y_min: -0.05, y_max: 0.05, hover_card: true, format: "0.000", unit: "%", series: [{ name: "Funding", color: "#94a3b8" }], }); ``` ### Scatter Each venue as a dot of funding against open interest change: the plane cut into four named quadrants at zero, a guide where funding turns rich, the funding axis pinned so the quadrants keep their place, venue names on the dots with leader lines where they would collide, and every dot trailing its last positions, the trail fading as it ages. ```typescript const venues = frame("venues", { max_bytes: 8192 }); panel.scatter({ name: "funding_vs_oi", title: "Funding against OI change", x: "number", place: "below", frame: venues, x_title: "8h funding", y_title: "OI change, 24h", x_min: -0.05, x_max: 0.1, labels: true, label_overlap: "leader", quadrants: { x: 0, y: 0, colors: ["#22c55e22", "#3b82f622", "#ef444422", "#f59e0b22"], labels: ["Longs crowding", "Shorts crowding", "Shorts unwinding", "Longs unwinding"], }, guides: [{ axis: "x", value: 0.03, label: "Rich", color: "#f59e0b", line_style: "dashed" }], trails: true, trail_width: 1.5, trail_fade: true, }); ``` ### Pie Open interest by expiry as a ring: the hole prints the total with a caption under it, a small gap between slices and a thin border on each in the pane's own ink. ```typescript const expiries = frame("expiries", { max_bytes: 4096 }); panel.pie({ name: "oi_by_expiry", title: "Open interest by expiry", x: "category", place: "below", frame: expiries, hole: 0.55, hole_total: true, hole_caption: "Total OI", slice_gap: 2, border_color: "#0f172a", border_width: 1, format: "usd", legend_style: "title", }); ``` The frame's rows are `[name, value, color?]` slices; for a run where the hole should say something other than the total, the frame carries its own words, `hole_text` with a `hole_caption` that replaces the declared one. ```json { "hole_text": "$1.92B", "hole_caption": "Expiring this week", "rows": [ ["04 Oct", 820000000, "#38bdf8"], ["11 Oct", 460000000, "#818cf8"], ["25 Oct", 390000000, "#a78bfa"], ["27 Dec", 250000000, "#c4b5fd"] ] } ``` ### Heatmap Funding by venue and hour as a signed heatmap, positive cells warm and negative cells cool around a neutral zero, the axes titled and a readout under the pointer. Reach for the signed scale when the data has a meaningful zero; a palette scale suits ranks and counts. ```typescript const hours = frame("hours", { max_bytes: 16384 }); panel.heatmap({ name: "funding_heat", title: "Funding by venue and hour", x: "category", place: "below", frame: hours, scale: "signed", positive_color: "#f97316", negative_color: "#38bdf8", row_title: "Venue", col_title: "Hour (UTC)", hover_card: true, format: "0.000", unit: "%", }); ``` The frame's rows are `[hour, venue, value]` cells; beside them it can light the live hour's column and add summary rows under the grid, their values following the columns in the order the rows first named them. ```json { "caption": "8h funding, the last 7 days", "highlight": { "col": "16:00" }, "summary": [{ "label": "Mean", "values": [0.0047, 0.0037] }], "rows": [ ["08:00", "Binance", 0.01], ["08:00", "Bybit", 0.0062], ["08:00", "OKX", -0.002], ["16:00", "Binance", 0.0071], ["16:00", "Bybit", 0.0045], ["16:00", "OKX", -0.0004] ] } ``` ### Tiles Tiles for the headline numbers, three across, each tile's accent following the sign of its value: green ink on a positive flow, red on a negative one, the numbers printed compact and signed. ```typescript const summary = frame("summary", { max_bytes: 4096 }); panel.tiles({ name: "flow_tiles", title: "24h flow", x: "category", place: "below", frame: summary, columns: 3, accent: "auto", positive_color: "#22c55e", negative_color: "#ef4444", hover_card: true, format: "si", signed: true, unit: "BTC", }); ``` ### Table A table beside the chart with its first column as the row headers: a dashed frame, muted header ink, hairlines between rows, every cell centred vertically, the two value columns right-aligned and each formatted its own way. ```typescript const board = frame("board", { max_bytes: 8192 }); panel.table({ name: "venue_board", title: "Venue board", x: "category", place: "side", frame: board, width_px: 320, header_column: true, header_text_color: "#94a3b8", header_background_color: "#1e293b", text_color: "#e2e8f0", border_color: "#475569", border_width: 1, border_style: "dashed", grid_color: "#334155", grid_width: 1, grid_lines: "rows", valign: "middle", cell_padding: 6, column_widths: [96, 0, 0, 0], series: [ { name: "Venue" }, { name: "Market" }, { name: "OI", align: "right", format: "usd" }, { name: "Funding", align: "right", format: "0.000", unit: "%" }, ], }); ``` The frame's cells are words, numbers or styled cells: a styled cell may span rows, so a venue's name sits once beside its two markets, and a `value` cell with `bar` draws an inline bar behind the number, its length 0 to 1 of the cell; `caption` prints a line under the table. ```json { "caption": "USDT perpetuals, 15:04 UTC", "rows": [ [ { "text": "Binance", "rowspan": 2, "valign": "middle", "font_weight": "bold" }, "BTCUSDT", { "value": 4210000000, "bar": 1 }, 0.01 ], ["", "ETHUSDT", { "value": 1830000000, "bar": 0.43 }, 0.0082], [ { "text": "Bybit", "font_weight": "bold" }, "BTCUSDT", { "value": 2640000000, "bar": 0.63 }, -0.0041 ] ] } ``` ## Ladder, feed and meter Three small widgets sit on the price pane. A ladder is a column of bars at their prices along one side, a feed is a few lines of text with their times, and a meter is one bar filled from 0 to 1. | Widget | Declare | Write | | --- | --- | --- | | Ladder | `draw.ladder({ name, frame, side, divider?, title?, ...style })`, `side` `"left"` or `"right"` | a frame `{ rows, divider?, title? }`: 1 to 256 rows `[price, value, fraction, color?]`, the fraction (0 to 1) the bar's length; `divider` `{ label, price }` marks one price, and a divider in the frame replaces the declared one | | Feed | `draw.feed({ name, frame, anchor?, offset?, z?, title?, time_format?, ...style })` | a frame `{ lines, title?, markets? }`: 1 to 50 lines `[time, text, color?]`, the time in epoch milliseconds and the text at most 80 characters; `markets` names each line's market ([Rows that open a market](#rows-that-open-a-market)) | | Meter | `draw.meter({ name, label, fraction: { output }, ramp, text?, anchor?, offset?, z?, title?, bar_height?, track_color?, ...style })` | no frame: the meter reads the output on the newest ready bar, a fraction from 0 to 1, colored along `ramp` (2 to 5 colors); `text` is a literal or `{ slot }` | The `title`, `time_format`, `bar_height` and `track_color` words, and the card surface and chrome a widget shares, are listed under Frames, panels and compact widgets above; a ladder's frame rows and a meter's ramp take colour words. The last bars' volume by price as a ladder on the right of the pane: ```typescript // The last bars' volume by price as a ladder on the right of the pane: eight rows from the window's low to its high, the busiest in amber. param.int("window", 100, { min: 10, max: 500, label: "Bars in the window" }); output("close_line", line, overlay, { color: "#94a3b8", description: "The close" }); const rows = frame("rows", { max_bytes: 2048 }); draw.ladder({ name: "volume_by_price", frame: rows, side: "right" }); const MAX = 500; const ROWS = 8; const closes = new StaticArray(MAX); const volumes = new StaticArray(MAX); const binned = new StaticArray(ROWS); let window: i32 = 100; let head: i32 = 0; let count: i32 = 0; function onStart(): void { window = i32(p_window()); } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; out_close_line(close); closes[head] = close; volumes[head] = bar.volume(); head = (head + 1) % window; if (count < window) count += 1; if (!bar.isLast()) return; let lo = Infinity; let hi = -Infinity; for (let i = 0; i < count; i++) { lo = Math.min(lo, closes[i]); hi = Math.max(hi, closes[i]); } if (!(hi > lo)) return; const step = (hi - lo) / f64(ROWS); for (let r = 0; r < ROWS; r++) binned[r] = 0.0; for (let i = 0; i < count; i++) { const r = i32(Math.min(f64(ROWS - 1), Math.floor((closes[i] - lo) / step))); binned[r] += volumes[i]; } let busiest = 0.0; for (let r = 0; r < ROWS; r++) busiest = Math.max(busiest, binned[r]); if (busiest <= 0.0) return; // One row per price band: [price, volume, the bar's length 0 to 1, color]. The divider marks the last close. fb_clear(); fb_text('{"rows":['); for (let r = 0; r < ROWS; r++) { if (r > 0) fb_text(","); fb_text("["); fb_num(lo + step * (f64(r) + 0.5)); fb_text(","); fb_f64(binned[r], 0); fb_text(","); fb_f64(binned[r] / busiest, 3); fb_text(","); fb_str(binned[r] == busiest ? "#f59e0b" : "#64748b"); fb_text("]"); } fb_text('],"divider":{"label":"Last","price":'); fb_num(close); fb_text("}}"); writeFrameBuffer(FRAME_ROWS); } ``` - **Rows at prices.** Each row is a price band's middle price, its volume, its bar's length against the busiest band, and its color. - **The divider.** `"divider": { "label": "Last", "price": close }` in the frame marks the last close. - **Sized once.** The window lives in two `StaticArray`s made at module start, so nothing allocates per bar. An RSI meter in the corner, and a feed of the RSI's last five crossings of 70 and 30: ```typescript // An RSI meter in the top-left corner, and a feed of the last five times the RSI crossed 70 or 30. param.int("length", 14, { min: 2, max: 100, label: "RSI length" }); output("rsi", line, lower, { color: "#a855f7", description: "RSI" }); output("rsi_fraction", none, lower, { description: "The RSI as a fraction, 0 to 1: the meter's fill" }); string("rsi_text", { max_bytes: 8 }); draw.meter({ name: "rsi_meter", label: "RSI", fraction: { output: "rsi_fraction" }, ramp: ["#3b82f6", "#64748b", "#ef4444"], text: { slot: "rsi_text" }, anchor: "top_left" }); const events = frame("events", { max_bytes: 2048 }); draw.feed({ name: "rsi_events", frame: events, anchor: "bottom_left" }); const KEEP = 5; const times = new StaticArray(KEEP); const ups = new StaticArray(KEEP); let head: i32 = 0; let count: i32 = 0; let rsi = new Rsi(14); let prev: f64 = NaN; function onStart(): void { rsi = new Rsi(i32(p_length())); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; out_rsi(value); out_rsi_fraction(value / 100.0); sb_clear(); sb_f64(value, 1); str_rsi_text_sb(); // A crossing joins the feed; the oldest of the five leaves. const above = prev <= 70.0 && value > 70.0; const below = prev >= 30.0 && value < 30.0; if (above || below) { times[head] = bar.time() * 1000.0; ups[head] = above; head = (head + 1) % KEEP; if (count < KEEP) count += 1; } prev = value; if (!bar.isLast() || count == 0) return; // One line per crossing, newest first: [time in milliseconds, text, color]. fb_clear(); fb_text('{"lines":['); for (let k = 0; k < count; k++) { const i = (head - 1 - k + KEEP) % KEEP; if (k > 0) fb_text(","); fb_text("["); fb_f64(times[i], 0); fb_text(","); fb_str(ups[i] ? "RSI crossed above 70" : "RSI crossed below 30"); fb_text(","); fb_str(ups[i] ? "#ef4444" : "#3b82f6"); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_EVENTS); } ``` - **The meter reads an output.** `fraction: { output: "rsi_fraction" }` takes the RSI over 100 on the newest bar, and `text: { slot: "rsi_text" }` prints the reading on it. - **The feed is a frame.** Each line is `[time, text, color]`, the time `bar.time() * 1000` because a feed counts milliseconds, newest first. - **Nothing to show, nothing written.** The feed is written only once a crossing exists; until then the frame stays unwritten and the feed is off the chart. ## Next - **Plotting:** lines, marks, tints and fills, one value per bar ([Plotting](plotting.md)) - **Drawing objects:** lines, boxes and labels your file places and moves ([Drawing objects](drawing-objects.md)) - **HUD and hover cards:** tiles in a corner and a card under the cursor ([HUD and hover cards](hud-and-hover-cards.md)) - **Limits:** every cap on frames, panels, tables and widgets ([Limits](../reference/limits.md)) # Price canvases Five declarations draw a canvas on the price chart from cells the chart already serves or from a frame the module writes: `plot.heatmap` (a time by price heatmap), `plot.footprint` (one footprint column per bar), `plot.tpo` (letter blocks per period and price), `plot.profile` (a volume profile anchored to a session, a range, the developing session or the visible window) and `plot.matrix` (a strike by expiry table docked on the price axis). A `place: "side"` panel is not a canvas: on a chart it mounts below like every panel, and its right-side home is a window ([Side placement and windows](cards-frames-panels.md#side-placement-and-windows)). Like `plot.levels`, each is an object literal the build reads and removes before the file compiles; the module declares the canvas and the chart draws it from the rows it already holds, so a footprint costs no output and no transport of its own. ## What the canvases share - **Names.** Every canvas has a `name`, unique across outputs, string slots, frames, levels, panels, renderers, drawings, heatmaps, profiles, matrices, marks, spans and rays. A canvas is a child of the indicator: it shows and hides with the indicator's eye, and its legend X removes the indicator. - **Cells.** A heatmap, footprint, TPO or profile reads a declared celled input through `cells`: `book` or `volume_profile` for a heatmap, `volume_profile` for a footprint or a profile, `volume_profile` or `intrabar` for a TPO (absent on a TPO means the chart's own candles). A `cells` word that names an input of another class is refused by name ("heatmap 'h' reads cells from a book or volume_profile input; 'm1' is intrabar"). - **Colours.** Every colour word takes `"#rrggbb"`, `"#rrggbbaa"` or a theme token (`theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid`, `theme.accent`); a token follows the chart's theme and re-resolves on a theme switch without a rerun. - **Type.** `font_family` is `"ui"`, `"mono"`, `"serif"` or `"rounded"` (system fonts only, nothing downloads); `font_weight` is `"normal"`, `"medium"` or `"bold"`; `font_size` is 6..64 px. - **Numbers.** `format` is one of `price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd`, `auto`; `decimals` (0..8), `signed` and `unit` (0..8 characters) refine it and are refused without it ("decimals needs format"). `price` prints at the chart's price digits. - **Settings.** Any style key except a name or a reference (`cells`, `grid`, `price_low`, `price_step`, `start`, `end`, `frame`) takes `"@"`, so a `param.color` or `param.choice` on the Style page repaints the canvas without a rerun of your code ([The Style page](../settings/style-page.md)). - **Caps.** At most 4 heatmaps and 4 matrices per indicator; footprints, TPOs and profiles share one cap of 4. The numbers are on [Limits](../reference/limits.md). - **Opt-in.** Every word has a default that keeps the chart's own look for that canvas; declare only what you want changed. ## Heatmaps `plot.heatmap(options)` paints one coloured cell per bar and price row. The cells come from a celled input (`cells`) or from a grid of outputs the module writes (`grid`); exactly one of the two is declared. ```typescript input("close", ohlcv.close); input("depth", book.cells, { max_cells: 1000, block_size: 10 }); // The book as a heatmap behind the candles: size per level, the 98th percentile as the top of the scale. plot.heatmap({ name: "liquidity", cells: "depth", value: "size", palette: ["theme.bg", "#2563eb", "#22d3ee", "#facc15"], opacity: 0.85, tooltip: "{{value:si}} at {{price}}" }); ``` | Word | Value | What it does | | --- | --- | --- | | `cells` | a `book` or `volume_profile` input | the rows to paint: book levels, or profile buckets | | `value` | book `"size"` (default), `"bid"`, `"ask"`, `"signed"`; profile `"total"` (default), `"buy"`, `"sell"`, `"delta"` | the number a cell carries; `signed` and `delta` make a diverging scale | | `grid` | an `out.grid` name | the module's own grid instead of cells (below) | | `price_low`, `price_step` | output names (`price_step` may be a number > 0) | with `grid`: the bottom edge of row 0 on each bar, and every row's height in price; both required, both refused beside `cells` | | `row_height` | number > 0 | with book cells: the row height in price (default the book's own grouping); refused on other cells | | `palette` | 2..8 colours, low to high | default `["theme.bg", "#2563eb", "#22d3ee", "#facc15"]`, or `["theme.down", "theme.bg", "theme.up"]` when `center` applies | | `min`, `max` | numbers, `min` below `max` | the ends of the scale (default from the data, below) | | `center` | number | the midpoint of a diverging scale; default 0 under `value: "signed"` or `"delta"`, else absent; refused outside `min..max` when both are declared | | `auto_quantile` | 0.5..1 (default 0.98) | the quantile that sets an automatic end of the scale; refused beside both `min` and `max`; the viewer's Sensitivity row moves it | | `scale` | `"linear"` (default), `"sqrt"`, `"log"` | how a value maps onto the palette; `"log"` is refused on a diverging scale | | `floor` | number >= 0 (default 0) | a cell whose distance from the centre is at or under it draws nothing (so does an empty cell) | | `opacity` | 0..1 (default 0.85) | multiplies every cell colour's own alpha | | `behind_candles` | boolean (default true) | under the candles; `false` paints over them | | `cell_gap` | 0..4 px (default 0) | a gap between neighbouring cells | | `labels` | boolean (default false) | print each cell's value where the cell is tall and wide enough | | `font_size`, `font_weight`, `font_family`, `text_color` | 6..64 (10), the weight word, the family word (`"ui"`), a colour (`theme.text`) | the label type | | `format`, `decimals`, `signed`, `unit` | the number words (default `"auto"`) | how a label and the readout print a value | | `tooltip` | a template of at most 200 characters | a hover readout over the cell; absent means no readout | | `label` | 1..40 characters (default the name in words) | the readout's title | The automatic scale is read over every cell of the full run: a one-sided scale runs from 0 (for `size`, `bid`, `ask`, `total`, `buy` and `sell`) or from the low quantile to the high quantile; a diverging scale runs the same distance either side of `center`. Live ticks keep the run's scale, so colours do not shift between runs. The viewer moves the automatic end with the heatmap's Sensitivity row on the Style page (Subtle to Vivid, starting at your `auto_quantile`), with no rerun ([The Style page](../settings/style-page.md#the-sensitivity-row)). The tooltip template reads `{{value}}` and `{{value:}}` (the cell's number), `{{price}}` (the row's middle), `{{price_low}}`, `{{price_high}}`, `{{time}}` and `{{label}}`; an unknown placeholder stays as written. A heatmap draws beside the chart's own book or options heatmap without touching it. A book heatmap on a slow chart reads better in coarser rows. This one regroups the book into rows of 25 price units, maps size through a square-root scale so a few large resting orders do not wash out the rest, leaves a one-pixel gap between cells and blanks the thinnest levels: ```typescript input("close", ohlcv.close); input("depth", book.cells, { max_cells: 1000, block_size: 10 }); plot.heatmap({ name: "depth_rows", cells: "depth", value: "size", row_height: 25, scale: "sqrt", cell_gap: 1, floor: 2, opacity: 0.9 }); ``` ### A grid the module computes `out.grid(name, { rows })` declares `rows` (2..128) data-only outputs named `_0` to `_` and generates one writer, `out_(row: i32, value: f64)`, for `onBar()`. A row left unwritten is an empty cell (NaN); a row outside `0..rows - 1` aborts the run by name. The heatmap then names the grid and two price outputs: the bottom edge of row 0 on each bar and the row height. ```typescript param("rows", 64, { min: 2, max: 128 }); input("close", ohlcv.close); output("low_edge", none, overlay, { description: "The bottom of row 0: 32 rows under the close" }); output("step", none, overlay, { description: "The row height in price" }); out.grid("heat", { rows: 64 }); plot.heatmap({ name: "liq", grid: "heat", price_low: "low_edge", price_step: "step", center: 0, floor: 0.5 }); function onBar(): void { const step = bar.close() * 0.0025; out_step(step); out_low_edge(bar.close() - 32.0 * step); // Row 32 sits on the close; rows above it read positive, rows below negative, fading with distance. for (let row = 0; row < 64; row++) out_heat(row, f64(row - 32) * bar.volume() / 32.0); } ``` The grid's outputs count toward the 256 outputs a file may declare, and the rows must be contiguous in declaration order (the build lays them out for you). The [Liquidation Heat](../cookbook/liquidation-heat.md) recipe is a complete grid heatmap, and [OI Liquidation Heat](../cookbook/liquidation-heat-oi.md) builds the same grid from open interest; [Book Heat](../cookbook/book-heat.md) paints the order book. ## Footprints `plot.footprint(options)` draws one footprint column per chart bar from the bar's `[low, high, buy, sell]` buckets: the module only declares it. ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); plot.footprint({ name: "fp", cells: "profile", mode: "split_bar", imbalance: true, imbalance_ratio: 3, stacked_imbalances: 3 }); ``` | Word | Value | What it does | | --- | --- | --- | | `cells` | a `volume_profile` input | required; a book input is refused by name | | `mode` | `"cluster"`, `"split_bar"` (default), `"stacked_bar"`, `"ladder"`, `"imbalance_only"` | the column's drawing | | `buy_color`, `sell_color` | colours | default the chart's profile pair | | `row_height` | number > 0 or `"auto"` (default) | the row height in price; `"auto"` is the input's bucket width times the footprint's row table ([Row height](#row-height)) | | `labels` | boolean (default true) | print the cell numbers | | `hide_zero` | boolean (default false) | leave zero cells blank | | `text_color` | colour | the cell ink (default the chart's footprint ink) | | `imbalance`, `imbalance_ratio`, `imbalance_buy_color`, `imbalance_sell_color`, `stacked_imbalances` | boolean (false), 1.1..20 (3), colours (`theme.up`, `theme.down`), 0..10 (3) | mark buy and sell imbalances at the ratio, and stacks of them | | `poc`, `poc_color`, `poc_width` | boolean (true), colour (`theme.text`), 1..10 px (1) | the point of control per column | | `value_area`, `vah`, `val`, `vah_color`, `val_color` | 0.5..0.95 (0.7), booleans (true), colours (`theme.text`) | the value area and its edges | | `cell_metric` | `"volume"`, `"delta"` (default), `"trades"` | what a cluster cell reads | | `volume_color` | colour (default `"#4a90e2"`) | the volume cell colour | | `grading` | `"candle"` (default), `"session"`, `"visible"` | the range the cell shading is scaled over | | `font_family`, `font_weight` | the family and weight words (default the chart's indicator font) | the type | | `cell_hover` | boolean (default true) | the chart's cell readout on hover | A cluster footprint reads volume per row rather than delta. This one shades every cell against the session's largest cell instead of its own candle's, in one teal, leaves zero cells blank in rows of 10 price units, and turns the chart's hover readout off so the numbers printed in the cells are the only readout: ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); plot.footprint({ name: "clusters", cells: "profile", mode: "cluster", cell_metric: "volume", volume_color: "#2dd4bf", grading: "session", hide_zero: true, row_height: 10, cell_hover: false }); ``` [Volume Footprint](../cookbook/volume-footprint.md) is the complete recipe. ## TPO letters `plot.tpo(options)` prints a letter for every letter interval of the period in which a price row traded (profile buckets) or lay inside the bar's range (finer bars, or the chart's own candles when `cells` is absent). ```typescript input("close", ohlcv.close); input("m5", intrabar.cells, { interval: "5m", max_cells: 288 }); plot.tpo({ name: "tpo", cells: "m5", period: "day", letter_minutes: 30, initial_balance: true, single_prints: true }); ``` | Word | Value | What it does | | --- | --- | --- | | `cells` | a `volume_profile` or `intrabar` input, or absent | the bars or buckets the letters are built from | | `period` | `"day"` (default), `"week"`, `"month"` | one profile per period | | `letter_minutes` | 1..240 (default 30) | the minutes one letter stands for | | `row_height` | number > 0 or `"auto"` (default) | the row height in price; `"auto"` comes from the market, and a period past 512 rows is coarsened ([Row height](#row-height)) | | `display` | `"letters"`, `"blocks"`, `"both"` (default) | letters, blocks, or both | | `palette` | 2..26 colours | the colours across the letters (default the chart's TPO scheme) | | `color_mode` | `"period"` (default), `"count"`, `"volume"`, `"delta"` | what colours a block; `"volume"` and `"delta"` need `volume_profile` cells | | `value_area`, `poc`, `vah`, `val`, `poc_color`, `vah_color`, `val_color` | 0.5..0.95 (0.7), booleans (true), colours (`theme.text`, `theme.muted`, `theme.muted`) | the value area and its edges | | `outside_va_opacity` | 0..1 (default 0.3) | how far rows outside the value area fade | | `initial_balance`, `ib_color` | boolean (true), colour (`theme.text`) | the initial balance bracket | | `single_prints`, `single_prints_color`, `poor_extremes`, `poor_extremes_color` | booleans (false), colours (`"#cc0033"`, `"#ffd966"`) | single prints and poor highs and lows | | `counts` | boolean (default false) | the TPO count per row | | `volume_profile` | boolean (default false) | a volume profile beside the letters; needs `volume_profile` cells | | `font_family`, `font_weight`, `cell_hover` | as a footprint | the type and the hover readout | A day profile coloured by what each row traded, with the structure marks a profile reader looks for: poor highs and lows in amber, single prints in red, the TPO count printed on every row and a volume profile beside the letters: ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); plot.tpo({ name: "day_tpo", cells: "profile", period: "day", color_mode: "volume", poor_extremes: true, poor_extremes_color: "#f59e0b", single_prints: true, single_prints_color: "#ef4444", counts: true, volume_profile: true }); ``` A letter must be a whole multiple of the feeding bars' interval: 30-minute letters over 1h candles cannot be placed, and the legend chip and the Console say so ("tpo 't': 30-minute letters need bars of 30 minutes or a whole divisor; the bars here are 1h (declare an intrabar input with interval "5m" and name it in cells)"). [TPO Letters](../cookbook/tpo-letters.md) is the complete recipe. ## Profiles anchored in time `plot.profile(options)` draws a volume profile over a span of time from `volume_profile` cells: one per session, one over a range two outputs mark, the developing session, or the visible window. ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); plot.profile({ name: "session_vp", cells: "profile", span: "session", session: "1d", value_area_shade: true, background: true }); ``` | Word | Value | What it does | | --- | --- | --- | | `cells` | a `volume_profile` input | required | | `span` | `"session"` (default), `"range"`, `"developing"`, `"visible"` | what one profile covers | | `session` | `"auto"` (default), `"1h"`, `"2h"`, `"4h"`, `"6h"`, `"12h"`, `"1d"`, `"1w"`, `"us"`, `"eu"`, `"asia"` | the session length under `"session"` and `"developing"`; refused on `"range"` and `"visible"`; `"auto"` follows the chart interval | | `start`, `end` | output names, epoch seconds read on the last ready row | the range under `span: "range"` (`start` required there, `end` defaults to the newest bar; both refused elsewhere); a run whose start is not a number, or whose end is not after it, mounts no profile and the legend chip says why | | `mode` | `"stacked_bar"` (default), `"split_bar"`, `"outline"`, `"delta"` | the bars' drawing | | `buy_color`, `sell_color` | colours | default the chart's profile pair | | `dock` | `"left"`, `"right"` | which edge of the span the bars grow from (default left, right on `"visible"`) | | `width_frac` | 0.05..1 | the bars' share of the span (default 0.7), or of the pane under `"developing"` and `"visible"` (default 0.2) | | `row_height` | number > 0 or `"auto"` (default) | the row height in price; `"auto"` is the input's bucket width times the profile's row table ([Row height](#row-height)) | | `value_area`, `value_area_shade`, `outside_buy_color`, `outside_sell_color` | 0.5..0.95 (0.7), boolean (true), colours (the base colours at half strength) | the value area and how rows outside it paint | | `poc`, `poc_color`, `poc_width`, `vah`, `val`, `vah_color`, `val_color` | booleans (true), colours (`theme.text`), 1..10 px (1) | the point of control and the value area edges | | `level_labels` | boolean (default false) | price tags on the three levels | | `naked` | boolean (default false) | keep a level drawn until price trades through it | | `extend` | `"none"`, `"right"` | extend the levels to the right (default right on `"developing"`, none otherwise) | | `behind_candles` | boolean (default false) | under the candles; needs `span: "session"` and a filled mode | | `background`, `background_color`, `background_opacity` | boolean (false), colour (`theme.text`), 0..1 (0.08) | a box behind each session; needs `span: "session"` | | `font_family`, `font_weight`, `cell_hover` | as a footprint | the type and the hover readout | [Session Volume Profile](../cookbook/session-volume-profile.md) is the complete recipe. A profile the module computes itself (open interest by strike, a liquidation map) is a `plot.levels` whose frame carries spans: ```typescript const oiFrame = frame("oi_spans", { max_bytes: 32768 }); plot.levels({ name: "oi", frame: oiFrame, dock: "left", span: "time", width_frac: 0.4 }); ``` With `span: "time"` the frame is `{ "spans": [...] }`, one entry per profile, each drawn inside its own time span (with `span: "pane"`, the default, the frame keeps the `{ prices, values, colors? }` shape docked on the pane edge): ```json { "spans": [ { "start": 1727740800, "end": 1727827200, "prices": [61000, 61500, 62000], "values": [120.5, 310.2, 88.0] }, { "start": 1727827200, "end": 1727913600, "prices": [61500, 62000, 62500], "values": [90.0, null, 140.0], "colors": ["theme.up", "theme.muted", "theme.up"] } ] } ``` A frame holds at most 64 spans, each `start` before its `end` in epoch seconds, 1..512 strictly ordered prices with as many values (null for a gap) and optional colours, and at most 4096 rows across every span. A span may also carry its own `labels_text`, `series` (one array per declared series, each the span's row count, never beside the span's own `colors`), `value_area`, `poc_price` and `poc_label_text` (the whole POC tag, printed as written), under the pane frame's rules (every span carries `series` or none does: with none, each span draws its rows whole); a span without its own POC or value area falls back to the level's own: the POC on the span's largest row, no value area. The row bands (`lows`, `highs`), `tooltips` and `scale_max` stay pane frame fields: those, or any other key on a span, refuse the run by name (`spans.1: unknown span key 'lows'`), and so does a frame whose shape does not match the declared `span`, with `wrun_frame_invalid`. Each span is laid out between its own start and end, so the words that place the pane dock do not apply: `offset`, `width_px`, `beside`, `scale: "shared"` and `step` are refused by name under `span: "time"`. Every other `plot.levels` word applies to each span, `hover` and `tag_place` among them. The words per span, the per-span frame fields and an example are under [Profiles in time spans](cards-frames-panels.md#profiles-in-time-spans); [Session OI Levels](../cookbook/session-oi-levels.md) is the recipe. ## Row height A footprint, a TPO and a profile draw one row per band of price, `row_height` tall. A number is used as written. `"auto"`, the default, takes its unit from the first of these the chart knows for the market, never from the decimals the closes print: 1. **The bucket width** of the `volume_profile` input named in `cells`. A footprint and a profile always read one, so their auto stops here. 2. **The block size the chart serves** for the market (its TPO catalog, else its volume profile catalog), or, with no catalog, the venue's instrument tick when the chart holds one (CME futures). 3. **The median candle range** divided by 4, snapped up to 1, 2 or 5 x 10^k. 4. **Otherwise 1.** Rungs 1 and 2 are multiplied by the chart's row table, the figures the chart's own footprint, TPO and session profile use; the range unit (rung 3) already scales with the interval, so it is used as is. | Chart interval | 1m | 5m | 15m | 30m | 1h | 4h | 1d | 1w | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | Footprint | 2 | 5 | 8 | 10 | 15 | 25 | 50 | 250 | | TPO | 5 | 10 | 15 | 20 | 25 | 30 | 50 | 100 | | Profile | 5 | 10 | 15 | 20 | 25 | 50 | 100 | 200 | A week TPO multiplies its figure by 1.5 and a month TPO by 2, rounded down (22 and 30 at 15m). ### 512 rows per period 512 rows is the most a TPO period (a day, a week or a month) holds before the chart steps in. Past that it doubles the row height and folds again until every period fits, at most 6 times, whether the height came from `"auto"` or from a number. The TPO still draws, and every run says so with a warning row in the editor's Console and the warning on the indicator's legend chip, naming the declaration and both heights: - `tpo 'tpo': row_height auto coarsened from 1.5 to 12 (512 rows per day is the chart's limit)` - `tpo 'tpo': row_height 1 coarsened to 8 (512 rows per day is the chart's limit)` The cap depends on how far the market's price moves, so only the running chart applies it; the build never refuses a row height for it. A number so fine that one bar alone spans more than 4,096 rows is still refused by name, and rows thinner than 3 px on screen merge as you zoom out ([Limits](../reference/limits.md)). ### BTC at 15m [TPO Letters](../cookbook/tpo-letters.md) declares no `row_height` and no `cells`. On Binance's BTCUSDC perpetual at 15m the chart serves a 5-dollar TPO block and the TPO figure at 15m is 15, so a row is 5 x 15 = 75 dollars, the row the chart's own TPO draws there. A day holds about 25 to 90 rows, each tall enough for its letters (a letter needs a row about 8 px tall). The price tick times the same figure would make 0.1 x 15 = 1.5-dollar rows: every row under a pixel at the default zoom, no letter printed, and 48 times the rows to fold and paint (22,946 over 16 days against 476). That is why `"auto"` reads what the venue serves and never the decimals the closes print. ## Strike matrices `plot.matrix(options)` docks a table of numbers on the price axis: one row per price, one column per expiry (or whatever the columns are), each cell read from a frame the module writes on the live bar. It needs `abi_version: "wrun-4"`, which a frame declaration stamps for you. ```typescript const board = frame("board", { max_bytes: 65536 }); plot.matrix({ name: "gex", frame: board, dock: "right", column_width: 56, price_column: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, format: "si", tooltip: "{{column}} {{value:si}} at {{price}}" }); ``` | Word | Value | What it does | | --- | --- | --- | | `frame` | a declared frame | the snapshot below; required | | `dock` | `"right"` (default), `"left"`, `"side"` | against the price axis, or in the strip beside the chart | | `columns` | 1..12 names of 1..16 characters | the column labels (default the frame's `cols`, else `"1"`, `"2"`, ...); a frame with another column count refuses the run | | `column_width` | 24..160 px (default 56) | one column's width | | `row_max_px` | 8..64 px (default 24) | the tallest a row may grow | | `price_column`, `header` | booleans (false, true) | a price column on the axis side; the sticky header row | | `palette`, `min`, `max`, `center`, `auto_quantile`, `scale` | as a heatmap (no default palette) | the fill behind a numeric cell; without a palette a cell has no fill unless it carries its own colour | | `opacity` | 0..1 (default 1) | multiplies every cell fill | | `format`, `decimals`, `signed`, `unit` | the number words (default `"auto"`) | how a numeric cell prints when it carries no text | | `font_size`, `font_weight`, `font_family`, `align`, `text_color` | 6..64 (10), the weight word, the family word (`"ui"`), `"left"`, `"center"`, `"right"` (`"right"`), a colour (`theme.text`) | the cell type | | `header_text_color`, `header_background_color` | colours (`theme.muted`, `theme.bg`) | the header row | | `background_color`, `background_opacity` | colour (`theme.bg`), 0..1 (0.85) | the backdrop behind the table | | `grid_color`, `grid_width`, `grid_style`, `grid_lines` | colour (`theme.grid`), 0..10 (1), `"solid"`, `"dashed"`, `"dotted"`, `"all"`, `"rows"`, `"cols"`, `"none"` | the lines between cells | | `border_color`, `border_width`, `border_style` | colour (`theme.grid`), 0..10 (0), the line style | the frame around the table | | `cell_padding` | 0..12 px (default 4) | the inset inside a cell | | `highlight_color` | colour (default `theme.accent`) | the outline of the frame's highlighted row and column | | `tooltip`, `label` | a template of at most 200 characters; 1..40 characters | the hover readout and its title; the template reads `{{value}}`, `{{value:}}`, `{{text}}`, `{{price}}`, `{{column}}` and `{{label}}` | A matrix can take chrome of its own. This board docks on the left, prints its header row in the accent colour on a dark fill, frames the table with a dashed border and draws lines between rows only: ```typescript const board = frame("board", { max_bytes: 65536 }); plot.matrix({ name: "oi_board", frame: board, dock: "left", header_text_color: "theme.accent", header_background_color: "#0f172a", border_color: "theme.grid", border_width: 1, border_style: "dashed", grid_lines: "rows" }); ``` The frame is a strict object: ```json { "prices": [60000, 62000, 64000, 66000], "cells": [ [1.2e6, -4.1e5, null], [2.5e6, 8.0e5, "n/a"], [ { "value": -3.3e6, "text_color": "theme.down", "font_weight": "bold" }, 1.1e6, 2.0e5 ], [4.0e5, 1.5e5, 9.0e4] ], "cols": ["27JUN", "25JUL", "26SEP"], "title": "GEX by expiry", "highlight": { "price": 64000, "col": 0 }, "range": { "min": -5e6, "max": 5e6 } } ``` `prices` holds 1..128 numbers in strictly rising or falling order; `cells` holds exactly one row per price, every row the same width (1..12 columns, at most 1536 cells in all); `cols` names the columns (1..16 characters each); `title` (1..40 characters) prints above the table; `highlight` marks a price row and a column index (0-based); `range` moves the palette bounds per run. A cell is `null` (empty), a number (printed through `format`), a string of up to 16 characters, or an object with any of `value`, `text`, `color` (the fill), `text_color` and `font_weight`. A frame that breaks any of this refuses the run with `wrun_frame_invalid: .`, never a truncated table. [Strike Matrix](../cookbook/strike-matrix.md) builds the board from the live options chain ([Options kit](../functions/options-kit.md)). ## The strip beside the chart A matrix joins a strip to the right of the price axis with `dock: "side"`, its rows still on the price pane's prices. The strip takes at most 40% of the chart's width and folds away on a chart narrower than 480 px, where its items are not drawn. Matrices sit nearest the axis, one column each; a column the strip cannot fit at its smallest size (24 px) is not drawn. The strip has no pointer interaction yet: no hover cards there, and no drag to resize it. Panels do not use the strip: a `place: "side"` panel mounts below the chart like every panel, and the chart offers it a window of its own ([Side placement and windows](cards-frames-panels.md#side-placement-and-windows)). Its `width_px` (160..480) and `height_px` (80..800) stay accepted with `place: "side"` only, reserved for a strip that panels do not use today. ## What refuses Every misuse is refused by name when Run derives the sheet: a fifth heatmap ("heatmaps must declare at most 4 entries"), `cells` beside `grid`, a `value` word of the other cell class, `out.grid` rows outside 2..128 ("out.grid 'heat' rows must be between 2 and 128"), a grid heatmap without `price_step`, a footprint over book cells, a TPO `color_mode` of `"volume"` without profile cells, `letter_minutes` of 0, `span: "range"` without `start`, `behind_candles` on a visible-window profile, a matrix under `wrun-3` ("matrices needs abi_version "wrun-4" (wrun-3 has no frame channel)"), 13 columns, `width_px` on a panel placed below. A frame that fails its shape refuses the run instead, as `wrun_frame_invalid`. The caps and ranges are on [Limits](../reference/limits.md). # Marks, spans and rays Three declarations draw many small things on each bar, in one batch: `plot.marks` (bubbles, dots, rings or squares, each at a price with a quantity), `plot.spans` (boxes, each a price range over a run of bars) and `plot.rays` (segments, each from one price to another over a run of bars). A section holds up to 64 records a bar. Each record is written on its own bar and rides that bar's outputs, so the chart draws and hovers a whole section at once: there are no ids to keep, nothing to delete and no live-object cap to stay under. A span or a ray may also run between two times your script knows, starting before the bar that writes it ([Timed spans and rays](#timed-spans-and-rays)). Anything drawn on most bars belongs here. An object that must move, restyle or vanish on a later bar is a [handle](drawing-objects.md#handles) instead, and so are a few objects across a chart (a session's box, a broken zone, a swing-to-swing line): a section spends its slots on every bar, record or not, and for tens of objects a chart handles measured cheaper to paint. ```typescript // One mark a bar on the close, sized by the bar's volume: an up bar takes the second colour. plot.marks({ name: "prints", slots: 1, size: { law: "sqrt", unit: 1000, scale: 5 }, colors: ["theme.down", "theme.up"], tooltip: "{{qty}} at {{price}}" }); function onBar(): void { const side = bar.close() >= bar.open() ? 1 : 0; out_prints_mark(0, bar.close(), bar.volume(), side, 1, 0); } ``` ## How a section works `plot.marks(options)`, `plot.spans(options)` and `plot.rays(options)` are top-level declarations: an object literal the build reads and removes before the file compiles, like every `plot` declaration. `name` and `slots` are required; `slots` (1..64, a number written out) is how many records the section holds on one bar. The build generates a record writer for each section, and `out__clear()`, which empties every slot: | Kind | Record writer | A slot holds | | --- | --- | --- | | marks | `out__mark(slot, price, qty, side, fills, offsetMs)` | the price, the quantity and the integer fields | | spans | `out__span(slot, top, bottom, lengthBars, style, word, extend)` | the top, the bottom, the length and the integer fields | | rays | `out__ray(slot, y1, y2, lengthBars, style, word, extend)` | the two prices, the length and the integer fields | | timed spans | `out__span_at(slot, top, bottom, startTs, endTs, style, word, extend)` | the top, the bottom, the start and end times and the integer fields | | timed rays | `out__ray_at(slot, y1, y2, startTs, endTs, style, word, extend)` | the two prices, the start and end times and the integer fields | A spans or rays section is timed when your file calls its `_at` writer and runs a length of bars when it calls the other one; a section takes one of the two, and calling both is refused by name. - **Slots.** `slot` runs from 0 to `slots - 1`; any other slot stops the run with the section's name ("marks 'prints': a slot outside 0..0 was written"). - **Empty slots.** A slot not written on a bar is empty and draws nothing. Every bar starts empty, so a bar that writes no record draws none, and a forming bar the chart evaluates again on a live update shows what the last evaluation wrote: four records, then one, leaves one. A file with the four functions (`init`, `state`, `finalize`, `reset`) calls `out__clear()` in `finalize()` before its writes, since every output there is written on every row. - **The integer fields.** `side` (0..3) picks a mark's colour, `fills` (0..65535) is a count the hover readout prints, and `offsetMs` (0 to 1,073,741,824 ms, about 12.4 days) places a mark inside its bar under `x: 1`. `style` (0..7) picks a span's or a ray's colour, `word` (0..30) picks one of its `words` (a negative word, or one past the list, draws none), and a nonzero `extend` runs it to the chart's right edge. `lengthBars` counts the chart's bars after the record's own (0 is that bar alone; below 0 reads 0). A value past its range is clamped to it. - **Outputs.** Each section adds `slots` x 3 (marks), `slots` x 4 (spans and rays) or `slots` x 5 (timed spans and rays) hidden outputs, named `__`, after every output you declare. They count toward the 256 outputs a file may declare; you never write them one by one. - **Per bar.** A section carries nothing from one bar to the next, so a [per-bar script](../core-concepts/per-bar-scripts.md) stays per bar with one: on a pan-back the chart computes only the bars it has not drawn. ## Marks `plot.marks(options)` draws up to 64 marks a bar, each at a price with a quantity. The size follows the quantity, the colour follows the side, and a caption can print the quantity on the larger marks. ```typescript // Up to 8 rings a bar, each placed at its own time inside the bar, the largest captioned. plot.marks({ name: "trades", slots: 8, size: { law: "sqrt", unit: 10, scale: 5 }, opacity_pct: 30, look: 2, text: { mode: 1, field: "qty", format: "compact", min_px: 22 }, x: 1, colors: ["#F05351", "#27A69A"], tooltip: "{{side}} {{qty}} at {{price}}, {{fills}} fills", panel: "overlay" }); ``` | Word | Value | What it does | | --- | --- | --- | | `slots` | 1..64, required | the marks one bar holds | | `size` | `{ law, unit, scale }` | how big a mark draws (below) | | `opacity_pct` | 10..80 (default 30) | the fill's opacity, in percent | | `look` | 0..3 (default 0) | 0 a bubble (a fill with a solid edge), 1 a soft dot (a denser fill, no edge), 2 a ring (a solid edge over a faint fill), 3 a square (a denser filled square) | | `text` | `{ mode, field, format, min_px }` | a caption: `mode` 0 off, 1 on the largest mark of each bar (default), 2 on every mark; `field` `"qty"`; `format` `"compact"` (default), `"price"` (the chart's price digits), `"int"`, `"usd"` or `"units"` (Number formats, below); `min_px` (0..64, default 22) the smallest diameter that takes one | | `x` | 0 or 1 (default 0) | 0 the bar's centre, 1 the mark's own time: the bar's open plus `offsetMs` | | `colors` | 2..4 colours (default `["theme.down", "theme.up"]`) | `side` picks one: 0 the first, 1 the second | | `tooltip` | a template of at most 200 characters, or `null` (default `null`, no readout) | the hover readout over a mark: `{{side}}`, `{{qty}}`, `{{price}}`, `{{fills}}`, each with an optional number format (below) | | `panel` | `"overlay"` | marks draw on the price pane | **Size.** `unit` (above 0, default 1) is the quantity a base-size mark holds and `scale` (1..10, default 5) sets the base: with `k = 0.5 + 0.1 x scale`, a mark's diameter is `11 x k x sqrt(qty / unit)` px, rounded and kept between `11 x k` and the smaller of 64 and `50 x k`. `law: "linear"` drops the square root, so the diameter follows the quantity instead of the area. **Order.** Larger marks draw first, so a small mark is never hidden under a large one, and each translucent mark composes over the marks under it; captions draw last, over every mark. **Number formats.** A tooltip placeholder takes one of the caption's five formats after a colon: `{{qty:compact}}` prints 1.2M or 1.2K, `{{qty:price}}` the chart's price digits and `{{qty:int}}` a whole number, so `"{{side}} ${{qty:compact}} at {{price}}"` reads "Buy $1.2M at 64250.5". `usd` prints a dollar sign before the compact number, so `{{qty:usd}}` reads $1.2M and a negative amount -$1.2K. `units` prints a mark's dollar `qty` in the market's own unit, `qty` over its `price` times the market's point value (20 on NQ, 1 on crypto and US stocks), compact, so 25 NQ contracts read 25 and 5.2 BTC read 5.2, or like `usd` where the chart holds no point value. Without a format, `{{qty}}` prints the full amount (1234568), `{{price}}` the price and `{{fills}}` a whole number. Spans and rays take the same five on their numbers (`{{top:price}}`, `{{length:int}}`), `units` printing any number but a mark's `qty` compact; `{{side}}` and `{{word}}` print words and `{{start}}` and `{{end}}` times, with or without one. ## Spans `plot.spans(options)` draws up to 64 boxes a bar. A box covers a price range from its own bar across `lengthBars` more of the chart's bars, or on to the right edge with `extend`. ```typescript // The range of a bar whose body fills most of it, held for 10 bars: an up bar takes the first colour and word. plot.spans({ name: "zones", slots: 1, colors: ["theme.up", "theme.down"], opacity: 0.15, border: { width: 1, opacity: 0.8 }, words: ["Up bar", "Down bar"], tooltip: "{{word}} {{bottom}} to {{top}} over {{length}} bars", panel: "overlay" }); function onBar(): void { if (Math.abs(bar.close() - bar.open()) < 0.7 * (bar.high() - bar.low())) return; const pick = bar.close() >= bar.open() ? 0 : 1; out_zones_span(0, bar.high(), bar.low(), 10, pick, pick, 0); } ``` | Word | Value | What it does | | --- | --- | --- | | `slots` | 1..64, required | the boxes one bar holds | | `colors` | 1..8 colours (default `["theme.accent"]`) | `style` picks one | | `opacity` | 0..1 (default 0.2) | the fill's opacity | | `border` | `{ width, opacity }` (default width 1, opacity 0.8), or `null` for none | the edge: `width` 0..4 px, `opacity` 0..1 | | `words` | up to 16, each 1..32 characters | `word` picks one, drawn with the box | | `tooltip` | a template of at most 200 characters, or `null` (default `null`, no readout) | the hover readout over a box: `{{top}}`, `{{bottom}}`, `{{length}}`, `{{word}}` | | `panel` | `"overlay"` | spans draw on the price pane | ## Rays `plot.rays(options)` draws up to 64 segments a bar, each from its own bar at `y1` to `lengthBars` bars later at `y2`, or on to the right edge with `extend`. A ray with a length of 0 and `extend` set is a level from its bar to the edge. ```typescript // A long upper wick's high, carried 20 bars; a long lower wick's low, run to the right edge. plot.rays({ name: "wicks", slots: 2, colors: ["theme.muted", "#f59e0b"], width: 1.5, line_style: "dashed", opacity: 0.9, words: ["Wick high", "Wick low"], tooltip: "{{word}} at {{y1}}", panel: "overlay" }); function onBar(): void { const range = bar.high() - bar.low(); if (range <= 0.0) return; if (bar.high() - Math.max(bar.open(), bar.close()) > 0.5 * range) out_wicks_ray(0, bar.high(), bar.high(), 20, 0, 0, 0); if (Math.min(bar.open(), bar.close()) - bar.low() > 0.5 * range) out_wicks_ray(1, bar.low(), bar.low(), 0, 1, 1, 1); } ``` | Word | Value | What it does | | --- | --- | --- | | `slots` | 1..64, required | the segments one bar holds | | `colors` | 1..8 colours (default `["theme.accent"]`) | `style` picks one | | `width` | 0.5..8 px (default 1) | the line's width | | `line_style` | `"solid"` (default), `"dashed"` or `"dotted"` | the line's pattern | | `opacity` | 0..1 (default 1) | the line's opacity | | `words` | up to 16, each 1..32 characters | `word` picks one, drawn with the segment | | `tooltip` | a template of at most 200 characters, or `null` (default `null`, no readout) | the hover readout over a segment: `{{y1}}`, `{{y2}}`, `{{length}}`, `{{word}}` | | `panel` | `"overlay"` | rays draw on the price pane | ## Timed spans and rays `out__span_at(slot, top, bottom, startTs, endTs, style, word, extend)` and `out__ray_at(slot, y1, y2, startTs, endTs, style, word, extend)` write a record that runs between two times your script knows: a box from the bar at `startTs` to the bar at `endTs`, or a segment from (`startTs`, `y1`) to (`endTs`, `y2`). The start may lie before the bar that writes the record, so a box over the bars a condition held, written on the bar it ended, is one record on one bar. The rule above still decides: timed records that land on most bars belong here; a session's box, a broken zone or a line between two swings, a few a chart, stay [handles](drawing-objects.md#handles). ```typescript // Each run of 10 bars boxed from its first bar's open to its last bar's close, written on the run's last bar. chart.interval_sec(); plot.spans({ name: "range", slots: 1, colors: ["theme.accent"], opacity: 0.1, tooltip: "{{bottom}} to {{top}}, {{start}} to {{end}}" }); let intervalSec = 0.0; let firstTs = 0.0; let hi = 0.0; let lo = 0.0; let count = 0; function onStart(): void { intervalSec = p_chart_interval_sec(); } function onBar(): void { if (count == 0) { firstTs = bar.time(); hi = bar.high(); lo = bar.low(); } hi = Math.max(hi, bar.high()); lo = Math.min(lo, bar.low()); count += 1; if (count == 10) { out_range_span_at(0, hi, lo, firstTs, bar.time() + intervalSec, 0, -1, 0); count = 0; } } ``` - **Times, not bar counts.** `startTs` and `endTs` are epoch seconds, the unit `bar.time()` reads, and the chart places both ends at their exact times, the way it places a handle's corners. A count of bars your script keeps is not the chart's count: the chart leaves out the bars it has no data for, a session market's grid skips its closed hours, and volume or range candles have no fixed width, so a box drawn back by a count lands on the wrong bar where a time lands exact. Take both ends from times your script stored (a bar's open is `bar.time()`, its close that plus `chart.interval_sec()`), and never convert them to milliseconds. - **The end.** An end not after the start is written as the start: the record covers its start alone. A nonzero `extend` continues the record past its end to the chart's right edge, a box at its prices and a ray along its slope, so a ray needs a real second point even when it is extended. - **The integer fields** are those of the run-of-bars writers: `style` picks a colour, `word` one of `words`, and a value past its range is clamped to it. - **The hover readout** takes `{{start}}` and `{{end}}` in place of `{{length}}`. - **A section's layout** follows the writer your file calls: a timed section holds `slots` x 5 outputs, `__top` (or `_y1`), `_bottom` (or `_y2`), `_start`, `_end` and `_meta`, and the sheet says `"stride": 5`. A chart built before timed spans and rays reads the run-of-bars layout only and refuses an indicator with a timed section by name ("stride must be 4"), so an indicator that uses one needs the current chart. ## Settings Every look key except `slots`, `panel` and `text.field` takes `"@"`, so a setting drives it ([Setting kinds](../settings/kinds.md)): a colour takes a `param.color`; a number key a `param.number` or `param.int` whose `min..max` lies inside the key's range; `size.law`, `text.format` and `line_style` a `param.choice` over their words (its choices, or its `style_values` when the choices are the dialog's labels: [Options on a setting](../settings/options.md)); and `look`, `text.mode` and `x` a `param.choice` with at most as many options as the key has, the picked option's position being the value ("Ring" below sets `look` to 2), or a `param.int` inside the key's range. ```typescript param.number("min_size", 10, { min: 0.0001, max: 1000000000 }); param.choice("look", ["Bubble", "Soft dot", "Ring", "Square"], "Ring"); param.int("bubble_size", 5, { min: 1, max: 10 }); param.int("opacity", 30, { min: 10, max: 80 }); param.choice("show_size", ["Off", "Big bubbles", "All"], "Big bubbles"); param.choice("position", ["Candle center", "Trade time"], "Trade time"); param.color("buy_color", "#27A69A"); param.color("sell_color", "#F05351"); plot.marks({ name: "trades", slots: 8, size: { unit: "@min_size", scale: "@bubble_size" }, look: "@look", opacity_pct: "@opacity", text: { mode: "@show_size" }, x: "@position", colors: ["@sell_color", "@buy_color"] }); ``` A setting writes one value to every key it drives, so one `param.choice` cannot set both a position key (`look`) and a word key (`line_style`): that is refused by name; declare two settings. ## What the chart receives Run writes each section into the sheet with the two numbers the chart reads it by: `first_output`, the index of the section's first output, and `stride`, the fields one slot holds (3 for marks, 4 for spans and rays, 5 for timed spans and rays). Slot `i`'s fields are the outputs whose indexes start at `first_output + stride x i`. A sheet always carries every look key: Run writes the default for each key a declaration leaves out (a nested key of `size`, `text` or `border` too), and the chart draws what the sheet says. The first example on this page derives: ```json { "outputs": [ { "index": 0, "name": "prints_0_price", "plot": "" }, { "index": 1, "name": "prints_0_qty", "plot": "" }, { "index": 2, "name": "prints_0_meta", "plot": "" } ], "marks": [ { "name": "prints", "slots": 1, "first_output": 0, "stride": 3, "size": { "law": "sqrt", "unit": 1000, "scale": 5 }, "opacity_pct": 30, "look": 0, "text": { "mode": 1, "field": "qty", "format": "compact", "min_px": 22 }, "x": 0, "colors": ["theme.down", "theme.up"], "tooltip": "{{qty}} at {{price}}", "panel": "overlay" } ] } ``` A slot's last field packs its integer fields into one number: a mark's `side + 4 x fills + 262144 x offsetMs`, a span's or a ray's (timed or not) `style + 8 x word + 256 x extend`. A timed slot's `start` and `end` fields hold the two times in epoch seconds. An empty slot is NaN in every field. ## What refuses Every misuse is refused by name when Run derives the sheet: - a fifth section of one kind ("marks must declare at most 4 entries"), or `slots` outside 1..64 ("plot.marks 'm' slots must be an integer from 1 to 64 (the records it holds a bar)"); - sections that take the file past 256 outputs ("plot.marks 'm2' derives 66 outputs (22 slots x 3 fields), which takes the sheet to 259 outputs; a row carries at most 256, so declare fewer slots or fewer outputs"); - an output you declare under a derived name ("plot.marks 'm' derives output 'm_0_price', which is already declared; rename one"), and a section named like an output, a canvas or any other named part: names share one namespace; - `colors` outside 2..4 on marks or 1..8 on spans and rays, a colour that is not `"#rrggbb"`, `"#rrggbbaa"` or a theme token, more than 16 `words`, and a `tooltip` over 200 characters, naming a field its kind does not carry ("tooltip names {{word}}, which a marks record does not carry") or a format other than `compact`, `price`, `int`, `usd` and `units` ("tooltip names {{qty:si}}, a format the chart does not print"); - a setting whose kind or range does not fit its key ("plot.marks 'm' look references "@look", which is not a param.choice of at most 4 options or a param.int within 0..3"); - both writers of one section in one file ("plot.spans 'z' is written by both out_z_span() (line 5, a run of bars) and out_z_span_at() (line 6, two timestamps); a section holds one record layout, so call one of the two writers"), and a timed section's tooltip naming `{{length}}`. Sections draw when the indicator runs in your browser and when it runs on OpenMarket's servers as a **Protected** indicator: the server keeps the section and sends its rows to your chart, which draws them. A timed section needs a chart that draws stride-5 records (it advertises `wrun-batched-v2`); an older chart keeps the indicator off its hosted lane by name. The caps are on [Limits](../reference/limits.md). # Legend The legend names the indicator, then shows each drawn output's label and value; every word on it comes from a declaration. ## What it is The legend shows each output's `label`, or its name read as words when there is none (`bb_upper` reads "Bb upper"), and its value in the output's `format`; `legend: false` keeps an output out of the legend, and `legend({ title: "..." })` adds words after the indicator's name. Outputs mount in declaration order, which is their legend and paint order. A `render.legend` entry adds a line the outputs do not carry, a string slot's words or an output's formatted value, printed after the value lines. The dot before an entry shows the colour the hovered bar is drawn in, so a `color_by` ladder, a packed colour or a column's sign pair reads in the legend as it does on the chart. A candle group is one entry reading its open, high, low and close (`O 1.20 H 1.31 L 1.18 C 1.29`), its dot the up or down colour of the hovered bar. A `range()` band has a row of its own (`legend: false` drops it, `label` names it), a guide (`role: "guide"`) never appears, and a pane declared with a `title` heads its own legend with that title. ## Declare it - `legend({ title })`: the words after the indicator's name, `(14)` style; `{{length}}` reads a setting by name. Without it the legend shows the package name. - Per output: `label` (the legend and Style page name), `format` (`price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd`, `auto`) with `decimals` (0..8), `signed` and `unit` (printed after the value; unbounded on an output, as it always was), and `legend: false`. `price` prints at the chart's price digits on every pane; `usd` reads `$1.2M`, `auto` six significant digits with `,` thousands ([Styling](styling.md#placement-per-output)). - Per band: `range(a, b, { legend: false, label: "Band" })`. - `render.legend(name, { text?, value?, format?, color?, color_by?, colors? })`: an entry in the legend, a string slot's words (`text`) or an output's formatted value (`value`), in a static `color` or colored per bar by a ladder (`color_by` and `colors`, both or neither). - `color: "@name"` on a legend entry, or an entry of its `colors`, binds that spot to a `param.color`, so the user picks the entry's color ([The Style page](../settings/style-page.md)). ```typescript param.int("length", 20, { min: 2, max: 500 }); const basis = output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); output("state", none); string("regime", { max_bytes: 16 }); legend({ title: "({{length}})" }); render.legend("regime_entry", { text: "regime", color_by: "state", colors: ["#ef5350", "#26a69a"] }); ``` ## What the chart draws ![the legend row: the name with its title suffix, then two labelled values](/wrun/images/wrun-legend.svg) The legend reads "Basis 20", then "Basis 64,120.5", "RSI 61.3" and the regime word in the ladder's color. An output's `tooltip` is shown on its legend entry, and resting the cursor on the entry opens the output's hover card ([Hover cards](hud-and-hover-cards.md#hover-cards)). ## Gotchas - `legend: false` keeps an output out of the legend; `visible: false` starts it hidden; a `role: "guide"` output is never listed. - `decimals`, `signed` and a printed `unit` need `format`; a `unit` without one is recorded and never printed. - A legend entry needs `text` (a string slot) or `value` (an output), and takes `color_by` and `colors` together, not one without the other. - `legend` needs a nonempty title. - A presentation name used twice is refused. - The legend is drawn where the indicator runs in the browser. ## Related - [What the chart shows](overview.md), [Hover cards](hud-and-hover-cards.md#hover-cards), [HUD cards](hud-and-hover-cards.md#hud-cards), [Blocks and tiles](hud-and-hover-cards.md#blocks-and-tiles) - [The Style page](../settings/style-page.md): the `"@name"` binding - [Plotting](plotting.md): the outputs the legend lists # Labels, tooltips, badges The words a plot, a text mark or a label answers with: the label's style, the tooltip template, and the badge chips a ladder output turns into. ## What it is `style` on a text or label renderer picks its look: `price_label` draws the price tag on the axis (the one word `render.text` takes), and a `render.label` also takes `plain`, `pill` (a rounded chip at the value), `callout` (a leader line to its bar) and `badge` (a dot in the label's color). `tooltip` on an output is a template over its own value and any output or string slot, shown on the legend entry and when the cursor nears the line; on `render.text` and `render.label` it is one per renderer, shown on its marks. `badges` names ANOTHER output, a ladder whose labels become chips on the hover card. `style`, `tooltip`, `hover` and `badges` are presentation keys, stripped before the compiler like an output's. ![The five label styles side by side on one small pane: plain words above their bar, a pill chip at the value, a callout chip with a leader line down to its bar, a badge dot in the label's color before its words, and a price_label tag on the price axis tied to its bar](/wrun/images/wrun-label-styles.svg) 1. **plain**: the words alone, at the label's `x` and `y`. 2. **price_label**: a tag on the price axis at the mark's price, the one style `render.text` also takes. 3. **pill**: a rounded chip at the value. 4. **callout**: a chip with a leader line down to its bar. 5. **badge**: a dot in the label's color, then the words. ## Declare it ```typescript const basis = output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); // A text mark on every stretched bar (the slot is left unwritten on quiet bars). render.text("stretch_mark", { y: "average", text: "readout", color: "#f59e0b", size: 10 }); // One label riding the newest bar, at the average. render.label("average_tag", { x: "bar_time", y: "average", text: "tag", color: "#38bdf8", size: 11 }); ``` A template placeholder is `{{name}}` for an output or a string slot, `{{name:format}}` with a format from the list (`price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`), `{{label}}` and `{{value}}` for the owning output: `"{{label}} {{value:price}} · {{state}}"`. A price tag on every signal bar is `render.text` with `style: "price_label"`: each written bar's text sits at `y` as a price tag. ![One tooltip template resolving: the declaration reads tooltip with label, value as a price and state in double braces; the legend entry shows Basis 83,600.00 and the word stretched; the same words sit under the cursor near the line on the chart; and the hover card carries the ladder output's labels as badge chips](/wrun/images/wrun-tooltip-template.svg) 1. **The template** on the output: `{{label}}` is the output's label, `{{value:price}}` its value at the chart's price precision, `{{state}}` a string slot or another output. 2. **On the legend entry**: the same words, resolved on the newest bar. 3. **Near the line**: the same tooltip when the cursor nears the plot. 4. **Badges**: the ladder output named in `badges` turns its labels into chips on the hover card. ## What the chart draws What each surface answers with: | Surface | Answers with | | --- | --- | | a plot (a line, columns, marks) | its `hover` blocks; without them its `tooltip`, else its label and value | | a legend entry | the output's `tooltip`, and the output's hover card when the cursor rests on it | | a text mark (`render.text`) | the renderer's `tooltip` on its marks, its `hover` list, its `badges`; `style: "price_label"` draws each mark as a price tag | | a label (`render.label`) | the same, with `style` one of `plain`, `price_label`, `pill`, `callout`, `badge` | | a HUD tile | the tile again as a hover card | | a table or a drawing | nothing | ## Gotchas - The pill, callout and badge label styles draw on the next engine pin. - `render.text` takes `price_label` only (no `style` is plain text); a label `style` outside the five words is refused. - `size` is an integer pixel count, 6..64, on `render.text` and `render.label` (`10` reads as small text, `16` as large); there is no alignment option on renderer text. - An output badging itself is refused; `badges` names a declared output. - A label has no corner position: it sits at its `x` and `y`, anchored to a bar and a price. A corner readout is a HUD card ([HUD cards](hud-and-hover-cards.md#hud-cards)). - In a template an unknown name stays as written. ## Related - [Hover cards](hud-and-hover-cards.md#hover-cards), [HUD cards](hud-and-hover-cards.md#hud-cards), [Legend](legend.md), [What the chart shows](overview.md) - [Plotting](plotting.md): the text, label and table renderers, and the string slots they read - [Styling](styling.md): the rest of the style vocabulary # HUD and hover cards Two surfaces read the indicator's newest values and are drawn by the chart from declarations alone: a HUD card of typed tiles pinned at one of the nine chart anchors, never moving with price, and the hover card that opens when the cursor rests on a legend entry, a HUD tile, a line, a text mark or a label. Both are built from one kit of blocks, `tile.*` on the HUD card and `block.*` on the hover card, and both are drawn where the indicator runs in the browser, on the desktop chart. The third surface, the legend entry, is on [Legend](legend.md); the three together, with a complete module, on [What the chart shows](overview.md). The status card, the meter, the feed, the ladder and the stats row share the HUD's words; their looks close the page ([The other widgets](#the-other-widgets)). ## HUD cards `render.hud(name, { position, title?, columns?, tiles, look?, ... })` is a card at one of the nine anchors, one or two columns, its tiles from the block kit under the `tile.*` name. It is the home for text that sits at a viewport anchor and does not move with price: a corner readout is a HUD card with one tile (or a `render.label` with a `position`, or a one-cell `render.table` at the same anchor, [Plotting](plotting.md#fixed-position-text)), a dashboard a card of several. Its surface, type and frame are words on the declaration, and `look` picks a whole set of them at once. A card with no `look` draws the default look ([The default look](#the-default-look)); a word declared on it still wins. ```typescript const basis = output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); output("basis_chg", none); output("state", none); string("regime", { max_bytes: 16 }); render.hud("board", { position: "top_right", title: "Basis", columns: 2, tiles: [tile.value("Basis", "basis", { format: "price", delta: "basis_chg" }), tile.spark("RSI", "rsi", { bars: 32 }), tile.gauge("RSI level", "rsi", { min: 0, max: 100, format: "int" }), tile.pill("Regime", "regime", { color_by: "state", colors: ["#ef5350", "#26a69a"] })] }); ``` - `position`: one of the nine anchors, `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`; a position outside them is refused. - `title`: the card's heading. `columns`: 1 or 2. - `tiles`: the card's tiles, any of the eight kinds ([Blocks and tiles](#blocks-and-tiles)); a presentation name used twice is refused. Every tile takes `color` or a `color_by` plus `colors` ladder (colour words, theme tokens included, never both); absent, the tile takes the look's ink, and the default look adds no colour of its own ([The default look](#the-default-look)). ![a card of four tiles in the top-right corner: a value with its change, a sparkline, a dial and a chip](/wrun/images/wrun-hud.svg) The card in the corner shows the basis with its change, a sparkline, a dial and the regime chip, and follows every live tick. Resting the cursor on a tile shows that tile again as a hover card, and a wheel over the card still zooms the chart. The card keeps clear of the pane chrome: the right anchors sit clear of the price axis, the bottom anchors clear of the time axis, and `safe_area: true` keeps the top anchors clear of the legend and the pane action bar too. It disappears with its indicator when the indicator is hidden or removed. ### The default look A card with no `look` word draws the default look, the first row of the [look table](#looks): a near-black translucent card (white paper on a light chart) with a 1 px hairline border and 12 px corners. The title is in sentence case at 12 px. The headline tile reads at 17 px bold with its label hidden, a value at 18 px, and a pill as text, with no capsule and no dot. Rows are 22 px tall, with a hairline between them and no leader marks. The type is white throughout on a dark chart; colour shows only where you declare it, and on a signed delta, which takes the up or down colour. ```typescript output("rr", none); output("rr_chg", none); string("skew_state", { max_bytes: 24 }); // No look word: the default look. render.hud("skew", { position: "top_right", title: "Skew history", tiles: [tile.value("Risk reversal", "rr", { format: "0.00", delta: "rr_chg", headline: true }), tile.pill("Skew", "skew_state"), tile.rows([["Risk reversal, 30 days", "rr", "0.00"]])] }); // A look from the table instead; a word declared beside it still wins. render.hud("skew_desk", { position: "bottom_right", title: "Skew history", look: "terminal", title_case: "none", tiles: [tile.value("Risk reversal", "rr", { format: "0.00", delta: "rr_chg", headline: true }), tile.pill("Skew", "skew_state")] }); ``` A card that names a look keeps it: the twelve looks of the table stay available, `look: "terminal"` and the others draw exactly as the table says, and the Look row on the indicator's Style page still offers every one. To leave the default look, declare a `look`; to keep it and change one thing, declare only that word. ### Moving a card A viewer can move any card on their chart: drag it from anywhere on the card (on a phone, hold its grip, then drag). Near one of the nine places it snaps in and a label names the place ("Top right, under Market"); anywhere else it stays where it is let go. Option (Alt) drops it without the snap, Esc cancels, and a double-click sends a moved card back. The move is the viewer's, saved with the overlay on that chart; `position` and `offset` stay the card's default, and the Position row on the indicator's Style page ([The Style page](../settings/style-page.md#the-position-row)) says where the card is and puts it back. A card moved into a place that already holds cards joins the far end of its stack. ### Collapsing and hiding a card Hovering a card shows a chevron and a cross on its title row; on a touch screen they always show. The chevron collapses the card into a chip at the same place, its title and the headline value, and a click on the chip expands it again. The cross hides the card, and the Show row on the indicator's Style page ([The Show row](../settings/style-page.md#the-show-row)) brings it back. Both are the viewer's, like a move: saved with the overlay on that chart, never written into the sheet, and nothing for the file to declare. A file cannot set a default yet: no word starts a card collapsed or chooses when the chevron and cross show. ### Surface, type and frame Every word is optional and absent keeps the default look ([The default look](#the-default-look)). Colours are `"#rrggbb"`, `"#rrggbbaa"` or a theme token (`"theme.bg"`, [Styling](styling.md#theme-colours)). ```typescript output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price" }); render.hud("board", { position: "top_right", title: "Market", columns: 2, width: 260, offset: [12, 8], safe_area: true, background_color: "theme.bg", background_opacity: 0.85, border_color: "theme.grid", corner_radius: 10, font_family: "mono", accent_color: "theme.up", chrome: "brackets", tiles: [tile.value("Basis", "basis", { format: "price", headline: true })] }); ``` - Size and place: `width` (80..1200 px; default 300, 180 at one column), `offset: [x, y]` (each -4096..4096 px; x moves inward from a left or right edge and y inward from the top or bottom, signed on the centre and middle anchors), `z` (an integer; cards in one anchor stack by it, lower nearer the anchor), `safe_area: true` (a top-left card starts under the legend, top-centre and top-right cards under the pane action bar, right-hand cards clear of the price-axis tags; `offset` applies from the cleared edge), `mobile: true` (the card shows on phones too, with pointer-free tiles and at most the larger of 140 px and 60 percent of its own width; absent, phones keep the chart as it is). - Surface: `background_color`, `background_opacity` (0..1, default 0.92), `background_gradient` (2 to 8 colours) with `gradient_direction` (`"vertical"`, the default, or `"horizontal"`), `border_color`, `border_width` (0..10, default 1), `border_style` (`"solid"`, `"dashed"`, `"dotted"`), `corner_radius` (0..32, default 12), `padding` (0..24), `shadow` (default true), `opacity` (0..1, the whole card). - Type: `text_color`, `title_text_color` (default the muted ink), `font_family` (`"ui"`, the app font; `"mono"`; `"serif"`; `"rounded"`; each a system stack, nothing downloads), `title_case` and `label_case` (`"none"`, `"upper"`, `"lower"`, `"small_caps"`; the title prints in sentence case in the default look and in capitals under another look, and labels as written, unless the look's row says otherwise; values and numbers never change case), `text_glow` (0..8 px, a static halo in the text colour). - Accent: `accent_color` inks every gauge, meter fill, spark and headline that declares no colour of its own; absent, a look's own accent or `"theme.accent"`, and none in the default look, which adds no colour you did not declare. `accent_color_by` plus `accent_colors` (2 to 8) make the whole card follow an output per bar (green rising, red falling), and the pair excludes `accent_color`. - Frame: `chrome` is `"card"` (a box, the default look's frame), `"none"` (no box, text over the chart; pair it with a translucent background), `"brackets"` (four corner marks in the accent), `"rules"` (a thick and a thin rule above the title), `"tag"` (a small accent block at the top left), `"title_bar"` (the title on a full-width bar in the accent), `"window"` (bevelled edges and a two-colour title bar, its buttons decoration only) or `"cover"` (a square tile left of the title holding the chart's base asset over the accent gradient); `texture` is `"none"` or `"scanlines"` (static 1 px lines every 3 px). A flat card that takes its colour from the data: a dashed hairline border, no drop shadow, the title in the full text ink, and every gauge, meter fill, spark and headline inked by the sign of the bar's basis change, red falling and green rising. Reach for it when the card should read as part of the chart, not as a window over it. ```typescript output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price" }); output("basis_chg", none); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); // 0 on a bar where the basis fell, 1 where it rose: the whole card's accent follows it. output("basis_dir", none); render.hud("flat", { position: "top_right", title: "Basis", tiles: [tile.value("Basis", "basis", { format: "price", delta: "basis_chg", headline: true }), tile.gauge("RSI", "rsi", { min: 0, max: 100, format: "int" })], accent_color_by: "basis_dir", accent_colors: ["theme.down", "theme.up"], border_style: "dashed", border_width: 1, padding: 14, shadow: false, title_text_color: "theme.text", }); ``` An instrument readout: mono type, the title and labels in capitals, a soft halo on the text, scanlines over the surface and bracket corners instead of a box. Reach for it on a dark chart where the card should look like a gauge cluster rather than a dialog. ```typescript output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); render.hud("instrument", { position: "bottom_left", title: "RSI", tiles: [tile.gauge("Level", "rsi", { min: 0, max: 100, format: "int", draw: "ticks" }), tile.spark("Trend", "rsi", { bars: 32 })], text_color: "#7DF9FF", font_family: "mono", title_case: "upper", label_case: "upper", text_glow: 4, texture: "scanlines", chrome: "brackets", }); ``` A pocket card that shows on phones too: one column, a fixed 160 px width, a small inset, no shadow, and `safe_area` so it starts under the legend. Absent `mobile`, a phone keeps the chart as it is and the card stays a desktop readout. ```typescript output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price" }); output("basis_chg", none); render.hud("pocket", { position: "top_left", columns: 1, tiles: [tile.value("Basis", "basis", { format: "price", delta: "basis_chg" })], mobile: true, safe_area: true, width: 160, padding: 8, shadow: false, }); ``` Nothing on a card animates, blurs or loads from outside the chart, and no script ever writes CSS: a shared indicator cannot paint over the chart with anything the words above do not describe. ### Looks `look` stands for a whole row of the table below; any word declared beside it wins, so a look is a starting point, not a cage. Absent, the card draws the `default` row ([The default look](#the-default-look)). The viewer can switch the look on the indicator's Style page ([The Style page](../settings/style-page.md)), where every HUD gets a Look row with "As made" first, unless the file bound the look to a setting (below). | look | surface | type | draws | chrome | palette | | --- | --- | --- | --- | --- | --- | | `default` | background near black and translucent (white paper on a light chart), border a 1 px hairline, corner radius 12 | title in sentence case at 12, headline 17 bold with its label hidden, values 18, rows 22 with hairline separators, white type | arc, line, bar, text | card | adaptive | | `glass` | background `#1c1c1ee6` (`#f2f2f7e6` on a light chart), border `#ffffff29` 1 px, corner radius 22, padding 16, shadow | `rounded`, no title, headline 34 | gauge ring, spark area, meter bar, pill dot | card | adaptive | | `stage` | background gradient `#2c6b46`, `#1b3a28`, `#121212`, `#121212` vertical, corner radius 10, padding 14 | `ui`, headline 30 bold, accent `#1ed760` | gauge bar, meter split, spark line, pill text | cover | home | | `signal` | background `#000000`, border `#1d1d1d` 1 px, corner radius 14 | `ui`, headline 38, no title | spark line (height 78, a zero line), meter split | card | home; the whole card's accent follows `accent_color_by` | | `terminal` | background `#000000`, border `#3a3a3a` 1 px, corner radius 0, padding 6 | `mono`, title and labels upper, label ink `#F7A21B`, text `#ffffff` | gauge text, spark text, meter text, pill text | title_bar (bar `#F7A21B`, title ink `#000000`) | home | | `broadsheet` | background `#F6F1E7`, text `#141414`, corner radius 0, padding 14 | `serif`, title small_caps, headline 20 | spark dots, meter bar, pill text, rows with dot leaders | rules | home | | `chart_desk` | background `#ffffff`, text `#121212`, corner radius 0, padding 14 | `ui`, no title | spark bars (height 96, the baseline at the meter mark), pill text | tag (`#E3120B`) | home | | `dial` | background `#EBE8E1`, text `#1d1d1b`, corner radius 16, padding 14, accent `#E05A1E` | `ui`, no title | gauge dial, meter scale, pill led | card | home | | `grid` | background `#F2F1EC`, text `#111111`, corner radius 0, padding 14, accent `#E30613` | `ui`, headline 44 bold | spark line (ink), meter split (ink and accent), pill text | rules | home | | `cockpit` | background `#030e12c2`, corner radius 0, padding 12, text `#7DF9FF`, accent `#FFB000` | `mono`, title and labels upper, text glow 6 | gauge ticks, meter segments, spark line, pill text | brackets | home | | `phosphor` | background `#05160B`, text `#3BFF73`, corner radius 12, padding 12 | `mono`, text glow 5 | gauge text, spark text, meter text, pill text | none | home; texture scanlines | | `classic` | background `#C0C0C0`, text `#000000`, corner radius 0, padding 8 | `ui` | gauge blocks, meter blocks, spark line, pill dot | window (bevels, a title bar from `#000080` to `#1084D0`) | home | A "home" look keeps its paper on a dark and a light chart alike (a printed object does not invert); an "adaptive" look resolves its theme tokens per theme. The "draws" column is each tile kind's `draw` default under that look ([Blocks and tiles](#blocks-and-tiles)); a tile that declares its own `draw` keeps it. To let the trader pick among looks you chose, bind `look` to a setting: `look: "@card_look"` names a `param.choice` whose every choice is one of the twelve looks. The build writes the setting's default look on the card, and the card takes the picked look the moment the setting changes. That setting's row is the look's one control: the Style page draws no Look row for a bound card (its Position and Show rows stay), and any word declared beside `look` still wins over the picked look. ```typescript param.choice("card_look", ["phosphor", "glass", "terminal"], "phosphor", { label: "Card look" }); render.hud("desk", { position: "top_right", title: "RSI", look: "@card_look", tiles: [tile.gauge("Level", "rsi", { min: 0, max: 100 })] }); ``` Start from a look and change only what you must. `phosphor` with the scanlines off, a softer glow, a card frame around it and an upper-case title keeps its green-on-black type and its text-drawn tiles; every word beside `look` wins. ```typescript output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); string("regime", { max_bytes: 16 }); render.hud("desk", { position: "top_right", title: "RSI", tiles: [tile.gauge("Level", "rsi", { min: 0, max: 100, format: "int" }), tile.pill("Regime", "regime")], look: "phosphor", texture: "none", text_glow: 2, chrome: "card", title_case: "upper", }); ``` The rules, each refused by name when broken: - `columns` takes 1 or 2; a `position` outside the nine anchors is refused. - `look`, `chrome`, `texture`, `title_case`, `label_case`, `font_family` and a tile's `draw` outside their words are refused by name, with the list; so are `width` outside 80..1200, `offset` outside -4096..4096, `corner_radius` outside 0..32 and `text_glow` outside 0..8. - `look: "@name"` naming no setting, or a setting that is not a `param.choice` over looks only, is refused by name (`render.hud 'desk' look references "@ink", which is not a param.choice over default|glass|...`); `look` is the card's only word a setting can drive, so a card colour stays a literal. - `accent_color` beside `accent_color_by` is refused, and the ladder needs its `accent_colors`. - One headline tile per card: a second `headline: true` is refused. - A corner readout is a HUD card, a `render.label` with a `position`, or a one-cell table; a label placed by `x` and `y` sits at its price. - A presentation name used twice is refused. - The HUD is drawn where the indicator runs in the browser; a phone shows a card only when it declares `mobile: true`. ## Hover cards `hover: [...]` on an output, `render.text` or `render.label`, or `hover(handle, [...])` at the top level, is the card the cursor opens, from the block kit under the `block.*` name: one card per output, either form. Without one the surface shows the output's `tooltip`, else its label and value ([Labels, tooltips, badges](labels-and-tooltips.md)). `badges` names another output, a ladder whose labels become chips on the card. ```typescript const basis = output("basis", line, overlay, { color: "#2962ff", width: 2, label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); output("basis_chg", none); string("regime", { max_bytes: 16 }); hover(basis, [block.value("Basis", "basis", { format: "price", delta: "basis_chg" }), block.rows([["RSI", "rsi", "0.0"], ["Regime", "regime"]]), block.meter("RSI", "rsi", { min: 0, max: 100, marks: [30, 70] }), block.chips("regime")]); ``` ![the card a tile opens under the cursor: a value block with its delta](/wrun/images/wrun-hover-card.svg) Where the card appears: - a line: the output whose value at the cursor's bar sits nearest the cursor. On the price pane the line has to be within 12 pixels of the cursor; in an indicator's own lower pane the card follows the cursor's bar anywhere in the pane (a histogram answers over its whole column); - a legend entry: the value under the cursor names its output; - a HUD tile: the tile is shown again as a hover card; - a text mark or a label: the `hover` list on the `render.text` or `render.label` that drew it ([Plotting](plotting.md#text-labels-tables-strips-tints)). Around the blocks: `hint` on the output, or on a value block, adds its words to the card; `badges` adds the chips of the ladder it names; the card's edge takes the output's color, the current rung of its `color_by` ladder when it has one, else its static `color`. The rules, each refused by name when broken: - `hover` takes an output handle first (bind a handle with a top-level `const h = output(...)` and pass `h`), not a string literal. - One hover per output: inline or top-level, never both. - A hover needs at least one block. - `badges` takes ANOTHER output; an output badging itself is refused. - A table or a drawing shows no card. - In a `tooltip` or a `value` template an unknown name stays as written. ## Blocks and tiles The block kit is one vocabulary with two names: `tile.*` builds the tiles of a `render.hud(...)` card, `block.*` the blocks of a `hover(...)` card, the same constructors under their other name. A constructor lives inside the card's literal only and is erased before the compiler. `value`, `spark`, `gauge` and `meter` read a numeric output, `pill` a string slot, `chips` either, `rows` a list of `[label, output or slot, format?]` lines, and `rings` one to three outputs each with its own range. Every block reads the newest row, so a data-only output written per bar is the way to carry a delta or a regime onto either card. | Constructor | Draws | Options | | --- | --- | --- | | `value(label, output, { format?, delta?, tooltip?, hint?, color?, color_by?, colors?, headline?, font_size? })` | the output's newest value under its label, a signed delta from the `delta` output beside it; `headline: true` spans every column of a HUD card at `font_size` (default 22) with a hairline under it | `format` one of the ten; `delta` an output; `tooltip` and `hint` words; `font_size` 6..64 (default 16) | | `spark(label, output, { bars?, color?, color_by?, colors?, draw?, height? })` | a sparkline of the output's last bars (64 at most) | `bars` a positive integer; `draw` `line` (the default), `area`, `dots`, `bars` or `text`; `height` 16..120 px (default 28) | | `gauge(label, output, { min, max, format?, color?, color_by?, colors?, draw? })` | a dial between `min` and `max` | `min` and `max` required, `min` below `max`; `format` one of the ten; `draw` `arc` (the default), `ring`, `dial`, `ticks`, `bar`, `blocks` or `text` | | `meter(label, output, { min, max, marks?, color?, color_by?, colors?, draw?, height? })` | a bar between `min` and `max` with marks | `min` and `max` required, `min` below `max`; `marks` a list of numbers; `draw` `bar` (the default), `split`, `blocks`, `segments`, `scale` or `text`; `height` 16..120 px (default 4) | | `pill(label, slot, { color?, color_by?, colors?, draw?, headline?, font_size? })` | the slot's words as a chip, colored by a ladder | `draw` `capsule` (the default), `dot`, `led` or `text`; `headline` and `font_size` as on `value` (default 10, 22 as a headline) | | `rows(label?, [[label, output or slot, format?], ...], { color?, color_by?, colors?, leader? })` | rows of label and value | the caption may be left out: the rows array alone; the options object after it is optional too; `leader` `none` (the default) or `dots`, a dotted rule between each key and its value | | `chips(slot or ladder output)` | the slot's words, or the ladder's labels, as chips | none | | `rings(label?, [[label, output, { min, max, color? }], ...], { height? })` | one to three concentric rings, outermost first, each the share of its own `min..max` its output holds, with a legend beside them (dot, label, value) | 1..3 entries, `min` below `max`; `color` a colour word (default the accent at full, 70 and 45 percent strength); `height` 16..120 px (default 86) | A default in the table is the kit's, and a hover card keeps it. On a HUD card the look's row comes first ([Looks](#looks)): with no `look`, a pill draws as text, a value at 18 px and the headline tile at 17 px bold with its label hidden. The ten formats are `price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd` (`$1.2M`) and `auto` (six significant digits with `,` thousands) ([Styling](styling.md#placement-per-output)). Colour: every block takes `color` (a colour word: `"#rrggbb"`, `"#rrggbbaa"` or a theme token such as `"theme.up"`) or a `color_by` output plus a `colors` ladder; with both, the ladder wins and `color` is the fallback where the index is not finite. Absent, a hover card's block keeps its ink, marks in the output's colour and text in the card's text colour, and a HUD tile takes the look's ink, none of its own in the default look. A `rows` block's colour inks every value in it. What the `draw` words mean: `ring` is one circular track; `dial` a printed dial with ticks every 5 and a needle over 270 degrees; `ticks` a half arc with a tick every 10 and the value in the middle; `bar` a track with a knob; `blocks` a segmented progress bar; `text` block characters in the card's font (a gauge or meter as `████▌·····` over 10 cells, a spark as `▁▂▃▄▅▆▇█` over at most 16 cells); `area` the line plus a faint fill and an end dot; `dots` a stippled line; `bars` one column per bar from the first meter mark or zero; `split` the fill in the accent and the rest in `theme.down`, with labels at both ends; `segments` 20 cells; `scale` a tuning scale with a pointer; `capsule` a tinted pill; `dot` the word in its colour after a small dot; `led` a lit lamp before the word; and `text` on a pill the word alone in its colour. A block that declares `draw` keeps it on either card. A reading column on a HUD card: an area spark taller than the default, a split meter with its marks, and rows with dotted leaders between each label and its value. Reach for the taller spark when the card has the room, and for the leaders when a label sits far from its value. ```typescript output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); string("regime", { max_bytes: 16 }); render.hud("column", { position: "middle_right", columns: 1, tiles: [ tile.spark("RSI", "rsi", { bars: 48, draw: "area", height: 48 }), tile.meter("Level", "rsi", { min: 0, max: 100, marks: [30, 70], draw: "split", height: 16 }), tile.rows("Readout", [["RSI", "rsi", "0.0"], ["Regime", "regime"]], { leader: "dots" }), ], }); ``` An options-desk tile: three rings, outermost first, the calls' share of open interest, the puts' share and the IV rank, each over its own range and in its own ink, with the legend beside them. Reach for rings when three shares belong together and a bar each would read as three unrelated meters. ```typescript // Each share is 0 to 1 and the IV rank 0 to 100: a ring fills by its output's place in its own range. output("calls_share", none); output("puts_share", none); output("iv_rank", none); render.hud("options_desk", { position: "top_right", title: "Options desk", columns: 1, tiles: [ tile.rings("Positioning", [ ["Calls", "calls_share", { min: 0, max: 1, color: "theme.up" }], ["Puts", "puts_share", { min: 0, max: 1, color: "theme.down" }], ["IV rank", "iv_rank", { min: 0, max: 100, color: "theme.accent" }], ], { height: 96 }), ], }); ``` Outputs and slots are named by a bound handle or by their name as a string: `tile.value("Basis", basis, ...)` with `const basis = output("basis", ...)` above it, or `tile.value("Basis", "basis", ...)`. The sheet records the name either way. The rules, each refused by name when broken: - A card takes block constructors (`block.(...)` or `tile.(...)`), kinds `value`, `spark`, `gauge`, `pill`, `rows`, `meter`, `chips`, `rings`, and needs at least one. - `gauge` and `meter` are refused without `min` and `max`, and need `min` below `max`; so does each ring. - `bars` takes a positive integer literal; `colors` needs at least one color. - A `pill` reads a string slot, `chips` a slot or a ladder output, the numeric kinds an output; a block whose output or slot does not exist is refused. - `draw` on a `value`, `rows` or `chips` block, or a word outside the kind's own list, is refused by name ("spark draw must be one of ..."); `headline` on a kind other than `value` or `pill`, two headline tiles in one card, and `height` on a kind other than `spark`, `meter` or `rings` are refused too. - A spark's `color` or a pill's `colors` is a literal (a theme token counts): a setting paints an output, a renderer or a legend entry only, never a block. - A block has no size, alignment or color of its own beyond these options: the chart draws it. ## HUD starters Fifteen complete cards to start from, under **HUDs** in the editor's template picker. Each answers one question first, as its headline, and reads the numbers behind it underneath: - [Market HUD](../cookbook/market-hud.md): the trend, then RSI, the taker buy share and the last closed bar's volume on three rings, ATR and the open-interest change in coins. - [Decision board](../cookbook/decision-board.md): a headline counting the six factors, the net score as a stippled line and the factors in rows with dotted leaders. - [Order flow HUD](../cookbook/order-flow-hud.md): who is pushing price, each bar's buy share as bars from the 50 mark, the window's buy share, the net delta and the liquidations. - [Order book HUD](../cookbook/order-book-hud.md): the heavier side of the book, the bid share in segments, the dollars resting by distance from the mid and the biggest walls. - [Session HUD](../cookbook/session-hud.md): the session trading now, how much of it has passed, the session up next, the day's range used and the distance from the VWAP and the prior day's high and low. - [Greek exposure](../cookbook/greek-exposure.md): the lens's plain line (long gamma, long vanna, dealers short vega), the net, the calls and puts, the same-day expiry and the strikes where the exposure sits. - [Risk reversal skew](../cookbook/skew.md): puts rich, calls rich or flat for the expiry nearest 30 days, the 25 and 10 delta risk reversals, the four wing IVs, the at-the-money IV and the smile's asymmetry. - [Expected move](../cookbook/expected-move.md): the expected move by the horizon (or to the earnings expiry on a US stock or ETF) in percent and in price, the 1σ range (68%) and where the band starts, the at-the-money IV at seven maturities and the next six expiries' expected moves, titled by the horizon. - [Volatility context](../cookbook/vol-context.md): contango or backwardation, puts or calls rich and IV over or under realized in one line, then the two IVs, the slope, the risk reversal, the scaled skew, the realized volatility and the front expiry's expected move. - [Contract odds](../cookbook/contract-odds.md): one contract's odds of profit and half Kelly, then the breakeven, the premium and its source, max gain and loss, the odds ratio and the three Kelly fractions. - [Options stats](../cookbook/options-stats.md): which side leads by today's put/call ratio of US listed option contracts, then call and put contracts, premium and open interest with their ratios, the net premium, the bullish share and the open interest change. - [Spot exposures](../cookbook/spot-exposures.md): long or short gamma over every expiry from the newest 10-minute chain statistics (the strike rows within 7 days where the chart has none), the three nets, the change since the session's first reading, the week's net gamma, the gamma flip, the walls, max pain and the put/call open interest. - [OI changes](../cookbook/oi-changes.md): the net open interest change with its calls and puts, the strikes that built and unwound most, the open interest, the day's volume and the contracts without both readings. - [Top contracts](../cookbook/top-contracts.md): the top contract by the ranking and its reading, the day's volume, put volume over call volume and the calls and puts traded. - [Options sentiment](../cookbook/options-sentiment.md): bullish, neutral or bearish with the score on a meter, then the volume-weighted strike offset, the 25 delta IV gap and the day's activity. ## The other widgets The HUD card is one of six widgets that share a vocabulary. The status card, the feed and the meter (`draw.card`, `draw.feed`, `draw.meter`) take the HUD's surface words plus a chrome of their own, the ladder (`draw.ladder`) its own short list, and the stats row under the price pane (`render.stats_row`) a colour ladder and a priority. Their contracts, with the full tables, are on [Cards, frames and panels](cards-frames-panels.md#status-cards) and [Plotting](plotting.md#text-labels-tables-strips-tints); this section shows them as looks. Every word is optional and absent keeps today's widget. A status card without the state chrome: no state word, no stripe, no hide or collapse glyphs until the viewer hovers it, painted over your drawings, a hairline in the grid colour between the headline and the rows, a small medium-weight title and muted labels. Reach for it when the card is a dashboard, not an alarm. ```typescript output("pnl", none); output("trades", none); output("win_rate", none); draw.card("session", { title: "{{symbol}} session", anchor: "top_left", headline: { output: "pnl", format: "usd", signed: true }, rows: [ { label: "Trades", value: { output: "trades", format: "int" } }, { label: "Win rate", value: { output: "win_rate", format: "%", decimals: 1 } }, ], show_state: false, stripe: false, controls: "none", above_drawings: true, rule_color: "theme.grid", title_font_size: 11, title_font_weight: "medium", label_text_color: "theme.muted", }); ``` An alarm card: the state word and the stripe on, the four state inks declared, the hide and collapse glyphs always visible, a hairline under the headline, a clock row and a countdown to the next close. Reach for it when the card is the indicator's alarm panel. ```typescript output("spread", none); // 0 ok, 1 armed, 2 fired, 3 error: the card's state word and inks follow it. output("alert_state", none); output("close_at_ms", none); draw.card("alarm", { title: "Spread alarm", anchor: "top_right", state_by: "alert_state", headline: { output: "spread", format: "0.00" }, rows: [ { label: "Now", clock: true }, { label: "Next close", countdown_to: { output: "close_at_ms" } }, ], show_state: true, stripe: true, controls: "always", state_colors: ["theme.muted", "theme.accent", "theme.up", "theme.down"], rule: true, }); ``` A meter with a thicker bar on a grey track, and a feed that prints each line's clock time, both showing their hide and collapse glyphs on hover only. Reach for the thicker bar when the meter stands alone in a corner; `time_format: "none"` drops the time column when the times add nothing. ```typescript output("rsi_fraction", none); string("rsi_text", { max_bytes: 8 }); const events = frame("events", { max_bytes: 2048 }); draw.meter({ name: "rsi_meter", label: "RSI", fraction: { output: "rsi_fraction" }, ramp: ["#3b82f6", "#64748b", "#ef4444"], text: { slot: "rsi_text" }, anchor: "top_left", bar_height: 8, track_color: "theme.grid", controls: "hover" }); draw.feed({ name: "rsi_events", frame: events, anchor: "bottom_left", title: "Crossings", time_format: "HH:mm", controls: "hover", stripe: false }); ``` The feed's frame as the script writes it: one to fifty `lines` of a time in milliseconds, a text of at most 80 characters and an optional colour, newest first, and a per-run `title` that replaces the declared one. ```json { "title": "Crossings", "lines": [ [1759536000000, "RSI crossed above 70", "#ef4444"], [1759532400000, "RSI crossed below 30", "#3b82f6"] ] } ``` A slim mono ladder with its row labels on and the divider line in the accent colour. The divider itself comes with the frame (its `divider`, a label and a price); `divider_color` inks it. ```typescript output("close_line", line, overlay, { color: "#94a3b8", label: "Close" }); const rows = frame("rows", { max_bytes: 2048 }); draw.ladder({ name: "volume_by_price", frame: rows, side: "right", width_frac: 0.12, labels: true, font_family: "mono", font_size: 10, color: "#64748b", divider_color: "theme.accent" }); ``` The ladder's frame: one to 256 `rows` of a price, a size, the bar's length from 0 to 1 and an optional colour, and a `divider` that marks one price. A divider in the frame replaces a declared one. ```json { "rows": [ [63950, 1820, 0.62, "#64748b"], [64000, 2940, 1, "#f59e0b"], [64050, 1210, 0.41, "#64748b"] ], "divider": { "label": "Last", "price": 64010 } } ``` Two rows in the statistics strip: a diverging row whose bull and bear inks are the `colors` pair, kept readable longest as bars narrow (`priority: 1`), and a row inked per bar by a packed colour the script writes (`color_packed_by`, [Colors](../functions/colors-kit.md)), the first to lose its text (`priority: 3`). ```typescript output("basis_chg", none); output("rsi", line, lower, { color: "#8b5cf6", label: "RSI", format: "0.0" }); // A packed colour per bar, written with toPacked(...) from the colors kit. output("rsi_ink", none); render.stats_row("basis_row", { output: "basis_chg", title: "Basis chg", format: "price", polarity: "diverging", colors: ["theme.up", "theme.down"], priority: 1 }); render.stats_row("rsi_row", { output: "rsi", title: "RSI", format: "0.0", color_packed_by: "rsi_ink", priority: 3 }); ``` ## Related - [Cards, frames and panels](cards-frames-panels.md#status-cards): the status card, the ladder, the feed and the meter in full - [What the chart shows](overview.md): the three surfaces together, with a complete module - [Legend](legend.md): the legend entry, and `color_by` on it - [Labels, tooltips, badges](labels-and-tooltips.md): the `tooltip` template a card falls back to, and `badges` - [Plotting](plotting.md): the outputs, string slots and renderers a card reads # TA library Every wrun indicator can use `./sdk/ta`, which ships with the editor: 52 stateful classes covering averages, statistics, oscillators, ranges, trend systems, and events. Each class folds one bar per `update()` call, keeps its own window, and has fixed arithmetic, warm-up, and missing-value rules, checked bit-exact against a reference run. This page is the catalog: every class with its constructor, its `update()` arguments, its fields, and the one convention you need to know about it. The function pages ([Moving averages](moving-averages.md), [Oscillators](oscillators.md), [Trend and volatility](trend-indicators.md), [Volume and VWAP](volume-indicators.md), [Series functions](series-functions.md)) go deeper on each group with compiled examples. Two sibling modules pick up where the catalog stops, there with classes of the same shape: `./sdk/ta-plus` adds the textbook indicators the catalog never had (the double and triple EMAs, TRIX, Kaufman's adaptive average, the ultimate oscillator, Vortex, Aroon, choppiness, the volume lines and more), and `./sdk/stats` adds allocation-free list math over a `StaticArray` plus `History`, the `x[n]` window every indicator needs sooner or later. Both are on [Extra indicators](extra-indicators.md); the kits for text, time, colors, order flow, levels and market structure sit beside it in this section. ## How every class works - **Allocate in the constructor, never in `update()`**, so per-bar memory stays flat. - **`update(...)` folds one bar and returns the current value**, `NaN` until the class is warm (a few classes report a partial window from bar 0 instead; the tables say which). - **Multi-output classes fill fields.** `update()` returns the primary line and the other lines sit in public fields you read after the call. - **`reset()` restores the just-constructed state.** Nothing on the chart calls it for you: a revised forming bar replays from a snapshot of the module taken after the last closed bar, so a live update never folds the same bar twice. - **Periods are `i32`, params are `f64`.** Construct in `onStart()` from a param (`new Sma(i32(p_period()))`), keep the object in a module-level `let`, and update it once per bar in `onBar()`. A period below 1 is clamped to 1 (except `Donchian`, which uses the period as given). ## The shipped classes ### Averages and smoothing | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Sma` | `new Sma(period)` | `.update(x)` | plain window mean; `NaN` until `period` bars exist and whenever the window holds a non-finite value | | `Ema` | `new Ema(period)` | `.update(x)` | the mean of the first `period` finite values seeds it, then `x * alpha + prev * (1 - alpha)` with `alpha = 2 / (period + 1)`; a non-finite input reads `NaN` on its bar and is skipped, the next value continues (TradingView's `ta.ema`) | | `Rma` | `new Rma(period)` | `.update(x)` | Wilder smoothing, the accumulator inside `Rsi` and `Atr`: same seed as `Ema`, then `(prev * (period - 1) + x) / period` | | `Wma` | `new Wma(period)` | `.update(x)` | linear weights, the newest value weighs `period`, the oldest 1; strict window | | `Hma` | `new Hma(period)` | `.update(x)` | `wma(2 * wma(x, round(period / 2)) - wma(x, period), round(sqrt(period)))`; first value at bar `period - 1 + round(sqrt(period)) - 1` | | `Vwma` | `new Vwma(period)` | `.update(x, volume)` | `sum(x * volume) / sum(volume)`; `NaN` when the volume sum is 0 | | `Alma` | `new Alma(length, offset = 0.85, sigma = 6)` | `.update(x)` | Gaussian weights centered at `offset * (length - 1)`, width `length / sigma`; strict window | | `Swma` | `new Swma()` | `.update(x)` | `(x[3] + 2 x[2] + 2 x[1] + x[0]) / 6` with `x[0]` the newest; first value at bar 3 | | `Linreg` | `new Linreg(period, offset = 0)` | `.update(x)` | least-squares line through the window evaluated at `period - 1 - offset` (offset truncated to an integer); strict window | ### Statistics and series math | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Sum` | `new Sum(period)` | `.update(x)` | no warm-up: bar 0 already returns the partial window; `NaN` inputs are skipped | | `Median` | `new Median(period)` | `.update(x)` | middle of the sorted window, the mean of the two middle values on an even period; strict window | | `Percentile` | `new Percentile(period, pct)` | `.update(x)` | nearest rank: `rank = ceil(pct * period / 100)` (the product first, so `Percentile(100, 7)` over 1..100 reads 7), result `sorted[max(0, rank - 1)]`; `pct` clamped to 0..100; strict window | | `Variance` | `new Variance(period)` | `.update(x)` | population variance (divide by `period`, not `period - 1`); strict window | | `Stdev` | `new Stdev(period)` | `.update(x)` | population standard deviation, the square root of `Variance`; strict window | | `Zscore` | `new Zscore(period)` | `.update(x)` | `(x - mean) / stdev` over the window; `NaN` bars inside the window are skipped for the sums, the variance still divides by `period`; `0` when the deviation is exactly 0 | | `Correlation` | `new Correlation(period)` | `.update(a, b)` | Pearson correlation of two series; `NaN` when either window holds a non-finite value or the denominator is 0 | | `Change` | `new Change(n = 1)` | `.update(x)` | `x - x[n]`; `NaN` for the first `n` bars | | `Mom` | `new Mom(n)` | `.update(x)` | the same math as `Change` under another name | | `Roc` | `new Roc(period)` | `.update(x)` | `(x - x[n]) / x[n] * 100`; `NaN` for the first `n` bars and when `x[n]` is 0 | | `Cum` | `new Cum()` | `.update(x)` | running sum from bar 0; a non-finite bar makes it `NaN` for good | | `Fixnan` | `new Fixnan()` | `.update(x)` | repeats the last finite value over a non-finite bar; `NaN` until the first finite value | ### Oscillators and momentum | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Rsi` | `new Rsi(period)` | `.update(x)` | Wilder RSI; bar 0 feeds nothing, first value at bar `period`; a zero average loss returns 100, so a flat window is 100 | | `Cmo` | `new Cmo(length)` | `.update(x)` | `100 * (up - down) / (up + down)` over the last `length` changes; first value at bar `length`; a zero total returns 0 | | `Tsi` | `new Tsi(short = 13, long = 25)` | `.update(x)` | double EMA (long, then short) of momentum over the double EMA of its absolute value; the engine's parameter order is `(short, long)`; first value at bar `long + short - 1` | | `Cci` | `new Cci(period = 20, constant = 0.015)` | `.update(high, low, close)` | over typical price `(high + low + close) / 3`; first value at bar `period - 1`; 0 when the mean deviation is 0 | | `Mfi` | `new Mfi(period = 14)` | `.update(high, low, close, volume)` | money flow over typical price times volume; first value at bar `period`; a zero negative flow returns 100; a typical price that moved `1e-10` or less counts as unchanged (TradingView's `ta.mfi`) | | `Wpr` | `new Wpr(length = 14)` | `.update(high, low, close)` | Williams %R; first value at bar `length - 1`; a flat window returns 0 | | `Stoch` | `new Stoch(periodK, smoothK, periodD)` | `.update(high, low, close)` returns `k` | fields `k`, `d`; raw %K is 0 on a flat window; first `k` at bar `periodK + smoothK - 2`, first `d` at bar `periodK + smoothK + periodD - 3` | | `Stochastic` | `new Stochastic(kPeriod = 14, kSmoothing = 3, dPeriod = 3)` | `.update(high, low, close)` returns `k` | the other spelling, with its own rules: `k = d = 0` before bar `kPeriod - 1` (never `NaN`), 50 on a flat window, a `NaN` `k` or `d` is reported as 50 | | `Macd` | `new Macd(fast = 12, slow = 26, signal = 9)` | `.update(x)` returns `macd` | fields `macd`, `signal`, `hist`; the line appears at bar `slow - 1`, the signal at bar `slow + signal - 2`; `hist = macd - signal` | | `Obv` | `new Obv()` | `.update(close, volume)` | on-balance volume; bar 0 returns 0; an unchanged close adds nothing | ### Ranges and bands | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Tr` | `new Tr()` | `.update(high, low, close)` | `max(high - low, abs(high - prevClose), abs(low - prevClose))`; bar 0 is plain `high - low` | | `Atr` | `new Atr(period = 14)` | `.update(high, low, close)` | `Rma` of `Tr`; first value at bar `period - 1`; a non-finite range reads `NaN` on its bar and is skipped, the next one continues (TradingView's `ta.rma` rule; on chart bars, which never miss a close, `ta.atr` to the bit) | | `Bb` | `new Bb(period, mult)` | `.update(x)` returns `basis` | fields `basis`, `upper`, `lower`; `Sma` basis and population `Stdev` width; all three `NaN` while the window holds a non-finite value | | `Keltner` | `new Keltner(period, mult, atrPeriod)` | `.update(x, high, low, close)` returns `basis` | fields `basis`, `upper`, `lower`; `Ema` basis plus `Atr` width; the basis is reported as soon as the EMA is seeded, the bands once the ATR is finite | | `Donchian` | `new Donchian(period = 12)` | `.update(high, low)` returns `basis` | fields `basis` (the midline `update()` returns), `upper`, `lower`; no warm-up, the window is partial at the start; older `NaN` highs and lows are skipped, the current bar's `NaN` propagates | | `Highest` | `new Highest(period = 12)` | `.update(x)` | the window maximum; field `bars` is the offset of that maximum (0 = this bar, negative = bars ago, the newest bar wins a tie); pass the high for a bar-high window | | `Lowest` | `new Lowest(period = 12)` | `.update(x)` | the window minimum; field `bars` is the offset of that minimum; pass the low for a bar-low window | | `HighestBars` | `new HighestBars(period)` | `.update(x)` | the offset as the primary value (0 or negative); field `value` is the matching high | | `LowestBars` | `new LowestBars(period)` | `.update(x)` | the offset as the primary value; field `value` is the matching low | ### Trend systems | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Adx` | `new Adx(period = 14)` | `.update(high, low, close)` returns `adx` | fields `adx`, `plusDi`, `minusDi`; the seed is the plain sum of the first `period` true ranges and directional moves, then `s = s - s / period + x` (the engine's form, not an `Rma`); `+DI` and `-DI` appear at bar `period`, ADX at bar `2 * period - 1`; a non-finite bar after the seed leaves every output `NaN` for good | | `Ichimoku` | `new Ichimoku(conversionPeriod = 9, basePeriod = 26, laggingSpanPeriod = 52, displacement = 26)` | `.update(high, low, close)` returns `tenkan` | fields `tenkan`, `kijun`, `senkouA`, `senkouB`, `chikou`; windows are partial from bar 0 (no `NaN` warm-up), the first `displacement` bars use the current bar's values instead of shifted ones, a `NaN` output is reported as 0; `chikou` is the current close (see the accuracy section) | | `Psar` | `new Psar(start = 0.02, increment = 0.02, maxValue = 0.2)` | `.update(high, low, close)` | the stop-and-reverse level; bar 0 is `NaN`, bar 1 picks the first trend from `close[1] >= close[0]`; a non-finite bar makes every later bar `NaN`, as the engine's full recompute does | | `Supertrend` | `new Supertrend(factor, atrPeriod)` | `.update(high, low, close)` returns `line` | fields `line`, `direction` (`1` up, the line sits below price; `-1` down); both `NaN` while the ATR is `NaN`, and the band state is left untouched across such a gap; `direction` is `+1` in an uptrend; Pine's `ta.supertrend` is `-1` | | `Vwap` | `new Vwap(anchor = "", price = "hlc3")` | `.update(open, high, low, close, volume, tsMs = NaN)` | `anchor` is `""` (one accumulation from bar 0), `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"` (UTC calendar boundaries) or a numeric string bucket width in whole milliseconds (up to 15 digits, `"14400000.0"` as a float prints it reads as `"14400000"`); `tsMs` is the bar's open time, `bar.time()` in seconds as it comes or the time in milliseconds (a value below `1e11` in size reads as seconds), read only when an anchor is set; an anchored `Vwap` given no time stops the run with a message naming the fix; `price` is `hlc3`, `hl2`, `ohlc4`, `hlcc4`, or `close`; a non-finite bar makes the current bucket `NaN` until the next one starts. Any other anchor or price is never read as the default: a literal fails the build on its line, and one computed at run time refuses softly, `refused()` is true, `refusedReason()` names the words it takes (Pine's `"1D"` is named as `"day"`) and `update()` answers `NaN` on every bar; `SourceVwap` passes both through | ### Events and conditions | Class | Construct | Per bar | Convention | | --- | --- | --- | --- | | `Rising` | `new Rising(period)` | `.update(x)` | 1 when `x` is strictly above every one of the previous `period` values, else 0; `NaN` while the bar index is below `period` | | `Falling` | `new Falling(period)` | `.update(x)` | the mirror of `Rising` | | `PivotHigh` | `new PivotHigh(leftbars, rightbars)` | `.update(high)` | the value of the bar `rightbars` back when none of the `leftbars` before it is higher and none of the `rightbars` after it is as high (TradingView's `ta.pivothigh`: a tie on the left counts, a tie on the right never does), reported only on the confirming bar, `NaN` otherwise; either count may be `0`, as in Pine (`rightbars` 0: the current bar is the candidate) | | `PivotLow` | `new PivotLow(leftbars, rightbars)` | `.update(low)` | the mirror of `PivotHigh` | | `ValueWhen` | `new ValueWhen(occurrence)` | `.update(condition, x)` | `x` on the most recent bar where `condition` was true (`occurrence` 0), or the one before (`1`); a condition is true when it is finite and not 0; the current bar counts | | `BarsSince` | `new BarsSince()` | `.update(condition)` | bars since the condition was last true, 0 on a true bar; `NaN` until the first true bar | | `Cross` | `new Cross()` | `.update(a, b): i32` | `+1` when `a` crosses above `b`, `-1` below, `0` otherwise; the engine's previous-bar rule: crossover is `prevA < prevB && a >= b`, crossunder is `prevA > prevB && a <= b`; any `NaN` among the four values gives 0, and so does the first bar | | `PineCross` | `new PineCross()` | `.update(a, b): i32`, then the fields `over`, `under`, `cross` | Pine's `ta.crossover`, `ta.crossunder` and `ta.cross` as TradingView computes them: crossover is `a > b` now and `a <= b` on the last earlier bar where both were defined, crossunder the mirror, cross a change of order that skips ties; a bar with a `NaN` answers false and is skipped ([Series functions](series-functions.md#pines-crosses-pinecross)) | `Cross` folds three questions into one return value: test `> 0`, `< 0`, or `!= 0`. A composite over the shipped classes: a `Macd` read through its three fields, a `Cross` gate over the line and its signal, and an `Rsi`. The declarations at the top name the four params and the four outputs; the module below them only folds the bars: ```typescript param("fast", 12, { min: 1, max: 200 }); param("slow", 26, { min: 2, max: 400 }); param("signal", 9, { min: 1, max: 200 }); param("rsi_len", 14, { min: 2, max: 200 }); output("macd", line, lower); output("signal", line, lower); output("rsi", line, lower); // Data-only: +1 on a bullish MACD cross, -1 on a bearish one, 0 otherwise. output("crossed", none); let macd = new Macd(12, 26, 9); let rsi = new Rsi(14); let cross = new Cross(); function onStart(): void { macd = new Macd(i32(p_fast()), i32(p_slow()), i32(p_signal())); rsi = new Rsi(i32(p_rsi_len())); cross = new Cross(); } function onBar(): void { const close = bar.close(); macd.update(close); const strength = rsi.update(close); const crossed = f64(cross.update(macd.macd, macd.signal)); if (isNaN(macd.signal) || isNaN(strength)) return; out_macd(macd.macd); out_signal(macd.signal); out_rsi(strength); out_crossed(crossed); } ``` ## The catalog by page Every class grouped by what it does. Every class ships in `./sdk/ta`; the page column is where the group is explained with compiled examples. **Moving averages and smoothing** | Class | Where | | --- | --- | | `Sma` | [Moving averages](moving-averages.md) | | `Ema` | [Moving averages](moving-averages.md) | | `Rma` | [Moving averages](moving-averages.md) | | `Wma` | [Moving averages](moving-averages.md) | | `Hma` | [Moving averages](moving-averages.md) | | `Vwma`, `update(x, volume)` | [Moving averages](moving-averages.md) | | `Alma` | [Moving averages](moving-averages.md) | | `Swma` | [Moving averages](moving-averages.md) | | `Linreg` | [Moving averages](moving-averages.md) | **Oscillators and momentum** | Class | Where | | --- | --- | | `Rsi` | [Oscillators](oscillators.md) | | `Wpr` | [Oscillators](oscillators.md) | | `Cmo` | [Oscillators](oscillators.md) | | `Tsi` | [Oscillators](oscillators.md) | | `Macd`, fields `macd`, `signal`, `hist` | [Oscillators](oscillators.md) | | `Stoch`, fields `k`, `d` | [Oscillators](oscillators.md) | | `Stochastic`, fields `k`, `d` | [Oscillators](oscillators.md) | | `Cci` | [Oscillators](oscillators.md) | | `Mfi` | [Oscillators](oscillators.md) | | `Change` | [Series functions](series-functions.md) | | `Mom` | [Oscillators](oscillators.md) | | `Roc` | [Oscillators](oscillators.md) | **Trend and volatility** | Class | Where | | --- | --- | | `Adx`, fields `adx`, `plusDi`, `minusDi` | [Trend and volatility](trend-indicators.md) | | `Ichimoku`, five fields | [Trend and volatility](trend-indicators.md) | | `Psar` | [Trend and volatility](trend-indicators.md) | | `Supertrend`, fields `line`, `direction` | [Trend and volatility](trend-indicators.md) | | `Tr` | [Trend and volatility](trend-indicators.md) | | `Atr` | [Trend and volatility](trend-indicators.md) | | `Bb`, fields `basis`, `upper`, `lower` | [Moving averages](moving-averages.md) | | `Keltner`, fields `basis`, `upper`, `lower` | [Moving averages](moving-averages.md) | | `Donchian`, fields `basis`, `upper`, `lower` | [Moving averages](moving-averages.md) | | `Stdev` | [Trend and volatility](trend-indicators.md) | | `Variance` | [Trend and volatility](trend-indicators.md) | | price helpers (`hl2`, `hlc3`, `ohlc4`, `hlcc4`): arithmetic on the declared inputs | [Series functions](series-functions.md) | **Volume** | Class | Where | | --- | --- | | `Obv`, `update(close, volume)` | [Volume and VWAP](volume-indicators.md) | | `Vwap`, anchored on the bar's open time | [Volume and VWAP](volume-indicators.md) | | `Cum` | [Volume and VWAP](volume-indicators.md) | **Statistics** | Class | Where | | --- | --- | | `Sum` | [Series functions](series-functions.md) | | `Median` | [Series functions](series-functions.md) | | `Percentile` | [Series functions](series-functions.md) | | `Correlation`, `update(a, b)` | [Series functions](series-functions.md) | | `Zscore` | [Series functions](series-functions.md) | **Bars and events** | Class | Where | | --- | --- | | `Highest`, `Lowest`, field `bars` | [Series functions](series-functions.md) | | `HighestBars`, `LowestBars`, field `value` | [Series functions](series-functions.md) | | `PivotHigh`, `PivotLow` | [Series functions](series-functions.md) | | `Rising`, `Falling` | [Series functions](series-functions.md) | | `ValueWhen` | [Series functions](series-functions.md) | | `BarsSince` | [Series functions](series-functions.md) | | `Cross`, `+1` / `-1` / `0` | [Series functions](series-functions.md) | | `Fixnan` | [Series functions](series-functions.md) | | `isNaN(x)` | [Series functions](series-functions.md) | | `nz(x, replacement)`, a two-line helper | [Series functions](series-functions.md) | The order book and volume profile scans are not classes: they are loops over a celled input on the [Order flow](order-flow-kit.md) page. ## Conventions (read this once) These rules hold across the library and explain nearly every edge case. **Warm-up is `NaN`, with named exceptions.** A windowed class returns `NaN` until it has a full window and never fabricates an early value. The classes that report a partial window from bar 0: `Sum`, `Donchian`, `Ichimoku`, `Cum` (bar 0 is `x`), `Obv` (bar 0 is 0), and `Stochastic` (0 before its window fills). Decide per bar whether to `return` from `onBar()` before writing or to write the `NaN`; either way the chart draws nothing on that bar ([Execution model](../core-concepts/execution-model.md)). **Windows are strict; accumulators poison.** A class that recomputes over its window (`Sma`, `Wma`, `Alma`, `Linreg`, `Median`, `Percentile`, `Variance`, `Stdev`, `Correlation`, `Bb`, `Highest`, `Lowest`, and the rest of the window family) yields `NaN` while any value inside the window is not finite and heals as soon as it leaves. A class that carries a running accumulator (`Adx`, `Cum`, `Psar`) restarts its seed when a non-finite value arrives before the seed completes, and turns `NaN` for good when one arrives after, because the engine never reseeds. `Ema`, `Rma` and `Rsi`, and the classes built on them (`Macd`, `Tsi`, `Atr`, `Supertrend`'s ATR), follow TradingView's `ta.ema`, `ta.rma` and `ta.rsi` instead: that bar reads `NaN`, the seed skips it, and the next finite value continues. `Sum` and `Zscore` skip `NaN` bars, and in `PivotHigh` and `PivotLow` a non-finite value ends the comparison on its side, as TradingView's pivots treat `na`. Run a sparse source through `Fixnan` or an `isNaN` guard before an accumulator. **Columns are yours to choose.** The classes take one value per bar: pass `bar.high()` to `Highest`, `HighestBars`, and `PivotHigh` for a bar-high window, `bar.low()` to their counterparts, or the close for a close-based one. **Classes compose.** `update()` takes any `f64`, including another class's output (`rsi.update(sma.update(close))`) and any series derived from a celled input. Warm-up propagates through the composition because `NaN` propagates through arithmetic. **Values carry; events do not.** A missing scalar carries the latest eligible value forward by default (the `missing` policy on the source decides), so math keeps working. Events are stricter: `Cross.update()` returns `0` on any bar where either side is `NaN`, `BarsSince` and `ValueWhen` read a condition you computed (finite and not 0), so stale data cannot fabricate a signal. **`Rma` is Wilder.** `Rsi`, `Atr`, `Keltner`, and `Supertrend` share the same accumulator, so an indicator built by hand over `Rma` agrees with the shipped classes. ## Multi-output indicators An indicator with several streams is a class with several fields. There are no tuple outputs and nothing indexes into an array: `update()` returns the primary line, and you read the other fields after the call and write each to its own output ([Named streams](../core-concepts/named-streams.md)). | Class | `update()` returns | Fields | | --- | --- | --- | | `Bb`, `Keltner`, `Donchian` | `basis` | `basis`, `upper`, `lower` | | `Macd` | `macd` | `macd`, `signal`, `hist` | | `Stoch`, `Stochastic` | `k` | `k`, `d` | | `Supertrend` | `line` | `line`, `direction` | | `Adx` | `adx` | `adx`, `plusDi`, `minusDi` | | `Ichimoku` | `tenkan` | `tenkan`, `kijun`, `senkouA`, `senkouB`, `chikou` | | `Highest`, `Lowest` | the extreme | `bars` (the offset of that extreme) | | `HighestBars`, `LowestBars` | the offset | `value` (the extreme at that offset) | Fields feed a band declaration or a box the same way outputs do: write `bb.upper` and `bb.lower` to two drawn outputs and declare a `range()` between their names ([Styling](../presentation/styling.md)), or a `box` between their handles ([Drawing objects](../presentation/drawing-objects.md)). ## Over microstructure Every windowed class also runs over order-flow series, which is where the library stops being a price-only kit. A celled `volume_profile` input delivers each bar's `[low, high, buy, sell]` tuples; sum the buy and sell columns into a per-bar delta and the delta is just an `f64` any class can fold: an `Rsi` over it is delta-RSI, a running sum is cumulative volume delta. Declaring the celled input switches the derived sheet to the second runtime contract, and the numeric classes compute exactly as before. ```typescript param("period", 14, { min: 2, max: 200, description: "RSI window over the per-bar delta" }); input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); output("delta", line, lower, { color: "#94a3b8", width: 1, description: "Buy minus sell volume across the bar's profile" }); output("delta_rsi", line, lower, { color: "#7c3aed", width: 2, description: "RSI of the per-bar delta" }); output("cvd", line, lower, { color: "#22d3ee", width: 2, description: "Cumulative volume delta" }); let rsi = new Rsi(14); let cvd: f64 = 0.0; function onStart(): void { rsi = new Rsi(i32(p_period())); } function onBar(): void { const n = in_profile_cells(); if (n < 0) return; // this bar carries no block let delta = 0.0; if (n > 0) { const cells = in_profile_view(); for (let i = 0; i + 3 < n; i += 4) delta += cells[i + 2] - cells[i + 3]; } cvd += delta; const deltaRsi = rsi.update(delta); out_delta(delta); out_delta_rsi(deltaRsi); out_cvd(cvd); } ``` The [Order flow](order-flow-kit.md) page has every footprint read as a scan over the same tuples, and does the same over book levels for a book-imbalance average. ## Accuracy as a contract **Every class is checked bit-exact against a reference implementation.** The reference run covers a 690-bar 1h BTCUSDT window; each class is compiled through the real build and executed through the real runtime over the same bars, and every output is compared per bar: a maximum absolute deviation of 0 and identical `NaN` placement (a bar that is `NaN` in the reference is `NaN` here, and only that bar). The conventions on this page are written down so that comparison holds, and a change that drifts a class from the reference numbers fails the build. **Three honest exceptions.** - **`Ichimoku.chikou` is the current close.** The engine computes the lagging span by reading `close[i + displacement]`, a bar in the future of bar `i`, and only falls back to the current close on the last `displacement` bars of the series. A class that sees one bar at a time cannot read ahead, so the field carries the current close on every bar; it matches the engine on those last bars only. The other four fields match bar for bar. - **`Vwap` anchors beyond `""`, `"day"`, and a numeric millisecond width are unproven on that window.** The `"week"`, `"month"`, `"quarter"`, and `"year"` boundaries follow the engine's UTC calendar arithmetic, but the 690-bar window does not exercise a deep-history quarter or year, and the engine's session-calendar bucketing and RTH session filter (venues with a trading-session calendar) are not mirrored, since a per-bar class never sees a session calendar. - **`PivotHigh` and `PivotLow` follow TradingView, not the engine.** They are measured against TradingView's own `ta.pivothigh` and `ta.pivotlow` output (every bar of 16 series over 24,207 BTCUSDT hours): a tie with a bar on the left counts and a non-finite value ends the comparison on its side, where the engine rejects any tie and any window holding a non-finite value. They differ from the engine exactly on those bars. Everything else in the catalog, warm-up bars included, matches the reference bar for bar. # Moving averages These classes smooth price into a trend line or wrap it in a band. Every one of them ships with the editor in the `./sdk/ta` module (`Sma`, `Ema`, `Wma`, `Hma`, `Alma`, `Swma`, `Vwma`, `Rma`, `Linreg`, `Bb`, `Keltner`, `Donchian`), each one built the same way: allocate in the constructor, fold one bar per `update()`, return `NaN` until the window is full, restore with `reset()`. Name the class you need (nothing to import), construct it in `onStart()`, and call `update()` once per bar in `onBar()`. Every class has fixed arithmetic and edge rules, named in its section ([TA library](ta-library.md) lists the full catalog and the proof). Every windowed average is `NaN` until its window fills. An `Sma(20)` draws nothing for its first 19 bars, then begins once the 20th has loaded; the Hull average warms up a little longer because of its internal weighted sub-windows. Donchian is the exception: it reads the rolling extreme of whatever has loaded from the very first bar. `NaN` is the warm-up signal, so a `NaN` written to one output and an early `return` from `onBar()` that leaves every output unwritten are the two honest ways to say "not yet" ([Execution model](../core-concepts/execution-model.md)). The shape every class shares: | Member | Meaning | | --- | --- | | `new X(period)` | allocates the window once; a `period` below 1 is clamped to 1 | | `.update(x): f64` | folds one bar, returns the current value, `NaN` until warm | | `.reset(): void` | back to the freshly constructed state; nothing on the chart calls it for you | A non-finite input (a `NaN` or an infinity) inside a window makes the windowed averages return `NaN` for as long as that bar sits in the window; the two running averages (`Ema`, `Rma`) never recover from one. ## Single-line averages ### Sma `new Sma(period)`, `.update(x)`: the unweighted mean of the last `period` values, summed oldest to newest and divided by the period. Warm-up is `period` bars (first value at bar `period - 1`). ```typescript let sma = new Sma(20); function onStart(): void { sma = new Sma(i32(p_period())); } ``` Read the period through its accessor and cast it: params are `f64`, class periods are `i32`, and AssemblyScript refuses the implicit conversion. ### Ema `new Ema(period)`, `.update(x)`: the exponential average. Weights recent bars more heavily, so it turns faster than `Sma`. The first `period` finite values seed it with their simple mean, then `x * alpha + prev * (1 - alpha)` with `alpha = 2 / (period + 1)` takes over, so it is `NaN` for `period - 1` bars. A non-finite input follows TradingView's `ta.ema`: that bar reads `NaN` and the state stays as it was, so the next finite value continues from the last average, and inside the seed it is skipped (the seed is the first `period` finite values, wherever they sit). ```typescript let ema = new Ema(20); ``` ### Wma `new Wma(period)`, `.update(x)`: the linearly weighted average. The newest bar carries weight `period`, the oldest weight `1`, so it sits between `Sma` and `Ema` in responsiveness. The weighted sum walks oldest to newest and is divided by `period * (period + 1) / 2`; `NaN` until `period` bars have been seen and whenever any value in the window is not finite. ```typescript let wma = new Wma(20); function onStart(): void { wma = new Wma(i32(p_period())); } ``` ### Hma `new Hma(period)`, `.update(x)`: the Hull average, three `Wma` windows composed as `WMA(2 * WMA(round(n / 2)) - WMA(n), round(sqrt(n)))`. Very low lag and smooth. The half and square-root lengths are rounded (never below 1), the inner difference is `NaN` until both inner windows are warm, and the outer window then needs `round(sqrt(n))` finite values, so the first value lands at bar `n - 1 + round(sqrt(n)) - 1`. ```typescript let hma = new Hma(21); function onStart(): void { hma = new Hma(i32(p_hull_period())); } ``` ### Alma `new Alma(length, offset = 0.85, sigma = 6)`, `.update(x)`: the Arnaud Legoux average, a Gaussian-weighted window. `offset` places the peak of the bell at `offset * (length - 1)` from the oldest bar (near the newest bar by default), `sigma` sets its width as `length / sigma`. The weights are computed once in the constructor with the engine's arithmetic, so `update()` is a single weighted pass, walked oldest to newest. `NaN` until `length` bars have been seen and whenever any value in the window is not finite. ```typescript let alma = new Alma(20); // offset 0.85, sigma 6 let sharp = new Alma(20, 0.9, 4.0); // peak closer to the newest bar, narrower bell ``` Omitting `offset` and `sigma` is the same as passing `0.85` and `6`. ### Swma `new Swma()`, `.update(x)`: the symmetrically weighted average, the fixed four-tap smoother `(x[3] + 2 * x[2] + 2 * x[1] + x[0]) / 6` with `x[0]` the newest bar. `NaN` on the first three bars (first value at bar 3) and whenever any of the four values is not finite; no period to choose. ```typescript let swma = new Swma(); ``` ### Vwma `new Vwma(period)`, `.update(price, volume)`: the volume-weighted average takes two values per bar, `sum(price * volume) / sum(volume)` over the window. Bars with more volume pull the average harder, so it tracks where trading actually happened. It needs the bar's volume beside the price (`bar.volume()`). `NaN` until `period` bars have been seen, whenever any price or volume in the window is not finite, and when the volume sum is exactly `0`. ```typescript let vwma = new Vwma(20); function onBar(): void { out_vwma(vwma.update(bar.close(), bar.volume())); } ``` ### Rma `new Rma(period)`, `.update(x)`: the running (Wilder) average, the smoothing inside RSI and ATR. The first `period` finite values seed it with their simple mean, then `rma = (rma * (period - 1) + x) / period`. Smoother and slower than `Ema` for the same period. This is the same Wilder accumulator `Rsi` and `Atr` use internally, so an RSI built by hand over `Rma` and the shipped `Rsi` agree. A non-finite input follows TradingView's `ta.rma`: that bar reads `NaN` and the state stays as it was, so the next finite value continues from the last average, and inside the seed it is skipped. ```typescript let rma = new Rma(14); ``` ### Linreg `new Linreg(period, offset = 0)`, `.update(x)`: linear regression fits a least-squares line over the last `period` bars (x positions `0` oldest to `period - 1` newest) and returns its value at the newest bar (`offset` `0`) or `offset` bars back along the fitted line: the trend's fitted price rather than an average. `offset` is an `f64` truncated to an integer. `NaN` until `period` bars have been seen and whenever any value in the window is not finite; a period of `1` returns the value itself. ```typescript let linreg = new Linreg(20); // value at the newest bar let lagged = new Linreg(20, 2.0); // the fitted line two bars back ``` ## Band helpers A band is three named streams. A wrun indicator has no tuple outputs: the class exposes `upper`, `basis`, and `lower` as fields after each `update()`, and you write each one to its own output ([Named streams](../core-concepts/named-streams.md)). Shading between the edges is a `range()` band over the two drawn edges ([Styling](../presentation/styling.md)) or a `box` on every bar ([Cards, frames and panels](../presentation/cards-frames-panels.md)). ### Bb `new Bb(period, mult)`, `.update(x)`: Bollinger bands. `basis` is the window mean (the same arithmetic as `Sma`), `upper` and `lower` sit `mult` population standard deviations away (the same arithmetic as `Stdev`, the textbook Bollinger form). `update()` returns the basis and fills the three fields. All three are `NaN` until `period` bars exist and whenever any bar of the window is not finite; the window heals as soon as the bad bar leaves it. Both arguments are required; the usual call is `new Bb(20, 2.0)`. ```typescript let bb = new Bb(20, 2.0); function onBar(): void { bb.update(bar.close()); out_bb_upper(bb.upper); out_bb_basis(bb.basis); out_bb_lower(bb.lower); } ``` ### Keltner `new Keltner(period, mult, atrPeriod)`, `.update(x, high, low, close)`: like Bollinger, but the width comes from the average true range instead of the standard deviation, so it reacts to range rather than dispersion. `basis` is an `Ema(period)` over `x` (usually the close), the width is an `Atr(atrPeriod)` over the three prices (the Wilder-smoothed true range; its class is on the [Trend and volatility](trend-indicators.md#volatility-primitives) page) multiplied by `mult`. `update()` returns the basis and fills the three fields. The basis is reported as soon as the `Ema` is seeded, even while the ATR is still warming up; `upper` and `lower` are `NaN` unless both the basis and the ATR are finite. ```typescript let kc = new Keltner(20, 1.5, 10); function onBar(): void { const close = bar.close(); kc.update(close, bar.high(), bar.low(), close); out_kc_upper(kc.upper); out_kc_basis(kc.basis); out_kc_lower(kc.lower); } ``` ### Donchian `new Donchian(period = 12)`, `.update(high, low)`: the highest high and lowest low over `period` bars as `upper` and `lower`, with their midpoint as `basis` (the value `update()` returns). Because it reads the rolling extreme rather than averaging, it is finite from the first loaded bar: the window is partial at the start, and bar 0 returns `(high + low) / 2` of that bar alone. The current bar's high and low always take part, even when `NaN` (so a `NaN` bar propagates), while non-finite highs or lows of older bars are skipped. The period is used as given: the clamp to 1 the other classes apply does not run here. ```typescript let dc = new Donchian(20); function onBar(): void { dc.update(bar.high(), bar.low()); out_dc_upper(dc.upper); out_dc_basis(dc.basis); out_dc_lower(dc.lower); } ``` ## Putting them together Every average and band on one chart: the nine single-line averages on the price pane, the three band helpers as nine more outputs. Every class is used by name with nothing to import. Each class is constructed in `onStart()` from a param, then updated once and its value written in `onBar()`. ```typescript param("period", 20, { min: 2, max: 400, description: "Window for every average and band" }); param("hull_period", 21, { min: 4, max: 400, description: "Hull average window" }); param("mult", 2, { min: 0.5, max: 5, description: "Bollinger standard-deviation multiplier" }); param("kc_mult", 1.5, { min: 0.5, max: 5, description: "Keltner ATR multiplier" }); param("atr_period", 10, { min: 1, max: 200, description: "Keltner ATR window" }); output("sma", line, overlay, { color: "#2563eb", width: 2, description: "Simple moving average" }); output("ema", line, overlay, { color: "#dc2626", width: 2, description: "Exponential moving average" }); output("hma", line, overlay, { color: "#7c3aed", width: 2, description: "Hull moving average" }); output("wma", line, overlay, { color: "#ea580c", width: 2, description: "Weighted moving average" }); output("alma", line, overlay, { color: "#0891b2", width: 2, description: "Arnaud Legoux moving average" }); output("swma", line, overlay, { color: "#0f766e", width: 1, description: "Symmetrically weighted moving average" }); output("vwma", line, overlay, { color: "#b45309", width: 2, description: "Volume-weighted moving average" }); output("rma", line, overlay, { color: "#059669", width: 2, description: "Wilder running moving average" }); output("linreg", line, overlay, { color: "#4b5563", width: 2, description: "Least-squares regression value" }); output("bb_upper", line, overlay, { color: "#0f766e", width: 1, description: "Bollinger upper band" }); output("bb_basis", line, overlay, { color: "#64748b", width: 1, description: "Bollinger basis" }); output("bb_lower", line, overlay, { color: "#be123c", width: 1, description: "Bollinger lower band" }); output("kc_upper", line, overlay, { color: "#16a34a", width: 1, description: "Keltner upper channel" }); output("kc_basis", line, overlay, { color: "#94a3b8", width: 1, description: "Keltner basis" }); output("kc_lower", line, overlay, { color: "#dc2626", width: 1, description: "Keltner lower channel" }); output("dc_upper", line, overlay, { color: "#0ea5e9", width: 1, description: "Donchian upper band" }); output("dc_basis", line, overlay, { color: "#94a3b8", width: 1, description: "Donchian midpoint" }); output("dc_lower", line, overlay, { color: "#f97316", width: 1, description: "Donchian lower band" }); let sma = new Sma(20); let ema = new Ema(20); let hma = new Hma(21); let wma = new Wma(20); let alma = new Alma(20); let swma = new Swma(); let vwma = new Vwma(20); let rma = new Rma(20); let linreg = new Linreg(20); let bb = new Bb(20, 2.0); let kc = new Keltner(20, 1.5, 10); let dc = new Donchian(20); function onStart(): void { const period = i32(p_period()); sma = new Sma(period); ema = new Ema(period); hma = new Hma(i32(p_hull_period())); wma = new Wma(period); alma = new Alma(period); swma = new Swma(); vwma = new Vwma(period); rma = new Rma(period); linreg = new Linreg(period, 0.0); bb = new Bb(period, p_mult()); kc = new Keltner(period, p_kc_mult(), i32(p_atr_period())); dc = new Donchian(period); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const smaValue = sma.update(close); const emaValue = ema.update(close); const hmaValue = hma.update(close); const wmaValue = wma.update(close); const almaValue = alma.update(close); const swmaValue = swma.update(close); const vwmaValue = vwma.update(close, bar.volume()); const rmaValue = rma.update(close); const linregValue = linreg.update(close); bb.update(close); kc.update(close, high, low, close); dc.update(high, low); // Donchian is finite from the first bar, so its band draws at once; // the slower lines simply write NaN until their own windows fill. out_sma(smaValue); out_ema(emaValue); out_hma(hmaValue); out_wma(wmaValue); out_alma(almaValue); out_swma(swmaValue); out_vwma(vwmaValue); out_rma(rmaValue); out_linreg(linregValue); out_bb_upper(bb.upper); out_bb_basis(bb.basis); out_bb_lower(bb.lower); out_kc_upper(kc.upper); out_kc_basis(kc.basis); out_kc_lower(kc.lower); out_dc_upper(dc.upper); out_dc_basis(dc.basis); out_dc_lower(dc.lower); } ``` The whole module is one chart overlay with eighteen legend entries, and once the indicator is published every one of them is an output an alert can follow ([Alerts](alerts.md)). ## Warm-up and named streams Two ideas worth seeing on their own: an average is blank until its window fills, and a band's three levels are three independent outputs you can draw or hide one at a time. The Bollinger edges below are drawn while the basis stays data-only (`none`): it still computes and you can read it at the Console prompt, but the chart shows only the two bands. All three begin together once the 20-bar window completes, because one `Bb` feeds them. ```typescript param("period", 20, { min: 2, max: 400 }); output("sma20", line, overlay, { color: "#2563eb", width: 2, description: "NaN until the window is complete" }); output("bb_upper", line, overlay, { color: "#16a34a", width: 2, description: "Bollinger upper band" }); output("bb_basis", none, overlay, { description: "Computed, never drawn: a value without a line" }); output("bb_lower", line, overlay, { color: "#dc2626", width: 2, description: "Bollinger lower band" }); let sma = new Sma(20); let bb = new Bb(20, 2.0); function onStart(): void { sma = new Sma(i32(p_period())); bb = new Bb(i32(p_period()), 2.0); } function onBar(): void { const close = bar.close(); const value = sma.update(close); bb.update(close); // Return before writing while the window is filling: no legend value, nothing drawn. if (isNaN(value)) return; out_sma20(value); out_bb_upper(bb.upper); out_bb_basis(bb.basis); out_bb_lower(bb.lower); } ``` ## Alma and Swma boundaries `Alma`'s omitted `offset` and `sigma` default to `0.85` and `6`, so a default construction and an explicit one agree to the last bit; `Swma` uses the fixed four-tap weighting, so it agrees with the arithmetic spelled out by hand over the last four closes. The module below computes both forms and writes each line only where the class agrees with the manual form, which is every bar once the windows are warm: a `NaN` written on a disagreeing bar would leave a visible hole. ```typescript param("length", 10, { min: 2, max: 200 }); output("alma_check", line, lower, { color: "#2563eb", width: 2, description: "ALMA with the default offset 0.85 and sigma 6" }); output("swma_check", line, lower, { color: "#16a34a", width: 2, description: "SWMA against the four-tap arithmetic" }); let almaDefault = new Alma(10); let almaExplicit = new Alma(10, 0.85, 6.0); let swma = new Swma(); // The manual SWMA keeps the last four closes by hand: x0 is the newest. let x0: f64 = NaN; let x1: f64 = NaN; let x2: f64 = NaN; let x3: f64 = NaN; function onStart(): void { almaDefault = new Alma(i32(p_length())); almaExplicit = new Alma(i32(p_length()), 0.85, 6.0); swma = new Swma(); } function onBar(): void { const close = bar.close(); const a = almaDefault.update(close); const b = almaExplicit.update(close); const s = swma.update(close); x3 = x2; x2 = x1; x1 = x0; x0 = close; const manual = (x3 + 2.0 * x2 + 2.0 * x1 + x0) / 6.0; const almaCheck = Math.abs(a - b) < 0.000001 ? b : NaN; const swmaCheck = Math.abs(s - manual) < 0.000001 ? s : NaN; out_alma_check(almaCheck); out_swma_check(swmaCheck); } ``` ## Points to remember - An average is an object you own: construct it in `onStart()`, keep it in a module-level `let`, feed it in `onBar()`. There is no series to pass in; the class sees one value per bar, which is the whole [execution model](../core-concepts/execution-model.md). - A band's `upper` / `basis` / `lower` streams are three fields read after `update()` and three outputs. Nothing indexes into a tuple. - `Vwma` reads volume through `bar.volume()` and a two-argument `update(price, volume)`: a wrun indicator names every field it reads. - Warm-up is `NaN`, and `NaN` propagates through arithmetic. `isNaN(x)` is the test; a two-line `nz` helper is on the [Series functions](series-functions.md) page. - Every class here is checked bit-exact against the reference run described on the [TA library](ta-library.md) page, edge rules included. # Oscillators Oscillators measure momentum and overbought or oversold pressure. Every oscillator ships with the editor as a stateful class in `./sdk/ta`: `Rsi`, `Wpr`, `Cmo`, `Tsi`, `Macd`, `Stoch`, `Stochastic`, `Cci`, `Mfi`, `Mom`, and `Roc` (the full catalog is on the [TA library](ta-library.md) page). Name the ones you use; there is nothing to import. A multi-output oscillator exposes its streams as fields after `update()` (`macd.signal`, `stoch.k`) and each one goes to its own output. Every oscillator needs a warm-up window. Until enough bars have loaded to fill its longest period the value is `NaN` and nothing draws. `Rsi(14)` is `NaN` for its seed window and `Macd` warms up over the slow average plus the signal period. Leading bars are blank, then the line begins. The compiled modules below also fold two classes that live elsewhere: `Adx`, which takes longest because it smooths directional movement twice, on [Trend and volatility](trend-indicators.md#adx), and `Obv` on [Volume and VWAP](volume-indicators.md#obv). ## Reference Every class allocates in its constructor, never in `update()`, and `reset()` restores the just-constructed state. A `period` below 1 is clamped to 1. Construct in `onStart()` from a param (params are `f64`, periods are `i32`, so `new Rsi(i32(p_rsi_period()))`). ### Rsi `new Rsi(period)`, `.update(x)`: the relative strength index, bounded 0..100. Wilder smoothing (the gain and loss averages of the first `period` one-bar changes seed it, then `avg = (avg * (period - 1) + gain) / period`), first value at bar `period`. The ratio step is `100 - 100 / (1 + gain / loss)`, and a zero average loss returns `100`: a flat window reads 100, never 50; all-loss reads 0. A non-finite input follows TradingView's `ta.rsi`: its bar and the next one (whose change has a non-finite side) read `NaN` and leave the averages as they were, and the seed counts the first `period` finite changes. ```typescript let rsi = new Rsi(14); function onStart(): void { rsi = new Rsi(i32(p_rsi_period())); } ``` ### Wpr `new Wpr(length = 14)`, `.update(high, low, close)`: Williams %R over a high/low window, `-100 * (highest high - close) / (highest high - lowest low)`, bounded -100..0. `NaN` for the first `length - 1` bars and whenever any high or low in the window (or the close) is non-finite; a flat window (highest equals lowest) returns `0`. ```typescript let wpr = new Wpr(14); function onStart(): void { wpr = new Wpr(i32(p_length())); } ``` ### Cmo `new Cmo(length = 9)`, `.update(x)`: the Chande momentum oscillator compares summed gains and losses over the last `length` one-bar changes, `100 * (up - down) / (up + down)`. `NaN` until bar `length` (the first bar has no previous value), `0` when `up + down == 0` (a flat window), and `NaN` when any value in the window, or the bar before it, is non-finite. ```typescript let cmo = new Cmo(14); function onStart(): void { cmo = new Cmo(i32(p_length())); } ``` ### Tsi `new Tsi(short = 13, long = 25)`, `.update(x)`: the true strength index double-smooths one-bar momentum and its absolute value with an EMA of `long` then an EMA of `short`, and returns their ratio times 100. The engine's parameter order is `short` first, then `long`. Each EMA stage seeds on the mean of its first `period` finite inputs, so the first value lands at bar `long + short - 1`; the ratio is `NaN` when either stage is not finite or the denominator is `0`. ```typescript let tsi = new Tsi(13, 25); function onStart(): void { tsi = new Tsi(i32(p_short()), i32(p_long())); } ``` ### Macd `new Macd(fastPeriod = 12, slowPeriod = 26, signalPeriod = 9)`, `.update(x)`: returns the MACD line and fills the fields `macd`, `signal`, and `hist`. The MACD line is the fast EMA minus the slow EMA, each leg seeded on the mean of its first `period` finite inputs (first value at bar `slowPeriod - 1`), the signal is an EMA of that line seeded on its first `signalPeriod` finite values (first value at bar `slowPeriod + signalPeriod - 2`), and `hist` is `macd - signal` when both are finite. A non-finite input reads `NaN` on that bar and every leg continues from its state on the next one, as TradingView's `ta.macd` does. Draw the histogram as a `histogram` output around zero, or test a signal-line cross with `Cross.update(macd.macd, macd.signal)` ([Series functions](series-functions.md)). ```typescript let macd = new Macd(12, 26, 9); function onStart(): void { macd = new Macd(i32(p_fast()), i32(p_slow()), i32(p_signal())); } // after macd.update(close): macd.macd, macd.signal, macd.hist ``` ### Stoch and Stochastic `new Stoch(periodK, smoothK, periodD)`, `.update(high, low, close)`: the stochastic oscillator. Raw %K is `100 * (close - lowest low) / (highest high - lowest low)` over `periodK` bars (`0` on a flat window, `NaN` while the window is short or holds a non-finite value), `k` is the strict simple average of the last `smoothK` raw values, and `d` is the same average of the last `periodD` values of `k`. `update()` returns `k`; read `k` and `d` as fields. First `k` at bar `periodK + smoothK - 2`, first `d` at bar `periodK + smoothK + periodD - 3`. Two spellings with different edge rules ship. `new Stochastic(kPeriod = 14, kSmoothing = 3, dPeriod = 3)` is the other one: bars before `kPeriod - 1` report `k = 0` and `d = 0` (not `NaN`), a flat window reads `50`, `k` is the raw value itself until the smoothing window fills, `d` equals `k` until its own window fills, and a `NaN` `k` or `d` is reported as `50`. Reach for `Stoch` unless you want those edge rules. ```typescript let stoch = new Stoch(14, 3, 3); function onStart(): void { stoch = new Stoch(i32(p_period_k()), 3, 3); } // after stoch.update(high, low, close): stoch.k, stoch.d ``` Both read the close as the source. Pine's `ta.stoch(source, high, low, length)` takes any source: `SourceStoch` in `./sdk/ta-plus` ([Extra indicators](extra-indicators.md)) moves the source into `update(source, high, low)` and keeps `Stoch`'s smoothing and fields; fed the close it is `Stoch` on every window with a range (on a flat window `Stoch` reads 0 where `SourceStoch` follows TradingView: the previous raw %K when the source sits on the window's value, `NaN` otherwise). ```typescript let stochHl2 = new SourceStoch(14, 3, 3); function onStart(): void { stochHl2 = new SourceStoch(i32(p_period_k()), 3, 3); } // in onBar(): stochHl2.update((bar.high() + bar.low()) / 2.0, bar.high(), bar.low()); stochHl2.k, stochHl2.d ``` ### Cci `new Cci(period = 20, constant = 0.015)`, `.update(high, low, close)`: the commodity channel index over the typical price `(high + low + close) / 3`, `(tp - sma) / (constant * meanDev)` where `sma` is the window mean of the typical price and `meanDev` the mean absolute deviation around it. Readings beyond +100 and -100 mark momentum extremes. `NaN` for the first `period - 1` bars; `0` when the mean deviation is `0`. ```typescript let cci = new Cci(20, 0.015); function onStart(): void { cci = new Cci(i32(p_period()), 0.015); } ``` ### Mfi `new Mfi(period = 14)`, `.update(high, low, close, volume)`: the money flow index, a volume-weighted RSI bounded 0..100. Each bar's raw flow is `typical price * volume`, added to the positive sum when the typical price rose against the previous bar by more than `1e-10`, to the negative sum when it fell by more than `1e-10`, and to neither otherwise (Pine's float tolerance: TradingView's `ta.mfi` reads a move of a float residue as no move); the result is `100 - 100 / (1 + positive / negative)`, and a zero negative sum returns `100`. `NaN` for the first `period` bars; a non-finite bar fails both comparisons and adds nothing, as in the engine. It needs volume, so pass `bar.volume()` beside the prices. Above 80 reads overbought and below 20 oversold; price at a new high while the index above 80 is not is a classic exhaustion read. ```typescript let mfi = new Mfi(14); function onStart(): void { mfi = new Mfi(i32(p_period())); } ``` ### Mom and Roc `new Roc(n)`, `.update(x)`: rate of change in percent, `((x - x[n]) / x[n]) * 100`, `NaN` for the first `n` bars and when the lagged value is `0`. `new Mom(n)`, `.update(x)`: momentum, the raw difference `x - x[n]`, `NaN` for the first `n` bars and when either value is non-finite. `Change` is the same math under another name with a one-bar default lag; it lives with the series helpers on [Series functions](series-functions.md#trend-extremes-and-counting). ```typescript let mom = new Mom(10); let roc = new Roc(10); function onStart(): void { mom = new Mom(i32(p_lag())); roc = new Roc(i32(p_lag())); } ``` ## Putting them together One module wiring every oscillator above into a lower pane, the multi-output ones (`Macd`, `Stoch`, `Adx`) written stream by stream. Every class is used by name with nothing to import. `onBar()` returns before writing until the slowest line (`Adx`) is warm so every output starts together; write each value as it comes instead if you want the fast lines to appear first, since a `NaN` draws nothing ([Execution model](../core-concepts/execution-model.md)). ```typescript param("rsi_period", 14, { min: 2, max: 200 }); param("fast", 12, { min: 1, max: 200, description: "MACD fast EMA" }); param("slow", 26, { min: 2, max: 400, description: "MACD slow EMA" }); param("signal", 9, { min: 1, max: 200, description: "MACD signal EMA" }); param("adx_period", 14, { min: 1, max: 200 }); output("rsi", line, lower, { color: "#7c3aed", width: 2, description: "Relative strength index" }); output("wpr", line, lower, { color: "#2563eb", width: 1, description: "Williams %R" }); output("cmo", line, lower, { color: "#16a34a", width: 1, description: "Chande momentum oscillator" }); output("tsi", line, lower, { color: "#9333ea", width: 1, description: "True strength index" }); output("macd", line, lower, { color: "#1d4ed8", width: 2, description: "MACD line" }); output("signal", line, lower, { color: "#ea580c", width: 2, description: "MACD signal" }); output("hist", histogram, lower, { color: "#15803d", description: "MACD histogram" }); output("stoch_k", line, lower, { color: "#0e7490", width: 2, description: "Stochastic %K" }); output("stoch_d", line, lower, { color: "#be123c", width: 2, description: "Stochastic %D" }); output("cci", line, lower, { color: "#4b5563", width: 1, description: "Commodity channel index" }); output("mfi", line, lower, { color: "#16a34a", width: 2, description: "Money flow index" }); output("mom", line, lower, { color: "#9333ea", width: 1, description: "Momentum over 10 bars" }); output("roc", line, lower, { color: "#0891b2", width: 1, unit: "%", description: "Rate of change over 10 bars" }); output("adx", line, lower, { color: "#111827", width: 2, description: "Average directional index" }); output("di_plus", line, lower, { color: "#2563eb", width: 1, description: "+DI" }); output("di_minus", line, lower, { color: "#dc2626", width: 1, description: "-DI" }); output("obv", line, lower, { color: "#0f766e", width: 1, description: "On-balance volume" }); let rsi = new Rsi(14); let wpr = new Wpr(14); let cmo = new Cmo(14); let tsi = new Tsi(13, 25); let macd = new Macd(12, 26, 9); let stoch = new Stoch(14, 3, 3); let cci = new Cci(20, 0.015); let mfi = new Mfi(14); let mom = new Mom(10); let roc = new Roc(10); let adx = new Adx(14); let obv = new Obv(); function onStart(): void { rsi = new Rsi(i32(p_rsi_period())); wpr = new Wpr(14); cmo = new Cmo(14); tsi = new Tsi(13, 25); macd = new Macd(i32(p_fast()), i32(p_slow()), i32(p_signal())); stoch = new Stoch(14, 3, 3); cci = new Cci(20, 0.015); mfi = new Mfi(14); mom = new Mom(10); roc = new Roc(10); adx = new Adx(i32(p_adx_period())); obv = new Obv(); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const volume = bar.volume(); const rsiValue = rsi.update(close); const wprValue = wpr.update(high, low, close); const cmoValue = cmo.update(close); const tsiValue = tsi.update(close); macd.update(close); stoch.update(high, low, close); const cciValue = cci.update(high, low, close); const mfiValue = mfi.update(high, low, close, volume); const momValue = mom.update(close); const rocValue = roc.update(close); adx.update(high, low, close); const obvValue = obv.update(close, volume); // ADX is the slowest line here; return before writing until it is warm so every output begins together. if (isNaN(adx.adx)) return; out_rsi(rsiValue); out_wpr(wprValue); out_cmo(cmoValue); out_tsi(tsiValue); out_macd(macd.macd); out_signal(macd.signal); out_hist(macd.hist); out_stoch_k(stoch.k); out_stoch_d(stoch.d); out_cci(cciValue); out_mfi(mfiValue); out_mom(momValue); out_roc(rocValue); out_adx(adx.adx); out_di_plus(adx.plusDi); out_di_minus(adx.minusDi); out_obv(obvValue); } ``` ## Edge behavior: Wpr, Cmo, Tsi Two edges are worth seeing: %R is `NaN` until its window fills, and CMO returns `0` on a flat series. One module shows both with the shipped classes. `flat` is a series held at 100 on every bar, so its `Cmo` changes are all zero and the class returns `0` once its window is full; `wpr_warm` is `1` on the bars where the class has an answer and `0` before, so the boundary is a step you can read off the pane. ```typescript param("length", 14, { min: 2, max: 200 }); output("wpr", line, lower, { color: "#2563eb", width: 2, description: "Williams %R" }); output("cmo", line, lower, { color: "#16a34a", width: 2, description: "Chande momentum oscillator" }); output("tsi", line, lower, { color: "#7c3aed", width: 2, description: "True strength index, short 13 long 25" }); output("wpr_warm", none, lower, { description: "1 once %R has a full window, 0 before" }); output("cmo_flat", line, lower, { color: "#ea580c", width: 1, description: "CMO of a flat series: 0 once its window fills" }); let wpr = new Wpr(14); let cmo = new Cmo(14); let cmoFlat = new Cmo(5); let tsi = new Tsi(13, 25); function onStart(): void { wpr = new Wpr(i32(p_length())); cmo = new Cmo(i32(p_length())); cmoFlat = new Cmo(5); tsi = new Tsi(13, 25); } function onBar(): void { const close = bar.close(); const wprValue = wpr.update(bar.high(), bar.low(), close); const cmoValue = cmo.update(close); const cmoFlatValue = cmoFlat.update(100.0); const tsiValue = tsi.update(close); out_wpr(wprValue); out_cmo(cmoValue); out_tsi(tsiValue); out_wpr_warm(isNaN(wprValue) ? 0.0 : 1.0); out_cmo_flat(cmoFlatValue); } ``` ## Warm-up in practice To see warm-up directly, draw a few oscillators and look at where each line begins. The leading gap is the seed window: each line stays blank until its longest period has enough bars, then turns finite. `Adx` starts last (bar `2 * period - 1`), `Rsi` first (bar `period`), `Stoch` at bar `period + 1` with its default smoothing of 3, and `Macd` once its slow EMA is seeded. This module writes every output on every bar (a `NaN` draws nothing) instead of returning early, so the pane shows each line switching on at its own bar. ```typescript param("period", 14, { min: 2, max: 200 }); output("rsi", line, lower, { color: "#7c3aed", width: 2, description: "Finite from bar period on" }); output("macd", line, lower, { color: "#2563eb", width: 2, description: "Finite once the slow EMA is seeded" }); output("stoch_k", line, lower, { color: "#0891b2", width: 2, description: "Finite after the %K window plus smoothing" }); output("adx", line, lower, { color: "#111827", width: 2, description: "Finite after two smoothing windows" }); let rsi = new Rsi(14); let macd = new Macd(12, 26, 9); let stoch = new Stoch(14, 3, 3); let adx = new Adx(14); function onStart(): void { const period = i32(p_period()); rsi = new Rsi(period); macd = new Macd(12, 26, 9); stoch = new Stoch(period, 3, 3); adx = new Adx(period); } function onBar(): void { const close = bar.close(); const rsiValue = rsi.update(close); macd.update(close); stoch.update(bar.high(), bar.low(), close); adx.update(bar.high(), bar.low(), close); // Every bar has a row; each output carries NaN until its own class is warm. out_rsi(rsiValue); out_macd(macd.macd); out_stoch_k(stoch.k); out_adx(adx.adx); } ``` ## Points to remember - Every oscillator takes the fields it needs as arguments, each one read from the bar (`bar.high()`, `bar.low()`, `bar.close()`, `bar.volume()`); reading a field is what puts it on the sheet. - `macd.hist`, `stoch.d`, and the ADX trio are fields on the class and one output each. - A MACD divergence (price at a new high while `macd.macd` is not) is a weakening trend; the `hist` output shrinking toward zero says the same thing earlier. - Every class here is checked bit-exact against the reference run on the [TA library](ta-library.md) page, edge rules included (`Rsi` at 100 on a flat window, `Stochastic` at 50, `Wpr` and `Cmo` at 0). # Trend and volatility Trend tools read direction and strength, volatility tools read range: the directional movement system, the Ichimoku cloud, the parabolic stop-and-reverse, the ATR trailing stop, the band pair, and the volatility primitives under them. Every one on this page ships as a class in `./sdk/ta` (`Adx`, `Ichimoku`, `Psar`, `Supertrend`, `Tr`, `Atr`, `Stdev`, `Variance`), and the bands are outputs plus a `range()` declaration. MACD is an oscillator and lives on the [Oscillators](oscillators.md#macd) page. The full catalog is on the [TA library](ta-library.md) page. | System | What it reads | | --- | --- | | Directional movement (`Adx`) | trend strength as `adx`, with `plusDi` and `minusDi`; above 25 is a strong trend, below 20 often a range | | Ichimoku cloud (`Ichimoku`) | five components; the two leading spans come out of the class already shifted, the lagging span is drawn back by declaration | | Parabolic SAR (`Psar`) | a dot that trails price and jumps to the other side when the trend flips | | Supertrend (`Supertrend`) | an ATR-banded trailing stop with a direction the chart colors by | ## Adx `new Adx(period = 14)`, `.update(high, low, close)` returns the ADX line; after each update the fields `adx`, `plusDi`, and `minusDi` hold the three streams. The class follows the engine's own arithmetic rather than a textbook Wilder average: the true range and the two directional movements are first summed over the first `period` bars (a plain sum, not a mean), then each running sum is smoothed as `s = s - s / period + x`; `plusDi` and `minusDi` are the smoothed movements over the smoothed true range times 100 (`0` when that range is exactly `0`); DX is the normalized DI difference, `0` when both DI lines are `0`; and `adx` seeds on the plain average of the first `period` DX values before smoothing as `(adx * (period - 1) + dx) / period`. So the DI lines appear at bar `period` and `adx` at bar `2 * period - 1`. Bar 0 has no previous bar and produces nothing; a non-finite bar before the seed clears the partial sums and restarts the run, and a non-finite bar after the seed leaves all three outputs `NaN` for the rest of the series. ```typescript let adx = new Adx(14); function onStart(): void { adx = new Adx(i32(p_adx_period())); } ``` Read `adx.plusDi > adx.minusDi` for direction and `adx.adx` rising for conviction; a `Cross` object over the two DI lines ([Series functions](series-functions.md)) turns the crossover into a signal. Pine's `ta.dmi(diLength, adxSmoothing)` takes two lengths: `+DI` and `-DI` over `diLength`, ADX over `adxSmoothing`. `Adx` smooths all three over one period, so when the two differ reach for `Dmi` in `./sdk/ta-plus` ([Extra indicators](extra-indicators.md)), which keeps Pine's form (Wilder's `Rma` on both) and the same three fields; with equal lengths the two classes agree on a series without a hole (`Dmi` skips a missing bar the way TradingView's `ta.dmi` does, where `Adx` reads `NaN` for good) and wherever the up and down moves are more than `1e-10` apart (`Dmi` reads closer moves as equal, as `ta.dmi` does). ```typescript let dmi = new Dmi(14, 14); function onStart(): void { dmi = new Dmi(i32(p_di_length()), i32(p_adx_smoothing())); } // after dmi.update(high, low, close): dmi.adx, dmi.plusDi, dmi.minusDi ``` ## Ichimoku `new Ichimoku(conversionPeriod = 9, basePeriod = 26, laggingSpanPeriod = 52, displacement = 26)`, `.update(high, low, close)` returns `tenkan`; fields `tenkan`, `kijun`, `senkouA`, `senkouB`, `chikou`. Each line is the midpoint of the highest high and lowest low over its period. The engine conventions the class keeps: - **Partial windows, no warm-up.** Bar 0 already has a value from its own bar; there is no `NaN` lead-in. A `NaN` high or low inside the window is skipped, but the current bar's own `NaN` poisons the value, and every output that comes out `NaN` is reported as `0`. - **The displacement is inside the math.** `senkouA` on bar `i` is `(tenkan + kijun) / 2` as it stood `displacement` bars earlier, and `senkouB` is the 52-bar midpoint from `displacement` bars earlier; on the first `displacement` bars both fall back to the current bar's values. The two fields are therefore already the cloud that belongs on the current bar, so write them to plain outputs with no `displacement_bars`. The projection past the newest loaded bar is not emitted, exactly as in the engine. - **`chikou` is the current close.** The engine reads the close of bar `i + displacement`, a future bar, and only falls back to the current close on the last `displacement` bars of the series; a class that sees one bar at a time cannot read ahead, so the field is the current close. Declaring `displacement_bars: -26` on its output makes the chart draw that close 26 bars back, which is the lagging span as the engine's chart shows it. That shift is drawing only: the value stays on the bar that computed it. ```typescript const cloud = new Ichimoku(9, 26, 52, 26); // In onBar(): one update per bar, then read the five lines by name. cloud.update(bar.high(), bar.low(), bar.close()); const bullish = cloud.senkouA >= cloud.senkouB; // the cloud on this bar, already shifted ``` The cloud itself is two boxes: `box("cloud_up", { top: senkouA, bottom: senkouB, when: aAbove })` draws, for each bar, a one-bar slice between the two spans the class reports for that bar, and a second box gated the other way draws the bearish slices in the other color. The declarations are compiled in [Cloud, stop, and dots](#cloud-stop-and-dots) below. ## Psar `new Psar(start = 0.02, increment = 0.02, maxValue = 0.2)`, `.update(high, low, close)` returns the SAR price for the bar, which jumps to the other side of price when the trend flips; there is no direction field, so read the side as `close > sar` (or the SAR against the low), or track the flips with a `Cross` object over price and the SAR. The acceleration factor starts at `start`, grows by `increment` on every new extreme, and caps at `maxValue`; the SAR never crosses the two prior bars' lows in an up trend or highs in a down trend, and when price trades through it the trend flips and the SAR jumps to the last extreme. Engine conventions: bar 0 is `NaN`; bar 1 decides the opening trend from `close[1] >= close[0]` and returns `low[0]` for an up trend or `high[0]` for a down one; the close is only read on those two bars; a non-finite high or low (or close on bars 0 and 1) makes the SAR `NaN` for that bar and every bar after it, because the engine recomputes the whole series and stops at the first bad bar. Lower acceleration (`0.01` to `0.02`) gives smoother stops with fewer reversals; `0.05` and up reacts faster and flips more in ranges. ```typescript let psar = new Psar(0.02, 0.02, 0.2); function onBar(): void { const close = bar.close(); const sar = psar.update(bar.high(), bar.low(), close); if (isNaN(sar)) return; const side = close > sar ? 1.0 : -1.0; out_psar(sar); out_side(side); } ``` Draw the SAR as a `scatter` output so it reads as dots, and color the dots by `side` through a `color_by` ladder ([Styling](../presentation/styling.md)). ## Supertrend `new Supertrend(factor, atrPeriod)` (no defaults; `3` and `10` are the usual values), `.update(high, low, close)` returns the stop line and fills the fields `line` and `direction` (`1` for an up trend, the line sits below price; `-1` for a down trend, the line sits above). The bands sit `factor` ATRs either side of the bar midpoint `(high + low) / 2`; the upper band ratchets down (a lower basic band, or the previous close above the old band, replaces it) and the lower band ratchets up symmetrically; the direction flips to `-1` when the close drops below the lower band in an up trend and to `1` when it rises above the upper band in a down trend; the line is the lower band in an up trend and the upper band in a down one. The ATR inside is the same Wilder smoothing as `Atr`, so the first finite bar is `atrPeriod - 1`, where the direction starts as `1` when the close is at or above the midpoint. While the ATR is `NaN` both fields are `NaN` and the band state is left untouched, so a gap neither resets nor advances the bands; a non-finite high, low, or close on a bar with a finite ATR gives `NaN` for that bar alone. Because a shape cannot read a bool, the direction is a number, ready to be written to a data-only output and used as a `color_by` index. `direction` is `+1` in an uptrend; Pine's `ta.supertrend` is `-1`. ```typescript let st = new Supertrend(3.0, 10); function onStart(): void { st = new Supertrend(p_factor(), i32(p_atr_period())); } function onBar(): void { st.update(bar.high(), bar.low(), bar.close()); if (isNaN(st.line)) return; out_st_line(st.line); out_st_dir(st.direction > 0.0 ? 1.0 : 0.0); } ``` ## Bands as outputs `Bb` and `Keltner` (both described on the [Moving averages](moving-averages.md) page) expose `basis`, `upper`, and `lower` fields; each becomes an output. A wrun indicator declares the band between them. `range(upper, lower, options)` names the two edge outputs (both must be drawn) and the chart draws the band: both edge lines at `edge_width` and `edge_line_style` with a tinted interior in `color`, a `colors` + `color_by` ladder to tint it per bar, or a vertical `gradient` ([Styling](../presentation/styling.md)). A `box` on every bar between the two edge outputs, with `from` and `to` left at `0`, is the other way to shade ([Cards, frames and panels](../presentation/cards-frames-panels.md)); the slices tile into a channel, and either edge may stay data-only. ## Volatility primitives | Class | Construct | Per bar | Returns | | --- | --- | --- | --- | | `Tr` | `new Tr()` | `.update(high, low, close)` | the true range of the current bar: the largest of `high - low`, `abs(high - prevClose)`, `abs(low - prevClose)`, taken pairwise left to right; on bar 0 just `high - low` | | `Atr` | `new Atr(period = 14)` | `.update(high, low, close)` | the Wilder-smoothed true range: the seed is the plain average of the first `period` true ranges (first value at bar `period - 1`), then `(prev * (period - 1) + tr) / period` | | `Stdev` | `new Stdev(period)` | `.update(x)` | the rolling population standard deviation (divide by `period`, not `period - 1`) | | `Variance` | `new Variance(period)` | `.update(x)` | the rolling population variance, the same window arithmetic as `Stdev` without the square root | All four ship in `./sdk/ta`; they are the building blocks the band and stop classes use internally, exposed so custom volatility logic composes the same way. Their `NaN` rules differ: `Tr` returns `NaN` on a non-finite high or low and on the bar after a non-finite close (the engine's rule); `Atr` follows TradingView's `ta.rma` over the true range, so a `NaN` range reads `NaN` on its bar, its seed skips it, and the next finite range continues the average; `Stdev` and `Variance` are strict windows, `NaN` until `period` bars exist and whenever any value in the window is not finite, healing as soon as the bad bar leaves. ```typescript const tr = new Tr(); let atr = new Atr(14); let stdev = new Stdev(20); let variance = new Variance(20); function onStart(): void { atr = new Atr(i32(p_atr_period())); stdev = new Stdev(i32(p_period())); variance = new Variance(i32(p_period())); } function onBar(): void { const close = bar.close(); const trValue = tr.update(bar.high(), bar.low(), close); const atrValue = atr.update(bar.high(), bar.low(), close); const stdevValue = stdev.update(close); const varianceValue = variance.update(close); if (isNaN(atrValue)) return; out_tr(trValue); out_atr(atrValue); out_stdev(stdevValue); out_variance(varianceValue); } ``` `Stdev` is strict: a `NaN` sample anywhere in its window makes the result `NaN` until the sample leaves the window; guard the input with `isNaN` when a sparse source feeds it. ## Putting them together The directional system, the SAR, the Supertrend stop, and the volatility primitives in one module. The stop line is colored by its regime through a `color_by` ladder over a data-only `st_dir` output, the SAR draws as dots, and the ADX trio and the four volatility lines share a lower pane. ```typescript param("adx_period", 14, { min: 1, max: 200 }); param("factor", 3, { min: 0.5, max: 10, description: "Supertrend ATR multiplier" }); param("atr_period", 10, { min: 1, max: 200, description: "ATR window for Supertrend and the atr line" }); output("st_line", line, overlay, { width: 2, color_by: "st_dir", colors: ["#dc2626", "#16a34a"], description: "Supertrend stop, red in a short regime, green in a long one" }); output("st_dir", none, overlay, { description: "0 short, 1 long: the palette index for st_line" }); output("psar", scatter, overlay, { color: "#9333ea", description: "Parabolic SAR dots" }); output("adx", line, lower, { color: "#111827", width: 2, description: "Average directional index" }); output("di_plus", line, lower, { color: "#2563eb", width: 1, description: "+DI" }); output("di_minus", line, lower, { color: "#dc2626", width: 1, description: "-DI" }); output("tr", line, lower, { color: "#94a3b8", width: 1, description: "True range" }); output("atr", line, lower, { color: "#f97316", width: 2, description: "Average true range" }); output("stdev", line, lower, { color: "#0891b2", width: 1, description: "Rolling standard deviation of the close" }); output("variance", line, lower, { color: "#7c3aed", width: 1, description: "Rolling variance of the close" }); let adx = new Adx(14); let psar = new Psar(0.02, 0.02, 0.2); let st = new Supertrend(3.0, 10); let tr = new Tr(); let atr = new Atr(10); let stdev = new Stdev(10); let variance = new Variance(10); function onStart(): void { adx = new Adx(i32(p_adx_period())); psar = new Psar(0.02, 0.02, 0.2); st = new Supertrend(p_factor(), i32(p_atr_period())); tr = new Tr(); atr = new Atr(i32(p_atr_period())); stdev = new Stdev(i32(p_atr_period())); variance = new Variance(i32(p_atr_period())); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); adx.update(high, low, close); const psarValue = psar.update(high, low, close); st.update(high, low, close); const trValue = tr.update(high, low, close); const atrValue = atr.update(high, low, close); const stdevValue = stdev.update(close); const varianceValue = variance.update(close); out_st_line(st.line); out_st_dir(st.direction > 0.0 ? 1.0 : 0.0); out_psar(psarValue); out_adx(adx.adx); out_di_plus(adx.plusDi); out_di_minus(adx.minusDi); out_tr(trValue); out_atr(atrValue); out_stdev(stdevValue); out_variance(varianceValue); } ``` ## Cloud, stop, and dots Ichimoku with its two-color cloud and the lagging span drawn back, the Supertrend stop colored by regime, and the SAR as dots, in one overlay. ```typescript param("factor", 3, { min: 0.5, max: 10, description: "Supertrend ATR multiplier" }); param("atr_period", 10, { min: 1, max: 200, description: "Supertrend ATR window" }); output("tenkan", line, overlay, { color: "#0891b2", width: 1, description: "Conversion line, 9-bar midpoint" }); output("kijun", line, overlay, { color: "#be123c", width: 1, description: "Base line, 26-bar midpoint" }); // The spans are already shifted inside the class: the value on a bar is the cloud for that bar. const senkouA = output("senkou_a", line, overlay, { color: "#0f766e", width: 1, description: "Leading span A, the class shifts it 26 bars ahead" }); const senkouB = output("senkou_b", line, overlay, { color: "#b45309", width: 1, description: "Leading span B, the class shifts it 26 bars ahead" }); output("chikou", line, overlay, { color: "#64748b", width: 1, displacement_bars: -26, description: "Lagging span, the close drawn 26 bars back" }); const aAbove = output("a_above", none, overlay, { description: "1 where span A is above span B: the bullish cloud gate" }); const bAbove = output("b_above", none, overlay, { description: "1 where span B is above span A: the bearish cloud gate" }); // The cloud: one slice per bar between the two spans, tinted by which span is on top. box("cloud_up", { top: senkouA, bottom: senkouB, when: aAbove, color: "#16a34a", opacity: 0.12, borderWidth: 0 }); box("cloud_down", { top: senkouB, bottom: senkouA, when: bAbove, color: "#dc2626", opacity: 0.12, borderWidth: 0 }); output("st_line", line, overlay, { width: 2, color_by: "st_dir", colors: ["#dc2626", "#16a34a"], description: "Supertrend stop, colored by regime" }); output("st_dir", none, overlay, { description: "0 short, 1 long" }); output("psar", scatter, overlay, { color: "#9333ea", description: "Parabolic SAR" }); let cloud = new Ichimoku(9, 26, 52, 26); let st = new Supertrend(3.0, 10); let psar = new Psar(0.02, 0.02, 0.2); function onStart(): void { cloud = new Ichimoku(9, 26, 52, 26); st = new Supertrend(p_factor(), i32(p_atr_period())); psar = new Psar(0.02, 0.02, 0.2); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); cloud.update(high, low, close); st.update(high, low, close); const psarValue = psar.update(high, low, close); out_tenkan(cloud.tenkan); out_kijun(cloud.kijun); out_senkou_a(cloud.senkouA); out_senkou_b(cloud.senkouB); out_chikou(cloud.chikou); out_a_above(cloud.senkouA >= cloud.senkouB ? 1.0 : 0.0); out_b_above(cloud.senkouB > cloud.senkouA ? 1.0 : 0.0); out_st_line(st.line); out_st_dir(st.direction > 0.0 ? 1.0 : 0.0); out_psar(psarValue); } ``` ## Bands: outputs, a range, and a shaded box The Bollinger pair as three outputs, a `range()` declaration recording the band in the sheet, and a `box` on every bar shading the same pair on the chart, gated so the shade only shows while the basis is rising. ```typescript param("period", 20, { min: 2, max: 400 }); param("mult", 2, { min: 0.5, max: 5, description: "Standard-deviation multiples" }); const upper = output("upper_band", line, overlay, { color: "#64748b", width: 1, description: "Basis plus mult deviations" }); output("basis", line, overlay, { color: "#2563eb", width: 1, description: "20-bar simple average" }); const lowerBand = output("lower_band", line, overlay, { color: "#64748b", width: 1, description: "Basis minus mult deviations" }); const rising = output("rising", none, overlay, { description: "1 while the basis rises: the shade gate" }); // The sheet-level band: honored by hosts that draw ranges, ignored by the chart lane today. range("upper_band", "lower_band", { color: "#2563eb", edge_width: 1, edge_line_style: "dotted" }); // The chart-drawn band: one slice per bar between the same two outputs, tiling into a channel. box("band_shade", { top: upper, bottom: lowerBand, when: rising, color: "#2563eb", opacity: 0.12, borderWidth: 0 }); let sma = new Sma(20); let stdev = new Stdev(20); let mult: f64 = 2.0; let mid: f64 = NaN; let prevMid: f64 = NaN; function onStart(): void { sma = new Sma(i32(p_period())); stdev = new Stdev(i32(p_period())); mult = p_mult(); } function onBar(): void { const close = bar.close(); prevMid = mid; mid = sma.update(close); const sd = stdev.update(close); if (isNaN(mid) || isNaN(sd)) return; out_upper_band(mid + mult * sd); out_basis(mid); out_lower_band(mid - mult * sd); out_rising(!isNaN(prevMid) && mid > prevMid ? 1.0 : 0.0); } ``` ## Reading them - **Ichimoku.** Price above the cloud (both spans) is an uptrend, below it a downtrend; a `tenkan` over `kijun` cross that agrees with the cloud is the classic entry. - **Supertrend.** The flip of `direction` is the signal; the line itself is the trailing stop for the position the regime implies. # Volume and VWAP Volume tools fold volume into the calculation to read buying and selling pressure, participation, and the price volume actually paid. Three ship as classes in the editor's `./sdk/ta` module (`Obv`, `Vwap`, `Cum`); the money flow index is an oscillator and lives on the [Oscillators](oscillators.md#mfi) page. Volume itself is the bar's own field (`bar.volume()`), and the buy and sell split is two `trades.volume` inputs with a `side`. | Type | What it reads | | --- | --- | | On-balance volume (`Obv`) | a cumulative line that adds volume on up bars and subtracts it on down bars | | Volume-weighted average price (`Vwap`) | the fair price weighted by where volume traded, cumulative or reset on a calendar anchor | | Cumulative sum (`Cum`) | the running total of any series, the primitive behind OBV-style accumulation | For volume-weighted moving averages see `Vwma` on the [Moving averages](moving-averages.md) page; for per-price buy and sell volume inside one bar see [Order flow](order-flow-kit.md). ## Obv `new Obv()`, `.update(close, volume)`. A running cumulative line with no period: bar 0 returns `0`, then the bar's volume is added when the close rose against the previous close, subtracted when it fell, and ignored when equal (or when either close is `NaN`). The whole state is the previous close and the running total, which `reset()` clears. Its level depends on how much history the chart loaded; its slope does not, and the slope is what confirms or contradicts price. ## Vwap `new Vwap(anchor = "", price = "hlc3")`, `.update(open, high, low, close, volume, tsMs)` returns the running VWAP: price times volume over volume, accumulated from an anchor and reset at each boundary. `price` picks the bar price: `hlc3`, `hl2`, `ohlc4` (the only mode that reads the open), `hlcc4`, or `close`. `tsMs` is the bar's open time since the epoch and is only read when an anchor is set: pass `bar.time()` as it comes (seconds) or the time in milliseconds. A value below `1e11` in size is read as seconds and scaled to milliseconds (`1e11` milliseconds is March 1973, `1e11` seconds the year 5138). An anchored `Vwap` given no time stops the run with `AssemblyScript abort:` and a message naming the fix, instead of a line that stays `NaN`. | Anchor | Boundary | First finite value | | --- | --- | --- | | `""` (none) | never; one accumulation from the first loaded bar | the first bar | | `"day"` | every 00:00 UTC | the first bar | | `"week"` | every Monday 00:00 UTC | the first bar | | `"month"`, `"quarter"`, `"year"` | the first of the period, 00:00 UTC | the first bar | | `"14400000"` (any number of milliseconds, as a string) | every bucket of that width, floored from the epoch | the first bar | A literal anchor or price outside these words fails the build on its line, naming the words: Pine's `"D"` or `"1D"` is `"day"` here, `"W"` `"week"`, `"M"` `"month"`, `"3M"` `"quarter"` and `"12M"` `"year"`; a width is whole milliseconds (`"14400000"`, or `"14400000.0"` as a float prints it); a price is one of the five above, in lower case. **No leading gap, and anchored lines are stable.** The engine starts a bucket on the first bar of the series whatever the calendar says, so an anchored line is finite from bar 0 and its first period is partial: inside it the level depends on where the loaded history starts, and from the first boundary on every period computes only from its own bars, so loading older history cannot change later buckets. The no-anchor form is partial for the whole series (two charts with different history depths disagree, and the level shifts when history loads), which is why the anchored forms are the ones to share. **Engine conventions.** A bar whose high, low, close or volume is not finite (or open, for `"ohlc4"`) marks the current bucket invalid: the value is `NaN` from that bar until the next bucket starts, forever in the no-anchor form. A zero total volume is `NaN`. With an anchor set, a `NaN` time stops the run like a missing one (the engine cleared the sums and returned `NaN`). The no-anchor, `"day"` and numeric-millisecond anchors match the engine bit for bit on the reference window; `"week"`, `"month"`, `"quarter"` and `"year"` are computed from the same calendar arithmetic but unproven on that window. Not mirrored, because a per-bar class never sees the data: the engine's session-calendar bucketing on venues with a trading calendar, its regular-trading-hours filter, and the extra history it loads for quarter and year anchors. ```typescript const weekly = new Vwap("week"); // hlc3 price, resets every Monday 00:00 UTC const session = new Vwap("14400000", "close"); // four-hour buckets over the close // In onBar(): bar.time() is epoch seconds, which the class reads as they are. const weekValue = weekly.update(bar.open(), bar.high(), bar.low(), bar.close(), bar.volume(), bar.time()); ``` **Any source.** The price is one of the five named ones. Pine's `ta.vwap(source)` takes any series: `SourceVwap(anchor)` in `./sdk/ta-plus` ([Extra indicators](extra-indicators.md)) keeps the same sums and anchors over a source you compute, `update(source, volume, tsMs)`; fed `(high + low + close) / 3` it is `Vwap(anchor, "hlc3")`. ```typescript const daily = new SourceVwap("day"); // In onBar(): the session VWAP of the bar's ohlc4. const o = bar.open(), h = bar.high(), l = bar.low(), c = bar.close(); const value = daily.update((o + h + l + c) / 4.0, bar.volume(), bar.time() * 1000.0); ``` **Custom anchors.** The anchor is a bucket id computed from the bar's open time: a UTC day index for `"day"`, a week index whose origin is three days before the epoch (so weeks start on Monday) for `"week"`, and civil calendar math for the month, quarter and year forms. When the id changes the sums reset, and the same reset-on-id rule is a few lines of arithmetic for any anchor the class does not name (a session open, a news bar, a manual level): ```typescript // The same rule the class applies, written out for a custom anchor. const DAY_MS: f64 = 86400000.0; const tMs = bar.time() * 1000.0; // the bar's open time in milliseconds const dayId = Math.floor(tMs / DAY_MS); // "day" const weekId = Math.floor((tMs + 3.0 * DAY_MS) / (7.0 * DAY_MS)); // "week", Monday origin const bucketId = Math.floor(tMs / 14400000.0); // "14400000" ``` Assign the class to a module-level `let` like any other; there is nothing to wait for, the line is finite on the first bar with volume. ## Cum `new Cum()`, `.update(x)`. It is barely a class: a running total of whatever you feed it from the start of the data, bar 0 returning `x` itself. It is the primitive behind OBV-style accumulation and custom anchored math (feed it signed volume for a delta proxy). ```typescript const cumDelta = new Cum(); function onBar(): void { const volume = bar.volume(); // Signed volume: the bar's volume counted toward the side of its close. const deltaValue = cumDelta.update(bar.close() >= bar.open() ? volume : -volume); out_cum_delta(deltaValue); } ``` A non-finite sample sets the running total to `NaN` for the rest of the history, which is the engine's `cum` rule; a sparse input that must not poison it goes through `Fixnan` first, or through a `missing: "zero"` policy on the source ([Series functions](series-functions.md)). ## Putting them together The four on one lower pane plus the two VWAP lines on the price pane: a money flow index, on-balance volume, a cumulative signed-volume delta proxy, and the cumulative and daily VWAPs. ```typescript param("mfi_period", 14, { min: 2, max: 200 }); output("vwap_cum", line, overlay, { color: "#2563eb", width: 1, description: "Cumulative VWAP from the first loaded bar" }); output("vwap_day", line, overlay, { color: "#eab308", width: 2, description: "VWAP reset at each UTC day boundary" }); output("mfi", line, lower, { color: "#16a34a", width: 2, description: "Money flow index, 0..100" }); output("obv", line, lower, { color: "#0f766e", width: 1, description: "On-balance volume" }); output("cum_delta", line, lower, { color: "#22d3ee", width: 1, description: "Cumulative signed volume: a delta proxy" }); let mfi = new Mfi(14); const obv = new Obv(); const cumDelta = new Cum(); const vwapCum = new Vwap(); const vwapDay = new Vwap("day"); function onStart(): void { mfi = new Mfi(i32(p_mfi_period())); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const volume = bar.volume(); const mfiValue = mfi.update(high, low, close, volume); const obvValue = obv.update(close, volume); const open = bar.open(); // Signed volume: the bar's volume counted toward the side of its close. const deltaValue = cumDelta.update(close >= open ? volume : -volume); const tsMs = bar.time() * 1000.0; const vwapCumValue = vwapCum.update(open, high, low, close, volume, tsMs); const vwapDayValue = vwapDay.update(open, high, low, close, volume, tsMs); out_vwap_cum(vwapCumValue); out_vwap_day(vwapDayValue); out_mfi(mfiValue); out_obv(obvValue); out_cum_delta(deltaValue); } ``` ## VWAP anchors side by side The four VWAP variants side by side. Every line is finite from the first bar; the anchored ones reset at their boundary and are partial before the first one. `day_start` is a data-only flag that is `1` on the bar that opens a new UTC day, the bar where the daily sums reset, so the boundary is a value you can read after a run or hand to a declared alert. ```typescript input("open", ohlcv.open); output("vwap_cum", line, overlay, { color: "#2563eb", width: 2, description: "VWAP with no anchor, from the first loaded bar" }); output("vwap_day", line, overlay, { color: "#16a34a", width: 2, description: "VWAP anchored to the UTC day" }); output("vwap_week", line, overlay, { color: "#f97316", width: 2, description: "VWAP anchored to the UTC week" }); output("vwap_month", line, overlay, { color: "#7c3aed", width: 2, description: "VWAP anchored to the UTC month" }); output("day_start", none, overlay, { description: "1 on the bar that opens a new UTC day" }); const DAY_MS: f64 = 86400000.0; const cumulative = new Vwap(""); const daily = new Vwap("day"); const weekly = new Vwap("week"); const monthly = new Vwap("month"); let prevDay: f64 = NaN; function onBar(): void { const open = bar.open(); const high = bar.high(); const low = bar.low(); const close = bar.close(); const volume = bar.volume(); const tMs = bar.time() * 1000.0; // bar.time() is seconds; the day id below reads milliseconds const day = Math.floor(tMs / DAY_MS); const dayStart = !isNaN(prevDay) && day != prevDay ? 1.0 : 0.0; prevDay = day; const cumValue = cumulative.update(open, high, low, close, volume, tMs); const dayValue = daily.update(open, high, low, close, volume, tMs); const weekValue = weekly.update(open, high, low, close, volume, tMs); const monthValue = monthly.update(open, high, low, close, volume, tMs); out_vwap_cum(cumValue); out_vwap_day(dayValue); out_vwap_week(weekValue); out_vwap_month(monthValue); out_day_start(dayStart); } ``` ## Seeing the VWAP anchor boundary To see exactly where each anchored line resets, write a flag that is `1` on the bar whose bucket id differs from the previous bar's, the way `day_start` does above for the daily line. The flag is an output, so after a **Run** the editor's Console prompt reads it without drawing it: `last 200 day_start` lists the newest 200 bars, and `at day_start` reads one bar. To see the boundaries on the chart instead, declare the flag as a `histogram` on `lower` while you check, then set it back to `none`. ## Buy and sell volume The close-versus-open sign above is a proxy. The real side split is a source: `trades` serves per-period volume aggregated by aggressor side, one series per side, so buy and sell volume are two inputs on the same feed with a `side`. A venue that skips bars on one side delivers nothing on that bar; `missing: "zero"` turns the gap into `0` so the delta stays finite. The chart serves `trades` as per-bar volume by side (`volume` with `side: "BUY"` or `"SELL"`, in base-asset units) over the loaded history and live; any other `trades` field is refused by name. ```typescript input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero", description: "Volume traded by aggressive buyers" }); input("sell", trades.volume, { side: "SELL", missing: "zero", description: "Volume traded by aggressive sellers" }); output("delta", histogram, lower, { color_by: "delta_sign", colors: ["#ef5350", "#26a69a"], description: "Buy minus sell volume per bar" }); output("delta_sign", none, lower, { description: "0 on a sell-dominant bar, 1 on a buy-dominant bar" }); output("cvd", line, lower, { color: "#22d3ee", width: 2, description: "Cumulative volume delta" }); let cvd: f64 = 0.0; function onBar(): void { const delta = in_buy() - in_sell(); cvd += delta; out_delta(delta); out_delta_sign(delta >= 0.0 ? 1.0 : 0.0); out_cvd(cvd); } ``` The primary input stays the close so the wrun indicator follows the chart's market and interval; the two side inputs align to its grid row for row. Side volume always comes from the chart's own market: the chart refuses a `symbol` + `exchange` pin on a `trades` input ("the browser lane serves market pins on secondary ohlcv inputs only (typed feeds, cells and time follow the chart's own market)"). The [aggregated CVD recipe](../cookbook/aggregated-cvd.md) builds on the same two inputs. ## Reading them - **Volume quality.** High volume on a breakout confirms the move; a low-volume breakout often reverses. `delta` and `cvd` say which side did the volume, not just how much. - **Divergence.** Price at a new high while `obv` or `cvd` is not is a warning. - **Anchors.** The daily VWAP is the intraday fair price; the cumulative line is context that drifts with the loaded window. # Series functions Series functions answer the questions that come up constantly when writing an indicator: did two lines just cross, is a series rising, what is the highest high in the last 10 bars, what is the window total or z-score, how many bars since a condition was true, and is this value real or missing. A wrun indicator sees one bar at a time ([Execution model](../core-concepts/execution-model.md)), so each is a small class in `./sdk/ta` that keeps the history it needs and folds one bar per `update()` call, or a two-line function over `NaN`. Every class on this page ships in the kit; the full catalog is on the [TA library](ta-library.md) page. The one series question this page does not answer is `source[n]`, the value a few bars back. That is `History` from `./sdk/stats`: construct it in `onStart()`, `push()` first thing each bar, then read `ago(n)`, `NaN` until the window holds the bar. The same module does the list math (`mean`, `stdev`, `slope`, `correlation`, `median`, `percentile`) over a `StaticArray` without allocating, and `./sdk/ta-plus` adds the running extremes, `PercentRank`, `Range` and `Mode` over a window; all on [Extra indicators](extra-indicators.md). The pivots below are also the raw material of the [Market structure kit](market-structure-kit.md), whose `Swings` turns them into confirmed swing highs and lows. ## Price-source helpers `hl2`, `hlc3`, `ohlc4`, and `hlcc4` are arithmetic on the bar's fields. Read the fields you need and write the formula: | Helper | Formula | | --- | --- | | `hl2` | `(high + low) / 2.0` | | `hlc3` | `(high + low + close) / 3.0` | | `ohlc4` | `(open + high + low + close) / 4.0` | | `hlcc4` | `(high + low + close + close) / 4.0` | There is no implicit source: a wrun indicator names every field it reads, `bar.high()` for the high, `bar.close()` for the close. ```typescript output("hl2", line, overlay, { color: "#2563eb", width: 1, description: "Bar midpoint" }); output("hlc3", line, overlay, { color: "#16a34a", width: 1, description: "Typical price" }); output("ohlc4", line, overlay, { color: "#f97316", width: 1, description: "Four-price average" }); output("hlcc4", line, overlay, { color: "#7c3aed", width: 1, description: "Close-weighted average" }); function onBar(): void { const open = bar.open(); const high = bar.high(); const low = bar.low(); const close = bar.close(); out_hl2((high + low) / 2.0); out_hlc3((high + low + close) / 3.0); out_ohlc4((open + high + low + close) / 4.0); out_hlcc4((high + low + close + close) / 4.0); } ``` ## Crossovers and signals `Cross` ships in `./sdk/ta`: `new Cross()`, `.update(a, b): i32` returns `+1` on the bar `a` crosses above `b`, `-1` on the bar it crosses below, and `0` otherwise, including the first bar and any bar where either side is `NaN`. The edge rule is the engine's: a crossover is `a` below `b` on the previous bar and `a` at or above `b` on this bar (touching counts on the current bar, not on the previous one), and a crossunder is the mirror image. One object answers all three questions: | You want | wrun form | | --- | --- | | a cross above | `cross.update(a, b) == 1` | | a cross below | `cross.update(a, b) == -1` | | a cross in either direction | `cross.update(a, b) != 0` | Call `update()` exactly once per bar per pair: it remembers the previous pair, so a second call on the same bar would compare the bar to itself. Keep the result in a local and test it as many times as you like. A crossover against a constant (`rsi` over `70`) is `cross.update(value, 70.0)`. The classic signal-line pattern is a `Cross` over the MACD line and its signal; the result is a `0`/`1` step you can draw, or a gate for a `shape` output that marks the price bar ([Plotting](../presentation/plotting.md)): ```typescript const crossed = cross.update(macd.macd, macd.signal); bullish = crossed == 1 ? 1.0 : 0.0; ``` ### Pine's crosses: `PineCross` A Pine port reads `ta.crossover`, `ta.crossunder` and `ta.cross` through `PineCross` (`./sdk/ta`), which follows TradingView's rule, measured on its servers bar for bar. `Cross` keeps the engine's touch rule above for the indicators already built on it. | Pine | wrun form | True when | | --- | --- | --- | | `ta.crossover(a, b)` | `pair.over` | `a > b` now, and `a <= b` on the last earlier bar where both were defined | | `ta.crossunder(a, b)` | `pair.under` | `a < b` now, and `a >= b` on that bar | | `ta.cross(a, b)` | `pair.cross` | `a != b` now, and the other order on the last earlier bar where both were defined and unequal | | `ta.crossover(b, a)` | `pair.under` | the same pair read the other way | `new PineCross()` builds one per pair; call `pair.update(a, b)` once on every bar, before any branch reads it (it returns `+1` on a crossover, `-1` on a crossunder, `0` otherwise), then read its three `bool` fields. Two differences from `Cross` matter on real data: - **A bar with an na is skipped, not a reset.** A `NaN` on either side answers false on that bar and is never remembered, so the next defined bar compares against the last bar where both sides were defined. - **A tie counts as Pine counts it.** Equal values on the previous bar still allow a crossover (`a <= b` then), equal values now never are one (`a > b` is needed); `ta.cross` skips the tie altogether, so a touch that turns back (above, equal, above) is a crossover but not a cross. Both compare exactly, as TradingView's three crossing builtins do: two values `1e-11` apart make a crossover there and here, although Pine's own `>`, `==` and `<` read two values within about `1e-10` as equal. ## Trend, extremes, and counting | You want | wrun form | Returns | | --- | --- | --- | | is the series rising | `new Rising(period)`, `.update(x)` | `1` when `x` is strictly above every one of the previous `period` values, else `0`; `NaN` for the first `period` bars | | is the series falling | `new Falling(period)`, `.update(x)` | `1` when `x` is strictly below every one of the previous `period` values, else `0`; `NaN` for the first `period` bars | | the change over `n` bars | `new Change(n)`, `.update(x)` | `x` now minus `x` `n` bars ago (`n` defaults to 1); `NaN` for the first `n` bars | | the window high | `new Highest(period)`, `.update(x)`, field `bars` | the highest value in the window; `bars` is the same offset `HighestBars` reports for the window | | the window low | `new Lowest(period)`, `.update(x)`, field `bars` | the lowest value in the window; `bars` is the same offset `LowestBars` reports | | how long ago the window high was | `new HighestBars(period)`, `.update(x)`, field `value` | how many bars ago the window's high sits, as `0` or a negative number (`0` = this bar, `-3` = three bars ago); `value` is the high itself | | how long ago the window low was | `new LowestBars(period)`, `.update(x)`, field `value` | the same offset for the window's low | | bars since a condition | `new BarsSince()`, `.update(cond)` | bars elapsed since `cond` was last true (`0` on that bar), `NaN` until it has been true once | | the value when a condition last held | `new ValueWhen(occurrence)`, `.update(cond, x)` | `x` on the `occurrence`-th most recent bar where `cond` was true (`0` = the latest, the current bar counts) | | a percentile over a window | `new Percentile(period, pct)`, `.update(x)` | the nearest-rank `pct`-th percentile over the window | | a median over a window | `new Median(period)`, `.update(x)` | the middle value (the mean of the two middle values on an even window) | | a correlation over a window | `new Correlation(period)`, `.update(a, b)` | the rolling Pearson correlation, -1..1 | | a window total | `new Sum(period)`, `.update(x)` | the sum of the last `period` values; no warm-up, bar 0 already returns the partial window | | a z-score over a window | `new Zscore(period)`, `.update(x)` | `(x - mean) / stdev` over the window; `0` when the deviation is exactly `0` | A condition is an `f64`: true means finite and not `0`, so a `0`/`1` series or a comparison cast with `? 1.0 : 0.0` both work. You feed the class the series it should scan, so `new Highest(20)` over `bar.high()` is the 20-bar high and a `Lowest(20)` over `bar.low()` is the 20-bar low. Among equal values the newest bar wins the offset. The `bars` fields are handy for "is the high in the window recent?" logic, and `BarsSince` counts up from the last time a condition fired, the natural cooldown and recency check. Construct the windowed ones in `onStart()` from a param and update each once per bar: ```typescript let highs = new Highest(20); let lows = new Lowest(20); let p80 = new Percentile(20, 80.0); let median = new Median(20); const rising = new Rising(3); // In onBar(): the return value is the extreme, the field is its offset. // const hi = highs.update(high); // highs.bars: 0 = this bar, -3 = three bars ago // const lo = lows.update(low); // const up = rising.update(close); // 1, 0, or NaN for the first 3 bars ``` Every windowed class here follows the strict window rule: `NaN` until `period` bars exist, and `NaN` whenever any value inside the window is not finite. `Percentile` keeps the window sorted and takes rank `ceil(pct * period / 100)` (1-based, the product first, `pct` clamped to 0..100); `Median` takes the middle of the same sorted window, averaging the two middle values on an even period; `Correlation` returns `NaN` when either side has no variance. None of them allocates after construction. `Sum` and `Zscore` are the two that skip a `NaN` bar instead of refusing the window (`Zscore` still divides its variance by `period`), and `Sum` has no warm-up at all: a 20-bar `Sum` draws from the first bar where a 20-bar `Stdev` draws from bar 19. ## Pivot confirmation `PivotHigh` and `PivotLow` are causal confirmation signals. A pivot only emits after `rightbars` later bars have closed, so the emitted value appears on the confirmation bar and lags the true pivot bar by `rightbars`. Nothing reads a future bar and no earlier bar repaints; an indicator could not do otherwise, because `onBar()` sees one bar. `new PivotHigh(leftbars, rightbars)` and `new PivotLow(leftbars, rightbars)` keep `left + right + 1` bars and, once the window is full, test the candidate `rightbars` back the way TradingView's `ta.pivothigh` and `ta.pivotlow` do (measured against TradingView's own output): a pivot high when none of the `leftbars` earlier values is higher and none of the `rightbars` later values is as high, so a tie with a bar on the left still counts and a tie on the right never does; a pivot low mirrors it. Each side is compared outward from the candidate, and a non-finite value ends that side's comparison; a non-finite candidate is no pivot. Either count may be `0`, as in Pine: `rightbars` 0 makes the current bar the candidate (`ta.pivothigh(high, 21, 0)` is `new PivotHigh(21, 0)`), and `leftbars` 0 compares the later bars only. `update(x)` returns the candidate's value on the confirmation bar only and `NaN` everywhere else. Feed `PivotHigh` the high and `PivotLow` the low. ```typescript const pivotHigh = new PivotHigh(2, 2); const pivotLow = new PivotLow(2, 2); const lastHigh = new Fixnan(); // In onBar(): a value on the confirmation bar, NaN between. // const confirmed = pivotHigh.update(bar.high()); // const level = lastHigh.update(confirmed); // the last confirmed pivot, carried forward ``` A confirmed pivot is a sparse series: one value on the confirmation bar, `NaN` between. To carry it forward into a continuous line, run it through `Fixnan` below. ## Handling missing values Warm-up is `NaN`, and any arithmetic touching `NaN` stays `NaN`. `isNaN` and `isFinite` are AssemblyScript builtins on `f64`; there is no separate missing-value type, so a missing value is `NaN` everywhere and these two are the whole vocabulary. The helpers are two lines each: | You want | wrun form | | --- | --- | | is the value missing | `isNaN(x)` | | is the value a real number | `isFinite(x)` (finite and not `NaN`) | | a replacement for a missing value | `nz(x, replacement)` below | | the last real value carried forward | `new Fixnan()`, `.update(x)`: carries the last finite value forward, `NaN` until the first one | ```typescript function nz(x: f64, replacement: f64): f64 { return isNaN(x) ? replacement : x; } const fixnan = new Fixnan(); // In onBar(): fixnan.update(sparse) repeats the last finite value across every NaN bar. ``` ## Every series function in one module A `sparse` series (forced `NaN` for the first 10 bars) drives the missing value helpers so you can see them flip; the rest run over real bars. The classes are the shipped ones from `./sdk/ta`. ```typescript param("fast", 5, { min: 1, max: 200 }); param("slow", 13, { min: 2, max: 400 }); param("window", 10, { min: 2, max: 200, description: "Window for the extremes, percentile, median, and correlation" }); output("crossover", line, lower, { color: "#2563eb", description: "1 on the bar the fast average crosses above the slow" }); output("crossunder", line, lower, { color: "#dc2626", description: "1 on the bar it crosses below" }); output("cross", line, lower, { color: "#7c3aed", description: "1 on either cross" }); output("rising", line, lower, { color: "#16a34a", description: "1 while the close is above its previous 3 values" }); output("falling", line, lower, { color: "#ea580c", description: "1 while the close is below its previous 3 values" }); output("barssince", line, lower, { color: "#0891b2", description: "Bars since the close was above the fast average" }); output("change", line, lower, { color: "#4b5563", description: "3-bar change" }); output("highest", line, lower, { color: "#0f766e", description: "Window highest high" }); output("lowest", line, lower, { color: "#be123c", description: "Window lowest low" }); output("highestbars", line, lower, { color: "#9333ea", description: "Offset of the window high (0 = this bar, negative = bars ago)" }); output("lowestbars", line, lower, { color: "#1d4ed8", description: "Offset of the window low" }); output("valuewhen", line, lower, { color: "#0e7490", description: "The close on the most recent bullish cross" }); output("percentile", line, lower, { color: "#b45309", description: "80th percentile of the close over the window" }); output("median", line, lower, { color: "#a16207", description: "Median close over the window" }); output("correlation", line, lower, { color: "#15803d", description: "Correlation between open and close over the window" }); output("nz", line, lower, { color: "#6d28d9", description: "nz over the sparse series, the open as the replacement" }); output("isna", line, lower, { color: "#0e7490", description: "1 while the sparse series is NaN" }); output("isnum", line, lower, { color: "#374151", description: "1 while the sparse series is a finite number" }); output("fixnan", line, lower, { color: "#3b82f6", description: "The sparse series with gaps carried forward" }); output("pivot_high", line, lower, { color: "#2563eb", description: "Confirmed 2/2 pivot highs, carried forward" }); output("pivot_low", line, lower, { color: "#dc2626", description: "Confirmed 2/2 pivot lows, carried forward" }); function nz(x: f64, replacement: f64): f64 { return isNaN(x) ? replacement : x; } let fast = new Sma(5); let slow = new Sma(13); const cross = new Cross(); const rising = new Rising(3); const falling = new Falling(3); const barsSince = new BarsSince(); const change = new Change(3); let highs = new Highest(10); let lows = new Lowest(10); const valueWhen = new ValueWhen(0); let percentile = new Percentile(10, 80.0); let median = new Median(10); let correlation = new Correlation(10); const fixnan = new Fixnan(); const pivotHigh = new PivotHigh(2, 2); const pivotLow = new PivotLow(2, 2); const stableHigh = new Fixnan(); const stableLow = new Fixnan(); let barIndex: i32 = 0; function onStart(): void { fast = new Sma(i32(p_fast())); slow = new Sma(i32(p_slow())); const window = i32(p_window()); highs = new Highest(window); lows = new Lowest(window); percentile = new Percentile(window, 80.0); median = new Median(window); correlation = new Correlation(window); } function onBar(): void { const close = bar.close(); const openValue = bar.open(); const f = fast.update(close); const s = slow.update(close); const crossed = cross.update(f, s); const risingValue = rising.update(close); const fallingValue = falling.update(close); const since = barsSince.update(!isNaN(f) && close > f ? 1.0 : 0.0); const changeValue = change.update(close); const highValue = highs.update(bar.high()); const lowValue = lows.update(bar.low()); const whenValue = valueWhen.update(crossed == 1 ? 1.0 : 0.0, close); const pctValue = percentile.update(close); const medianValue = median.update(close); const corrValue = correlation.update(openValue, close); const sparse = barIndex < 10 ? NaN : close; const fixed = fixnan.update(sparse); const pivotHighValue = stableHigh.update(pivotHigh.update(bar.high())); const pivotLowValue = stableLow.update(pivotLow.update(bar.low())); barIndex += 1; out_crossover(crossed == 1 ? 1.0 : 0.0); out_crossunder(crossed == -1 ? 1.0 : 0.0); out_cross(crossed != 0 ? 1.0 : 0.0); out_rising(risingValue); out_falling(fallingValue); out_barssince(since); out_change(changeValue); out_highest(highValue); out_lowest(lowValue); out_highestbars(highs.bars); out_lowestbars(lows.bars); out_valuewhen(whenValue); out_percentile(pctValue); out_median(medianValue); out_correlation(corrValue); out_nz(nz(sparse, openValue)); out_isna(isNaN(sparse) ? 1.0 : 0.0); out_isnum(isFinite(sparse) ? 1.0 : 0.0); out_fixnan(fixed); out_pivot_high(pivotHighValue); out_pivot_low(pivotLowValue); } ``` `barIndex` is state the module counts itself: there is no `barIndex` global, so it lives at module level with the rest of the state that spans bars. ## A Donchian breakout A 20-bar high and low channel as a `Highest` over the high and a `Lowest` over the low, with a gated mark on the bar that closes above the channel. The gate is a data-only output, and the `shape` output draws only where it is nonzero. ```typescript param("period", 20, { min: 2, max: 400, description: "Channel lookback" }); output("hi", line, overlay, { color: "#16a34a", width: 1, description: "Upper Donchian band" }); output("lo", line, overlay, { color: "#dc2626", width: 1, description: "Lower Donchian band" }); output("breakout_mark", shape, overlay, { color: "#16a34a", shape_where: "breakout", description: "The close on a breakout bar" }); output("breakout", none, overlay, { description: "1 when the close is above the previous bar's upper band" }); let highs = new Highest(20); let lows = new Lowest(20); let prevHi: f64 = NaN; function onStart(): void { highs = new Highest(i32(p_period())); lows = new Lowest(i32(p_period())); } function onBar(): void { const close = bar.close(); // Test against the channel as it stood BEFORE this bar, so the bar cannot break its own high. const breakout = !isNaN(prevHi) && close > prevHi ? 1.0 : 0.0; const hi = highs.update(bar.high()); const lo = lows.update(bar.low()); prevHi = hi; if (isNaN(hi)) return; out_hi(hi); out_lo(lo); out_breakout_mark(close); out_breakout(breakout); } ``` ## Window statistics, a channel, and a cross The window statistics (`Highest`, `Lowest`, `Sum`, `Stdev`), a `Donchian` channel, a `Cross` over two averages, and an `isFinite` gate in one module. `Stdev` and `Donchian` are explained with their families, on [Trend and volatility](trend-indicators.md#volatility-primitives) and [Moving averages](moving-averages.md#donchian). ```typescript param("period", 20, { min: 2, max: 400 }); output("low20", line, overlay, { color: "#dc2626", width: 1, description: "Lowest low over the period" }); output("high20", line, overlay, { color: "#16a34a", width: 1, description: "Highest high over the period" }); output("donchian_mid", line, overlay, { color: "#94a3b8", width: 1, description: "Donchian midpoint" }); output("volume_sum", line, lower, { color: "#0891b2", description: "Volume summed over the period" }); output("volatility", line, lower, { color: "#7c3aed", description: "Standard deviation of the close" }); output("bullish", none, lower, { description: "1 on the bar the fast average crosses above the slow" }); output("bearish", none, lower, { description: "1 on the bar it crosses below" }); output("any_cross", none, lower, { description: "1 on either" }); output("valid", none, lower, { description: "1 when every input on the bar is a finite number" }); let highs = new Highest(20); let lows = new Lowest(20); let volumeSum = new Sum(20); let stdev = new Stdev(20); let donchian = new Donchian(20); let fast = new Sma(5); let slow = new Sma(20); const cross = new Cross(); function onStart(): void { const period = i32(p_period()); highs = new Highest(period); lows = new Lowest(period); volumeSum = new Sum(period); stdev = new Stdev(period); donchian = new Donchian(period); fast = new Sma(5); slow = new Sma(period); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const volume = bar.volume(); const valid = isFinite(close) && isFinite(high) && isFinite(low) && isFinite(volume) ? 1.0 : 0.0; const highValue = highs.update(high); const lowValue = lows.update(low); const sumValue = volumeSum.update(volume); const volatility = stdev.update(close); donchian.update(high, low); const crossed = cross.update(fast.update(close), slow.update(close)); out_low20(lowValue); out_high20(highValue); out_donchian_mid(donchian.basis); out_volume_sum(sumValue); out_volatility(volatility); out_bullish(crossed == 1 ? 1.0 : 0.0); out_bearish(crossed == -1 ? 1.0 : 0.0); out_any_cross(crossed != 0 ? 1.0 : 0.0); out_valid(valid); } ``` ## Warm-up and the missing-value window Windowed functions cannot produce a value until they have seen enough bars: a 20-bar `Percentile` or `Correlation` returns `NaN` until 20 bars exist, just as a 20-bar `Sma` does. When the underlying series is itself `NaN` for a stretch, the warm-up shifts forward by the same amount, because the windowed classes refuse a window with a `NaN` inside it. `Fixnan` shows the recovery: it produces its first real value the moment the source has one, then holds it across every gap. Feed the `sparse` series from the tour into a 5-bar `Percentile` and the `percentile` output stays `NaN` through bar 14, not bar 4. ## Practices that carry over - **Lookback periods.** Choose them for the interval you trade: short windows for scalping and lower timeframes, longer ones for swing context. Declare the range on the param (`min`, `max`) and size buffers from `max` so the module never allocates per bar. - **One object per statistic.** Compute a statistic once per bar and reuse the return value or field rather than constructing a second object over the same series. - **Cross detection.** Combine a cross with a trend read (`Adx`, a slope, a higher-timeframe fold) before treating it as a signal; in a chop the cross flips every few bars. - **Donchian channels.** Breakout logic in trends, support and resistance in ranges: the same two outputs, different rules on top. - **Data validation.** Check `isFinite` before a division, and write `NaN` rather than a made-up number when a value has no answer; a `NaN` draws nothing and never trips an alert. # Extra indicators The [TA library](ta-library.md) is the core catalog of 52 classes. The `./sdk/ta-plus` module adds 30 more with the same shape: construct the class in `onStart()`, call `update()` once per bar. Twenty-six are textbook indicators the catalog never had; four are Pine's own spellings of classes the library has in another shape. The 26 are the mean and percent-rank deviations, Bollinger and Keltner widths, the volume lines (accumulation and distribution, the Williams pair, the volume indices, price-volume trend, intraday intensity), the running extremes, mode, range and centre of gravity, the double and triple EMAs, the zero-lag EMA, TRIX, Kaufman's efficiency ratio and adaptive average, the ultimate oscillator, Vortex, Aroon and choppiness. The four are `Dmi` with its two lengths, `SourceStoch` and `SourceVwap` over any source series, and `HeikinAshi`. Every class composes the library's own primitives and follows its three rules: `NaN` until the class is warm, `NaN` while a non-finite input sits in its window (the two volume indices carry instead), and no allocation after the constructor. The window arithmetic under them (`History`, `List`, the `stats.*` functions, rounding and a seeded random) is on [Stats, history and lists](stats-history-lists.md). ## Every class in `./sdk/ta-plus` `update()` returns the primary stream; the extra streams are public fields you read after the call. "First value" is the bar index of the first non-`NaN` result on a clean series (bar 0 is the first bar). Periods below 1 are clamped to 1. | Class | Construct | `update(...)` | Fields | Definition | First value | | --- | --- | --- | --- | --- | --- | | `Dev` | `(period)` | `(x)` | | mean absolute deviation of the last `period` values from their `Sma`: `sum(abs(x - sma)) / period` | bar `period - 1` | | `PercentRank` | `(period)` | `(x)` | | `100 * count(previous period values <= x) / period`, the current bar excluded from the count | bar `period` | | `Bbw` | `(period, mult)` | `(x)` | `basis`, `upper`, `lower` | `(upper - lower) / basis` over `Bb(period, mult)`; `NaN` when the basis is 0 | bar `period - 1` | | `Kcw` | `(period, mult, atrPeriod)` | `(x, high, low, close)` | `basis`, `upper`, `lower` | `(upper - lower) / basis` over `Keltner(period, mult, atrPeriod)`; `NaN` when the basis is 0 | bar `max(period, atrPeriod) - 1` | | `AccDist` | `()` | `(high, low, close, volume)` | | running sum of `((2 * close - high - low) / (high - low)) * volume`, the term 0 when `high == low` | bar 0 | | `Wad` | `()` | `(high, low, close)` | | running sum of: `close - min(low, prevClose)` when the close rose, `close - max(high, prevClose)` when it fell, else 0; bar 0 returns 0 | bar 0 | | `Wvad` | `()` | `(open, high, low, close, volume)` | | `((close - open) / (high - low)) * volume` for this bar, never a running sum; `NaN` when `high == low` | bar 0 | | `Nvi` | `()` | `(close, volume)` | | starts at 1; when `volume < prevVolume`: `nvi = prev + ((close - prevClose) / prevClose) * prev`, else `prev`; a close of 0 or `NaN`, on this bar or the previous one, keeps `prev` | bar 0 | | `Pvi` | `()` | `(close, volume)` | | the same with `volume > prevVolume` | bar 0 | | `Pvt` | `()` | `(close, volume)` | | running sum of `((close - prevClose) / prevClose) * volume`; bar 0 returns 0 | bar 0 | | `RunningMax` | `()` | `(x)` | | the largest finite `x` seen so far (a non-finite `x` is skipped) | the first finite bar | | `RunningMin` | `()` | `(x)` | | the smallest finite `x` seen so far (a non-finite `x` is skipped) | the first finite bar | | `Mode` | `(period)` | `(x)` | | the most frequent value of the window (exact equality); ties go to the smallest | bar `period - 1` | | `Range` | `(period)` | `(x)` | | `Highest - Lowest` of the last `period` values | bar `period - 1` | | `Cog` | `(period)` | `(x)` | | `-(sum of x[i] * (i + 1)) / sum(x[i])` for `i = 0` (the newest) to `period - 1`; `NaN` when the sum is 0 | bar `period - 1` | | `Iii` | `()` | `(high, low, close, volume)` | | `(2 * close - high - low) / ((high - low) * volume)` for this bar; `NaN` when the denominator is 0 | bar 0 | | `Dema` | `(period)` | `(x)` | | `2 * e1 - e2`, `e1 = Ema(period)` of `x`, `e2 = Ema(period)` of `e1` | bar `2 * period - 2` | | `Tema` | `(period)` | `(x)` | | `3 * e1 - 3 * e2 + e3` | bar `3 * period - 3` | | `Zlema` | `(period)` | `(x)` | | `Ema(period)` of `x + (x - x[lag])`, `lag = floor((period - 1) / 2)` | bar `lag + period - 1` | | `Trix` | `(period)` | `(x)` | | `10000 *` the one-bar change of `Ema(Ema(Ema(ln x)))`; `NaN` when `x <= 0` | bar `3 * period - 2` | | `Ultimate` | `(p1 = 7, p2 = 14, p3 = 28)` | `(high, low, close)` | | `BP = close - min(low, prevClose)`, `TR = max(high, prevClose) - min(low, prevClose)`, `avg_n = Sum(BP, n) / Sum(TR, n)`, result `100 * (4 * avg1 + 2 * avg2 + avg3) / 7` | bar `p3` | | `Vortex` | `(period)` | `(high, low, close)` | `plus`, `minus` | `VM+ = abs(high - prevLow)`, `VM- = abs(low - prevHigh)`; `plus = Sum(VM+) / Sum(TR)`, `minus = Sum(VM-) / Sum(TR)` over `period`; returns `plus` | bar `period` | | `Aroon` | `(period)` | `(high, low)` | `up`, `down`, `osc` | `up = 100 * (Highest(period + 1).bars + period) / period`, `down` likewise with `Lowest`, `osc = up - down`; returns `osc` | bar `period` | | `Choppiness` | `(period)` | `(high, low, close)` | | `100 * log10(Sum(TR, period) / (Highest(high, period) - Lowest(low, period))) / log10(period)`; `NaN` when the range is 0 | bar `period - 1` | | `Efficiency` | `(period)` | `(x)` | | `abs(x - x[period]) / Sum(abs(x - x[1]), period)`; `NaN` when the sum is 0 | bar `period` | | `Kama` | `(period, fast = 2, slow = 30)` | `(x)` | | `sc = (er * (2 / (fast + 1) - 2 / (slow + 1)) + 2 / (slow + 1))^2` with `er = Efficiency(period)`; `kama = prev + sc * (x - prev)`, seeded with `x` on the first bar `er` exists | bar `period` | | `Dmi` | `(diLength, adxSmoothing)` | `(high, low, close)` | `adx`, `plusDi`, `minusDi` | Pine's `ta.dmi`: `+DI = 100 * Rma(+DM, diLength) / Rma(TR, diLength)`, `-DI` likewise, `DX = abs(+DI - -DI) / (+DI + -DI)` (over 1 when the sum is 0), `adx = 100 * Rma(DX, adxSmoothing)`; a zero smoothed range holds `+DI` and `-DI` (Pine's `fixnan`); a missing bar is skipped the way TradingView skips it (see below); `+DM` beats `-DM` only by more than `1e-10`, Pine's float tolerance, as `ta.dmi` does; equal lengths give the library's `Adx` on a series without a hole, except where the two moves are `1e-10` apart or less (`Adx` compares exactly); returns `adx` | `plusDi`, `minusDi` at bar `diLength`; `adx` at bar `diLength + adxSmoothing - 1` | | `SourceStoch` | `(periodK, smoothK = 1, periodD = 1)` | `(source, high, low)` | `k`, `d` | Pine's `ta.stoch(source, high, low, length)`: raw %K is `100 * (source - Lowest(low)) / (Highest(high) - Lowest(low))` over `periodK`, `k = Sma(smoothK)` of it, `d = Sma(periodD)` of `k`; a flat window follows TradingView (the previous raw %K when the source sits on the window's value, `NaN` otherwise) where the library's `Stoch` reads 0, so fed the close it is `Stoch` on every window with a range; returns `k` | `k` at bar `periodK + smoothK - 2`, `d` at bar `periodK + smoothK + periodD - 3` | | `SourceVwap` | `(anchor = "")` | `(source, volume, tsMs = NaN)` | | Pine's `ta.vwap(source)`: the library's `Vwap` sums, `sum(source * volume) / sum(volume)` from the anchor (`""`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"` or a bucket width in milliseconds; `tsMs` is `bar.time() * 1000.0`, read only with an anchor), over any source; fed `(high + low + close) / 3` it is `Vwap(anchor, "hlc3")` | bar 0 | | `HeikinAshi` | `()` | `(open, high, low, close)` | `open`, `high`, `low`, `close` | Pine's `ticker.heikinashi`: `close = (open + high + low + close) / 4`, `open = (previous ha open + previous ha close) / 2` (the bar's own `(open + close) / 2` on the first bar), `high = max(high, ha open, ha close)`, `low = min(low, ha open, ha close)`; returns the smoothed close | bar 0 | A non-finite input (`NaN` or infinite) is handled by shape. A windowed class (`Dev`, `PercentRank`, `Bbw`, `Mode`, `Range`, `Cog`, `Ultimate`, `Vortex`, `Aroon`, `Choppiness`, `Efficiency`, `SourceStoch`) returns `NaN` while the bad bar sits inside its window and heals when it leaves; the running sums (`AccDist`, `Wad`, `Pvt`) stay `NaN` until `reset()`; the per-bar readings (`Wvad`, `Iii`) are `NaN` on that bar alone; the classes built on `Ema` (`Dema`, `Tema`, `Zlema`, `Trix`, and `Kcw` through `Keltner`) follow the `Ema` rule, TradingView's `ta.ema`: a bad bar reads `NaN`, a seed skips it, and the next finite value continues from the state it had. `Dmi` keeps TradingView's own rule for `ta.dmi` instead: `ta.rma` skips a na bar with its state untouched, `ta.tr` and the two changes are na on that bar and on the next one, so each smoother is fed only when its own input is a value, `fixnan` holds `plusDi` and `minusDi` meanwhile, `adx` keeps smoothing the DX of the held values, and two bars after the hole every stream continues from the state it had (the library's `Adx` goes `NaN` for good there). `Kama` re-seeds with the next `x` once its efficiency window is clean again, the running extremes skip the bar, and `Nvi` and `Pvi` never turn `NaN`: they carry their value across a bar whose close, or previous close, is 0 or not a number. `SourceVwap` keeps the `Vwap` rule (the current bucket is `NaN` until the next one starts), and `HeikinAshi` reads `NaN` on the bad bar and restarts its chain on the next finite one, seeding the open as the first bar does. ## Deviation, rank and width Seven classes read one series. `Dev` and `PercentRank` say how far and how high the newest value sits in its window; `Bbw` and `Kcw` are the band widths as one number, with the bands in fields; `Range`, `Mode` and `Cog` are the window's shape. ```typescript param("period", 20, { min: 2, max: 400, description: "Window for every class" }); param("mult", 2, { min: 0.5, max: 5, description: "Band multiplier" }); output("dev", line, lower, { color: "#2563eb", description: "Mean absolute deviation of the close" }); output("prank", line, lower, { color: "#7c3aed", description: "Percent rank of the close" }); output("bbw", line, lower, { color: "#16a34a", description: "Bollinger band width" }); output("bb_upper", line, lower, { color: "#15803d", description: "Upper Bollinger band" }); output("kcw", line, lower, { color: "#ea580c", description: "Keltner channel width" }); output("range", line, lower, { color: "#0891b2", description: "Highest minus lowest close" }); output("mode", line, lower, { color: "#4b5563", description: "Most frequent close" }); output("cog", line, lower, { color: "#be123c", description: "Centre of gravity" }); let dev = new Dev(20); let prank = new PercentRank(20); let bbw = new Bbw(20, 2.0); let kcw = new Kcw(20, 2.0, 10); let closeRange = new Range(20); let mode = new Mode(20); let cog = new Cog(20); function onStart(): void { const period = i32(p_period()); dev = new Dev(period); prank = new PercentRank(period); bbw = new Bbw(period, p_mult()); kcw = new Kcw(period, p_mult(), period / 2); closeRange = new Range(period); mode = new Mode(period); cog = new Cog(period); } function onBar(): void { const close = bar.close(); const devValue = dev.update(close); const prankValue = prank.update(close); const bbwValue = bbw.update(close); const kcwValue = kcw.update(close, bar.high(), bar.low(), close); const rangeValue = closeRange.update(close); const modeValue = mode.update(close); const cogValue = cog.update(close); if (isNaN(devValue)) return; out_dev(devValue); out_prank(prankValue); out_bbw(bbwValue); out_bb_upper(bbw.upper); out_kcw(kcwValue); out_range(rangeValue); out_mode(modeValue); out_cog(cogValue); } ``` `PercentRank` counts the previous `period` values, never the current bar, so its first value lands one bar after `Dev`'s: `onBar()` gates on `Dev` and the first ready row draws a gap for the rank. `Kcw` reports its `basis` once the EMA is seeded and the width once the ATR is warm too. ## Volume and money flow `AccDist`, `Wad` and `Pvt` are running sums: the line so far, from the first bar. `Nvi` and `Pvi` are indices that start at 1 and move only on a bar whose volume fell (`Nvi`) or rose (`Pvi`). `Wvad` and `Iii` are per-bar readings with no memory; for a running line feed one to the library's `Cum`, as the sample does for `Wvad`. ```typescript input("open", ohlcv.open); output("accdist", line, lower, { color: "#2563eb", description: "Accumulation/distribution line" }); output("wad", line, lower, { color: "#7c3aed", description: "Williams accumulation/distribution" }); output("wvad", line, lower, { color: "#16a34a", description: "Williams variable A/D of this bar" }); output("wvad_line", line, lower, { color: "#65a30d", description: "Running total of wvad" }); output("nvi", line, lower, { color: "#dc2626", description: "Negative volume index, from 1" }); output("pvi", line, lower, { color: "#ea580c", description: "Positive volume index, from 1" }); output("pvt", line, lower, { color: "#0891b2", description: "Price-volume trend" }); output("iii", line, lower, { color: "#4b5563", description: "Intraday intensity of this bar" }); output("running_max", line, lower, { color: "#15803d", description: "Highest close so far" }); output("running_min", line, lower, { color: "#be123c", description: "Lowest close so far" }); let accdist = new AccDist(); let wad = new Wad(); let wvad = new Wvad(); let wvadLine = new Cum(); let nvi = new Nvi(); let pvi = new Pvi(); let pvt = new Pvt(); let iii = new Iii(); let runningMax = new RunningMax(); let runningMin = new RunningMin(); function onStart(): void { accdist = new AccDist(); wad = new Wad(); wvad = new Wvad(); wvadLine = new Cum(); nvi = new Nvi(); pvi = new Pvi(); pvt = new Pvt(); iii = new Iii(); runningMax = new RunningMax(); runningMin = new RunningMin(); } function onBar(): void { const open = bar.open(); const high = bar.high(); const low = bar.low(); const close = bar.close(); const volume = bar.volume(); const accdistValue = accdist.update(high, low, close, volume); const wadValue = wad.update(high, low, close); const wvadValue = wvad.update(open, high, low, close, volume); // A flat bar has no reading: add 0, Cum keeps a NaN. const wvadTotal = wvadLine.update(isNaN(wvadValue) ? 0.0 : wvadValue); const nviValue = nvi.update(close, volume); const pviValue = pvi.update(close, volume); const pvtValue = pvt.update(close, volume); const iiiValue = iii.update(high, low, close, volume); const maxValue = runningMax.update(close); const minValue = runningMin.update(close); if (isNaN(accdistValue)) return; out_accdist(accdistValue); out_wad(wadValue); out_wvad(wvadValue); out_wvad_line(wvadTotal); out_nvi(nviValue); out_pvi(pviValue); out_pvt(pvtValue); out_iii(iiiValue); out_running_max(maxValue); out_running_min(minValue); } ``` A running line depends on where the history starts: the chart feeds the module the bars it fetched, so the newest bar's value moves when that window does. Read `AccDist`, `Wad`, `Pvt` and the two indices as shapes, not as levels to alert on. ## Smoothers on the EMA `Dema`, `Tema` and `Zlema` stack the library's `Ema`; `Trix` stacks three of them over the logarithm of the price and reads the one-bar change; `Efficiency` and `Kama` are Kaufman's pair, the ratio of net move to total move and the average whose smoothing follows it. ```typescript param("period", 20, { min: 2, max: 400 }); param("fast", 2, { min: 1, max: 100, description: "Kama fast length" }); param("slow", 30, { min: 1, max: 400, description: "Kama slow length" }); output("dema", line, overlay, { color: "#2563eb", description: "Double EMA" }); output("tema", line, overlay, { color: "#7c3aed", description: "Triple EMA" }); output("zlema", line, overlay, { color: "#16a34a", description: "Zero-lag EMA" }); output("kama", line, overlay, { color: "#ea580c", width: 2, description: "Kaufman adaptive average" }); output("trix", line, lower, { color: "#dc2626", description: "TRIX" }); output("efficiency", line, lower, { color: "#0891b2", description: "Efficiency ratio, 0..1" }); let dema = new Dema(20); let tema = new Tema(20); let zlema = new Zlema(20); let trix = new Trix(20); let efficiency = new Efficiency(20); let kama = new Kama(20, 2, 30); function onStart(): void { const period = i32(p_period()); dema = new Dema(period); tema = new Tema(period); zlema = new Zlema(period); trix = new Trix(period); efficiency = new Efficiency(period); kama = new Kama(period, i32(p_fast()), i32(p_slow())); } function onBar(): void { const close = bar.close(); const demaValue = dema.update(close); const temaValue = tema.update(close); const zlemaValue = zlema.update(close); const trixValue = trix.update(close); const erValue = efficiency.update(close); const kamaValue = kama.update(close); if (isNaN(kamaValue)) return; out_dema(demaValue); out_tema(temaValue); out_zlema(zlemaValue); out_kama(kamaValue); out_trix(trixValue); out_efficiency(erValue); } ``` The warm-ups differ: `Kama` has its first value at bar `period` while `Tema(20)` waits until bar 57 and `Trix(20)` until bar 58. Gate readiness on the line you plot as primary, not on the slowest class. ## Two oscillators `Ultimate` blends buying pressure over three windows; `Vortex` reads the two movement sums against the true range and exposes both lines. ```typescript param("period", 14, { min: 2, max: 400, description: "Vortex window" }); input("high", ohlcv.high); output("ultimate", line, lower, { color: "#2563eb", description: "Ultimate oscillator (7, 14, 28)" }); output("vortex_plus", line, lower, { color: "#16a34a", description: "VI+" }); output("vortex_minus", line, lower, { color: "#dc2626", description: "VI-" }); let ultimate = new Ultimate(7, 14, 28); let vortex = new Vortex(14); function onStart(): void { ultimate = new Ultimate(7, 14, 28); vortex = new Vortex(i32(p_period())); } function onBar(): void { const high = bar.high(); const low = bar.low(); const close = bar.close(); const ultimateValue = ultimate.update(high, low, close); const plus = vortex.update(high, low, close); const minus = vortex.minus; if (isNaN(plus)) return; out_ultimate(ultimateValue); out_vortex_plus(plus); out_vortex_minus(minus); } ``` ## A regime from Aroon and choppiness `Aroon` says which way the recent extreme sits, `Choppiness` says whether the window went anywhere at all. Together they make a three-way regime: trending up, trending down, or ranging. The regime is a data-only output that tints a shape through `color_by` ([Colors](colors-kit.md)). ```typescript param("period", 25, { min: 2, max: 400, description: "Aroon and choppiness window" }); param("chop_ceiling", 61.8, { min: 0, max: 100, description: "Choppiness above this reads as ranging" }); input("high", ohlcv.high); output("aroon_up", line, lower, { color: "#16a34a", description: "Aroon up" }); output("aroon_down", line, lower, { color: "#dc2626", description: "Aroon down" }); output("chop", line, lower, { color: "#4b5563", description: "Choppiness index, 0..100" }); output("regime", none, overlay, { description: "0 ranging, 1 trending up, 2 trending down" }); output("regime_mark", shape, overlay, { color: "#94a3b8", color_by: "regime", colors: ["#94a3b8", "#16a34a", "#dc2626"], description: "The close, tinted by regime", }); let aroon = new Aroon(25); let chop = new Choppiness(25); let chopCeiling: f64 = 61.8; function onStart(): void { const period = i32(p_period()); aroon = new Aroon(period); chop = new Choppiness(period); chopCeiling = p_chop_ceiling(); } function onBar(): void { const high = bar.high(); const low = bar.low(); const close = bar.close(); const osc = aroon.update(high, low); const chopValue = chop.update(high, low, close); if (isNaN(osc) || isNaN(chopValue)) return; let regime: f64 = 0.0; if (chopValue > chopCeiling) regime = 0.0; else regime = osc > 0.0 ? 1.0 : 2.0; out_aroon_up(aroon.up); out_aroon_down(aroon.down); out_chop(chopValue); out_regime(regime); out_regime_mark(close); } ``` `Aroon` runs a `Highest` and a `Lowest` over `period + 1` bars and reads their `bars` offsets, so `up` is 100 on the bar of a fresh high and falls by `100 / period` on every bar the high ages; `Choppiness` is the log ratio of the true-range sum to the window's range, near 100 when the bars overlap and near 0 when they march in one direction. `onBar()` returns before writing until both are warm: `Aroon` needs `period + 1` bars, `Choppiness` needs `period`. ## Pine's spellings of four library classes The library's `Adx`, `Stoch` and `Vwap` are the engine's forms: one length, the close as the source, a named bar price. Four classes here carry the Pine spellings a ported script writes. `Dmi(diLength, adxSmoothing)` is `ta.dmi` with its two lengths (`+DI` and `-DI` smoothed over `diLength`, ADX over `adxSmoothing`, both with the library's `Rma`); with equal lengths it is `Adx` to the last bit of the arithmetic, except where the up and down moves differ by `1e-10` or less: `Dmi` reads them as equal, as TradingView's `ta.dmi` does, and `Adx` compares them exactly. Across a missing bar it keeps TradingView's state rules (nothing restarts, nothing is poisoned). `SourceStoch` is `ta.stoch(source, high, low, length)` over any source, smoothed like `Stoch`; fed the close it is `Stoch` on every window with a range (a flat window follows TradingView: the previous raw %K when the source sits on the window's value, `NaN` otherwise, where `Stoch` reads 0). `SourceVwap` is `ta.vwap(source)` over any source with `Vwap`'s anchors; fed `(high + low + close) / 3` it is `Vwap(anchor, "hlc3")`. `HeikinAshi` is `ticker.heikinashi` as a class over the bars you feed it (this chart's, or another market's candles); the recursion forgets its start by half every bar, so after about 50 bars the values no longer depend on where the loaded history begins. ```typescript param("di_length", 14, { min: 1, max: 200 }); param("adx_smoothing", 7, { min: 1, max: 200 }); param("stoch_length", 14, { min: 1, max: 200 }); output("adx", line, lower, { color: "#111827", description: "ADX over its own smoothing" }); output("plus_di", line, lower, { color: "#16a34a", description: "+DI" }); output("minus_di", line, lower, { color: "#dc2626", description: "-DI" }); output("stoch_hl2", line, lower, { color: "#2563eb", description: "Stochastic of the bar midpoint" }); output("vwap_ohlc4", line, overlay, { color: "#f59e0b", description: "Session VWAP over ohlc4" }); output("ha_close", line, overlay, { color: "#7c3aed", description: "Heikin Ashi close" }); let dmi = new Dmi(14, 7); let stoch = new SourceStoch(14); const vwap = new SourceVwap("day"); const ha = new HeikinAshi(); function onStart(): void { dmi = new Dmi(i32(p_di_length()), i32(p_adx_smoothing())); stoch = new SourceStoch(i32(p_stoch_length())); } function onBar(): void { const o = bar.open(); const h = bar.high(); const l = bar.low(); const c = bar.close(); const adx = dmi.update(h, l, c); const k = stoch.update((h + l) / 2.0, h, l); const vwapValue = vwap.update((o + h + l + c) / 4.0, bar.volume(), bar.time() * 1000.0); const haClose = ha.update(o, h, l, c); if (isNaN(adx)) return; out_adx(adx); out_plus_di(dmi.plusDi); out_minus_di(dmi.minusDi); out_stoch_hl2(k); out_vwap_ohlc4(vwapValue); out_ha_close(haClose); } ``` `Dmi` warms up last (`diLength + adxSmoothing - 1` bars), so the sample gates on it. `SourceStoch(length)` is the raw %K; pass `smoothK` and `periodD` for the `ta.sma` smoothing a Pine script applies afterwards. `SourceVwap` takes the bar's open time like `Vwap`, `bar.time()` in seconds as it comes or the time in milliseconds ([Volume and VWAP](volume-indicators.md#vwap)); `HeikinAshi` exposes the four smoothed values as fields, read after `update()`. ## History and lists `History` (Pine's `close[1]` as `history.ago(1)`), `List`, the `stats.*` window functions, `HandleRing`, `roundTo`, `roundToTick` and `Random` have their own page: [Stats, history and lists](stats-history-lists.md). ## From Pine One to one: the class returns Pine's value on the same bars. The second table holds the three that share Pine's formula with one difference. The `array.*`, `x[n]`, `math.round` and `math.random` rows are on [Stats, history and lists](stats-history-lists.md#from-pine). | Pine | Extra indicators | | --- | --- | | `ta.dev(source, length)` | `new Dev(length)`, `.update(x)` | | `ta.percentrank(source, length)` | `new PercentRank(length)`, `.update(x)` | | `ta.bbw(source, length, mult)` | `new Bbw(length, mult)`, `.update(x)` | | `ta.accdist` | `new AccDist()`, `.update(high, low, close, volume)` | | `ta.wad` | `new Wad()`, `.update(high, low, close)` | | `ta.wvad` | `new Wvad()`, `.update(open, high, low, close, volume)` | | `ta.nvi` | `new Nvi()`, `.update(close, volume)` | | `ta.pvi` | `new Pvi()`, `.update(close, volume)` | | `ta.max(source)` | `new RunningMax()`, `.update(x)` | | `ta.min(source)` | `new RunningMin()`, `.update(x)` | | `ta.mode(source, length)` | `new Mode(length)`, `.update(x)` | | `ta.range(source, length)` | `new Range(length)`, `.update(x)` | | `ta.cog(source, length)` | `new Cog(length)`, `.update(x)` | | `ta.iii` | `new Iii()`, `.update(high, low, close, volume)` | | Pine | Extra indicators | The difference | | --- | --- | --- | | `ta.stoch(source, high, low, length)` with a `na` source, high or low | `new SourceStoch(length)`, `.update(source, high, low)` | TradingView carries the previous %K over a bar whose input is `na`; here the class reads `NaN` while that bar sits in its windows (the library's windowed rule) and heals when it leaves | | `ta.pvt` | `new Pvt()`, `.update(close, volume)` | the same line from the second bar on; the first bar, with no previous close, reads 0 here | | `ta.kcw(source, length, mult, true)` | `new Kcw(length, mult, length)`, `.update(x, high, low, close)` | the range average is the library's Wilder `Atr`; Pine's is an EMA of the true range, so the widths track each other without being equal | # Stats, history and lists The `./sdk/stats` module is the window arithmetic under the [TA library](ta-library.md) and the [extra indicators](extra-indicators.md). It holds a `stats` namespace of allocation-free functions over a `StaticArray` you fill yourself, a `History` that keeps the last `n` values of a series so Pine's `close[1]` becomes `history.ago(1)`, a fixed-capacity `List` for Pine's `array.*` idiom, a `HandleRing` that keeps the newest N drawing ids so the oldest line can be deleted, `roundTo` for `math.round(x, n)`, `roundToTick` for `math.round_to_mintick(x)` and a seeded `Random` for `math.random(min, max, seed)`. Everything here composes the library's own primitives, so a window mean is the library's `Sma` to the last bit, and the library's rules hold: `NaN` until a class is warm, `NaN` while a non-finite entry sits in its window, and no allocation after the constructor. ## Which one | Need | Reach for | | --- | --- | | The previous bar's value of a series you compute, Pine's `x[n]` | `History`: `push()` first in `onBar()`, then read `ago(n)` | | Entries that come and go on their own schedule, by index, Pine's `array.*` | `List`, with its capacity declared in `onStart()` | | Several readings over one window you fill yourself | the `stats.*` functions over a `StaticArray` and a count | | The ids of the newest N drawings, so the oldest can be deleted | `HandleRing` | | `math.round(x, n)`, `math.round_to_mintick(x)`, `math.random(min, max, seed)` | `roundTo`, `roundToTick`, `Random` | ## Window arithmetic: `stats` `stats` is a namespace of functions over the first `n` entries of a `StaticArray` you own. Nothing here allocates: you size the array in `onStart()`, fill it as bars arrive, and hand the count you filled. A count above the array's length reads the whole array; a count below 1 reads nothing. A non-finite entry among the first `n` makes the result `NaN`, except in `min`, `max`, `argmin` and `argmax`, which skip it. | Function | Returns | | --- | --- | | `stats.sum(a, n)` | the entries added index 0 first; 0 when `n < 1` | | `stats.mean(a, n)` | `sum / n`; `NaN` when `n < 1` | | `stats.variance(a, n)` | the population variance (divide by `n`, the library's `Variance`) | | `stats.stdev(a, n)` | `sqrt(variance)` | | `stats.min(a, n)` | the smallest finite entry; `NaN` when none is finite | | `stats.max(a, n)` | the largest finite entry; `NaN` when none is finite | | `stats.argmin(a, n)` | the index of the smallest finite entry (the lowest index on a tie); `-1` when none | | `stats.argmax(a, n)` | the index of the largest finite entry (the lowest index on a tie); `-1` when none | | `stats.slope(a, n)` | the least-squares slope against the index `0..n-1`, in value per entry; `NaN` when `n < 2` | | `stats.covariance(a, b, n)` | the population covariance of the two arrays' first `n` entries | | `stats.correlation(a, b, n)` | the Pearson correlation, `-1..1`; `NaN` when either side has no variance | | `stats.zscore(x, a, n)` | `(x - mean) / stdev`; 0 when the standard deviation is 0 (the library's `Zscore`) | | `stats.sortAscending(a, n)` | sorts the first `n` entries in place, ascending, `NaN` entries last | | `stats.median(a, n, scratch)` | the middle of the sorted entries (the mean of the two middle ones on an even `n`); copies into `scratch` and sorts there, so `a` keeps its order | | `stats.percentile(a, n, pct, scratch)` | the nearest-rank percentile, `pct` in `0..100`: rank `ceil(pct * n / 100)`, entry `rank - 1` of the sorted copy (the library's `Percentile`) | | `stats.percentileLinearInterpolation(a, n, pct, scratch)` | the percentile by linear interpolation between the two nearest ranks, `pct` in `0..100`: TradingView's position `k = pct * n / 100 - 0.5` over the sorted copy, `sorted[floor(k)]` plus the fraction of the way to `sorted[floor(k) + 1]`, the smallest entry at or below `k = 0` and the largest at or above `k = n - 1` (so `array.from(3, 1, 8, 5)` reads `1, 1, 2, 3.2, 4, 5, 6.5, 8, 8` at `0, 10, 25, 40, 50, 62.5, 75, 90, 100`, the values captured on TradingView); the result need not be an entry (Pine's `array.percentile_linear_interpolation` and `ta.percentile_linear_interpolation`) | `scratch` is a second array of at least `n` you allocate once beside the first; `median` and the two percentiles copy into it and sort it, and return `NaN` when it is too small. The fence keeps a sliding window of the last `period` closes and volumes, oldest first, and reads it every bar. ```typescript param("period", 50, { min: 2, max: 400, description: "Bars in the window" }); output("mean", line, lower, { color: "#2563eb", description: "Mean close" }); output("stdev", line, lower, { color: "#7c3aed", description: "Standard deviation" }); output("slope", line, lower, { color: "#16a34a", description: "Least-squares slope, price per bar" }); output("correlation", line, lower, { color: "#ea580c", description: "Close-volume correlation" }); output("zscore", line, lower, { color: "#dc2626", description: "Z-score of this close" }); output("median", line, lower, { color: "#0891b2", description: "Median" }); output("p90", line, lower, { color: "#4b5563", description: "90th percentile of the close" }); let period: i32 = 50; let closes = new StaticArray(50); let volumes = new StaticArray(50); let scratch = new StaticArray(50); let filled: i32 = 0; function onStart(): void { period = i32(p_period()); closes = new StaticArray(period); volumes = new StaticArray(period); scratch = new StaticArray(period); } function onBar(): void { const close = bar.close(); const volume = bar.volume(); // Slide the window one bar: drop the oldest, append the newest. if (filled < period) filled += 1; else { for (let k = 1; k < period; k++) { unchecked((closes[k - 1] = closes[k])); unchecked((volumes[k - 1] = volumes[k])); } } unchecked((closes[filled - 1] = close)); unchecked((volumes[filled - 1] = volume)); if (filled < period) return; out_mean(stats.mean(closes, filled)); out_stdev(stats.stdev(closes, filled)); out_slope(stats.slope(closes, filled)); out_correlation(stats.correlation(closes, volumes, filled)); out_zscore(stats.zscore(close, closes, filled)); out_median(stats.median(closes, filled, scratch)); out_p90(stats.percentile(closes, filled, 90.0, scratch)); } ``` The library's `Sma`, `Stdev`, `Correlation`, `Median` and `Percentile` give the same numbers with their own rings; reach for `stats` when one window feeds several readings or is not a fixed number of bars (a session, a swing, the bars since a signal). ## History: `x[n]` from Pine `History` keeps the last `size` values of one series. Construct it in `onStart()`, `push()` once per bar, and read `ago(n)`: `ago(0)` is the value just pushed, `ago(1)` the previous bar's. | Member | Meaning | | --- | --- | | `new History(size)` | keep the last `size` values (a size below 1 keeps one) | | `push(v)` | record this bar's value; the oldest one falls out once full | | `ago(n)` | the value pushed `n` bars ago; `NaN` before `n + 1` pushes or outside `0..size - 1` | | `latest()` | `ago(0)` | | `count()` | how many values it holds, at most `size` | | `size()` | the size it was constructed with | | `max()`, `min()`, `mean()`, `sum()` | over the values held; `NaN` while empty or when one of them is not finite | | `reset()` | empty it | Two Pine idioms port directly: `close[1]` is `history.ago(1)` read after this bar's `push()` (push at the top of `onBar()`; a read before the push is one bar older), and `ta.highest(close, 20)` is `max()` over a `History(20)` of the close (the library's `Highest(20)` gives the same number and the offset of the high as well). ```typescript output("prev_close", line, overlay, { color: "#4b5563", description: "close[1]: the previous bar's close" }); output("highest", line, overlay, { color: "#16a34a", description: "Highest close of the last 20 bars" }); output("change", line, lower, { color: "#2563eb", description: "close - close[1]" }); let history = new History(20); let highest = new Highest(20); function onStart(): void { history = new History(20); highest = new Highest(20); } function onBar(): void { const close = bar.close(); history.push(close); const prevClose = history.ago(1); const highestClose = history.max(); // The library class over the same 20 bars reads the same high. const check = highest.update(close); if (!isNaN(check) && check != highestClose) return; if (isNaN(prevClose)) return; out_prev_close(prevClose); out_highest(highestClose); out_change(close - prevClose); } ``` `history.max()` reads the values held so far: on bar 5 it is the high of six bars while `Highest(20)` is still `NaN`, and from bar 19 on the two agree (the fence checks it). Reach for `History` to look back on a series you compute yourself, an RSI or a spread. ## A percent rank of volume Where does this bar's volume sit against the last 100 bars? `PercentRank` ([Extra indicators](extra-indicators.md#deviation-rank-and-width)) answers it directly, and a `History` of the volumes hands the same window to `stats.percentile` for the threshold the rank crossed. The mark draws on bars whose volume ranks in the top decile. ```typescript param("period", 100, { min: 2, max: 400, description: "Bars in the window" }); input("volume", ohlcv.volume); output("rank", line, lower, { color: "#2563eb", description: "Percent rank of the volume" }); output("p90", line, lower, { color: "#4b5563", description: "90th percentile of volume" }); output("heavy", none, overlay, { description: "1 when the rank is 90 or above" }); output("heavy_mark", shape, overlay, { color: "#ea580c", shape_where: "heavy", description: "The close on a heavy-volume bar" }); let rank = new PercentRank(100); let history = new History(100); let window = new StaticArray(100); let scratch = new StaticArray(100); function onStart(): void { const period = i32(p_period()); rank = new PercentRank(period); history = new History(period); window = new StaticArray(period); scratch = new StaticArray(period); } function onBar(): void { const close = bar.close(); const volume = bar.volume(); const rankValue = rank.update(volume); history.push(volume); // Copy the held volumes into the window, oldest first, and read it. const held = history.count(); for (let k = 0; k < held; k++) unchecked((window[k] = history.ago(held - 1 - k))); const p90Value = stats.percentile(window, held, 90.0, scratch); const heavy = !isNaN(rankValue) && rankValue >= 90.0 ? 1.0 : 0.0; if (isNaN(rankValue)) return; out_rank(rankValue); out_p90(p90Value); out_heavy(heavy); out_heavy_mark(close); } ``` ## Lists: `List` `List` is a fixed-capacity list of `f64` values, Pine's `array.*` idiom with the one difference that the module declares its size up front. Construct it in `onStart()` with the most entries it will hold (a capacity below 1 keeps one; the buffer is allocated once), then push, insert, remove, read and sort it on any bar: no method allocates after the constructor, so a list never grows the module's memory per bar. Index 0 is the oldest entry and a negative index counts from the end, so `get(-1)` is the last entry. Three conventions cover every miss: a read outside the list is `NaN`, a change that does not fit (the list is full, or the index is out of range) returns `false` and changes nothing, and `pushEvict()` is the one way a full list takes a new value: it drops the oldest entry and hands it back. | Member | Meaning | | --- | --- | | `new List(capacity)` | hold at most `capacity` entries (below 1 keeps one); construct in `onStart()` | | `capacity()`, `size()` | the limit, and how many entries are held now | | `isEmpty()`, `isFull()` | `size() == 0`, `size() == capacity()` | | `clear()` | empty the list; the capacity is unchanged | | `push(v)` | append `v` as the last entry; `false` and no change when full | | `pushEvict(v)` | append `v`; when full, first remove and return the oldest entry (index 0), else return `NaN` | | `unshift(v)` | insert `v` at index 0; `false` when full | | `pop()`, `shift()` | remove and return the last, or the first, entry; `NaN` when empty | | `get(i)` | the entry at `i`; a negative `i` counts from the end (`-1` is the last); `NaN` outside the list | | `set(i, v)` | overwrite the entry at `i`, the same indexing; `false` outside the list | | `insert(i, v)` | insert `v` before index `i`, `i` in `0..size()` (`size()` appends); `false` when full or out of range | | `remove(i)` | remove and return the entry at `i`, the same indexing as `get`; `NaN` outside the list | | `first()`, `last()` | the entries at `0` and `size() - 1`; `NaN` when empty | | `indexOf(v)`, `includes(v)` | the lowest index whose entry equals `v`, or `-1`; `NaN` never matches | | `sort(ascending = true)` | sort in place; `NaN` entries sit last in either direction | | `sum()`, `mean()`, `min()`, `max()`, `stdev()` | the `stats.*` definitions over the entries held (population `stdev`); `NaN` while empty or when an entry is not finite, the `History` rule | | `values()` | the backing `StaticArray`: entries `0..size() - 1` are the list, so `stats.median(list.values(), list.size(), scratch)` reads it | The members below give the rest of Pine's `array.*` calls their own name. A Pine call that makes a second array (`array.copy`, `slice`, `abs`, `standardize`, `sort_indices`) writes here into a destination you constructed in `onStart()`: a second `List` with enough capacity (it may be the list itself where that makes sense), or a `StaticArray` of at least `size()` for the indexes. `median` and the two percentiles find their entry by counting, so they need no scratch array and leave the list's order alone, and they read a `NaN` (or infinite) entry as Pine's `na`: `median` skips it, the percentiles count it in `size()` and sort it last, as TradingView does. Nothing below allocates; `List.from` is the one exception and belongs in `onStart()`. | Member | Meaning | | --- | --- | | `List.from([v0, v1, ...], capacity = 0)` | a list holding the values in order, with room for `capacity` entries or for exactly the values given when `capacity` is below their count (`List.from([1.0, 2.0])` is full: size the capacity when the list will grow); construct in `onStart()` | | `copy(into)` | replace the entries of `into` with this list's; `false` and no change when `into` cannot hold `size()` entries | | `slice(into, from, to = size())` | write the entries from index `from` up to but not including `to` into `into`; a negative bound counts from the end, both are clamped to the list, a range that ends at or before it starts leaves `into` empty; `false` when `into` cannot hold the range; a copy, not Pine's live view | | `fill(v, from = 0, to = size())` | set every entry in the same range to `v`, in place; the size is unchanged | | `reverse()` | reverse the entries in place | | `abs(into)` | write the absolute value of every entry into `into` (`into` may be the list itself); `false` when it cannot hold them | | `standardize(into)` | write every entry's `(x - mean()) / stdev()` into `into` (`into` may be the list itself); every result `NaN` when the list is empty, holds a non-finite entry or has no spread; `false` when `into` cannot hold them | | `every()`, `some()` | read the list as a Pine `array` held as `1.0` and `0.0`: an entry is true when it is neither `0` nor `NaN`; both are `false` for an empty list, as on TradingView (`array.every(array.new_bool(0))` is `false` there) | | `sortIndices(into, ascending = true)` | write into the `StaticArray` the indexes `0..size() - 1` ordered by their entries, so `get(into[0])` is the smallest (or, with `false`, the largest) entry; ascending is stable (equal entries keep their index order) with the indexes of `NaN` entries last, and descending is that order reversed as on TradingView, so ties come in reverse index order and the `NaN` indexes first (`[2, 1, 2, 1, 2]` reads `1, 3, 0, 2, 4` and `4, 2, 0, 3, 1`; `[3, NaN, 1, 2]` reads `2, 3, 0, 1` and `1, 0, 3, 2`); the list is untouched; `false` when `into` is shorter than `size()` | | `median()` | the middle entry of the finite entries sorted, the mean of the two middle ones when their count is even; a `NaN` entry is skipped as TradingView skips `na` (`[3, NaN, 1, 8, 5]` reads `4`); `NaN` while no entry is finite | | `percentileNearestRank(pct)` | the nearest-rank percentile, `pct` in `0..100`: rank `ceil(pct * size() / 100)`, the entry at `max(0, rank - 1)` of the sorted list with the `NaN` entries last, so a rank that lands on one reads `NaN`; `NaN` while empty or when `pct` is not finite | | `percentileLinearInterpolation(pct)` | the percentile by linear interpolation between the two nearest ranks: TradingView's position `k = pct * size() / 100 - 0.5` over the sorted list (`NaN` entries last), the entry at `floor(k)` plus the fraction of the way to the next one, the smallest entry at or below `k = 0` and the largest at or above `k = size() - 1`, so `50` is the median of an even count and the result need not be an entry; with a `NaN` entry held a whole position reads the entry there and a fractional one reads `NaN`, as on TradingView (`[3, NaN, 1, 8, 5]` reads `1` at `10`, `NaN` at `25`, `5` at `50`); `NaN` while empty or when `pct` is not finite | The list below keeps impulse closes as levels: a close more than `step_pct` above the previous one goes in through `pushEvict()`, so the newest `keep` of them are held, and a level the close has risen above is removed. Walking `remove()` from the end keeps the lower indexes valid. The nearest level above price is the list's `min()`, and the mean level is rounded with `roundTo` for the legend. ```typescript param("keep", 8, { min: 1, max: 50, description: "Impulse closes kept" }); param("step_pct", 1, { min: 0.1, max: 20, description: "Rise from the previous close that marks an impulse, in percent" }); output("nearest_above", line, overlay, { color: "#16a34a", description: "The lowest kept level above the close" }); output("mean_level", line, overlay, { color: "#94a3b8", description: "Mean of the kept levels, two decimals" }); output("count", none, lower, { description: "Levels kept on this bar" }); let levels = new List(8); let step: f64 = 0.01; let prevClose: f64 = NaN; function onStart(): void { // Construct in onStart(): the list's buffer is allocated once, sized by the param. levels = new List(i32(p_keep())); step = p_step_pct() / 100.0; } function onBar(): void { const close = bar.close(); // An impulse close joins the list; once the list is full the oldest level leaves. if (!isNaN(prevClose) && close > prevClose * (1.0 + step)) levels.pushEvict(close); prevClose = close; // A level the close has risen above is spent: remove it, walking from the end. for (let i = levels.size() - 1; i >= 0; i--) { if (close > levels.get(i)) levels.remove(i); } // No level yet: the outputs stay unwritten and draw nothing on this bar. if (levels.isEmpty()) return; out_nearest_above(levels.min()); out_mean_level(roundTo(levels.mean(), 2)); out_count(f64(levels.size())); } function onReset(): void { levels.clear(); prevClose = NaN; } ``` Only a `List` hands its entries to the `stats` functions, through `values()` and `size()`; a `History` is read with `ago(n)` and its own aggregates, or copied into a window as the volume-rank sample above does. ## Percentiles of a list The close against its own recent spread: the 10th and 90th percentiles of the last closes, their median, and how long ago the highest of them closed, each level rounded to the market's tick. ```typescript // The close against its own recent spread: the 10th and 90th percentiles of the last closes and their median, on the market's tick. param.int("keep", 50, { min: 5, max: 500, label: "Closes kept" }); market.tick_size(); market.price_precision(); output("p90", line, overlay, { color: "#16a34a", description: "90th percentile of the kept closes" }); output("median", line, overlay, { color: "#94a3b8", line_style: "dashed", description: "Median of the kept closes" }); output("p10", line, overlay, { color: "#dc2626", description: "10th percentile of the kept closes" }); output("top_age", none, lower, { description: "Bars since the highest kept close" }); let closes = new List(50); let order = new StaticArray(50); let tick: f64 = 0; let decimals: i32 = 2; function onStart(): void { const keep = i32(p_keep()); closes = new List(keep); order = new StaticArray(keep); tick = p_market_tick_size(); decimals = i32(p_market_price_precision()); } // A level on the market's tick where it publishes one, else at its price decimals. function snap(x: f64): f64 { return tick > 0 ? roundToTick(x, tick) : roundTo(x, decimals); } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; // Keep the newest closes: once the list is full, the oldest leaves. closes.pushEvict(close); if (!closes.isFull()) return; out_p90(snap(closes.percentileLinearInterpolation(90))); out_median(snap(closes.median())); out_p10(snap(closes.percentileLinearInterpolation(10))); // The indexes ordered from the highest close down: order[0] is where the highest sits, 0 the oldest. closes.sortIndices(order, false); out_top_age(f64(closes.size() - 1 - order[0])); } ``` - **The newest closes.** `pushEvict()` appends the close and, once the list is full, drops the oldest, so the list always holds the last `keep` closes. - **Percentiles and the median.** `percentileLinearInterpolation(90)` is Pine's `array.percentile_linear_interpolation(a, 90)`, and `median()` is `array.median(a)`. Both count their way to the answer, so the list keeps its order. - **An order without sorting.** `sortIndices(order, false)` writes the indexes from the highest close down into `order`, a `StaticArray` made in `onStart()`. Ties come newest first, as on TradingView. - **On the tick.** `roundToTick(x, tick)` puts each level on the market's tick. Where the tick reads 0 (only CME markets publish one today), `roundTo(x, decimals)` rounds to the chart's price decimals instead. ## Keep the last N drawings: `HandleRing` Lines, boxes, labels and polylines share one id space, and a drawing stays on the chart until its id is deleted ([Drawing objects](../presentation/drawing-objects.md)). "Keep only the newest five lines" therefore means remembering the ids you created and deleting the oldest when the sixth arrives. `HandleRing` is that memory: `push(id)` records an id and, when the ring is already full, hands back the oldest id for you to delete: `const old = ring.push(id); if (old >= 0) lines[old].delete();` | Member | Meaning | | --- | --- | | `new HandleRing(capacity)` | keep the newest `capacity` ids (below 1 keeps one); construct in `onStart()` | | `push(id)` | record `id` as the newest; when full, first drop and return the oldest id (delete that drawing), else return `-1`; a negative id is not recorded and returns `-1` | | `size()`, `capacity()` | how many ids are held, and the limit | | `get(i)` | the id at `i`, `0` the oldest and `size() - 1` the newest; `-1` outside the ring | | `oldest()`, `newest()` | `get(0)` and `get(size() - 1)`; `-1` when empty | | `remove(id)` | forget an id you deleted early, so it is not handed back later; `false` when the ring does not hold it | | `clear()` | forget every id; the drawings themselves stay | Two rules from the drawing page shape the idiom. A handle object allocates when it is made, so make them once in `onStart()` rather than calling `draw.line(old)` on every eviction: let the ids cycle through one more value than the ring keeps (`KEEP + 1`), make that many handle objects, and the id you set next is never one still on the chart. And the chart caps live handles at 1000 per kind and 1500 in all, so a ring's capacity sits well under those. The sample draws a dashed ray at every new `period`-bar high and keeps the newest five: ```typescript param("period", 20, { min: 2, max: 400, description: "Bars a high must top" }); output("highest", line, overlay, { color: "#f5a623", description: "Highest high of the window" }); output("lines", none, lower, { description: "Rays on the chart" }); handles.line({ color: "#f5a623", width: 1, lineStyle: "dashed", extend: "right" }); // Five rays stay on the chart. Ids cycle through six, one more than the ring keeps, // so the id set next is never one still drawn; the six handle objects are made once. const KEEP = 5; const IDS = KEEP + 1; const lines = new Array(); let ring = new HandleRing(KEEP); let highest = new Highest(20); let nextId: i32 = 0; let prevT: f64 = NaN; function onStart(): void { highest = new Highest(i32(p_period())); ring = new HandleRing(KEEP); for (let id = 0; id < IDS; id++) lines.push(draw.line(id)); } function onBar(): void { const t = bar.time(); const high = bar.high(); const top = highest.update(high); const width = isNaN(prevT) ? 60.0 : t - prevT; prevT = t; if (isNaN(top)) return; // bars == 0: this bar set the window's high. if (highest.bars == 0.0) { const id = nextId; nextId = (nextId + 1) % IDS; // Record the id; when the ring is full the oldest comes back and its ray goes. const old = ring.push(id); if (old >= 0) lines[old].delete(); lines[id].set(t, high, t + width, high); } out_highest(top); out_lines(f64(ring.size())); } function onReset(): void { highest.reset(); ring.clear(); nextId = 0; prevT = NaN; } ``` `lines` reads 1, 2, 3, 4 on the first four highs and 5 from then on: the sixth high evicts the first ray's id, `delete()` removes it, and that id is the one set on the very next high. A ray you delete for another reason (a level broken, say) is also handed to `ring.remove(id)`, so the ring never returns an id that is already free. ## Rounding: `roundTo` `roundTo(x, decimals)` rounds `x` to `decimals` places with halves away from zero, Pine's `math.round(x, n)`. `decimals` is clamped to `0..15`; `NaN` and the infinities pass through unchanged. `Math.round` follows JavaScript, where a negative half goes up (`Math.round(-2.5)` is `-2`) and there is no decimals argument; `roundTo(-2.5, 0)` is `-3`. | Call | Result | | --- | --- | | `roundTo(2.5, 0)` | `3` | | `roundTo(-2.5, 0)` | `-3` | | `roundTo(7.125, 2)` | `7.13` | | `roundTo(1.23456, 3)` | `1.235` | | `roundTo(x, -1)` | the same as `roundTo(x, 0)` | | `roundTo(x, 40)` | the same as `roundTo(x, 15)` | | `roundTo(NaN, 2)` | `NaN` | The decision reads the fractional part of `abs(x) * 10^decimals` in `f64` (a fraction of `0.5` or more rounds up, nothing is added first), the result is that integer divided back with the sign restored, and `x` comes back unchanged when it already sits at that precision or when `abs(x)` is `2^52` or more, where every `f64` is an integer. A value whose binary form sits just under a half, `1.005` at two places, rounds down the way its `f64` does. Use `roundTo` for values you compute with, plot or compare; to print a value at a fixed number of decimals use the text builder's `f64(x, decimals)` ([Strings and text](text-formatting.md)), which formats without rounding the number you keep. ## Rounding to a tick: `roundToTick` `roundToTick(x, tick)` rounds `x` to the nearest multiple of `tick`, ties away from zero as `roundTo` does: Pine's `math.round_to_mintick(x)` with the tick given. Pine words the ties of `math.round` and `math.round_to_mintick` the same way ("ties rounding up"), and on TradingView `math.round(-2.5)` reads `-3` (captured), so the tick form follows `roundTo` on a negative tie; a negative tie has not been captured for `math.round_to_mintick` itself, since prices are positive, so that one case rests on the shared wording. On a chart whose market publishes a tick size the call is `roundToTick(x, p_market_tick_size())`; where the tick size reads `0` (the market has only its price decimals) use `roundTo(x, i32(p_market_price_precision()))` instead. `x` comes back unchanged when `tick` is not finite or not above `0`, when `x` is `NaN` or infinite, and when `x` already sits on a tick. | Call | Result | | --- | --- | | `roundToTick(1.125, 0.25)` | `1.25` (a tie, away from zero) | | `roundToTick(-1.125, 0.25)` | `-1.25` | | `roundToTick(1.1, 0.25)` | `1` | | `roundToTick(6.25, 2.5)` | `7.5` | | `roundToTick(100.08, 0.05)` | `100.1` | | `roundToTick(x, 0.01)` | the same as `roundTo(x, 2)`, to the bit | | `roundToTick(x, 0)` | `x` | | `roundToTick(NaN, 0.5)` | `NaN` | A tick that is a unit fraction (`0.01`, `0.25`, `0.0001`, `0.5`, `1`: one over an integer `k`) is handled the way `roundTo` handles decimals, the decision on the fractional part of `abs(x) * k` in `f64` and the result that integer divided by `k`, so the answer is the nearest `f64` to the decimal a trader would write (`100.1`, not `100.10000000000001`). Any other tick (`2.5`, `5`, `0.3`) rounds `abs(x) / tick` and multiplies back. The levels in [Percentiles of a list](#percentiles-of-a-list) are rounded this way, with `roundTo` where the tick reads 0. ## Repeatable random numbers: `Random` `Random` is a seeded generator for Pine's `math.random(min, max, seed)`: the same seed gives the same sequence on every host and every run, and `reseed(seed)` in `onReset()` replays it. Construct it in `onStart()`; `next()` and `between()` never allocate. Pine's unseeded `math.random()` differs on every run and there is no clock here to draw a seed from, so pick one. The generator is TradingView's: a seeded `math.random` there draws `java.util.Random`'s `nextDouble()` sequence for the seed, and so does `Random`, draw for draw (seed `42` starts `0.7275636800328681`, `0.6832234717598454`, `0.30871945533265976`; seed `1` starts `0.7308781907032909`, `0.41008081149220166`, the values captured on TradingView). TradingView keeps one sequence per `math.random` call site, so construct one `Random` per call a Pine script makes. | Member | Meaning | | --- | --- | | `new Random(seed)` | a generator at `seed` (an integer); construct in `onStart()` | | `next()` | the next value in `[0, 1)`, a multiple of `2^-53`, so `1.0` never comes out; Pine's `math.random()` with the seed | | `between(min, max)` | `min + (max - min) * next()`, a value in `[min, max)`; Pine's `math.random(min, max)` | | `reseed(seed)` | restart the sequence from `seed`: the values that follow are those a new `Random(seed)` gives | A random walk from the first close, the same path on every run: a baseline to test a signal against. ```typescript // A random walk from the first close, up to 1% a bar either way: the same path on every run for one seed, a baseline to test a signal against. param.int("seed", 42, { min: 1, max: 1000000, label: "Seed" }); output("walk", line, overlay, { color: "#a855f7", description: "A seeded random walk from the first close" }); let random = new Random(42); let seed: i64 = 42; let walk: f64 = NaN; function onStart(): void { seed = i64(p_seed()); random = new Random(seed); } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; walk = isNaN(walk) ? close : walk * (1.0 + random.between(-0.01, 0.01)); out_walk(walk); } // A reset replays the same path from the seed. function onReset(): void { random.reseed(seed); walk = NaN; } ``` - **One seed, one path.** `between(-0.01, 0.01)` draws one step per bar, and seed `42` draws the same steps on every run and every host: the walk's first step is `0.7275636800328681` of the way through the range, the value TradingView's `math.random` gives for that seed. - **A reset replays it.** `reseed(seed)` in `onReset()` restarts the sequence, so a reset chart draws the same walk again. - **A baseline.** A signal that scores as well on the walk as on the price has found nothing. ## From Pine One to one: the call returns Pine's value on the same bars. The second table holds the three `List` calls that differ from Pine's `array.*`. | Pine | Here | | --- | --- | | `array.sum`, `array.avg`, `array.variance`, `array.stdev`, `array.min`, `array.max`, `array.indexof(array.min(a))`, `array.covariance`, `array.sort`, `array.median`, `array.percentile_nearest_rank`, `array.percentile_linear_interpolation` | `stats.sum`, `stats.mean`, `stats.variance`, `stats.stdev`, `stats.min`, `stats.max`, `stats.argmin` (and `argmax`), `stats.covariance`, `stats.sortAscending`, `stats.median`, `stats.percentile`, `stats.percentileLinearInterpolation` over a `StaticArray` and a count | | `x[n]` | `new History(size)`, `.push(x)` at the top of `onBar()`, then `.ago(n)` | | `array.new()`, `array.push`, `array.pop`, `array.shift`, `array.unshift`, `array.get`, `array.set`, `array.insert`, `array.remove`, `array.first`, `array.last`, `array.indexof`, `array.includes`, `array.size`, `array.clear` | `new List(capacity)` in `onStart()`, then `.push`, `.pop`, `.shift`, `.unshift`, `.get`, `.set`, `.insert`, `.remove`, `.first`, `.last`, `.indexOf`, `.includes`, `.size`, `.clear` | | `array.sort(a)`, `array.sort(a, order.descending)` | `list.sort()`, `list.sort(false)` | | `array.sum`, `array.avg`, `array.min`, `array.max`, `array.stdev` on an array you keep | `list.sum()`, `.mean()`, `.min()`, `.max()`, `.stdev()` | | `array.from(v0, v1, ...)` | `List.from([v0, v1, ...], capacity)` in `onStart()` | | `array.copy(a)`, `array.slice(a, from, to)`, `array.abs(a)`, `array.standardize(a)` | `list.copy(into)`, `.slice(into, from, to)`, `.abs(into)`, `.standardize(into)` with `into` a second `List` made in `onStart()` | | `array.fill(a, v, from, to)`, `array.reverse(a)` | `list.fill(v, from, to)`, `.reverse()` | | `array.every(a)`, `array.some(a)` | `list.every()`, `.some()` over entries held as `1.0` and `0.0` | | `array.sort_indices(a, order)` | `list.sortIndices(into)` / `.sortIndices(into, false)` with `into` a `StaticArray` made in `onStart()` (TradingView's orders: stable ascending with `na` last, that order reversed descending) | | `array.median(a)`, `array.percentile_nearest_rank(a, pct)`, `array.percentile_linear_interpolation(a, pct)` | `list.median()`, `.percentileNearestRank(pct)`, `.percentileLinearInterpolation(pct)` | | `if array.size(lines) > N` then `line.delete(array.shift(lines))` | `new HandleRing(N)` in `onStart()`; `const old = ring.push(id); if (old >= 0) lines[old].delete();` | | `math.round(x, n)` | `roundTo(x, n)` | | `math.round_to_mintick(x)` | `roundToTick(x, p_market_tick_size())` | | `math.random(min, max, seed)` | `new Random(seed)` in `onStart()`, then `.between(min, max)` (`.next()` for `math.random()`) | | Pine | Here | The difference | | --- | --- | --- | | `array.push(a, v)` on an array that grows without bound | `list.push(v)` | a `List` has the capacity it was given in `onStart()`: `push` returns `false` when full, and `pushEvict` drops the oldest entry instead, the keep-the-last-N shape most scripts want | | `array.get(a, i)` | `list.get(i)` | a negative `i` counts from the end here (`get(-1)` is the last entry) and an index outside the list reads `NaN` instead of stopping the script | | `array.slice(a, from, to)` | `list.slice(into, from, to)` | a copy into `into`, where Pine's slice is a live view of the original; a bound outside the list is clamped instead of stopping the script | # Math functions Math in a wrun indicator is AssemblyScript's `Math`: absolute value, rounding, powers and roots, logarithms, and the full trig and hyperbolic families, on `f64`. Call them on any number in `onBar()` and they evaluate per bar, exactly like their JavaScript counterparts, with one difference worth knowing: the compiler is typed, so an integer and a float never mix silently. Every method lives under the `Math.` prefix (capital M). There is no global `abs()` or `round()` for floats; it is always `Math.abs(...)`, `Math.round(...)`. Use them to normalize a signal, scale a value into a range, or build a custom indicator from primitives. ```typescript const spread = close - average; // How far is price from its average, regardless of direction? distance = Math.abs(spread); ``` ## What is available | Group | Methods | | --- | --- | | Basic | `abs`, `sign` | | Rounding | `round`, `floor`, `ceil`, `trunc` | | Powers and roots | `pow`, `sqrt`, `cbrt`, `hypot` | | Exp and log | `exp`, `expm1`, `log`, `log1p`, `log2`, `log10` | | Comparison | `max`, `min` | | Trig (radians) | `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2` | | Hyperbolic | `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` | Constants: `Math.PI`, `Math.E`, `Math.SQRT2`, `Math.SQRT1_2`, `Math.LN2`, `Math.LN10`, `Math.LOG2E`, `Math.LOG10E`. Each behaves like its JavaScript counterpart. `Math.max` and `Math.min` take two `f64` arguments and return the larger or smaller; nest them for three. `Math.round` rounds to the nearest integer and returns an `f64`. Trig functions work in radians, so divide a bar count or an angle accordingly (`Math.sin(f64(barIndex) / 10.0)`). **Types.** `Math.*` takes and returns `f64`. An `i32` (a bar count, a loop index, a ring cursor) must be cast in (`f64(count)`) and a result used as an index must be cast out (`i32(Math.floor(x))`); the compiler refuses the implicit conversion with `AS200`. For integer work AssemblyScript has typed builtins that need no cast: `abs(n)`, `max(a, b)`, `min(a, b)`, and integer division truncates on its own (`7 / 2` is `3` for two `i32` values, `3.5` for two `f64`). **There is no `Math.avg`.** To average two values, write the arithmetic (`(a + b) / 2.0`); for a rolling average over a window, use `Sma` ([Moving averages](moving-averages.md)). Calling a method that does not exist is a compile error, not a runtime one: `Math.unknownFn(x)` stops the build with `TS2339: Property 'unknownFn' does not exist on type '~lib/math/NativeMath'`, with the line and column. ## Every method in one module This module runs the full namespace at once. It builds a few helper values first (a `centered` series of price minus its average, a `bounded` value safe for `asin` and `acos`, a `positive` value safe for `log` and `sqrt`, and a `small` value safe for `exp`, `sinh` and `cosh`: `centered` as a fraction of the average, so it stays near zero on any market), then writes each `Math.*` result to its own output. ```typescript param("period", 5, { min: 2, max: 200 }); output("abs", line, lower, { description: "Math.abs of the centered close" }); output("round", line, lower, { description: "Math.round" }); output("max", line, lower, { description: "Math.max of high and close" }); output("min", line, lower, { description: "Math.min of low and close" }); output("pow", line, lower, { description: "Math.pow of the small value, squared" }); output("sqrt", line, lower, { description: "Math.sqrt of the positive value" }); output("log", line, lower, { description: "Math.log of the positive value" }); output("floor", line, lower, { description: "Math.floor" }); output("ceil", line, lower, { description: "Math.ceil" }); output("sign", line, lower, { description: "Math.sign: -1, 0, or 1" }); output("sin", line, lower, { description: "Math.sin of the bar index over 8" }); output("cos", line, lower, { description: "Math.cos of the bar index over 8" }); output("tan", line, lower, { description: "Math.tan of the bar index over 40" }); output("asin", line, lower, { description: "Math.asin of the bounded value" }); output("acos", line, lower, { description: "Math.acos of the bounded value" }); output("atan", line, lower, { description: "Math.atan of the centered close" }); output("atan2", line, lower, { description: "Math.atan2 of centered over positive" }); output("sinh", line, lower, { description: "Math.sinh of the small value" }); output("cosh", line, lower, { description: "Math.cosh of the small value" }); output("tanh", line, lower, { description: "Math.tanh of the small value" }); output("asinh", line, lower, { description: "Math.asinh of the small value" }); output("acosh", line, lower, { description: "Math.acosh of the positive value" }); output("atanh", line, lower, { description: "Math.atanh of half the bounded value" }); output("exp", line, lower, { description: "Math.exp of the small value" }); output("expm1", line, lower, { description: "Math.expm1 of the small value" }); output("log1p", line, lower, { description: "Math.log1p of the small value's magnitude" }); output("log2", line, lower, { description: "Math.log2 of the positive value" }); output("log10", line, lower, { description: "Math.log10 of the positive value" }); output("cbrt", line, lower, { description: "Math.cbrt of the centered close" }); output("hypot", line, lower, { description: "Math.hypot of centered and small" }); output("trunc", line, lower, { description: "Math.trunc of the centered close" }); let sma = new Sma(5); let barIndex: i32 = 0; function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const average = sma.update(close); const centered = close - average; // The bar index is an i32 counter; the trig helpers want an f64 in radians. const bounded = Math.sin(f64(barIndex) / 10.0); const positive = Math.abs(centered) + 1.0; const small = centered / (Math.abs(average) + 1.0); barIndex += 1; if (isNaN(average)) return; const angle = f64(barIndex) / 8.0; out_abs(Math.abs(centered)); out_round(Math.round(centered)); out_max(Math.max(high, close)); out_min(Math.min(low, close)); out_pow(Math.pow(small, 2.0)); out_sqrt(Math.sqrt(positive)); out_log(Math.log(positive)); out_floor(Math.floor(centered)); out_ceil(Math.ceil(centered)); out_sign(Math.sign(centered)); out_sin(Math.sin(angle)); out_cos(Math.cos(angle)); out_tan(Math.tan(f64(barIndex) / 40.0)); out_asin(Math.asin(bounded)); out_acos(Math.acos(bounded)); out_atan(Math.atan(centered)); out_atan2(Math.atan2(centered, positive)); out_sinh(Math.sinh(small)); out_cosh(Math.cosh(small)); out_tanh(Math.tanh(small)); out_asinh(Math.asinh(small)); out_acosh(Math.acosh(positive)); out_atanh(Math.atanh(bounded / 2.0)); out_exp(Math.exp(small)); out_expm1(Math.expm1(small)); out_log1p(Math.log1p(Math.abs(small))); out_log2(Math.log2(positive)); out_log10(Math.log10(positive)); out_cbrt(Math.cbrt(centered)); out_hypot(Math.hypot(centered, small)); out_trunc(Math.trunc(centered)); } ``` ## Domain notes A few methods are only defined for part of the number line, exactly as in standard math: - `Math.sqrt` and `Math.log` expect non-negative input. Guard with `Math.abs(x) + 1.0` or a `Math.max` floor if your series can go negative or hit zero. - `Math.asin` and `Math.acos` only accept values in `[-1, 1]`. Feed them something already bounded (the module uses `Math.sin(...)`). - `Math.acosh` expects input `>= 1`. - `Math.exp` and `Math.expm1` overflow to infinity above about 709.78, and `Math.sinh` and `Math.cosh` once the input passes about 710.48 either way. A price, or a price difference, gets there on a high-priced market or a long interval, and an infinite output stops the Indicator wherever it runs. Feed these a ratio (the module's `small`), never a price or a price difference. Out-of-domain input produces `NaN` rather than trapping, so an output may simply show gaps where the input left the valid range, and `NaN` written to an output draws nothing and never trips an alert. A division by zero on `f64` yields an infinity rather than a WebAssembly trap, but no host takes an infinite output: the run stops on the first bar that writes one. `isFinite(x)` catches `NaN` and both infinities before the value reaches an output; write `NaN` instead to leave a gap. Integer division by zero DOES trap and aborts the evaluation, so guard an `i32` divisor. # Control flow Control flow decides what runs on each bar. A wrun indicator is AssemblyScript, so the constructs are the typed C-style ones: `if`/`else`, the `? :` ternary, `switch`, `for`, `while`, `do`/`while`, `break` and `continue`. Everything here runs inside `onBar()`, which the host calls once per bar as it walks the loaded history. The bar loop belongs to the host: your code sees one bar per call, and a loop inside it walks memory you own, never history you do not have. Module-level variables are where state lives between calls. | Construct | Use it for | | --- | --- | | `if` / `else` | decision logic; the condition must be a `bool` | | `? :` | one inline choice; both branches share a type | | `switch` | mapping a discrete code (a mode param) to a value or a branch | | `for` | a known iteration count: a ring buffer, a cell block, a bounded scan | | `while`, `do`/`while` | a condition-driven search with a bound you can prove | | `break`, `continue` | leaving a loop early, skipping an iteration | ## if / else Branch on any boolean condition; the `else` is optional and `else if` chains as usual. The condition must be a real `bool`: `if (value)` on a number is a compile error (`AS200`), so compare (`if (value > 0.0)`, `if (!isNaN(value))`). ```typescript if (close > open) { direction = 1.0; // up bar } else if (close < open) { direction = -1.0; // down bar } else { direction = 0.0; // doji } ``` A value from the last bar, such as the previous close, is a module-level variable the module kept from the last call, not `close[1]` ([Execution model](../core-concepts/execution-model.md)). ## Ternary expressions For a single inline choice, `condition ? a : b` is cleaner than a full `if`. Both branches must have the same type: write `1.0 : 0.0` for an `f64`, not `1 : 0`, or the compiler infers an integer and refuses the assignment. It is the idiomatic way to pick a value or to suppress a draw, since `NaN` written to an output draws nothing: ```typescript // Pick a price based on the bar's direction. const anchor = close > open ? high : low; // Write the low only on signal bars; NaN draws nothing (a shape_where gate is the declared form). const signal = crossed == 1 ? low : NaN; ``` ## switch `switch` matches an integer against `case` labels with a `default` fallback, and falls through without `break` exactly as JavaScript does. Use it to map a discrete code (a mode param) to a value or a branch. ```typescript switch (mode) { case 0: picked = close; break; case 1: picked = high; break; default: picked = low; } ``` ## for loops Use a C-style `for` when you need a fixed number of iterations: summing a window, scanning buckets, accumulating a value. The form is `for (let i = 0; i < end; i++) { ... }`: the counter is an `i32` (`i++` and `i += 1` both work), so cast it when it meets an `f64`. Loop bodies work with locals and with the module's buffers. A `StaticArray` sized from a param's `max` in `onStart()` or at module start is the usual target, and `unchecked(ring[i])` skips the bounds check once the index is provably inside. ```typescript // Sum the last closes by hand, from a ring buffer the module keeps; count is how many slots are filled. let total = 0.0; for (let i = 0; i < count; i++) { total += unchecked(ring[i]); } ``` A celled input's block is the other common loop target: `for (let i = 0; i + 3 < n; i += 4)` walks `[low, high, buy, sell]` tuples ([Order flow](order-flow-kit.md)). There is no history array to loop over (`close[n]` does not exist): a wrun indicator has no timeseries. A window is a `History` you `push()` once per bar and read with `ago(n)` ([Stats, history and lists](stats-history-lists.md)), or by hand a `StaticArray` ring the module fills one bar at a time, sized once from the param's `max` ([Collections](../core-concepts/collections.md)). The ring is the window, and it is yours to size and index. ## while and do/while `while (condition) { ... }` and `do { ... } while (condition)`. Use them when the iteration count depends on what you find, and make the bound explicit: a search back through a ring stops at the ring's size whatever the data says. Here `above` is a ring of booleans (was the close above its average on that bar) and `slot(back)` maps "bars back" to a ring index. ```typescript let back = 0; while (back < count && !unchecked(above[slot(back)])) { back += 1; } ``` A counted `for` is clearer and safer when you know the bound. Reach for `while` only for genuine search-until-found logic, and make sure the condition can end. ## break and continue `break` leaves the loop; `continue` skips to the next iteration. Both work in `for`, `while`, and `do`/`while`, and both are the idiomatic way to stop a scan the moment it has its answer. ## Branches in one module A `for` loop, an `if`/`else` branch, a ternary, and a `switch`, folded into one value, with a bar counter the module keeps itself (there is no `barIndex` global). The `if`/`else`, ternary, `switch` and `for` snippets above appear verbatim inside `onBar()`. ```typescript param("mode", 0, { min: 0, max: 2, description: "0 rotate by bar, 1 high, 2 low: which price the switch picks" }); param("window", 5, { min: 2, max: 50, description: "Closes summed by the for loop" }); output("direction", line, lower, { description: "+1 up bar, -1 down bar, 0 doji" }); output("anchor", line, lower, { description: "The high on up bars, the low otherwise" }); output("signal", none, lower, { description: "The low on bullish-cross bars, NaN elsewhere" }); output("total", line, lower, { description: "The last closes summed by hand" }); output("picked", line, lower, { description: "The price the switch picked" }); output("folded", line, lower, { description: "All four results in one number" }); const MAX_WINDOW = 50; const ring = new StaticArray(MAX_WINDOW); let n: i32 = 5; let cursor: i32 = 0; let count: i32 = 0; let modeParam: i32 = 0; let barIndex: i32 = 0; let sma = new Sma(5); const cross = new Cross(); function onStart(): void { modeParam = i32(p_mode()); n = i32(p_window()); sma = new Sma(n); } function onBar(): void { const close = bar.close(); const open = bar.open(); const high = bar.high(); const low = bar.low(); unchecked((ring[cursor] = close)); cursor = (cursor + 1) % n; if (count < n) count += 1; const crossed = cross.update(close, sma.update(close)); let direction = 0.0; if (close > open) { direction = 1.0; // up bar } else if (close < open) { direction = -1.0; // down bar } else { direction = 0.0; // doji } // Pick a price based on the bar's direction. const anchor = close > open ? high : low; // Write the low only on signal bars; NaN draws nothing (a shape_where gate is the declared form). const signal = crossed == 1 ? low : NaN; // Sum the last closes by hand, from a ring buffer the module keeps; count is how many slots are filled. let total = 0.0; for (let i = 0; i < count; i++) { total += unchecked(ring[i]); } // A per-bar mode: the param, or the bar index modulo 3 when the param is 0. const mode = modeParam == 0 ? barIndex % 3 : modeParam; let picked = NaN; switch (mode) { case 0: picked = close; break; case 1: picked = high; break; default: picked = low; } barIndex += 1; out_direction(direction); out_anchor(anchor); out_signal(signal); out_total(total); out_picked(picked); out_folded(anchor + picked / 100.0 + total); } ``` ## Loops in one module A search-until-found: how many bars back the close last traded above its average, found with a `while` over a ring buffer, plus a `for` that sums the ring, a `for` with `continue` that counts up bars while skipping doji bars, and a `do`/`while` with `break` that finds the first bar back whose range exceeds the current one. The `for` and `while` snippets above appear verbatim inside `onBar()`. ```typescript param("period", 20, { min: 2, max: 200, description: "Average window and search depth" }); output("direction", line, lower, { color: "#94a3b8", description: "+1 when the close rose, -1 when it fell, 0 flat" }); output("close_sum", line, lower, { color: "#7c3aed", description: "The window's closes summed by the for loop" }); output("bars_since_above", line, lower, { color: "#2563eb", description: "Bars back to the last close above the average (0 = this bar), NaN if none in the window" }); output("bars_above", line, lower, { color: "#16a34a", description: "Up bars in the window, doji bars skipped" }); output("wider_back", line, lower, { color: "#f97316", description: "Bars back to the first bar with a wider range than this one, NaN if none" }); const MAX_PERIOD = 200; const ring = new StaticArray(MAX_PERIOD); const opens = new StaticArray(MAX_PERIOD); const ranges = new StaticArray(MAX_PERIOD); const above = new StaticArray(MAX_PERIOD); let size: i32 = 20; let sma = new Sma(20); let cursor: i32 = 0; let count: i32 = 0; let prevClose: f64 = NaN; // The ring slot `back` bars behind the newest write. function slot(back: i32): i32 { return (cursor - 1 - back + size) % size; } function onStart(): void { size = i32(p_period()); sma = new Sma(size); } function onBar(): void { const close = bar.close(); const open = bar.open(); const average = sma.update(close); // if / else: the bar's direction against the previous close the module kept. let direction = 0.0; if (close > prevClose) { direction = 1.0; } else if (close < prevClose) { direction = -1.0; } prevClose = close; unchecked((ring[cursor] = close)); unchecked((opens[cursor] = open)); unchecked((ranges[cursor] = bar.high() - bar.low())); unchecked((above[cursor] = !isNaN(average) && close > average)); cursor = (cursor + 1) % size; if (count < size) count += 1; if (isNaN(average)) return; // for: sum the filled slots of the ring. let total = 0.0; for (let i = 0; i < count; i++) { total += unchecked(ring[i]); } // while: search back until a bar above the average is found, or the window runs out. let back = 0; while (back < count && !unchecked(above[slot(back)])) { back += 1; } const barsSinceAbove = back < count ? f64(back) : NaN; // for with continue: count up bars, skipping doji bars. let ups = 0; for (let i = 0; i < count; i++) { const c = unchecked(ring[i]); const o = unchecked(opens[i]); if (c == o) continue; if (c > o) ups += 1; } // do/while with break: the first bar back whose range exceeds this one. const current = unchecked(ranges[slot(0)]); let probe = 1; let widerBack = NaN; if (count > 1) { do { if (unchecked(ranges[slot(probe)]) > current) { widerBack = f64(probe); break; } probe += 1; } while (probe < count); } out_direction(direction); out_close_sum(total); out_bars_since_above(barsSinceAbove); out_bars_above(f64(ups)); out_wider_back(widerBack); } ``` Every loop here is bounded by `count`, which is bounded by `size`, which is bounded by the param's declared `max`: the module allocates its rings once for `MAX_PERIOD` and never grows. ## Loop limits A wrun indicator has no iteration counter: the chart bounds the whole evaluation with an execution timeout (20 s per run). A module that overruns it is stopped and its worker replaced, so a runaway loop, or a `while` whose condition never becomes false, fails the run loudly rather than hanging the chart. In practice a loop bounded by a param's declared `max` never approaches the timeout; keep loop bounds tied to declared ranges and the module stays cheap on a long history ([Execution model](../core-concepts/execution-model.md)). Loops run once per bar over the loaded history and again each time a live update re-evaluates the forming bar (at most about once a second). A scan of a 200-slot ring is cheap; a scan inside a scan is not, so cache a statistic once per bar and reuse it. ## What to keep in mind - **Per-bar execution.** `onBar()` re-runs on every bar. To carry a value across bars, keep it in a module-level `let`. A `let` inside `onBar()`, a loop or a branch is local to that block and gone when the call returns. - **Typed branches.** Every branch of a ternary and every assignment agrees on a type; `f64` values get float literals (`0.0`, `1.0`), counts and indexes are `i32`. # Strings and text Strings in a wrun indicator live in string slots: byte-capped channels written once per bar from `onBar()` and read by a text mark, a label, a table cell or a card. Typed words enter once, through a text setting (`pt_()` in `onStart()`, [Setting kinds](../settings/kinds.md#text-settings)); per-bar text leaves through string slots and never becomes an output. On the way out, the generated `sb_*` builder turns the numbers the indicator computes into the words the chart shows, without allocating: a price with the decimals its tick size calls for, a percent with its sign, a volume as `1.2M`, a span as `2h 15m`, the bar's clock in a pattern you choose. Inside the module, AssemblyScript's `String` has the JavaScript-style methods for one-time work. This page is the slot, the builder's three steps and every call, the capacity rule, a second builder, the `String` methods and the Pine mappings. ## Where strings go Declare a slot at the top of the file, and what reads it, then send text to it from `onBar()`: ```typescript string("note", { max_bytes: 64 }); render.text("note_mark", { y: "average", text: "note" }); ``` The build generates three senders per slot: `str_note(s)` encodes and sends a whole string, `str_note_sb()` sends the shared line buffer, and `str_note_tb(tb)` sends a `TextBuilder` of your own. Text built per bar with `+` allocates on every bar, so the `./sdk/fmt` module ships a `TextBuilder`: a byte buffer allocated once that spells text and numbers into itself, and the generated `./gen/strings` module builds its `sb_*` calls on one of them. The senders belong in `onBar()`. A slot not written that bar is absent, which is distinct from a written empty string, and the difference is what gates `render.text`: an absent slot draws nothing. ## The `string` name The declaration is called `string`, the same word as the type, and the two share a file without a clash: the declaration is a top-level statement that only writes the sheet, so `let label: string = "";` compiles beside it: ```typescript string("note", { max_bytes: 64 }); let label: string = ""; ``` ## Three steps 1. Declare the slot at the top of the file, and what reads it (a text mark, a label, a table cell). 2. Build the line in `onBar()`: `sb_clear()` first, then the `sb_*` calls in reading order. Nothing here allocates, so the same line can be rebuilt on every bar of the history and on every live tick. 3. Send it with `str__sb()`. The sender hands the chart the line and returns the slot's index (a label handle's `text(...)` takes that index). ```typescript output("average", line, overlay, { color: "#38bdf8", width: 2, description: "20-bar average" }); string("readout", { max_bytes: 48 }); // step 1: the slot render.text("readout_mark", { y: "average", text: "readout", size: 10 }); // and what reads it let sma = new Sma(20); function onStart(): void { sma = new Sma(20); } function onBar(): void { const close = bar.close(); const average = sma.update(close); if (isNaN(average)) return; out_average(average); sb_clear(); // step 2: build the line sb_price(close, 0.01); // 1234.57 when close is 1234.5678 and the tick is 0.01 sb_text(" is "); sb_signed(((close - average) / average) * 100.0, 1); // +1.3 or -0.8 sb_text("% from the average"); str_readout_sb(); // step 3: send it } ``` ## Every call The generated `./gen/strings` module wraps one shared `TextBuilder` sized to the largest `max_bytes` you declared. Every `sb_*` call appends to it; every `str__*` call sends it. | Call | Appends | | --- | --- | | `sb_clear()` | nothing: starts a new line (call it first) | | `sb_text(s: string)` | the string's UTF-8, one code point at a time | | `sb_char(code: i32)` | one code point (a code outside 0..0x10FFFF or a surrogate becomes U+FFFD) | | `sb_int(value: i64)` | an integer, `-` first when negative | | `sb_f64(value: f64, decimals: i32)` | fixed point with `decimals` (0..9) fraction digits, rounded half up; `NaN`, `Inf`, `-Inf` spelled out | | `sb_auto(value: f64)` | five significant digits with the trailing fraction zeros trimmed; the digits left of the point are never rounded away | | `sb_price(value: f64, tick: f64 = 0)` | fixed point with the decimals the tick implies (0.5 is 1, 0.01 is 2, 0.00001 is 5, at most 9); tick 0 or `NaN` means unknown and formats like `sb_auto` | | `sb_pct(value: f64, decimals: i32 = 1)` | the value, already in percent units, in fixed point then `%` | | `sb_signed(value: f64, decimals: i32)` | fixed point with `+` above zero, `-` below, no sign at zero | | `sb_compact(value: f64, decimals: i32 = 1)` | the value scaled to `K`, `M`, `B` or `T` at 1e3, 1e6, 1e9, 1e12, trailing fraction zeros trimmed, sign kept | | `sb_mask(value: f64, mask: string, tick: f64 = 0)` | the value as TradingView spells Pine's `str.tostring(value, mask)`: `#` an optional digit, `0` a required one, `,` groups, any other character literal (`%` scales by 100); rounded half away from zero on the shortest decimal; `""` is `str.tostring(value)`, and `"mintick"` (at `tick`), `"percent"` and `"volume"` are the format words | | `sb_time(t: f64, pattern: string, offsetSec: i32 = 0)` | the clock time of `t` (epoch seconds) shifted by `offsetSec`, spelled by the pattern's tokens `yyyy` `MM` `dd` `HH` `mm` `ss` `MMM` `EEE`; other characters copied; `NaN` is `NaN` | | `sb_duration(seconds: f64)` | the two largest non-zero units of `d`, `h`, `m`, `s`; zero is `0s` | | `sb_spaces(n: i32)` | `n` spaces | | `sb_overflowed(): bool` | nothing: answers whether the line has outgrown the buffer since `sb_clear()` (sending it would be refused) | | `str__sb(): i32` | nothing: sends the shared line to the slot, returns its index; a line over the slot's `max_bytes` is refused by name | | `str_(s: string): i32` | nothing: clears, appends `s`, sends the same way | | `str__tb(tb: TextBuilder): i32` | nothing: sends another builder's line to the slot, returns its index; a builder that overflowed stops the run by name | A non-finite number spells its word (`NaN`, `Inf`, `-Inf`) and nothing else: no sign, no `%`, no unit. Every formatting call below shows its output for the value it is given. ```typescript output("last_close", line, overlay, { color: "#94a3b8", description: "The close, drawn so the table has a chart" }); string("numbers", { max_bytes: 64 }); string("sizes", { max_bytes: 64 }); string("clock", { max_bytes: 64 }); string("words", { max_bytes: 64 }); render.table("catalog", { rows: 4, cols: 1, cells: ["numbers", "sizes", "clock", "words"], position: "top_left" }); let firstBarTime: f64 = NaN; function onBar(): void { const close = bar.close(); const volume = bar.volume(); const barTime = bar.time(); if (isNaN(firstBarTime)) firstBarTime = barTime; if (isNaN(close)) return; out_last_close(close); sb_clear(); sb_f64(1234.5678, 2); // 1234.57 sb_spaces(1); // one space sb_auto(1234.5678); // 1234.6 sb_spaces(1); sb_auto(0.00012345); // 0.00012345 sb_spaces(1); sb_price(1234.5678, 0.5); // 1234.6 (a 0.5 tick: one decimal) sb_spaces(1); sb_pct(12.345, 1); // 12.3% sb_spaces(1); sb_signed(3.5, 1); // +3.5 sb_spaces(1); sb_int(-42); // -42 str_numbers_sb(); // 1234.57 1234.6 0.00012345 1234.6 12.3% +3.5 -42 sb_clear(); sb_compact(1500.0, 1); // 1.5K sb_text(" "); sb_compact(2000000.0, 1); // 2M sb_text(" "); sb_compact(-1234567.0, 2); // -1.23M sb_text(" "); sb_compact(volume, 1); // the bar's volume: 850.3M, 1.2B, ... str_sizes_sb(); sb_clear(); sb_time(1700000000.0, "yyyy-MM-dd HH:mm:ss", 0); // 2023-11-14 22:13:20 sb_text(" "); sb_time(1700000000.0, "EEE dd MMM yyyy", -18000); // Tue 14 Nov 2023 (five hours west of UTC) sb_text(" "); sb_duration(7500.0); // 2h 5m sb_text(" "); sb_duration(barTime - firstBarTime); // the history's span so far: 3d 4h, 12h 30m, ... str_clock_sb(); sb_clear(); sb_text("héllo"); // héllo (UTF-8 as is) sb_char(0x2192); // one arrow character sb_text("wörld"); // wörld if (sb_overflowed()) sb_clear(); // false here: 15 bytes fit; a line that outgrew the buffer would be refused str_words_sb(); } ``` `sb_time` takes the time zone as an offset in seconds (`-18000` is five hours west of UTC); a run of any other letters in the pattern, and every other character, is copied as is. `sb_duration` floors to whole seconds. ## Capacity and overflow Strings are never truncated. A slot refuses a line longer than its own `max_bytes` by name: the run stops and the Console says `string slot 0 write of 40 bytes exceeds the slot's max_bytes 32`. That holds for a line built with the `sb_*` calls and for a string handed whole to `str_(s)`. The shared builder holds as many bytes as the largest `max_bytes` you declared, and its sender passes the bytes the line asked for, so a line that outgrew the buffer is over every slot's cap and is refused the same way. Inside a builder, an append that does not fit is dropped whole (a text append stops at the first code point that does not fit; a number, a time or a duration is never split) and every later append is dropped too, so the bytes it holds stay valid. That is bookkeeping, not delivery: the line is still refused when it is sent. `sb_overflowed()` answers `true` from the first dropped append until the next `sb_clear()`, so when a line can run long, check it before sending and build a shorter line instead. A `TextBuilder` you construct holds the capacity you give it. It answers the same question with `overflowed()`, and `needed()` tells the bytes the whole line asked for, which is the capacity and the `max_bytes` to declare. Sending one that overflowed stops the run by name: `string slot 'mid_text': the TextBuilder overflowed before str_mid_text_tb(); size the builder to the text`. The caps: per slot `max_bytes` is at most 4096; 64 slots per indicator; 64 KiB of string bytes per row; 2 MiB per run on the chart, strings and frames together. Each is a named refusal, never a truncation ([Limits](../reference/limits.md)). ## A second builder The `TextBuilder` class is the same code the `sb_*` calls use. Construct one in `onStart()` (it allocates its buffer there, once). Every method returns the builder, so calls chain, and `str__tb(tb)` sends it to a slot. | Method | Signature | Definition | | --- | --- | --- | | `constructor` | `new TextBuilder(capacity: i32)` | a builder holding at most `capacity` bytes; allocate at module start or in `onStart()` | | `clear` | `clear(): TextBuilder` | starts a new line; `length()`, `needed()` and `overflowed()` return to 0, 0 and `false` | | `text` | `text(s: string): TextBuilder` | appends the string's UTF-8 one code point at a time (a lone surrogate becomes U+FFFD) | | `char` | `char(code: i32): TextBuilder` | appends one code point | | `int` | `int(v: i64): TextBuilder` | appends an integer | | `f64` | `f64(x: f64, decimals: i32): TextBuilder` | appends fixed point with `decimals` (0..9) fraction digits, rounded half up, every finite double exact | | `auto` | `auto(x: f64): TextBuilder` | appends five significant digits, trailing fraction zeros trimmed, the digits left of the point exact at every magnitude | | `price` | `price(x: f64, tick: f64 = 0): TextBuilder` | appends fixed point with the tick's decimal places (at most 9); tick 0 or `NaN` formats like `auto` | | `pct` | `pct(x: f64, decimals: i32 = 1): TextBuilder` | appends fixed point then `%` | | `signed` | `signed(x: f64, decimals: i32): TextBuilder` | appends fixed point with `+` above zero, `-` below, no sign at zero | | `compact` | `compact(x: f64, decimals: i32 = 1): TextBuilder` | appends `K` `M` `B` `T` scaling at 1e3, 1e6, 1e9, 1e12, trailing fraction zeros trimmed, sign kept | | `mask` | `mask(x: f64, mask: string, tick: f64 = 0): TextBuilder` | appends `x` as TradingView spells `str.tostring(x, mask)`, the rules in [From Pine](#from-pine) | | `time` | `time(t: f64, pattern: string, offsetSec: i32 = 0): TextBuilder` | appends the clock time of `t` shifted by `offsetSec`, tokens `yyyy` `MM` `dd` `HH` `mm` `ss` `MMM` `EEE` | | `duration` | `duration(seconds: f64): TextBuilder` | appends the two largest non-zero units of `d` `h` `m` `s`, `0s` for zero | | `expiry` | `expiry(expiryMs: f64, nowMs: f64, zone: i32): TextBuilder` | appends an option expiry's label: its trade date on the market's clock (`zone` is `i32(p_market_zone())`, the date `optionsTradeDay` reads) as `15 Jan`, or `15 Jan '27` when that year is not the year of `nowMs`; both times in epoch ms, at most ten characters | | `spaces` | `spaces(n: i32): TextBuilder` | appends `n` spaces | | `length` | `length(): i32` | the bytes stored, never above the capacity | | `needed` | `needed(): i32` | the bytes every append since `clear()` asked for, stored or dropped | | `ptr` | `ptr(): i32` | the address of the stored bytes (what a sender hands the chart) | | `overflowed` | `overflowed(): bool` | `true` when an append was dropped since `clear()`; sending the builder then stops the run by name | Every method on one builder, each with its output: ```typescript output("close_line", line, overlay, { color: "#94a3b8", description: "The close" }); output("line_bytes", line, lower, { description: "Bytes the tour line holds" }); // a count, so its own pane, not the price scale string("tour", { max_bytes: 96 }); render.table("tour_table", { rows: 1, cols: 1, cells: ["tour"], position: "bottom_left" }); let tb = new TextBuilder(1); function onStart(): void { tb = new TextBuilder(96); // capacity 96: allocated here, once } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; out_close_line(close); tb.clear() // length() 0, needed() 0, overflowed() false .text("px ") // px .price(1234.5678, 0.01) // 1234.57 .char(0x20) // one space .f64(0.125, 2) // 0.13 .spaces(1) // one space .auto(0.00012345) // 0.00012345 .spaces(1) .pct(12.345, 1) // 12.3% .spaces(1) .signed(-3.5, 1) // -3.5 .spaces(1) .int(42) // 42 .spaces(1) .compact(2500000.0, 1) // 2.5M .spaces(1) .time(1700000000.0, "HH:mm", 0) // 22:13 .spaces(1) .duration(3661.0); // 1h 1m // The line: "px 1234.57 0.13 0.00012345 12.3% -3.5 42 2.5M 22:13 1h 1m" out_line_bytes(f64(tb.length())); // 57, and needed() is 57: nothing was dropped str_tour_tb(tb); // sends ptr() and length() to the slot; overflowed() is false } ``` When a line should survive the shared builder's next `sb_clear()`, when two lines are built side by side, or when you want the overflow check before sending, a builder of your own is the tool: ```typescript input("high", ohlcv.high); output("mid", line, overlay, { color: "#f59e0b", description: "Bar midpoint" }); string("range", { max_bytes: 32 }); string("mid_text", { max_bytes: 24 }); render.text("range_mark", { y: "mid", text: "range", size: 10 }); render.table("mid_table", { rows: 1, cols: 1, cells: ["mid_text"], position: "top_right" }); let tb = new TextBuilder(1); function onStart(): void { tb = new TextBuilder(24); // its own buffer, allocated once, here } function onBar(): void { const high = bar.high(); const low = bar.low(); const mid = (high + low) / 2.0; if (isNaN(mid)) return; out_mid(mid); // The shared builder, sent to one slot: "1230.00 .. 1240.50". sb_clear(); sb_price(low, 0.01); sb_text(" .. "); sb_price(high, 0.01); str_range_sb(); // A second builder keeps its own line: build, check, then send it to // another slot. "mid 1235.25 (10.5 wide)" is 23 bytes and fits; a wider // market with more digits would not, and the shorter line goes instead. tb.clear().text("mid ").price(mid, 0.01).text(" (").auto(high - low).text(" wide)"); if (tb.overflowed()) tb.clear().text("mid ").price(mid, 0.01); str_mid_text_tb(tb); } ``` The check before `str_mid_text_tb(tb)` is what keeps a long line from ending the run: a builder that overflowed is never sent short. The builder never sends anything itself: only the generated `str__*` calls reach the chart, so a slot is always named by its declaration. ## Chart names in text `{{symbol}}`, `{{exchange}}` and `{{timeframe}}` inside a string output, a label, a table cell or a card are replaced by the chart when it draws them: the symbol the chart header shows, its exchange name, and the short label the interval button shows. The indicator never sees the names: it writes the placeholder as plain text and the chart fills it in at display time, so one module reads right on every chart it is added to. ```typescript sb_clear(); sb_text("{{symbol}} {{timeframe}} on {{exchange}}: "); sb_signed(change, 2); sb_text("%"); str_readout_sb(); ``` Any other `{{...}}` text is shown as written. Alert messages keep their own placeholders ([Alerts](alerts.md)). Protected indicators that run in the cloud show the placeholders as written for now. ## String methods AssemblyScript's `String` has the JavaScript methods you expect. They work on `string` values in the module, in `onStart()` or per bar, and the result goes out through `str_(s)`. | Method | Signature | Description | | --- | --- | --- | | `split` | `s.split(separator)` | splits into an array of substrings (`string[]`) | | `concat` | `s.concat(other)` | joins two strings; `+` does the same | | `substring` | `s.substring(start, end?)` | the characters between two indexes | | `toUpperCase` | `s.toUpperCase()` | uppercase copy | | `toLowerCase` | `s.toLowerCase()` | lowercase copy | | `trim` | `s.trim()` | whitespace removed from both ends (`trimStart`, `trimEnd` too) | | `replace` | `s.replace(search, replaceWith)` | the first occurrence replaced (`replaceAll` for every one) | | `indexOf` | `s.indexOf(search)` | the index of the first occurrence, `-1` if absent | | `startsWith`, `endsWith` | `s.startsWith(prefix)` | prefix and suffix tests | | `includes` | `s.includes(search)` | containment test | | `length` | `s.length` | the number of UTF-16 units; a property, not a call | | `charCodeAt` | `s.charCodeAt(i)` | the code unit at `i` | | `padStart`, `padEnd` | `s.padStart(width, fill)` | padding to a width | Numbers do not stringify themselves cheaply: `sb_f64` and `sb_int` are the way to put a number in a line, and the builder is where per-bar text belongs. ## Allocation Every `String` method that returns a new string allocates it. The module frees a string the bar drops, and in a file with `onBar()` the build reserves scratch for such temporaries before the first bar, so per-bar `String` work runs; a module whose memory grows after `onStart()` is still refused (4 MiB is the ceiling), and a file with the four functions gets no scratch. The `sb_*` builder is allocation-free by design (one shared buffer sized to the largest slot at module start), so the rule is: `String` methods for one-time work in `onStart()` or at module start (a label, a market name, a template), `sb_*` for everything that happens per bar. ## The String methods in one module A label assembled once in `onStart()` with the `String` methods, and per-bar text built with the `sb_*` builder into a mark and a live tag. ```typescript param("period", 20, { min: 1, max: 200 }); output("average", line, overlay, { color: "#38bdf8", width: 2, description: "Simple average" }); output("bar_time", none, overlay, { description: "Bar open in epoch seconds" }); output("stretched", none, overlay, { description: "1 while the close is over two percent from the average" }); string("readout", { max_bytes: 48 }); string("tag", { max_bytes: 48 }); render.text("stretch_mark", { y: "average", text: "readout", size: 10 }); render.label("average_tag", { x: "bar_time", y: "average", text: "tag", size: 11 }); let sma = new Sma(20); let label: string = ""; let period: i32 = 20; let barIndex: i32 = 0; function onStart(): void { period = i32(p_period()); sma = new Sma(period); // One-time string work: every method from the table, on a market label. const raw = " btc-usdt:perp "; const parts = raw.trim().split(":"); let name = parts[0].toUpperCase().replace("-", "/"); if (name.startsWith("BTC") && name.endsWith("USDT") && name.indexOf("/") == 3 && name.includes("USD")) { name = name.concat(" ").concat(parts[1].toLowerCase()); } label = name.substring(0, name.length).padEnd(12, "."); } function onBar(): void { const close = bar.close(); const barTime = bar.time(); const value = sma.update(close); barIndex += 1; if (isNaN(value)) return; const stretch = ((close - value) / value) * 100.0; const stretched = Math.abs(stretch) >= 2.0; out_average(value); out_bar_time(barTime); out_stretched(stretched ? 1.0 : 0.0); if (stretched) { // Per-bar text: the builder, no allocation. sb_clear(); sb_f64(stretch, 1); sb_text("% at bar "); sb_int(barIndex); str_readout_sb(); } sb_clear(); sb_text(label); sb_text(" SMA "); sb_f64(value, 2); str_tag_sb(); } ``` `label` is built once in `onStart()` and reused on every bar. The readout is written only on stretched bars, so the mark appears only there. ## From Pine - `str.tostring(x, mask)` is `sb_mask(x, mask)`, which spells the number the way TradingView does (measured against its own output for 1,936 values and masks): a `#` fraction digit drops a trailing zero (`12.5` at `"#.##"` reads `12.5`, `1` reads `1`) and a `0` digit keeps it (`1.5` at `"0.00"` reads `1.50`); `,` groups the digits left of the point; rounding is half away from zero on the shortest decimal that spells the value (`1.005` and `0.145` at `"#.##"` read `1.01` and `0.15`, `-2.5` at `"#"` reads `-3`), and a value that rounds to zero carries no `-`. Text around the number is copied (`"$#.##"` reads `$12.5`), and a `%` in it multiplies by 100 first. - `str.tostring(x)` is `sb_mask(x, "")`: up to ten decimals, the number's shortest spelling. `str.tostring(x, format.mintick)` is `sb_mask(x, "mintick", tick)` with the market's tick: a whole number of ticks, rounded half away from zero, every tick decimal written (`0.145` reads `0.14` at a 0.01 tick). `format.percent` is `sb_mask(x, "percent")` (`12.5` reads `12.50%`, not scaled) and `format.volume` is `sb_mask(x, "volume")` (`999` reads `999`, `1234.5` reads `1.235K`). `sb_f64` and `sb_auto` stay the kit's own spellings: `sb_f64(12.5, 2)` always writes `12.50`, and `sb_auto` keeps five significant digits. - `str.format("{0} / {1}", a, b)` is the chained calls: `sb_mask(a, "")`, `sb_text(" / ")`, `sb_mask(b, "")`; `{0,number,#.##}` is `sb_mask(a, "#.##")`, and a `{0,date,...}` or `{0,time,...}` is spelled in UTC (`sb_time(t, pattern, 0)`). - `str.format_time(t, "yyyy-MM-dd HH:mm", tz)` is `sb_time(t, "yyyy-MM-dd HH:mm", offsetSec)`, with the zone as an offset in seconds. # Colors A color in a wrun indicator lives in one of three places: as a literal on a declaration, as a per-bar palette index on a `color_by` output, or as a packed number that `./sdk/color` computes for a drawing handle while the module runs; in every place, seven theme tokens name the chart's own colours instead of a fixed one. This page covers the forms a declaration accepts and where a name is refused, the theme tokens, the per-bar ladder, and the run-time kit: `ink`, `fromHex`, `alpha`, `mix`, `fromGradient`, `lighten`, `darken`, the channel readers, `toPacked` and `fromPacked` for the packed colour an output carries, `ColorScale` and `Thresholds`. ## Where a color lives | Place | What it is | Who reads it | | --- | --- | --- | | a declaration (`color`, `colors`, `borderColor`, a renderer's `color`) | a string literal, or a `param.color` named as `"@name"` | **Run** reads it as text; the module never executes it | | a `color_by` output | a number per bar, floored into the `colors` palette | the chart, per bar | | a drawing handle (`draw.line`, `draw.box`, `draw.label`, `draw.polyline`) | a packed `i32` from `./sdk/color` or `rgba(...)` | the module, through `color(...)`, `fill(...)` and a box's or polyline's `gradient(...)` while it runs | The split is the one behind every declaration: the module computes numbers and the chart draws them from the declaration, so the decision behind a color (a regime, a bucket) stays a number your file can test, read at the Console prompt, or hand to a declared alert. What you would ask a color function for, and where each answer lives: | You want | On a declaration | On a handle | | --- | --- | --- | | an RGB color | a literal: `"#2563eb"`, `"rgb(37, 99, 235)"`, `"hsl(221, 83%, 53%)"` | `ink.SKY`, `fromHex("#0ea5e9")`, or `rgba(14, 165, 233, 255)` from `./gen/draw` | | transparency | the `opacity` option (0..1), or alpha inside the color (`"#2563eb66"`) | `alpha(c, 0.4)` | | a lighter, darker or blended color | write the result as a literal | `lighten`, `darken`, `mix` | | a gradient driven by a value | a `colors` palette plus `color_by` over a bucket index: stepped, as fine as the palette is long | `fromGradient(value, bottom, top, a, b)` per bar, Pine's `color.from_gradient`: continuous (or `mix(a, b, t)`) | | a fill that fades across a shape | a box's `gradient` (2..8 stops) and `gradient_direction` | `gradient(start, end, GradientDirection)` on a box or a polyline: two packed colours painted over the shape's bounding box, top to bottom or left to right; `alpha(c, 0.0)` as the end fades it out | | a named palette | a `colors` literal array; there are no named palettes | `ink.*`, twenty named packed colors | | a color the user picks | `param.color`, bound by `"@name"` ([The Style page](../settings/style-page.md)) | `p_()` reads it as one packed number ([Setting kinds](../settings/kinds.md)) | ## Color forms on declarations The chart parses a declared color string as a CSS color. Every form, and where it is accepted: | Form | Example | Accepted on | | --- | --- | --- | | six-digit hex | `"#2563eb"` | everything | | eight-digit hex, alpha in the last two digits | `"#2563eb66"` | everything; the built-in way to carry alpha | | `rgb()` / `rgba()` | `"rgb(37, 99, 235)"` | everything | | `hsl()` / `hsla()` | `"hsl(221, 83%, 53%)"` | everything | | a named color | `"orange"` | an output's `color` and its `colors` palette, a segment, a box `borderColor`, `render.*`, `draw.*`, a `range()`; refused on a box fill | | `"@name"` | `"@basis_color"` | `color` and a `colors` entry, naming a `param.color` | | a theme token | `"theme.up"` | everything: the chart's own colour, resolved when it paints ([Theme tokens](#theme-tokens)) | A box's `color` is its fill, and the fill takes the box's `opacity`, so the host must be able to rewrite the color with an alpha channel. That is why a box `color` must be hex (3, 4, 6 or 8 digits), `rgb()` / `rgba()`, `hsl()` / `hsla()` or a theme token: a name there is refused at validation with `color must be a hex, rgb() or hsl() color (the fill takes the opacity)`. `borderColor` is a stroke and takes any form. Alpha has two spellings. An eight-digit hex, `rgba()` or `hsla()` bakes it into the color; the `opacity` option (0..1) on an output, a box, a range, a fill, a handle or a card applies it on top. The two compose: a box with `color: "#2563eb"` and `opacity: 0.15` fills at fifteen percent, and an output's `opacity` fades every colour it draws, a ladder's rungs and a candle's border and wick included. The sheet validator checks a box fill's form before the module runs; the chart parses every other color string when it draws. A channel outside its range (`rgb(300, 0, 0)`) is not a build error, but it is not a color the chart can render either, so keep channels in `0..255` and hue, saturation and lightness in their own ranges. Six- or eight-digit hex everywhere is the safe habit: it validates on a fill, it carries alpha, and it is what every worked example in this tree uses. ### Theme tokens Seven words name the chart's own colours instead of a fixed one, and every colour key accepts them: `theme.up` and `theme.down` (the candle colours), `theme.text` (the axis text), `theme.muted` (that text at 55 percent), `theme.bg` (the background), `theme.grid` (the grid lines) and `theme.accent` (the app's accent). The chart resolves a token when it paints and again when the theme switches, with no rerun, so an indicator whose chrome is inked `"theme.text"` over `"theme.bg"` reads on a dark and a light chart alike. A token carries no alpha of its own: fade it through the `opacity` word of the surface (`opacity`, `fill_opacity`, `background_opacity`) or, at run time, `alpha(theme.UP, 0.2)` from `./sdk/color`, which also has the tokens as packed values for the drawing handles ([Theme colours](#theme-colours)). A `theme.` word outside the seven is refused by name, and a `param.color` default or preset stays a concrete colour: put the token on the colour key, not on the setting. The colour words that arrived with the styling round (an output's `fill_color`, `fill_gradient`, `gradient`, `up_color`, `down_color`, `border_colors`, `wick_colors`; a `fill(...)`; a card, feed, meter, ladder or HUD surface; a tile; a `plot.levels` profile and a `panel.*` series; a frame's colour strings) take `#rrggbb`, `#rrggbbaa` or a theme token only, one colour grammar on every new surface: the refusal reads `a colour must be #rrggbb, #rrggbbaa or one of theme.up, theme.down, theme.text, theme.muted, theme.bg, theme.grid, theme.accent`. The older surfaces (an output's `color` and `colors`, a segment, a box border, the `render.*` and `draw.*` colours, a `range()`) keep taking a CSS name, `rgb()` and `hsl()` beside the token, and the new keys of those surfaces (`background_color`, `border_color`, `glow_color`, `emblem_color`, `text_color`, `fill_color`, a `gradient` stop) take the same forms as their siblings. ### Named colors The common names and the hex each one stands for. Write the hex instead of the name and the result is identical on every surface, including the one that refuses names. | Name | Hex | Name | Hex | Name | Hex | | --- | --- | --- | --- | --- | --- | | `red` | `#FF0000` | `green` | `#008000` | `blue` | `#0000FF` | | `orange` | `#FFA500` | `lime` | `#00FF00` | `navy` | `#000080` | | `yellow` | `#FFFF00` | `olive` | `#808000` | `teal` | `#008080` | | `maroon` | `#800000` | `purple` | `#800080` | `aqua` | `#00FFFF` | | `fuchsia` | `#FF00FF` | `gray` | `#808080` | `silver` | `#C0C0C0` | | `black` | `#000000` | `white` | `#FFFFFF` | | | A name and its hex are interchangeable on an output, and each output owns its color: there is no shared array with an index argument. ```text output("sma20", line, overlay, { color: "orange", width: 2 }); output("sma50", line, overlay, { color: "#FFA500", width: 2 }); // the same orange ``` ### Choosing colors - Never rely on color alone: a `shape` mark or a data-only output carries the same decision for anyone who cannot see the tint, and for an alert, which cannot see it at all. - Semantic colors read fastest: green for bullish signals and positive values, red for bearish signals and losses, blue for neutral lines and references, orange or yellow for warnings. - Keep one scheme across related indicators. A package's colors are declarations, so they stay aligned across versions. - Three sets that read well together: `green`, `red`, `blue` for signals; `orange`, `purple`, `teal` for overlays; `lime`, `yellow`, `fuchsia` for volume. - The worked examples in this tree use one muted set that reads on dark and light themes alike: `#2563eb` blue, `#16a34a` green, `#dc2626` red, `#f59e0b` amber, `#7c3aed` violet, `#94a3b8` slate for reference lines, and `#22d3a5` / `#ff5b7f` for bull and bear tints. - **Theme tokens for chrome, fixed colours for meaning.** Ink a label's background `theme.bg`, its text `theme.text` and a grid line `theme.grid`, so the indicator follows the viewer's theme; keep the colours that carry a signal (green, red, amber) as hex, so they mean the same on every chart. - **The light-theme guard.** On a light chart the chart darkens a colour that would vanish against the background; an indicator whose colours are chosen for both themes (theme tokens, or a palette tested on both) opts out with `chart.contrast_guard(false)` at the top of the file and draws exactly as written. ## Per-bar color A declared color cannot change per bar, and the module cannot compute one for a declaration. Per-bar color is a ladder: a data-only (`none`) output holds a palette index, and the drawn output names it with `color_by` over a literal `colors` array. Normalize the value into `0 .. n - 1`, floor it, write it to the `none` output, and put an `n`-entry palette on the drawn output. What each bar draws: | Index on this bar | The output draws | | --- | --- | | finite, inside the palette | that entry (floored) | | finite, outside the palette | entry 0 | | `NaN` or infinite | its static `color`; entry 0 when none is declared | `color_by` and `colors` go together: either without the other is refused by name. An output cannot color itself, so the decision is its own output. The ramp is as fine as the palette is long, and the palette is yours. Five stops of a viridis ramp over RSI, a declared opacity, a two-literal blend driven by a 0/1 index, and a box fill in hex: ```typescript param("period", 14, { min: 2, max: 200 }); // A five-step color ladder over RSI: cool when oversold, hot when overbought. output("rsi", line, lower, { width: 2, color_by: "heat", colors: ["#440154", "#3b528b", "#21918c", "#5ec962", "#fde725"], description: "RSI colored by its own level" }); output("heat", none, lower, { description: "0..4: which fifth of 0..100 the RSI sits in" }); // opacity(color, 40) as a declared opacity. output("sma20", line, overlay, { color: "#2563eb", opacity: 0.4, width: 2, description: "A faded average" }); // blend(green, red, weight) per regime as two literals and a 0/1 index. output("trend", line, overlay, { width: 2, color_by: "trend_up", colors: ["#dc2626", "#16a34a"], description: "The average, red falling, green rising" }); output("trend_up", none, overlay, { description: "1 while the average rises" }); // A box fill: a hex color with the transparency in the declared opacity. const bandHi = output("band_hi", none, overlay); const bandLo = output("band_lo", none, overlay); box("band", { top: bandHi, bottom: bandLo, color: "#2563eb", opacity: 0.12, borderWidth: 0 }); let rsi = new Rsi(14); let sma = new Sma(20); let average: f64 = NaN; let prevAverage: f64 = NaN; function onStart(): void { rsi = new Rsi(i32(p_period())); sma = new Sma(20); } function onBar(): void { const close = bar.close(); const strength = rsi.update(close); prevAverage = average; average = sma.update(close); if (isNaN(strength) || isNaN(average)) return; // Bucket 0..100 into five steps; 100 itself lands in the last bucket. let bucket = Math.floor(strength / 20.0); if (bucket > 4.0) bucket = 4.0; out_rsi(strength); out_heat(bucket); out_sma20(average); out_trend(average); out_trend_up(!isNaN(prevAverage) && average >= prevAverage ? 1.0 : 0.0); out_band_hi(average * 1.01); out_band_lo(average * 0.99); } ``` The `heat` output draws nothing, but it is a value like any other: after a **Run**, type `last 20 heat` at the editor's Console prompt to read the bucket on the newest twenty bars. The index need not be a floor. A condition that answers `0`, `1` or `2` is the same ladder over a three-entry palette, and a name is accepted as an entry: ```typescript param("period", 14, { min: 2, max: 200, description: "RSI length" }); // colors is the palette; level picks the entry per bar: 0 red (overbought), 1 green (oversold), 2 blue (neutral). output("rsi", line, lower, { width: 2, color_by: "level", colors: ["#FF0000", "green", "#0000FF"], description: "RSI with conditional colors" }); output("level", none, lower, { description: "0 above 70, 1 below 30, 2 in between" }); let rsi = new Rsi(14); function onStart(): void { rsi = new Rsi(i32(p_period())); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; out_rsi(value); out_level(value > 70.0 ? 0.0 : value < 30.0 ? 1.0 : 2.0); } ``` The same pair works on a `width_by` output with a `widths` array for line width, on a `render.legend` entry, and on a `shape` output ([Styling](../presentation/styling.md), [Legend](../presentation/legend.md)). ### Tinting bars The ladder also drives a background tint through `render.bgcolor` and a candle tint through `render.barcolor` ([Plotting](../presentation/plotting.md)): a `where` gate says which bars get a tint, and `color_by` with `colors` picks it per bar. A non-finite index means no tint on that bar (the static `color` never substitutes), so a `NaN` bucket is a clean way to leave a bar alone. ```typescript param("period", 14, { min: 2, max: 100, description: "RSI Period" }); param("overbought", 70, { min: 50, max: 100, description: "Overbought Level" }); param("oversold", 30, { min: 0, max: 50, description: "Oversold Level" }); output("rsi", line, lower, { color: "#2962ff", width: 2, description: "Relative strength index" }); output("zone", none, lower, { description: "0 oversold, 1 overbought: the tint ladder index; NaN in between" }); output("extreme", none, lower, { description: "1 on bars in either zone: the tint gate" }); // A background tint per condition: one declaration, a gate, and a two-entry ladder. render.bgcolor("zones", { where: "extreme", color_by: "zone", colors: ["rgba(76, 175, 80, 0.3)", "rgba(244, 67, 54, 0.3)"] }); let rsi = new Rsi(14); let overbought: f64 = 70.0; let oversold: f64 = 30.0; function onStart(): void { rsi = new Rsi(i32(p_period())); overbought = p_overbought(); oversold = p_oversold(); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; const hot = value > overbought; const cold = value < oversold; out_rsi(value); out_zone(cold ? 0.0 : hot ? 1.0 : NaN); out_extreme(hot || cold ? 1.0 : 0.0); } ``` Five zones (extreme oversold, oversold, neutral, overbought, extreme overbought) are a five-entry palette and a bucket that lands in `0 .. 4`; the module above keeps two for clarity. ### What has no form A declared color is never computed at run time. Compute the color you want ahead of time and write it as a literal; a blend that depends on a per-bar weight is a ladder over a few blended literals, with the weight bucketed into the index. The module has no color variable type: a declared color is a string literal read once when the sheet is derived, and the only setting that holds a color is a `param.color`. The one place a computed color lands is a drawing handle, through the kit below. ## Colors computed at run time The line, box, label and polyline handles from `./gen/draw` are created and restyled by the module while it runs, and their `color(...)` and `fill(...)` setters take a packed `i32`, a box's or a polyline's `gradient(start, end, dir)` two of them, its stops ([Drawing objects](../presentation/drawing-objects.md)). That is where `./sdk/color` goes: a color computed from a value on this bar, applied to a handle on this bar. Its two scales, `ColorScale` and `Thresholds`, serve the other half: they compute the index a `color_by` output carries, so the color itself stays a literal and the decision stays a number. ### Every export | Export | Signature | Definition | | --- | --- | --- | | `ink` | `ink.RED`, `ink.ORANGE`, `ink.AMBER`, `ink.YELLOW`, `ink.LIME`, `ink.GREEN`, `ink.EMERALD`, `ink.TEAL`, `ink.CYAN`, `ink.SKY`, `ink.BLUE`, `ink.INDIGO`, `ink.VIOLET`, `ink.PURPLE`, `ink.PINK`, `ink.ROSE`, `ink.SLATE`, `ink.GRAY`, `ink.WHITE`, `ink.BLACK` (`i32`) | opaque packed colors, the palette below, packed exactly as `rgba(...)` from `./gen/draw` packs | | `fromHex` | `fromHex(hex: string): i32` | `"#rrggbb"` (opaque) or `"#rrggbbaa"`, either case; any other text reads `0`, the transparent `na` colour | | `hexRefusal` | `hexRefusal(hex: string): string` | why `fromHex` read `0`, as `color: bad hex : ...` with the forms it takes (`"ff0000"` is named as `"#ff0000"`, `"#f00"` as `"#ff0000"`); the empty string for a text `fromHex` reads | | `alpha` | `alpha(color: i32, a: f64): i32` | the color with its alpha byte set from an opacity `0..1`, RGB untouched | | `mix` | `mix(a: i32, b: i32, t: f64): i32` | every channel, alpha included, `t` of the way from `a` to `b`, linear in sRGB | | `fromGradient` | `fromGradient(value: f64, bottom: f64, top: f64, bottomColor: i32, topColor: i32): i32` | Pine's `color.from_gradient` as TradingView computes it: `value` held to `bottom..top`, each colour weighted by its alpha, every channel floored; `0` (Pine's `na` colour) for a `NaN` value or bound and for equal bounds | | `lighten` | `lighten(color: i32, amount: f64): i32` | each RGB channel moved toward 255 by the fraction, alpha kept | | `darken` | `darken(color: i32, amount: f64): i32` | each RGB channel moved toward 0 by the fraction, alpha kept | | `red`, `green`, `blue` | `red(color: i32): i32` | one channel of a packed color, `0..255` (Pine's `color.r`, `color.g`, `color.b`) | | `opacity` | `opacity(color: i32): f64` | the alpha byte over `255`, `0..1`: what `alpha` takes, so `alpha(c, opacity(c))` is `c` again | | `transparency` | `transparency(color: i32): f64` | Pine's `color.t`: `(255 - alpha) * 100 / 255`, `0` opaque to `100` invisible | | `ColorScale` | `new ColorScale(min: f64, max: f64, steps: i32)`, `.index(v: f64): f64` | `floor((v - min) / (max - min) * steps)` clamped to `0..steps - 1`; `NaN` in, `NaN` out | | `Thresholds` | `new Thresholds(levels: StaticArray)`, `.index(v: f64): f64` | the number of levels at or below `v`, `0..levels.length`; `NaN` in, `NaN` out | | `theme` | `theme.UP`, `theme.DOWN`, `theme.TEXT`, `theme.MUTED`, `theme.BG`, `theme.GRID`, `theme.ACCENT` (`i32`) | the seven theme tokens as packed values the chart resolves when it paints: the candle up and down colours, the axis text, that text at 55 percent, the background, the grid lines and the app's accent | | `isThemeToken` | `isThemeToken(c: i32): bool` | whether a packed value is one of the seven tokens (at any alpha) | | `toPacked`, `fromPacked` | `toPacked(c: i32): f64`, `fromPacked(v: f64): i32` | a packed color as the `f64` a `color_packed_by` output carries, and back; both keep a theme token a token | Construct the scales and parse hex literals in `onStart()`: the constructors allocate, and nothing else in the module allocates per bar. ### Theme colours A theme token is a colour the module names but never computes: the chart fills it in when it paints, from its own theme, and again when the theme switches, so a label inked `theme.TEXT` reads on a dark and a light chart alike. `alpha(theme.UP, 0.2)` is still a token, carrying the alpha with it, and `opacity(c)` and `transparency(c)` read that alpha back; `mix`, `lighten`, `darken`, `red`, `green` and `blue` have no concrete colour to work on and abort with `color: takes a concrete colour; theme tokens resolve at paint time`. A concrete colour never spells a token by accident: an alpha-0 result whose red byte is `0x7e` and green byte `1..7` (an invisible colour before tokens existed) reads as `0`, transparent black, from `rgba(...)`, `alpha`, `mix`, `lighten`, `darken`, `fromHex` and `fromPacked` alike, so it stays invisible and never aborts the readers. A token goes anywhere a packed colour goes: a handle's `color(...)` or `fill(...)`, and an output a drawn output names with `color_packed_by` (write `toPacked(theme.UP)` to it). The same seven words ride every declared colour as strings (`"theme.up"`, [Styling](../presentation/styling.md#theme-colours)). For a concrete colour the module can compute with, the chart hands over its own: `chart.up_color()`, `chart.down_color()` and `chart.grid_color()` declared at the top of the file (like `chart.bg_color()`) are read in `onStart()` through `i32(p_chart_up_color())` and the two others as packed colours, `0` when no chart is there to answer ([Chart context](../settings/sessions-and-units.md#chart-context)); `mix(i32(p_chart_up_color()), ink.WHITE, 0.3)` is a lighter version of the chart's own up colour. The chart's font needs no reader: `font_family: "ui"` on any text resolves to the chart's own typography. ### The palette `ink` names the 500 row of the Tailwind palette plus white and black, each opaque. The swatch column is the hex you would write as a declared literal for the same color. | Name | Swatch | Name | Swatch | | --- | --- | --- | --- | | `ink.RED` | `#ef4444` | `ink.INDIGO` | `#6366f1` | | `ink.ORANGE` | `#f97316` | `ink.VIOLET` | `#8b5cf6` | | `ink.AMBER` | `#f59e0b` | `ink.PURPLE` | `#a855f7` | | `ink.YELLOW` | `#eab308` | `ink.PINK` | `#ec4899` | | `ink.LIME` | `#84cc16` | `ink.ROSE` | `#f43f5e` | | `ink.GREEN` | `#22c55e` | `ink.SLATE` | `#64748b` | | `ink.EMERALD` | `#10b981` | `ink.GRAY` | `#9ca3af` | | `ink.TEAL` | `#14b8a6` | `ink.WHITE` | `#ffffff` | | `ink.CYAN` | `#06b6d4` | `ink.BLACK` | `#000000` | | `ink.SKY` | `#0ea5e9` | `ink.BLUE` | `#3b82f6` | A packed color is one `i32`: `((r & 0xff) << 24) | ((g & 0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff)`, copied from `rgba(...)` in `./gen/draw` bit for bit, so `ink.RED == rgba(239, 68, 68, 255)` and the two mix freely. Because red sits in the top byte, most inks are negative numbers when you print them: that is the packing, not a fault. ### An index from a value `ColorScale` slices `min..max` into `steps` equal bands and answers the band a value falls in, so a `colors` palette with `steps` entries on the drawn output gets one entry per band. `Thresholds` answers how many of its levels sit at or below the value, so a palette with one entry more than the level count gets one entry per zone. Both return an `f64` that goes straight into a data-only output, and the drawn output names that output with `color_by`. The RSI ladder with the kit computing the index, and a zone number you can read after a **Run** with `last 20 zone` at the Console prompt: ```typescript param("period", 14, { min: 2, max: 200, description: "RSI period" }); // Five bands of 0..100, coolest at the bottom: heat picks the entry per bar. output("rsi", line, lower, { width: 2, color_by: "heat", colors: ["#3b82f6", "#0ea5e9", "#64748b", "#f97316", "#ef4444"], description: "RSI colored by its level" }); output("heat", none, lower, { description: "0..4: the fifth of 0..100 the RSI sits in" }); output("zone", none, lower, { description: "0 below 30, 1 between, 2 at or above 70" }); let rsi = new Rsi(14); let scale = new ColorScale(0.0, 100.0, 5); let zones = new Thresholds(new StaticArray(0)); function onStart(): void { rsi = new Rsi(i32(p_period())); // Built once here: index() never allocates, and neither holds bar state. scale = new ColorScale(0.0, 100.0, 5); const levels = new StaticArray(2); levels[0] = 30.0; levels[1] = 70.0; zones = new Thresholds(levels); } function onBar(): void { const strength = rsi.update(bar.close()); out_rsi(strength); out_heat(scale.index(strength)); out_zone(zones.index(strength)); } ``` An RSI of exactly `100` lands in the last band (the scale clamps, it never answers `steps`), and a value on a threshold counts that threshold (`70` is zone `2`). A `NaN` RSI gives a `NaN` index, and the drawn output falls back to its static color on that bar. ### Colors on a handle Handle setters take the packed color as it is computed, so here color can follow a value continuously instead of through a ladder. The window mean drawn as a line handle in `ink.SKY`, restyled to `alpha(ink.SKY, 0.4)` on the newest bar (the forming one), and the window's range as a box whose tint is mixed at run time between two hex literals parsed in `onStart()`: ```typescript param("period", 20, { min: 2, max: 200, description: "Bars in the window" }); output("mean", line, overlay, { color: "#64748b", description: "The window mean" }); output("up_share", none, overlay, { description: "0..1: the share of up closes in the window, the box's mix weight" }); handles.line({ color: "#0ea5e9", width: 2 }); handles.box({ color: "#0ea5e9", opacity: 0.15, borderWidth: 1 }); const level = draw.line(0); const span = draw.box(1); let period: i32 = 20; let sma = new Sma(20); let ups = new Sma(20); let highs = new Highest(20); let lows = new Lowest(20); let bull: i32 = 0; let bear: i32 = 0; let t: f64 = NaN; let prevT: f64 = NaN; let close: f64 = NaN; let prevClose: f64 = NaN; function onStart(): void { period = i32(p_period()); sma = new Sma(period); ups = new Sma(period); highs = new Highest(period); lows = new Lowest(period); // A literal is checked when the indicator builds: a bad one fails the build on its line. bull = fromHex("#16a34a"); bear = fromHex("#dc2626"); } function onBar(): void { prevT = t; t = bar.time(); prevClose = close; close = bar.close(); const mean = sma.update(close); const share = ups.update(!isNaN(prevClose) && close > prevClose ? 1.0 : 0.0); const hi = highs.update(bar.high()); const lo = lows.update(bar.low()); if (isNaN(mean) || isNaN(hi) || isNaN(prevT)) return; out_mean(mean); out_up_share(share); const start = t - (t - prevT) * f64(period - 1); // The mean across the window: sky, and on the newest bar the same sky at 40% opacity. level.set(start, mean, t, mean).color(bar.isLast() ? alpha(ink.SKY, 0.4) : ink.SKY); // The window's range, tinted by the share of up closes: a gradient computed per bar, not a ladder. const tone = mix(bear, bull, share); span.set(start, hi, t, lo).fill(alpha(lighten(tone, 0.2), 0.15)).color(darken(tone, 0.3)); } ``` `bar.isLast()` answers `1` on the newest bar the chart holds, so the line is drawn faint while that bar is still forming and turns solid once the next bar opens. The box's fill and border are two derivations of one `tone`, so the pair always agree. ### Read a color back `red`, `green` and `blue` read one channel of a packed color, and `opacity` and `transparency` read its alpha. The chart's background arrives packed (`chart.bg_color()`), so a file can pick its ink from it: dark words on a light chart, light words on a dark one. ```typescript // A price tag on the newest bar whose words follow the chart's background: dark on a light chart, light on a dark one. chart.bg_color(); output("close_line", line, overlay, { color: "#94a3b8", description: "The close" }); output("brightness", none, overlay, { description: "The background's brightness, 0 (black) to 255 (white); NaN when the chart did not say" }); output("bg_opacity", none, overlay, { description: "How solid the background is, 0 to 1" }); string("tag", { max_bytes: 32 }); handles.label({ text: "tag", size: 12 }); const tag = draw.label(0); let words: i32 = 0; let brightness: f64 = NaN; let bgOpacity: f64 = NaN; function onStart(): void { const bg = i32(p_chart_bg_color()); // 0 means the chart did not fill the color; then the words stay light. if (bg != 0) { brightness = 0.299 * f64(red(bg)) + 0.587 * f64(green(bg)) + 0.114 * f64(blue(bg)); bgOpacity = opacity(bg); } words = !isNaN(brightness) && brightness > 140.0 ? ink.BLACK : ink.WHITE; } function onBar(): void { const close = bar.close(); if (isNaN(close)) return; out_close_line(close); out_brightness(brightness); out_bg_opacity(bgOpacity); if (!bar.isLast()) return; sb_clear(); sb_text("last "); sb_auto(close); tag.set(bar.time(), close).text(str_tag_sb).color(words); } ``` - **Brightness from the channels.** The three channels weighted `0.299`, `0.587` and `0.114` give 0 for black and 255 for white; above about 140 the background reads as light. On a cream background (`#f4f1ea`) the tag is black. - **0 means unknown.** Where the chart did not fill the background, `p_chart_bg_color()` reads 0 and the words stay white. - **The alpha.** `opacity(bg)` is 1 for a solid background; `transparency(bg)` is the same reading on Pine's 0 to 100 scale, where 0 is solid. - **Only a handle takes it.** The computed color lands on the label through `.color(...)`; a declared color stays a literal (What has no form, above). ### The rules, written out - **Fractions.** An opacity, a mix weight and a lighten or darken amount are clamped to `0..1`; `NaN` reads as `0`, so `alpha(c, NaN)` is invisible, `mix(a, b, NaN)` is `a`, and `lighten(c, NaN)` is `c`. - **Rounding.** A derived channel is `floor(x + 0.5)` held to `0..255`: `alpha(c, 0.5)` sets the alpha byte to `128`, `mix(ink.RED, ink.BLUE, 0.5)` is `#95639d`, `lighten(ink.BLUE, 0.5)` is `#9dc1fb`, `darken(ink.BLUE, 0.5)` is `#1e417b`. `fromGradient` floors instead, as TradingView does. - **`fromGradient`.** Measured against TradingView's `color.from_gradient` over 8,000 values. `value` is held to the range first, `max(bottom, min(top, value))`, so a `bottom` above `top` holds every value at `bottom` (the bottom colour), and `t` is `(held - bottom) / (top - bottom)`. The alpha byte is `floor(a1 * (1 - t) + a2 * t)` and each RGB channel is `floor(((c1 * a1 / 255) * (1 - t) + (c2 * a2 / 255) * t) / (a / 255))`, with `a` that alpha before the floor: each colour counts as much as it is opaque, so an opaque red fading into a clear blue stays red while it fades (`mix` would turn it purple at the middle). A `NaN` value or bound, equal bounds and a blend with no alpha at all give `0`, the transparent colour Pine's `na` paints as nothing. Concrete colours only, like `mix`. - **Readers.** `red`, `green` and `blue` are the packed bytes, exact; `alpha(c, opacity(c))` rebuilds `c` bit for bit; `transparency(c)` is `(255 - alpha) * 100 / 255`, so a color at alpha `128` reads `49.80...`, and `alpha(c, 1.0 - transparency(c) / 100.0)` is `c` again. - **`fromHex`.** Seven characters (`#rrggbb`, alpha `255`) or nine (`#rrggbbaa`), hex digits in either case. Anything else never stops your indicator: it reads `0`, the transparent colour Pine's `na` paints as nothing, and `hexRefusal(text)` says why (`color: bad hex : ...`, with the spelling meant for a text missing its `#` or a three-digit `#f00`). A literal is read when the indicator builds, so `fromHex("ff0000")` fails the build on its line in the same words. - **`ColorScale`.** `v` at `max` lands in the last band. `steps` below `1` reads as `1`; `max` below `min` runs the scale backwards; `max` equal to `min` puts every value above it in the last band and the rest in band `0`. An infinite value clamps to the end it points at. - **`Thresholds`.** A value exactly on a level counts it. The constructor copies the array, order does not matter, and a `NaN` level never counts. - **State and allocation.** Neither scale holds bar state, so a reset has nothing to restore and a reset bar answers the same as any other. `index()`, `alpha`, `mix`, `lighten`, `darken`, the five readers and a successful `fromHex` never allocate, so the per-bar path stays allocation-free. ### From Pine | Pine | wrun | | --- | --- | | `color.new(c, transp)` | on a handle, `alpha(c, 1.0 - transp / 100.0)`: Pine counts transparency `0..100`, `alpha` takes opacity `0..1`, and this form lands on TradingView's alpha byte; on a declaration, the `opacity` option | | `color.from_gradient(value, bottom, top, c1, c2)` | on a handle, `fromGradient(value, bottom, top, c1, c2)`, TradingView's blend; on a declaration, `new ColorScale(bottom, top, n).index(value)` into a `color_by` output over an `n`-entry `colors` palette from `c1` to `c2` (stepped) | | `color.rgb(r, g, b)` | `rgba(r, g, b, 255)` from `./gen/draw` (or `rgb(r, g, b)` there) | | `color.r(c)`, `color.g(c)`, `color.b(c)` | `red(c)`, `green(c)`, `blue(c)` on a packed handle color (a declared color is a literal the module never reads) | | `color.t(c)` | `transparency(c)`, `0..100` as Pine counts it; `opacity(c)` is the same channel on the `0..1` scale `alpha` takes | # Clock and sessions kit The `./sdk/clock` module turns the one number `bar.time()` gives a wrun indicator, the bar's open time in UTC epoch seconds, into the questions a trader asks of a bar: what hour is it in New York, is this the first bar of the day, is the cash session open, which bar is this, how long is a bar, when does it close. A `Clock` answers the calendar questions in a named time zone with its daylight rule applied; a `Session` answers whether the bar sits inside an `0930-1600` window on the days you list, when a session instance starts and when it has just closed. Both are fed once per bar with `update(t)` and read as often as you like, and neither allocates per bar. A `MarketSession` asks the market instead of a zone: it reads the bar's trade date and session phase from the `time` source (Market sessions, below). A higher timeframe built from the chart's own bars or from a `candles` stream is the [Higher-timeframe kit](higher-timeframe-kit.md). The hand-rolled integer math they replace is still on [Time and sessions](../core-concepts/time-and-sessions.md), the manual way, if you want to see what the modules do for you. Construct both classes in `onStart()`, from the settings they read. A zone, session spec or day list the constructor cannot read never stops your indicator: the object refuses softly, `refused()` is true and `refusedReason()` names the rule and the words it takes, and it answers nothing (a `Clock` keeps every calendar field at `0` and `epochSec` at `NaN`, a `Session` never opens). A literal one fails the build on its line instead, in the same words. ## The clock | Export | Signature | Answers | | --- | --- | --- | | `Clock` | `new Clock(zone: string = "UTC")` | a bar clock in one zone; an unknown zone refuses softly with `Clock: unknown zone : ...` (a table name in other capitals, `"asia/kolkata"`, is named as `"Asia/Kolkata"`) | | `refused`, `refusedReason` | `clock.refused(): bool` | the zone could not be read, and why; the empty string while the zone is taken | | `update` | `clock.update(t: f64): void` | folds the bar's open time (`bar.time()`, UTC epoch seconds); call once per bar | | `offsetSec` | `clock.offsetSec(): i32` | the zone's offset from UTC for this bar in seconds, daylight time applied (New York reads `-18000` in winter, `-14400` in summer) | | `hour`, `minute`, `second` | `clock.hour(): i32` | the local time of the bar's open: `0`..`23`, `0`..`59`, `0`..`59` (`second` is `0` on every candle grid) | | `weekday` | `clock.weekday(): i32` | `0` Sunday .. `6` Saturday | | `dayOfMonth`, `month`, `year`, `dayOfYear` | `clock.month(): i32` | `1`..`31`, `1`..`12`, the four-digit year, `1`..`366` | | `dayKey` | `clock.dayKey(): i32` | local days since 1970-01-01: the same number on every bar of one local day | | `weekKey` | `clock.weekKey(): i32` | local weeks since Monday 1970-01-05, a monotonic count (weeks start on Monday) | | `monthKey` | `clock.monthKey(): i32` | `year * 12 + (month - 1)` | | `quarterKey` | `clock.quarterKey(): i32` | `year * 4 + (month - 1) / 3` in integer division: the same number on every bar of one local quarter (the year's own key is `year()`) | | `isNewDay`, `isNewWeek`, `isNewMonth`, `isNewQuarter`, `isNewYear` | `clock.isNewDay(): bool` | `true` on the first bar of the period and on the very first update; a quarter opens on January, April, July or October 1st | | `index` | `clock.index(): i32` | updates seen so far, 0-based: `0` on the first bar, `-1` before any | | `intervalSec` | `clock.intervalSec(): f64` | the smallest positive gap between consecutive bar opens seen so far (a weekend gap never widens it); `NaN` until two bars | | `barCloseSec` | `clock.barCloseSec(): f64` | `t + intervalSec()`: where this bar closes, `NaN` while the interval is unknown | | `dayOfWeek` | `clock.dayOfWeek(): i32` | Pine's `dayofweek`: `1` Sunday .. `7` Saturday (`weekday() + 1`), the scale of the `dayofweek.*` constants | | `weekOfYear` | `clock.weekOfYear(): i32` | Pine's `weekofyear`, the ISO 8601 week: weeks run Monday to Sunday and belong to the year their Thursday is in, so week 1 holds January 4th, January 1st to 3rd can still be week 52 or 53 of the year before, and a late-December Monday can already be week 1; `0` before any update | | `epochSec` | `clock.epochSec(year, month, day, hour = 0, minute = 0, second = 0): f64` | Pine's `timestamp(...)` in the clock's zone, in seconds: the UTC instant of a wall-clock time with the daylight rule applied; the parts normalise as Pine's do (month `13`, day `0`, `dayOfMonth + 1` past a month end, hour `24`, negative parts) | | `reset` | `clock.reset(): void` | back to the freshly constructed state; the zone stays | Two more names come with the clock, for a wall-clock time that needs no zone and for Pine's weekday constants: | Export | Signature | Answers | | --- | --- | --- | | `epochSec` | `epochSec(year, month, day, hour = 0, minute = 0, second = 0): f64` | the same instant read in UTC, with no clock: Pine's `timestamp("UTC", ...)`, in seconds, the parts normalised the same way | | `dayofweek` | `dayofweek.SUNDAY` .. `dayofweek.SATURDAY` (`i32`, `1`..`7`) | Pine's `dayofweek.*` constants, the scale `dayOfWeek()` answers on | `epochSec` answers seconds because every time in a wrun indicator is seconds (`bar.time()`, a `param.time` default, a drawing's x); Pine's `timestamp()` answers milliseconds, so a value a script holds in Pine's unit is this times `1000.0`. A wall time inside a daylight gap (02:30 on the morning the clocks go forward) moves forward by the gap, and one in the repeated autumn hour reads as its first, daylight, occurrence: the answers the Java calendar gives TradingView. Neither call allocates, so `clock.epochSec(clock.year(), clock.month(), clock.dayOfMonth(), 9, 30)` on every bar is fine. Dates from 1970-01-01 to 2099-12-31 are valid, and the calendar is integer math (days from civil and civil from days, no floating-point days), so every field is exact. A non-finite `t` does not move the clock: the fields keep their last values, the new-period flags read `false`, the interval is not fed; only `index()` advances. ### Zones and their daylight rules | Zone | Offset (standard / daylight) | Daylight rule | | --- | --- | --- | | `"UTC"`, `"GMT"`, `"Etc/UTC"`, `"Etc/GMT"` | `+00:00` | none | | `"America/New_York"` | `-05:00` / `-04:00` | US: from the second Sunday of March 02:00 local standard time to the first Sunday of November 02:00 local daylight time | | `"America/Toronto"` | `-05:00` / `-04:00` | US | | `"America/Chicago"` | `-06:00` / `-05:00` | US | | `"America/Denver"` | `-07:00` / `-06:00` | US | | `"America/Phoenix"` | `-07:00` | none | | `"America/Los_Angeles"` | `-08:00` / `-07:00` | US | | `"America/Mexico_City"` | `-06:00` | none since 2023 | | `"America/Bogota"` | `-05:00` | none | | `"America/Lima"` | `-05:00` | none | | `"America/Sao_Paulo"` | `-03:00` | none since 2020 | | `"America/Argentina/Buenos_Aires"`, `"America/Buenos_Aires"` | `-03:00` | none since 2010 | | `"Europe/London"` | `+00:00` / `+01:00` | EU: from the last Sunday of March 01:00 UTC to the last Sunday of October 01:00 UTC | | `"Europe/Dublin"` | `+00:00` / `+01:00` | EU | | `"Europe/Lisbon"` | `+00:00` / `+01:00` | EU | | `"Atlantic/Reykjavik"` | `+00:00` | none | | `"Europe/Paris"` | `+01:00` / `+02:00` | EU | | `"Europe/Brussels"` | `+01:00` / `+02:00` | EU | | `"Europe/Amsterdam"` | `+01:00` / `+02:00` | EU | | `"Europe/Berlin"` | `+01:00` / `+02:00` | EU | | `"Europe/Zurich"` | `+01:00` / `+02:00` | EU | | `"Europe/Madrid"` | `+01:00` / `+02:00` | EU | | `"Europe/Rome"` | `+01:00` / `+02:00` | EU | | `"Europe/Vienna"` | `+01:00` / `+02:00` | EU | | `"Europe/Stockholm"` | `+01:00` / `+02:00` | EU | | `"Europe/Oslo"` | `+01:00` / `+02:00` | EU | | `"Europe/Copenhagen"` | `+01:00` / `+02:00` | EU | | `"Europe/Prague"` | `+01:00` / `+02:00` | EU | | `"Europe/Warsaw"` | `+01:00` / `+02:00` | EU | | `"Europe/Budapest"` | `+01:00` / `+02:00` | EU | | `"Europe/Luxembourg"` | `+01:00` / `+02:00` | EU | | `"Europe/Malta"` | `+01:00` / `+02:00` | EU | | `"Europe/Monaco"` | `+01:00` / `+02:00` | EU | | `"Europe/Zagreb"` | `+01:00` / `+02:00` | EU | | `"Europe/Ljubljana"` | `+01:00` / `+02:00` | EU | | `"Europe/Bratislava"` | `+01:00` / `+02:00` | EU | | `"Europe/Belgrade"` | `+01:00` / `+02:00` | EU | | `"Europe/Sarajevo"` | `+01:00` / `+02:00` | EU | | `"Europe/Podgorica"` | `+01:00` / `+02:00` | EU | | `"Europe/Skopje"` | `+01:00` / `+02:00` | EU | | `"Europe/Tirane"` | `+01:00` / `+02:00` | EU | | `"Europe/Vaduz"` | `+01:00` / `+02:00` | EU | | `"Europe/Andorra"` | `+01:00` / `+02:00` | EU | | `"Europe/Gibraltar"` | `+01:00` / `+02:00` | EU | | `"Europe/San_Marino"` | `+01:00` / `+02:00` | EU | | `"Europe/Vatican"` | `+01:00` / `+02:00` | EU | | `"Europe/Helsinki"` | `+02:00` / `+03:00` | EU | | `"Europe/Athens"` | `+02:00` / `+03:00` | EU | | `"Europe/Bucharest"` | `+02:00` / `+03:00` | EU | | `"Europe/Sofia"` | `+02:00` / `+03:00` | EU | | `"Europe/Riga"` | `+02:00` / `+03:00` | EU | | `"Europe/Tallinn"` | `+02:00` / `+03:00` | EU | | `"Europe/Vilnius"` | `+02:00` / `+03:00` | EU | | `"Europe/Kyiv"`, `"Europe/Kiev"` | `+02:00` / `+03:00` | EU | | `"Europe/Chisinau"` | `+02:00` / `+03:00` | EU (since 2022; Moldova switched at 00:00 UTC before) | | `"Asia/Nicosia"`, `"Europe/Nicosia"` | `+02:00` / `+03:00` | EU | | `"Europe/Istanbul"` | `+03:00` | none since 2017 | | `"Europe/Moscow"` | `+03:00` | none since 2015 | | `"Europe/Minsk"` | `+03:00` | none since 2012 | | `"Africa/Johannesburg"` | `+02:00` | none | | `"Africa/Cairo"` | `+02:00` / `+03:00` | Egypt: from the last Friday of April 00:00 local standard time to the last Thursday of October 24:00 local daylight time (since 2023) | | `"Africa/Lagos"` | `+01:00` | none | | `"Africa/Nairobi"` | `+03:00` | none | | `"Asia/Jerusalem"`, `"Asia/Tel_Aviv"` | `+02:00` / `+03:00` | Israel: from the Friday before the last Sunday of March 02:00 local standard time to the last Sunday of October 02:00 local daylight time (since 2013) | | `"Asia/Riyadh"` | `+03:00` | none | | `"Asia/Dubai"` | `+04:00` | none | | `"Asia/Tehran"` | `+03:30` | none since 2023 | | `"Asia/Karachi"` | `+05:00` | none since 2010 | | `"Asia/Kolkata"`, `"Asia/Calcutta"` | `+05:30` | none | | `"Asia/Kathmandu"`, `"Asia/Katmandu"` | `+05:45` | none | | `"Asia/Dhaka"` | `+06:00` | none since 2010 | | `"Asia/Yangon"`, `"Asia/Rangoon"` | `+06:30` | none | | `"Asia/Bangkok"` | `+07:00` | none | | `"Asia/Jakarta"` | `+07:00` | none | | `"Asia/Ho_Chi_Minh"`, `"Asia/Saigon"` | `+07:00` | none | | `"Asia/Singapore"` | `+08:00` | none | | `"Asia/Kuala_Lumpur"` | `+08:00` | none | | `"Asia/Manila"` | `+08:00` | none | | `"Asia/Hong_Kong"` | `+08:00` | none | | `"Asia/Shanghai"` | `+08:00` | none | | `"Asia/Taipei"` | `+08:00` | none | | `"Asia/Seoul"` | `+09:00` | none | | `"Asia/Tokyo"` | `+09:00` | none | | `"Australia/Perth"` | `+08:00` | none since 2010 | | `"Australia/Darwin"` | `+09:30` | none | | `"Australia/Adelaide"` | `+09:30` / `+10:30` | AU: from the first Sunday of October 02:00 local standard time to the first Sunday of April 03:00 local daylight time (it spans the new year; since 2008) | | `"Australia/Brisbane"` | `+10:00` | none | | `"Australia/Sydney"` | `+10:00` / `+11:00` | AU (since 2008) | | `"Australia/Melbourne"` | `+10:00` / `+11:00` | AU (since 2008) | | `"Australia/Hobart"` | `+10:00` / `+11:00` | AU (since 2008) | | `"Pacific/Auckland"` | `+12:00` / `+13:00` | NZ: from the last Sunday of September 02:00 local standard time to the first Sunday of April 03:00 local daylight time (it spans the new year; since 2008) | | `"+HH:MM"`, `"-HH:MM"`, `"+H:MM"` | as written | none: a fixed offset written with a colon, such as `"+05:30"` or `"+5:30"`, hours `00`..`23` (the bound the first `Clock` had, so `"+15:00"` still builds) | | `"+H"`, `"+HHMM"` | as written | none: the same without a colon, such as `"-3"` or `"+0530"`, at most `14:00` either way so a typo cannot pass as an offset | | `"UTC+5:30"`, `"GMT-4"`, `"UTC+0530"` | as written | none: the same offsets after a `UTC` or `GMT` prefix, the way Pine scripts spell them, with the same bounds (`"UTC+15:30"` builds, `"UTC+15"` refuses) | | `"Etc/GMT+N"`, `"Etc/GMT-N"` | the sign inverted | none: the tz database's `Etc` zones, whole hours up to `14` with the sign inverted (`"Etc/GMT+5"` is `-05:00`) | Every year in the valid range follows today's rule for its zone; where a rule changed after 2007 the row says since when (Mexico City kept daylight time until 2022, so a 2019 summer bar reads one hour off here), and a zone's history before that year is not modelled. The table holds every European capital with a zone of its own in the tz database, Reykjavik to Nicosia and Chisinau (Pristina has none: Kosovo keeps Belgrade's time, so `"Europe/Belgrade"` serves it). Anything else passed as a zone refuses softly at construction with `Clock: unknown zone `. ## Sessions | Export | Signature | Answers | | --- | --- | --- | | `Session` | `new Session(spec: string, zone: string = "UTC", days: string = "0123456")` | an `"HHMM-HHMM"` window in the zone's local time on the weekdays listed; a spec that is not `HHMM-HHMM` refuses softly with `Session: bad spec : ...`, a day list with a character outside `0`..`6` with `Session: bad days : ...` (none at all with `Session: no days`), and the session never opens | | `refused`, `refusedReason` | `session.refused(): bool` | the spec, the days or the zone could not be read, and why (the first of them) | | `update` | `session.update(t: f64): void` | folds the bar's open time; call once per bar | | `isIn` | `session.isIn(): bool` | the bar's open sits inside the window on a listed day | | `isFirst` | `session.isFirst(): bool` | this is the first in-session bar of an instance | | `closed` | `session.closed(): bool` | an instance ended before this bar: `true` on the first update after it, whether this bar is outside or already inside the next instance | | `key` | `session.key(): i32` | the `dayKey` of the instance's opening day while in, `-1` outside | | `reset` | `session.reset(): void` | forgets the running instance; the spec, zone and days stay | The rules, written out: - **Half-open.** A bar is in when `open <= local time of day < close`, tested on the bar's open time. `"0930-1600"` includes the 09:30 bar and excludes the 16:00 bar. `open == close` is never in. `"2400"` is accepted as a close, so `"0000-2400"` is the whole day. - **Crossing midnight.** A close before its open wraps: `"2200-0400"` runs from 22:00 to 04:00 the next morning. Every bar of that window belongs to the day it opened on, so a Friday-night session keyed to Friday runs into Saturday morning. - **The day digits.** `days` lists the weekdays the session may OPEN on, as the same digits `weekday()` uses: `0` Sunday .. `6` Saturday. `"12345"` is Monday to Friday; a `"2200-0400"` session on `"12345"` never opens on Saturday or Sunday night. Pine's session day string counts Sunday as `1`, so its `"23456"` is `"12345"` here. A `7`, or Pine's days written into the spec (`"0930-1600:23456"`), is refused by name with this kit's spelling, never read as something else; a list of `1`..`6` alone is read as this kit's digits. - **One instance per opening day.** `key()` is the local `dayKey` of the opening day; it stays the same across a midnight crossing and changes when the next instance opens. `isFirst()` marks the first bar of an instance. `closed()` marks the first update after an instance ended: on a daily chart, where every bar is a new instance, `closed()` and `isFirst()` are both `true` on every bar after the first. ## Market sessions `Session` is a window you define; `MarketSession` is the market's own calendar, read from the two market facts the chart fills on every bar: `time.trade_date` (the exchange trade date, epoch seconds at 00:00 UTC) and `time.session` (`1` regular, `2` pre-market, `3` after-hours, `0` closed). A CME evening bar already belongs to the next trade date, a US stock bar is pre-market, regular or after-hours by the New York clock, and a market without sessions is regular on every bar with the UTC date as its trade date ([Data sources](../core-concepts/data-sources.md)). | Export | Signature | Answers | | --- | --- | --- | | `MarketSession` | `new MarketSession()` | the market's trade date and session phase, bar by bar | | `update` | `ms.update(tradeDateSec: f64, session: f64): void` | folds `time.trade_date` and `time.session`; call once per bar | | `isRegular`, `isPremarket`, `isAfterHours` | `ms.isRegular(): bool` | the bar's phase: regular, pre-market, after-hours | | `isExtended` | `ms.isExtended(): bool` | pre-market or after-hours | | `isClosed` | `ms.isClosed(): bool` | the market is closed on this bar (any session value other than `1`, `2`, `3`) | | `isNewTradingDay` | `ms.isNewTradingDay(): bool` | the first bar of a trade date, and the very first update | | `isFirstRegularBar` | `ms.isFirstRegularBar(): bool` | the first regular bar of a trade date, after its pre-market bars | | `tradingDayKey` | `ms.tradingDayKey(): i32` | the trade date as days since 1970-01-01 | | `tradingWeekKey` | `ms.tradingWeekKey(): i32` | weeks since Monday 1970-01-05 of the trade date: one number from a Monday trade date through its Sunday | | `tradingMonthKey` | `ms.tradingMonthKey(): i32` | `year * 12 + (month - 1)` of the trade date | | `reset` | `ms.reset(): void` | back to the freshly constructed state | The warm-up rule is the `Clock`'s: the very first update is a new trading day, and the first regular bar seen is a first regular bar even when the loaded history starts inside a session. A non-finite trade date or session moves nothing (the phase and keys keep their values, both flags read `false`); before the first update every check reads `false` and the keys read `0`. The checks map one to one onto Pine's `session.*` variables ([Pine equivalents](../core-concepts/time-and-sessions.md#pine-equivalents)). ## A New York session filter The close, drawn only while the cash session is open, with a data-only flag for the session and one for its first bar. The chart's bars are in UTC; the session is in New York time, daylight rule included, so the window moves with the clocks in March and November without any change to the file. ```typescript output("cash_close", line, overlay, { color: "#2563eb", width: 2, description: "The close while the New York cash session is open, NaN outside" }); output("session_open", none, overlay, { description: "1 from 09:30 to 16:00 New York time on a weekday" }); output("session_start", none, overlay, { description: "1 on the first bar of each cash session" }); let cash = new Session("0930-1600"); function onStart(): void { // Constructed here, where a setting can reach it; a spec or zone it // cannot read refuses softly (session.refusedReason() says why). cash = new Session("0930-1600", "America/New_York", "12345"); } function onBar(): void { const close = bar.close(); cash.update(bar.time()); const inSession = cash.isIn(); const first = cash.isFirst(); out_cash_close(inSession ? close : NaN); out_session_open(inSession ? 1.0 : 0.0); out_session_start(first ? 1.0 : 0.0); } ``` `session_open` is the gate a mark or an alert reads; `session_start` is where an anchored VWAP or a session high-low box begins. ## A new-day reset of a running sum Volume accumulated since the New York day started, and since the week started, with the bar's position inside the day. `isNewDay()` is `true` on the first bar after local midnight and on the very first bar, so the sums start clean at both; `isNewWeek()` flips on the first bar of Monday. ```typescript output("day_volume", histogram, lower, { color: "#2563eb", description: "Volume since the New York day started" }); output("week_volume", line, lower, { color: "#f59e0b", description: "Volume since the week started (Monday, New York time)" }); output("bars_today", none, lower, { description: "Bars since the day started, 0 on its first bar" }); let clock = new Clock(); let dayVolume: f64 = 0.0; let weekVolume: f64 = 0.0; let barsToday: i32 = 0; function onStart(): void { clock = new Clock("America/New_York"); } function onBar(): void { clock.update(bar.time()); if (clock.isNewDay()) { dayVolume = 0.0; barsToday = 0; } else { barsToday += 1; } if (clock.isNewWeek()) weekVolume = 0.0; const volume = bar.volume(); dayVolume += volume; weekVolume += volume; if (isNaN(bar.close())) return; out_day_volume(dayVolume); out_week_volume(weekVolume); out_bars_today(f64(barsToday)); } ``` The same shape resets on `isNewMonth()`, `isNewQuarter()` or `isNewYear()`, or compares `dayKey()` with a stored value when the period is yours to define. ## An interval-aware bar-close estimate The module never sees a wall clock, but it sees the gaps between bar opens: `intervalSec()` is the smallest positive gap so far, so after two bars it is the chart interval, and a weekend gap never stretches it. `barCloseSec()` adds that interval to the open. A second `Clock` fed the close time answers what hour the bar closes in, which is how a file knows that the 15:30 bar on a 1-hour chart runs past the cash close. ```typescript output("bar_close", none, overlay, { description: "The bar's close time in epoch seconds, NaN until the interval is known" }); output("bar_minutes", none, lower, { description: "The chart interval in minutes, from the smallest gap seen" }); output("close_hour", none, lower, { description: "The New York hour the bar closes in, NaN on the first bar" }); let opens = new Clock(); let closes = new Clock(); function onStart(): void { opens = new Clock("America/New_York"); closes = new Clock("America/New_York"); } function onBar(): void { opens.update(bar.time()); // NaN on the first bar: a non-finite time does not move a clock. closes.update(opens.barCloseSec()); if (isNaN(bar.close())) return; const interval = opens.intervalSec(); out_bar_close(opens.barCloseSec()); out_bar_minutes(interval / 60.0); out_close_hour(isNaN(interval) ? NaN : f64(closes.hour())); } ``` `index()` on the same clock is the bar index, 0 on the first bar the chart loaded; it counts every update, so it restarts after `reset()`. ## Calendar questions Pine's calendar calls answer on the same clock: a wall-clock time as a timestamp, the quarter, the ISO week and the weekday. The price at the New York cash open held through the day, the open of the running quarter, and two data-only readings: ```typescript // The price at the New York cash open, held through the day; the open of the running quarter; the ISO week and a Monday flag. output("cash_open", line, overlay, { color: "#2563eb", width: 2, description: "The open of the bar that holds 09:30 New York time, held for the rest of the day" }); output("quarter_open", line, overlay, { color: "#94a3b8", line_style: "dashed", description: "The open of the running quarter, New York time" }); output("iso_week", none, lower, { description: "The ISO 8601 week of the bar, 1 to 53" }); output("monday", none, lower, { description: "1 on a Monday in New York, else 0" }); let clock = new Clock(); let cashOpen: f64 = NaN; let quarterOpen: f64 = NaN; function onStart(): void { clock = new Clock("America/New_York"); } function onBar(): void { const t = bar.time(); clock.update(t); if (clock.isNewDay()) cashOpen = NaN; if (clock.isNewQuarter()) quarterOpen = bar.open(); // Today's 09:30 in New York as UTC epoch seconds, daylight time applied. const cashOpenSec = clock.epochSec(clock.year(), clock.month(), clock.dayOfMonth(), 9, 30); // The bar that holds 09:30 sets the level. The interval is NaN on the first bar, so nothing is set there. if (t <= cashOpenSec && cashOpenSec < t + clock.intervalSec()) cashOpen = bar.open(); out_cash_open(cashOpen); out_quarter_open(quarterOpen); out_iso_week(f64(clock.weekOfYear())); out_monday(clock.dayOfWeek() == dayofweek.MONDAY ? 1.0 : 0.0); } ``` - **A wall-clock time.** `clock.epochSec(year, month, day, 9, 30)` is that day's 09:30 in New York as UTC epoch seconds: 14:30 UTC in winter, 13:30 UTC in summer. The bar that holds it sets the level, so on a 1-hour chart the line starts at the 09:00 New York bar. - **The quarter.** `isNewQuarter()` is true on the first bar of January, April, July and October, so the open is taken there. The first quarter on the chart starts at the first loaded bar. `quarterKey()` holds one number for the whole quarter, for a reset you compare yourself. - **The week.** `weekOfYear()` is Pine's `weekofyear`, the ISO week: Monday to Sunday, and week 1 holds January 4th. - **The weekday.** `dayOfWeek()` counts 1 Sunday to 7 Saturday, as Pine does, so it compares with `dayofweek.MONDAY`. `weekday()` counts from 0. ## Bar times by bar index Pine places a drawing by bar index (`xloc.bar_index`: `bar_index - 2`, a saved pivot's index, `bar_index + 20`); a drawing here takes a time. On a 24/7 market the two are the same arithmetic, but a stock's nights, weekends and holidays hold no bars, so `t - 2 * interval` lands in a closed hour where Pine means the bar two bars back. `BarTimes` keeps the bars' real times by index: | Call | Answers | | --- | --- | | `new BarTimes(capacity, intervalSec)` | keeps the last `capacity` bars' times (size it to the history the chart holds: 25,000 covers 1h crypto since 2024; 8 bytes a bar); `intervalSec` is `p_chart_interval_sec()` (declare `chart.interval_sec()`), or `0` to use the smallest spacing seen | | `bars.update(bar.time())` | once per bar, oldest first; the same bar fed again changes nothing | | `bars.index()` | Pine's `bar_index`: `0` on the first bar | | `bars.at(i)` | the time a drawing's x takes for bar index `i`: the real bar's open for `i <= index()` (`NaN` once it is older than `capacity` bars), this bar's time plus whole intervals for a later `i` | | `bars.ago(n)` | `at(index() - n)`: Pine's `time[n]` and `bar_index - n` | | `bars.intervalSec()` | the interval a later index steps by | A later index (`bar_index + 20`) has no bar yet. The chart draws a time past the last bar one interval per slot, so `bars.at(bars.index() + 20)` lands in the slot TradingView uses, 20 slots right; only the empty future axis's time labels differ. Keep the target index beside the drawing and set its x to `bars.at(target)` on every bar while `target >= bars.index()`: on the bar that reaches the target, the drawing takes its real time. Set once at creation, the x drifts across every night and weekend on a stock. ```typescript // The open time of the bar a chosen number of bars back: Pine's time[n], nights and weekends skipped on a stock. param.int("back", 50, { min: 1, max: 500, label: "Bars back" }); chart.interval_sec(); output("then", none, overlay, { description: "The open time of the bar the chosen number of bars back" }); let bars = new BarTimes(25000, 0.0); function onStart(): void { bars = new BarTimes(25000, p_chart_interval_sec()); } function onBar(): void { bars.update(bar.time()); out_then(bars.ago(i32(p_back()))); } ``` ## From Pine One-to-one where the meaning is the same; the zone is the difference, since Pine reads the chart's exchange time and a `Clock` reads the zone you name. | Pine | Here | | --- | --- | | `hour`, `minute`, `second` | `clock.hour()`, `clock.minute()`, `clock.second()` | | `dayofweek` (`1` Sunday .. `7` Saturday), `dayofweek.monday` | `clock.dayOfWeek()`, `dayofweek.MONDAY` (`clock.weekday()` counts the same day from `0`) | | `weekofyear` | `clock.weekOfYear()`: the ISO 8601 week, Monday to Sunday (TradingView's own week-of-month example shows a Sunday-evening open still in the week before, and PineTS implements the ISO number) | | `timestamp(year, month, dayofmonth, 9, 30)` | `clock.epochSec(clock.year(), clock.month(), clock.dayOfMonth(), 9, 30)`, in seconds (`* 1000.0` where a script holds Pine's milliseconds) | | `timestamp("America/New_York", 2024, 1, 15, 9, 30)` | `ny.epochSec(2024, 1, 15, 9, 30)` on a `Clock` built in that zone | | `timestamp("UTC", 2024, 1, 15, 9, 30)`, or `timestamp(2024, 1, 15, 9, 30)` on a 24/7 venue (its exchange zone is UTC) | `epochSec(2024, 1, 15, 9, 30)`; a literal date the user may change is a `param.time` default | | `dayofmonth`, `month`, `year` | `clock.dayOfMonth()`, `clock.month()`, `clock.year()` | | `timeframe.change("D")`, `("W")`, `("M")`, `("3M")`, `("12M")` | `clock.isNewDay()`, `isNewWeek()`, `isNewMonth()`, `isNewQuarter()`, `isNewYear()` in the zone you name; a `PeriodLevels` built from the same word answers the same with `isNew()` ([Levels kit](levels-kit.md)) | | `bar_index` | `clock.index()`, or `bars.index()` on a `BarTimes` | | `time[n]`, an x of `bar_index - n` | `bars.ago(n)` on a `BarTimes` (Bar times by bar index, above) | | an x of `bar_index + n`, a saved index `i` | `bars.at(bars.index() + n)`, `bars.at(i)`; re-set a later index's x every bar until its bar exists | | `not na(time(timeframe.period, "0930-1600:23456"))` | `session.isIn()` with `new Session("0930-1600", zone, "12345")` | | `time_close` | `clock.barCloseSec()` (in seconds, from the observed interval) | | `session.ismarket`, `session.isfirstbar_regular`, `time_tradingday` | `MarketSession` over `time.session` and `time.trade_date` (Market sessions, above) | # Higher-timeframe kit Two modules build a higher timeframe without a second data feed. `./sdk/resample` folds the chart's own bars: a `Resampler` for the eight timeframes the built-in indicators' Timeframe setting offers, chart to 1W, and a `Bucket` for any span Pine spells, `"120"`, `"2D"`, `"2W"` or `"3M"`. `./sdk/candles` reads a `candles` stream instead: `Periods` folds its candles into calendar periods, a `CandleList` keeps the newest of them. The other two streams, `oi_candles` and `volume_profile_candles`, carry five-wide tuples the kit does not read: a module loops over their blocks itself. Feed each class every chart bar. Each section writes its rules out: how buckets are keyed, when one closes, what a read shows. The clock, session and market-session classes beside them are the [Clock and sessions kit](time-and-sessions-kit.md); the fold itself, and the `interval` pin for a real coarser feed, are on [Multi-timeframe](../core-concepts/multi-timeframe.md). ## Which one | Class | Module | Reads | Spans | Reaches back | | --- | --- | --- | --- | --- | | `Resampler` | `./sdk/resample` | the chart's own bars | the built-ins' eight timeframes: chart, 5m, 15m, 30m, 1h, 4h, 1D, 1W | the loaded history | | `Bucket` | `./sdk/resample` | the chart's own bars, on 24/7 markets | any span Pine spells: `"120"`, `"2h"`, `"2D"`, `"2W"`, `"3M"` | the loaded history | | `Periods` | `./sdk/candles` | a `candles` stream | calendar day, week, month, quarter, year | the stream's `bars` | | `CandleList` | `./sdk/candles` | a `candles` stream | the newest N closed candles of the stream's timeframe | the stream's `bars` | `Periods` and `CandleList` read the six-wide `candles` tuple only. An `oi_candles` or `volume_profile_candles` stream is read by hand, its calendar period keyed on each candle's open (`bar.time() + offset_ms / 1000`), as the [Open Interest Profile](../cookbook/open-interest-profile.md) recipe folds a day, a week or a month of hourly candles. ## From the chart bars: `Resampler` The `./sdk/resample` module builds a higher timeframe from the chart's own bars, the way the built-in indicators' Timeframe setting does: a 20-bar average at 1h on a 5m chart averages twenty closed 1h candles, never twenty 5m bars. Feed every chart bar to a `Resampler`; when a selected bar closes, push its value into a `ClosedWindow` or commit it to a `Smoothed`; then read either the closed bars alone (confirmed) or the closed bars plus the forming one as a trial step that is never stored (developing). | Export | Signature | Answers | | --- | --- | --- | | `Resampler` | `new Resampler(option: i32, waitForClose: bool = true)` | the selected timeframe, numbered like the built-ins' Timeframe setting: `tf.CHART`, `tf.FIVE_MINUTES`, `tf.FIFTEEN_MINUTES`, `tf.THIRTY_MINUTES`, `tf.HOUR`, `tf.FOUR_HOURS`, `tf.DAY`, `tf.WEEK` (`0`..`7`); any other number refuses softly: `refused()` is true from the first bar, `refusedReason()` names the timeframes, and nothing folds | | `update` | `r.update(t, tradeDate, open, high, low, close, volume): void` | folds one chart bar: `t` is `bar.time()`, `tradeDate` is `time.trade_date`; call once per bar | | `closed` | `r.closed(): bool` | a selected bar closed on this chart bar, and `r.last` is its candle | | `newBucket` | `r.newBucket(): bool` | this chart bar starts a selected bar | | `last`, `forming` | `r.last.close`, `r.forming.high` | the last closed candle and the forming one: `open`, `high`, `low`, `close`, `volume` and `startSec`, `NaN` until each exists | | `source` | `r.source(which: i32, forming: bool): f64` | one price of either candle: `field.CLOSE`, `field.OPEN`, `field.HIGH` or `field.LOW`, numbered like the built-ins' Source setting | | `confirmed` | `r.confirmed(): bool` | read the committed state alone: `waitForClose` is on, or the timeframe is the chart's | | `refused` | `r.refused(): bool` | your indicator must write `NaN` to every output while this is true (nothing is blanked for you): the selected bar is narrower than the chart's bars, or a 1D or 1W bar came without a trade date; from the start for a timeframe it cannot read | | `refusedReason` | `r.refusedReason(): string` | why, as readable text; the empty string while the timeframe is served | | `widthSec`, `prevStartSec` | `r.widthSec(): f64` | the selected bar's width in seconds; the start of the selected bar before the forming one | | `ClosedWindow` | `new ClosedWindow(cap: i32, keepNa: bool = false)` | the last `cap` closed values: `push(x)`, `count()`, `back(n, x, withX)`, then `mean`, `wma`, `stdev`, `highest`, `lowest`, `highestOffset`, `lowestOffset` and `sum`, each `(p, x, withX)`, and `vwma(volumes, p, x, v, withX)` | | `Smoothed` | `new Smoothed(kind: string, period: i32)` | an `"ema"` or `"rma"` over closed values: `commit(x)`, `value()`, `peek(x)` (one more step, not stored) and `copyFrom(other)` for a scratch copy; any other kind refuses softly (`refused()`, `refusedReason()`, every read `NaN`) | The rules, written out: - **Buckets.** 5m to 4h are rolling, `floor(t / width)` from the epoch, on every market. 1D is the exchange trade date and 1W a Monday week of trade dates, both read from `time.trade_date`: a CME bar from the 17:00 Chicago open already belongs to the next day's candle, and a Sunday-evening bar to Monday's week. - **Closing.** A selected bar closes on the first chart bar of the next one, and a gap simply skips the empty buckets. Its candle holds the first bar's open and the last bar's close as those bars gave them, the highest high, the lowest low and the summed volume; a `NaN` high, low or volume on any bar carries into that field. A candle whose last bar closed at `NaN` never closes, while a `NaN` close on an earlier bar does not matter. - **Confirmed and developing.** Confirmed: every chart bar inside selected bar k shows the state after bar k - 1, so a value never changes once it is drawn. Developing: that state plus one step on the forming candle, which is `withX = true` with the forming value on a window and `peek` on a smoother. - **Warm-up** counts closed selected bars: a 20-bar average at 1h needs 20 closed hours inside the loaded history (19 and the forming one when developing). The first bucket may be partial; it still closes and counts. - **Refusal.** `refused()` blanks nothing by itself: while it is true, your indicator must write `NaN` to every output, as the sample below does. The `Resampler` keeps folding underneath, so its candles, windows and smoothers still answer and would draw numbers that mean nothing. It turns true when the selected bar is narrower than the chart's bars (known from the second bar on, once the bar spacing is measured), and stays true from a 1D or 1W bar without a trade date on. A moving average and an EMA of the selected timeframe's closes, with the built-ins' Timeframe and Wait for close settings. The default reads 1h on a 1h chart or a finer one, and refuses on a coarser one: ```typescript param("timeframe", 4, { min: 0, max: 7, description: "0 chart, 1 5m, 2 15m, 3 30m, 4 1h, 5 4h, 6 1D, 7 1W" }); param("period", 20, { min: 1, max: 200, description: "Length in bars of the selected timeframe" }); param("wait_for_close", 1, { min: 0, max: 1, description: "1 confirmed values, 0 developing values" }); input("close", ohlcv.close); input("trade_date", time.trade_date); output("htf_sma", line, overlay, { color: "#2563eb", width: 2, description: "Average of the selected timeframe's closes" }); output("htf_ema", line, overlay, { color: "#f59e0b", width: 2, description: "EMA of the selected timeframe's closes" }); let r = new Resampler(tf.HOUR, true); let closes = new ClosedWindow(20); let ema = new Smoothed("ema", 20); let period: i32 = 20; function onStart(): void { // Constructed here so a bad setting reports in the Console. period = i32(p_period()); r = new Resampler(i32(p_timeframe()), p_wait_for_close() >= 0.5); closes = new ClosedWindow(period); ema = new Smoothed("ema", period); } function onBar(): void { r.update(bar.time(), in_trade_date(), bar.open(), bar.high(), bar.low(), bar.close(), bar.volume()); if (r.closed()) { // A selected bar just closed: its candle is final, so it joins the state. closes.push(r.last.close); ema.commit(r.last.close); } // Developing reads add the forming bar as one trial step, never stored. const live = !r.confirmed(); let sma = closes.mean(period, r.forming.close, live); let smoothed = live ? ema.peek(r.forming.close) : ema.value(); if (r.refused()) { sma = NaN; smoothed = NaN; } out_htf_sma(sma); out_htf_ema(smoothed); } ``` Confirmed, both lines step once per closed hour and hold between; with Wait for close off they follow the forming hour on every chart bar. A chain reads the same way: a signal line over a closed MACD commits each closed MACD value, and its developing read peeks with the trial MACD. ### Pine equivalents | Pine | Here | | --- | --- | | `request.security(syminfo.tickerid, "60", ta.sma(close, 20)[1], lookahead = barmerge.lookahead_on)`: the last closed hour, never repainting | `new Resampler(tf.HOUR, true)` and `closes.mean(20)` over a `ClosedWindow` pushed on `closed()` | | `request.security(syminfo.tickerid, "60", ta.ema(close, 20))` on the realtime bar: the forming hour | `new Resampler(tf.HOUR, false)` and `ema.peek(r.forming.close)` | | `barstate.isconfirmed` before using a higher-timeframe value | confirmed reads (`waitForClose` on), which only ever show closed selected bars | | `timeframe.change("60")` | `r.newBucket()` | | `request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)` | `r.last.close` on `tf.DAY`: the exchange trade date's candle | ## Any span: `Bucket` A `Bucket` folds the chart's own bars into a span the chart does not serve, keyed the way TradingView aligns a multi-period timeframe, so `request.security(syminfo.tickerid, "120", close)` and its `"2D"`, `"2W"` and `"3M"` cousins port without a pinned input. The constructor takes the span and the chart's bar interval in seconds: declare `chart.interval_sec();` at top level and pass `p_chart_interval_sec()` from `onStart()`, as the sample below does, so the module knows where each bar closes instead of guessing from the gaps between bars. The span is Pine's timeframe string plus the kit's own letters: digits alone or with `m` are minutes (`"120"`, `"45"`, `"5m"`), `s` seconds, `h` or `H` hours (`"2h"`), `d` or `D` days (`"2D"`; a bare `"D"` is one), `w` or `W` weeks (`"2W"`) and `M` months (`"3M"`): the capital M is months as in Pine, the small m minutes as in the kit's interval pins. The count is up to nine digits (`"14400s"`), and a whole count written the way a float prints reads as that count: `"300.0"` is `"300"`, the text a span built from `p_chart_interval_sec()` takes. A span the `Bucket` cannot read never stops your indicator; it refuses softly, the rule below. A span written as a literal is read when the indicator builds, with the same grammar: `new Bucket("1.5h", p_chart_interval_sec())` fails the build on its line with the words `refusedReason()` would give. So does a span spelled from a float, such as `p_minutes().toString() + "m"`: a float prints its fraction (`"7.5m"`), which the span refuses on the charts where it appears. Convert it first, `i32(p_minutes()).toString() + "m"`. | Export | Signature | Answers | | --- | --- | --- | | `Bucket` | `new Bucket(spec: string, chartIntervalSec: f64)` | buckets of one span over the chart's bars, whose interval is `p_chart_interval_sec()` | | `update` | `b.update(t, open, high, low, close, volume): void` | folds one chart bar: `t` is `bar.time()`; call once per bar | | `updateSession` | `b.updateSession(t, open, high, low, close, volume, kind, zone): void` | `update` on the market's own session grid, for a US stock: pass `i32(p_market_kind())` and `i32(p_market_zone())`; any other market is `update` itself (the rule below) | | `closed`, `newBucket` | `b.closed(): bool` | a bucket closed on this chart bar (`b.last` is its candle); this chart bar starts a bucket | | `isLastBar` | `b.isLastBar(): bool` | this chart bar's close (its open plus the chart interval) reaches the bucket's end: the bucket's last bar, where `b.forming` already holds its final candle | | `complete` | `b.complete(): Candle` | the newest bucket complete at this bar's close: `forming` on the bucket's last bar, `last` on every other bar; what Pine's `request.security` shows on historical bars with lookahead off | | `last`, `forming` | `b.last.close`, `b.forming.high` | the last closed bucket and the forming one: `open`, `high`, `low`, `close`, `volume` and `startSec`, `NaN` until each exists | | `startSec`, `endSec`, `widthSec`, `lastEndSec` | `b.endSec(): f64` | the forming bucket's bounds in epoch seconds and its width (shorter than the span on the last bucket of a day or year); the last closed bucket's end | | `lastWhole`, `formingWhole` | `b.lastWhole(): bool` | the candle's bucket started at or after the first bar fed, so it holds every bar of the bucket (the first bucket may have started before the history) | | `refused` | `b.refused(): bool` | the span cannot be read, or the chart's bars cannot build it (the rules below); your indicator must write `NaN` to every output while it is true | | `refusedReason` | `b.refusedReason(): string` | why, as readable text (`Bucket: span 45 is not a whole multiple of the chart's 1800s bars`); the empty string while the span is served | | `reset` | `b.reset(): void` | back to the freshly constructed state; the span, the interval and a refusal decided at construction stay, a straddle refusal clears | The rules, written out (TradingView's bar alignment on a 24/7 market): - **A span it cannot read** refuses softly from the first bar: anything outside the grammar above (`"1.5h"`, ten digits or more), a count of `0`, an intraday span past a day (`"10080"` minutes is a week: write `"7D"`), or a day, week or month span past a year (buckets restart every year: at most 366 days, 53 weeks or 12 months). `refusedReason()` names the rule and the words a span takes, and the `Bucket` folds nothing: every candle and bound reads `NaN`, so an output written from it draws nothing. - **The chart interval** decides what the bars can build. The span is refused from the first bar, with its reason, when the interval is unknown (`chart.interval_sec()` reads `0`; every place an indicator runs fills it today), when the span is narrower than the bars, or when it is not a whole multiple of them: `"45"` on a 30-minute chart would put the 00:30 bar astride 00:45, a candle Pine serves from finer data the chart does not have (a month counts as 28 days for both tests). Where the bars' own grid cannot meet a boundary, the first bar that straddles one (hourly bars opening on the half hour under `"2h"`, a month boundary that is not a Monday on a weekly chart) refuses the span from that bar on, until `reset()`. A monthly chart's bars have no fixed width, so a `Bucket` refuses them. - **Intraday spans** count from 00:00 UTC of each day, so `"2h"`, `"3h"`, `"4h"`, `"6h"`, `"8h"` and `"12h"` are the epoch floor the `Resampler` uses, while a span that does not divide the day (`"7h"`, `"50"`) ends its last bucket of the day short, at midnight. - **Day spans** count calendar days from January 1st and restart every year: on `"3D"` the bucket after 2026-12-30 is two days long, and 2027-01-01 starts a new one. - **Week spans** count Monday weeks from the year's first Monday, and the days before that Monday belong to the last bucket of the year before: 2027 starts on a Friday, so January 1st to 3rd 2027 sit in the `"2W"` bucket that began on Monday 2026-12-21. - **Month spans** count from January and restart every year: `"3M"` is the quarter, and a `"5M"` year ends with a two-month bucket. - **Closing** is the `Resampler`'s rule: a bucket closes on the first chart bar of a later bucket, when its last bar's close is finite, and `b.last` is never revised; gaps skip empty buckets; the first bucket may be partial, and `lastWhole()` says so. - **Sessions**: `update` counts from 00:00 UTC on every market, so on a session venue a grid of bars opening on the half hour refuses as a straddle. On a US stock call `b.updateSession(...)` instead, with the market facts (declare `market.kind();` and `market.zone();` at top level and pass `i32(p_market_kind())` and `i32(p_market_zone())`): an intraday span then counts from the 09:30 New York open, the session's last bucket ends at the 16:00 close and the last bar's close is clipped there, so `"240"` on an hourly chart is 09:30 to 13:30 and 13:30 to 16:00 and the 15:30 bar completes the second, the candle TradingView shows on every bar (measured on NASDAQ:AAPL). A half day's 13:00 close is not known: its last bucket keeps the 16:00 end and closes on the next session's first bar, so that bucket's end reads later than TradingView's 13:00 and `"180"` or `"720"` show it one bar late. On all-hours candles (pre- and post-market bars) the span counts from midnight New York up to the open and from the 16:00 close up to midnight, each stretch's last bucket ending with it. Day, week and month spans count calendar days on every market, not trading days, and on any other market `updateSession` is `update`. The close, high and low of the newest two-hour bucket complete at each bar, the way `request.security(syminfo.tickerid, "120", close)` shows them on historical bars, with the span as a setting and the chart's bar interval passed in: ```typescript param("hours", 2, { min: 1, max: 24, description: "Hours per bucket" }); chart.interval_sec(); output("htf_close", line, overlay, { color: "#2563eb", width: 2, description: "Close of the newest bucket complete at this bar" }); output("htf_high", line, overlay, { color: "#16a34a", description: "Its high" }); output("htf_low", line, overlay, { color: "#dc2626", description: "Its low" }); output("bucket_start", none, overlay, { description: "1 on the bar that starts a bucket" }); let b = new Bucket("2h", 0.0); function onStart(): void { // Built here from the setting (a whole number, so it never prints a // fraction) and the chart's interval: a span the bars cannot build // refuses with a readable reason. b = new Bucket(i32(p_hours()).toString() + "h", p_chart_interval_sec()); } function onBar(): void { b.update(bar.time(), bar.open(), bar.high(), bar.low(), bar.close(), bar.volume()); // complete() is the forming bucket on its last bar and the last closed one otherwise. const c = b.complete(); const blank = b.refused() || isNaN(c.close); out_htf_close(blank ? NaN : c.close); out_htf_high(blank ? NaN : c.high); out_htf_low(blank ? NaN : c.low); out_bucket_start(b.newBucket() ? 1.0 : 0.0); } ``` `b.last` alone is Pine's `request.security(..., close[1], lookahead = barmerge.lookahead_on)`, the previous bucket on every bar of the current one, and `b.forming` its repainting reading of the realtime bar. A `ClosedWindow` or a `Smoothed` pushed on `b.closed()` gives an indicator on the span, exactly as with a `Resampler`. On a chart whose bars cannot build the span (a 3-hour setting on a 2-hour chart) every output reads `NaN` and `b.refusedReason()` says why; show it in a label or a HUD when the port should explain itself. | Pine | Here | | --- | --- | | `request.security(syminfo.tickerid, "120", close)` on historical bars | `b.complete().close` with `new Bucket("120", p_chart_interval_sec())` | | `request.security(syminfo.tickerid, "2D", high[1], lookahead = barmerge.lookahead_on)` | `b.last.high` with `new Bucket("2D", p_chart_interval_sec())` | | `request.security(syminfo.tickerid, "2W", close)` on the realtime bar | `b.forming.close` with `new Bucket("2W", p_chart_interval_sec())` | | `timeframe.change("120")` | `b.newBucket()` | ## Calendar periods and candle lists The `./sdk/candles` module reads a `candles` stream (never `oi_candles` or `volume_profile_candles`, whose tuples are five wide), the closed candles of one timeframe reaching back `bars` deep ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). A `Periods` folds the candles into calendar periods; a `CandleList` keeps the newest of them. Feed each one every bar, an empty block included, with `load(in__view(), in__cells(), bar.time())`: the bar moves the clock even when no candle arrives. Construct them at module start when the period is a constant, or in `onStart()` when a setting picks it. | Export | Signature | Answers | | --- | --- | --- | | `period` | `period.DAY`, `period.WEEK`, `period.MONTH`, `period.QUARTER`, `period.YEAR` | the period a `Periods` folds, numbered `0`..`4` so a choice setting's index passes straight through | | `Periods` | `new Periods(kind: i32, keep: i32 = 1, leg: i32 = period.DAY)` | calendar periods of one kind, keeping the newest `keep` closed ones readable; `leg` is the stream's interval, `period.WEEK` for a `1w` stream and `period.DAY` for `1d` or finer; an unknown kind or any other leg refuses softly: `refused()` is true, `refusedReason()` reads `Periods: unknown period : ...` or `Periods: a stream's leg is period.DAY (1d or finer) or period.WEEK (1w), not `, and every read is the all-`NaN` candle | | `load` | `p.load(cells: StaticArray, count: i32, t: f64): i32` | moves the clock to the bar's open `t`, then folds this bar's block; returns the candles taken | | `confirmed` | `p.confirmed(n: i32 = 0): PeriodCandle` | the n-th newest closed period, `0` the last one; all `NaN` for an `n` past `keep - 1` or before n + 1 periods have closed | | `developing` | `p.developing(): PeriodCandle` | the bar's own period, folded from the candles closed so far | | `isNew`, `startSec`, `endSec`, `complete` | `p.isNew(): bool` | the bar starts a new period; the period's bounds in epoch seconds; whether the stream reaches back to its start | | `add`, `at`, `reset` | `p.add(t, open, high, low, close, volume): bool` | folds one candle by hand; moves the clock to a bar opening at `t` (call it before that bar's `add` calls, as `load` does); back to the constructed state | | `PeriodCandle` | `open`, `high`, `low`, `close`, `volume`, `startSec`, `endSec`, `pv`, `pvVolume`, `count`; `vwap()` | one period: the first open, the highest high, the lowest low, the last close, the summed volume, and its VWAP sums | | `CandleList` | `new CandleList(cap: i32)` | the newest `cap` closed candles of the stream | | `load`, `count` | `list.load(cells, count, t): i32`, `list.count(): i32` | keeps this bar's candles; how many it holds, at most `cap` | | `openSec`, `open`, `high`, `low`, `close`, `volume` | `list.high(i: i32): f64` | candle `i`, `0` the oldest kept and `count() - 1` the newest; `NaN` outside the list | The rules, written out: - **Buckets.** Every boundary is 00:00 UTC: a week starts on Monday, a month on the 1st, a quarter on January, April, July or October 1st, a year on January 1st. A candle belongs to the period holding its open, and a daily candle of a market with sessions is stamped with its trade date. - **Confirmed.** A period is confirmed on every bar that opens at or after its end. All of its candles have arrived by then, so a confirmed period never changes. `developing()` never holds the forming candle, so it reads `NaN` until the period's first candle closes. - **Never partial.** A period that began before the stream's first candle reads `NaN` from `confirmed()` and `developing()`, and `complete()` says whether the bar's own period is whole. Ask for enough `bars` to reach the start of every period you read: 366 daily candles always hold the current year. - **Any bar width.** On a monthly or yearly chart one bar carries a month or a year of candles. `Periods` keeps every period a read can still reach, the `keep` newest closed ones and the bar's own, whatever a bar spans, in the memory it allocated at construction. - **Weekly streams.** Construct a `Periods` fed a `1w` stream with `period.WEEK` as its third argument. Its clock then runs on the start of the bar's week, so a week that straddles a month, quarter or year boundary counts in the period it opens in, as calendar requests over weekly candles count it. The stream's interval is declared, never read from the candles, so a `1d` stream with days missing keeps its daily clock. Feed a `1d` stream for exact periods. - **The list.** On the newest bar, a stream declared `bars: N` read through `CandleList(N)` holds the newest N closed candles: the rows `requestBars(sym, tf, { bars: N + 1 })` returns, without its last, the forming candle. That one is the interval's `forming` view, folded from the chart's own bars. On an earlier bar the list holds the candles delivered through that bar, so it serves per-bar math as well as drawing. Last month's high and low, and the average close of the last 20 closed days, on any chart interval: ```typescript input("close", ohlcv.close); input("d", candles.cells, { interval: "1d", bars: 70, description: "The newest 70 closed days" }); output("pm_high", line, overlay, { color: "#16a34a", description: "Last month's high" }); output("pm_low", line, overlay, { color: "#dc2626", description: "Last month's low" }); output("avg20", line, overlay, { color: "#2563eb", description: "Average close of the last 20 closed days" }); const month = new Periods(period.MONTH); const days = new CandleList(20); function onBar(): void { const block = in_d_view(); const n = in_d_cells(); const t = bar.time(); month.load(block, n, t); days.load(block, n, t); const last = month.confirmed(0); // NaN until a whole month has closed inside the stream out_pm_high(last.high); out_pm_low(last.low); let avg: f64 = NaN; if (days.count() == 20) { let sum = 0.0; for (let i = 0; i < 20; i++) sum += days.close(i); avg = sum / 20.0; } out_avg20(avg); } ``` `bars: 70` reaches back past the start of last month on every day of the year, so even a short chart shows it whole. On a chart that loaded more than 70 days, the stream starts just before the first loaded bar instead, and the first month or two read `NaN`: a month that began before the stream is never shown partial. # Order flow The chart serves order flow a candle alone cannot show: the bar's aggressive buy and sell volume as two sided inputs, the bar's volume profile as `volume_profile` cells, a book snapshot as `book` cells and the bar's forced liquidations per side. This page is the arithmetic on top. The `./sdk/orderflow` module ships `delta` and `deltaPct` for a bar, a `Cvd` you restart where you choose, a `VolumeProfile` with its point of control and value area, a `BookImbalance`, and the two detectors the cookbook recipes use, `Absorption` and `LiquidationBurst`. The same scans written by hand over the profile and book cells follow each class, with the readers those cells come through; the classes are those scans with the edge rules pinned. ## What the chart serves | Source | What one bar carries | Notes | | --- | --- | --- | | `trades.volume` with a `side` | the bar's aggressive buy volume, or its sell volume, as one number | declared twice, `side: "BUY"` and `side: "SELL"`; `missing: "zero"` reads 0 on a bar without prints; `currency: "USD"` reads dollars instead of coins, `"Auto"` contracts on a futures market and dollars elsewhere | | `volume_profile.cells` | one `[low, high, buy, sell]` tuple per price level | real band edges, in ascending price order, a level with a non-finite member skipped; `buy` and `sell` are the aggressor volumes at that level in coins (base-asset units); the count varies with the bar's range | | `book.cells` | one `[price, size, side]` tuple per level | `side` is `+1` for a bid and `-1` for an ask, `size` the absolute resting quantity; the bids as the snapshot lists them, then the asks from the highest price down; up to 500 levels a side, so a full book is up to 1,000 tuples | | `liquidations.liquidations` with a `side` | the bar's forced liquidations on one side, in USD | the detector sample reads long liquidations from the `SELL` side and short ones from the `BUY` side, both `missing: "zero"` | The two celled sources share these rules: - `max_cells` is required and counts tuples. A bar whose block exceeds it refuses the whole run rather than truncating ("max_cells is 512, so the evaluation is refused (a block is never truncated)"), except on a profile declared `missing: "empty"` (below), where that bar reads an empty block and the run goes on. A profile has one tuple per bucket the bar crossed: BTCUSDT's bucket is $5, so 512 refuses any bar wider than about $2,560, while 8192 covers the majors' profiles at native bucket width; 1000 holds a full book. A low cap refuses wide bars, a high cap reserves memory you never use (8192 profile tuples are 256 KB). - A celled input cannot be the primary input (a celled class has no clock of its own), so a scalar input comes first and sets the grid the blocks join row for row. Declaring one derives the sheet on the second runtime contract (`abi_version: "wrun-2"`); Run does that for you. - Both follow the chart's own market and interval: a `symbol` + `exchange` pin or an `interval` pin is refused ("the browser lane serves market pins on secondary ohlcv inputs only (typed feeds, cells and time follow the chart's own market)"). `description` is the only other option the profile takes. - The book declaration requires `block_size` and accepts `max_depth`, but the chart reads neither: it serves the same snapshots its own order book lane fetches for the chart's market. Size `max_cells` for the deepest book the market shows, not from `max_depth`. - The profile arrives at the market's own bucket width, one tick per bucket, in coins, unless the input says otherwise. `ticks_per_bar` merges that many of the market's own buckets into one, a whole number from 1 to 500 (left out, or 1, the market's own width), and `currency: "USD"` quotes bucket volume in dollars instead of coins (`"Coin"`, the default, keeps coins, and `"Auto"` reads the contracts traded on a futures market and dollars on every other market): `input("profile", volume_profile.cells, { max_cells: 8192, ticks_per_bar: 5, currency: "USD" })`. Any other value stops the build with the option's name. - The bucket size can be a setting: `ticks_per_bar: "@node_ticks"` names a `param.int` whose `min..max` lies inside 1..500, the chart asks for the profile at the setting's value and fetches again when the user changes it: `param.int("node_ticks", 10, { min: 1, max: 50 }); input("profile", volume_profile.cells, { max_cells: 8192, ticks_per_bar: "@node_ticks" })`. - The profile is required: a market without one stops the run with a message naming it. `missing: "empty"` makes it optional, so on a market that serves no profile, or a stretch without one, every bar reads an empty block (`in_profile_cells()` is `0`) and the rest of the indicator draws as usual: `input("profile", volume_profile.cells, { max_cells: 8192, missing: "empty" })`. A bar whose profile has more buckets than `max_cells` reads the same empty block on an optional profile, never a truncated one, so a wide bar blanks that bar's profile parts instead of stopping the run. Scans over an empty block find no level, so code that reads the profile blanks those outputs by itself. Only `"empty"`, and only on `volume_profile.cells`. - Neither block carries the bar's timestamp: the `time` source does when a scan needs one. ## Reading the cells Declare a celled input behind a scalar one, with its cap: ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); input("book", book.cells, { max_cells: 1000, block_size: 10 }); ``` A celled input has no scalar reader (`in_profile()` does not exist). It reaches `onBar()` through a generated pair, four cells per profile tuple and three per book tuple: | Accessor | Returns | | --- | --- | | `in_profile_cells(): i32`, `in_book_cells(): i32` | the number of `f64` cells this bar (tuples times the tuple width); `0` for a present, empty block; `-1` when the bar carries no block | | `in_profile_view(): StaticArray`, `in_book_view(): StaticArray` | the bar's cells in place: one buffer the build owns, filled before `onBar()` runs and never copied; only the first `in__cells()` values belong to this bar | Read the count, then the block, where you use them. Past the count the view reads NaN up to its capacity (an absent or empty bar reads NaN throughout), so bound every scan by the count. Profile tuple `i` is `cells[4 * i]` through `cells[4 * i + 3]` and `n / 4` is the count; a loop guarded by `i + 3 < n` (`i + 2 < n` over the book) walks whole tuples only, so a block that is not a multiple of the tuple width (it never is, but the guard costs nothing) cannot read past the last cell. The copying reader and the capacity constants are on [Data sources](../core-concepts/data-sources.md#reading-a-block). ## Every export | Export | Signature | What it gives | | --- | --- | --- | | `delta` | `delta(buy: f64, sell: f64): f64` | `buy - sell`; NaN when a side is not finite | | `deltaPct` | `deltaPct(buy: f64, sell: f64): f64` | `(buy - sell) / (buy + sell) * 100`, -100..100; NaN when the sum is 0 | | `Cvd` | `update(buy, sell): f64`, `value(): f64`, `delta(): f64`, `reset()` | the running sum of `buy - sell` since construction or the last `reset()`; a non-finite side counts as 0 on its bar | | `VolumeProfile` | `constructor(rows: i32)`, `begin(low, high)`, `add(low, high, buy, sell)`, `end(valueAreaPct: f64 = 70.0): bool`, `poc()`, `vah()`, `val()`, `total()`, `rowCount()`, `rowLow(i)`, `rowVolume(i)`, `rowBuy(i)`, `rowSell(i)`, `pocRow()`, `vahRow()`, `valRow()`, `reset()` | bands spread over `rows` equal-width rows across `[low, high)`, buy and sell kept per row; the POC row, its centre, and the value area's edges | | `BookImbalance` | `constructor(levels: i32)`, `begin()`, `add(price, size, side: i32)`, `end()`, `bidSize()`, `askSize()`, `ratio()`, `imbalance()`, `bestBid()`, `bestAsk()`, `spread()`, `reset()` | the `levels` highest bids and lowest asks kept whatever order the cells arrive in; their sizes summed, `bid / (bid + ask)`, `(bid - ask) / (bid + ask)`, the touch and the spread | | `Absorption` | `constructor(deltaWindow: i32, atrLength: i32, deltaSpike: f64, maxRange: f64)`, `update(high, low, close, buy, sell): i32`, `delta()`, `norm()`, `range()`, `reset()` | +1 buying absorbed, -1 selling absorbed, 0 otherwise: the absorption recipe's test | | `LiquidationBurst` | `constructor(window: i32, burstZ: f64)`, `update(longLiq, shortLiq): i32`, `longZ()`, `shortZ()`, `reset()` | -1 a long burst, +1 a short burst, 0 neither: the liquidation-bursts recipe's test | Every class allocates in its constructor and never per bar, `NaN` means "nothing" (not warm yet, no such row, no level on that side), and `reset()` restores the freshly constructed state. Counts below 1 (rows, levels, windows) are clamped to 1. Construct the objects in `onStart()` (a settings change rebuilds them there); an abort at module start loses its message. ## Delta and CVD `delta(buy, sell)` is the bar's `buy - sell` and `deltaPct` the same as a percent of the bar's sided volume. `Cvd` keeps the running sum: every `update(buy, sell)` adds the bar's delta and returns the sum, `value()` reads it again, `delta()` reads the last bar's own delta. The sum has no anchor of its own: you decide where it restarts by calling `reset()`. The sample below restarts it on the first bar of each UTC day, gated by a data-only `new_day` flag computed from `bar.time()` (the bar's open in UTC seconds), so the flag is on the chart too and an alert can read it. ```typescript input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero" }); input("sell", trades.volume, { side: "SELL", missing: "zero" }); output("cvd", line, lower, { color: "#2563eb", width: 2, description: "Cumulative volume delta, restarted each UTC day" }); output("bar_delta", line, lower, { color: "#94a3b8", description: "This bar's buy minus sell volume" }); output("new_day", none, lower, { description: "1 on the first bar of a UTC day (the reset gate)" }); let cvd = new Cvd(); let prevDay: f64 = NaN; function onStart(): void { cvd = new Cvd(); } function onBar(): void { const day = Math.floor(bar.time() / 86400.0); const newDay = !isNaN(prevDay) && day != prevDay ? 1.0 : 0.0; prevDay = day; if (newDay == 1.0) cvd.reset(); const buy = in_buy(); const sell = in_sell(); const barDelta = delta(buy, sell); const sum = cvd.update(buy, sell); out_cvd(sum); out_bar_delta(barDelta); out_new_day(newDay); } ``` The first bar of the history is not a "new day" (there is no previous day to compare), so the sum starts there and restarts at every day boundary after it. Read `new_day` in the Console to check the gate before you alert on the line. ## Volume profile A `VolumeProfile` is built from bands. `begin(low, high)` opens a profile over `[low, high)` split into the constructor's `rows` equal-width rows and clears them; `add(low, high, buy, sell)` folds one band; `end(valueAreaPct)` closes the profile and answers `false` when nothing landed. Call `add()` per cell across as many bars as the profile should cover: a bar profile is `begin`, the bar's cells, `end`; a rolling profile is one `begin`, cells from every bar, `end` when you read it. The frozen rules, the ones the [Volume profile and value area](../cookbook/volume-profile-value-area.md) recipe uses: - A band is spread over the rows it overlaps in proportion to the overlap. A band whose two edges fall in the same row, a band thinner than a row and a point band with `low == high` land whole in that row. - A band entirely outside the span lands whole in the nearest edge row; a band crossing the span's edge keeps the part inside. - The POC is the heaviest row; the lower row wins a tie. `poc()` is that row's centre. - The value area starts at the POC and grows toward the heavier neighbour (up wins a tie) until it holds `valueAreaPct` percent of the total. `vah()` is the area's top row's upper edge and `val()` its bottom row's lower edge, both row EDGES. - Buy and sell are kept per row: `rowBuy(i)`, `rowSell(i)` and their sum `rowVolume(i)`; `rowLow(i)` is the row's lower edge and `total()` what every row holds. The sample reads the bar's `volume_profile` cells with the generated `in_profile_cells()` / `in_profile_view()` pair, loops the four-cell tuples into `add()`, and draws the three levels as lines on price. ```typescript param("rows", 24, { min: 2, max: 128, description: "Price rows across the bar's range" }); param("value_area", 70, { min: 50, max: 95, description: "Value area as a percent of the bar's volume" }); input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 4096, description: "This bar's volume by price level" }); output("poc", line, overlay, { color: "#f59e0b", width: 2, description: "Point of control: the heaviest row's centre" }); output("vah", line, overlay, { color: "#38bdf8", description: "Value area high: the area's upper edge" }); output("val", line, overlay, { color: "#38bdf8", description: "Value area low: the area's lower edge" }); let profile = new VolumeProfile(24); let valueArea: f64 = 70.0; function onStart(): void { profile = new VolumeProfile(i32(p_rows())); valueArea = p_value_area(); } function onBar(): void { profile.begin(bar.low(), bar.high()); // the bar's own range; a flat bar keeps the profile closed const n = in_profile_cells(); if (n >= 4) { const cells = in_profile_view(); for (let i = 0; i + 3 < n; i += 4) { profile.add(cells[i], cells[i + 1], cells[i + 2], cells[i + 3]); } } const ok = profile.end(valueArea); out_poc(ok ? profile.poc() : NaN); out_vah(ok ? profile.vah() : NaN); out_val(ok ? profile.val() : NaN); } ``` `end()` answers `false` on a bar with no bands or a flat range and the three outputs are written `NaN` there, so the lines simply skip it. A clamp such bands into the edge rows on purpose, or skip them before `add()` when you want the recipe's stray-print rule. ### Profile scans by hand The class re-bins the bar's bands into rows you choose. When the native buckets are what you want (the heaviest level as the chart serves it, the bar's sided totals, the range the profile spans), read the tuples directly. Each read is a function over the block, `cells` being the view and `n` the cell count for the bar. All nine take the same two arguments, so a module scans once and reads as many as it likes. | Function | Returns | | --- | --- | | `vpBuy(cells, n)` | total buy volume across the bar's buckets | | `vpSell(cells, n)` | total sell volume | | `vpDelta(cells, n)` | `vpBuy - vpSell`; positive is buy dominant | | `vpTotal(cells, n)` | combined buy + sell volume | | `vpPoc(cells, n)` | the point of control: the midprice of the highest-volume bucket, `NaN` if no buckets | | `vpPocVolume(cells, n)` | combined volume at the point-of-control bucket | | `vpBucketCount(n)` | the number of buckets this bar | | `vpPriceHigh(cells, n)` | the highest `high` across buckets, `NaN` if empty | | `vpPriceLow(cells, n)` | the lowest `low` across buckets, `NaN` if empty | How the two readings differ: | | `VolumeProfile` | Hand scan | | --- | --- | --- | | Rows | `rows` equal-width rows across the span you pass to `begin()` | the chart's native buckets, one tick each | | Point of control | the heaviest row's centre, the lower row on a tie | the heaviest bucket's midprice, the lower bucket on a tie | | Value area | `vah()` and `val()` at `valueAreaPct` | none | | Totals | `total()`, buy and sell per row | `vpBuy`, `vpSell`, `vpDelta`, `vpTotal` | | Range | the span you passed | `vpPriceLow` and `vpPriceHigh` from the buckets | The module below writes nine outputs from one scan per bar. The delta draws as a histogram tinted by sign, the point of control as a line on the price pane, and the rest in a lower pane. A bar with no block (`n < 0`) abstains; a bar with an empty block (`n == 0`) is a real observation of zero volume and writes zeros and `NaN` prices. ```typescript input("close", ohlcv.close); input("profile", volume_profile.cells, { max_cells: 8192 }); output("poc", line, overlay, { color: "#ff9800", width: 2, description: "Point of control" }); output("price_high", line, overlay, { color: "#94a3b8", width: 1, description: "Top of the profile" }); output("price_low", line, overlay, { color: "#94a3b8", width: 1, description: "Bottom of the profile" }); output("total_buy", line, lower, { color: "#26a69a", width: 2, description: "Buy volume summed over the profile" }); output("total_sell", line, lower, { color: "#ef5350", width: 2, description: "Sell volume summed over the profile" }); output("delta", histogram, lower, { color_by: "delta_sign", colors: ["#ef5350", "#26a69a"], description: "Net buy minus sell volume" }); output("delta_sign", none, lower, { description: "0 sell dominant, 1 buy dominant: the delta palette index" }); output("total_volume", line, lower, { color: "#9e9e9e", width: 1, description: "Combined volume" }); output("poc_volume", line, lower, { color: "#ff9800", width: 1, description: "Volume at the point of control" }); output("bucket_count", line, lower, { color: "#64748b", width: 1, description: "Price levels this bar" }); function vpBuy(cells: StaticArray, n: i32): f64 { let total = 0.0; for (let i = 0; i + 3 < n; i += 4) total += cells[i + 2]; return total; } function vpSell(cells: StaticArray, n: i32): f64 { let total = 0.0; for (let i = 0; i + 3 < n; i += 4) total += cells[i + 3]; return total; } function vpDelta(cells: StaticArray, n: i32): f64 { return vpBuy(cells, n) - vpSell(cells, n); } function vpTotal(cells: StaticArray, n: i32): f64 { return vpBuy(cells, n) + vpSell(cells, n); } // The index of the bucket with the most combined volume, or -1 for an empty block. function vpPocIndex(cells: StaticArray, n: i32): i32 { let best = -1; let bestVolume = -1.0; for (let i = 0; i + 3 < n; i += 4) { const volume = cells[i + 2] + cells[i + 3]; if (volume > bestVolume) { bestVolume = volume; best = i; } } return best; } function vpPoc(cells: StaticArray, n: i32): f64 { const i = vpPocIndex(cells, n); return i < 0 ? NaN : (cells[i] + cells[i + 1]) / 2.0; } function vpPocVolume(cells: StaticArray, n: i32): f64 { const i = vpPocIndex(cells, n); return i < 0 ? NaN : cells[i + 2] + cells[i + 3]; } function vpBucketCount(n: i32): f64 { return n < 0 ? 0.0 : f64(n / 4); } function vpPriceHigh(cells: StaticArray, n: i32): f64 { let top = NaN; for (let i = 0; i + 3 < n; i += 4) { if (isNaN(top) || cells[i + 1] > top) top = cells[i + 1]; } return top; } function vpPriceLow(cells: StaticArray, n: i32): f64 { let bottom = NaN; for (let i = 0; i + 3 < n; i += 4) { if (isNaN(bottom) || cells[i] < bottom) bottom = cells[i]; } return bottom; } function onBar(): void { const n = in_profile_cells(); if (n < 0) return; // no block on this bar: abstain const cells = in_profile_view(); const delta = vpDelta(cells, n); out_poc(vpPoc(cells, n)); out_price_high(vpPriceHigh(cells, n)); out_price_low(vpPriceLow(cells, n)); out_total_buy(vpBuy(cells, n)); out_total_sell(vpSell(cells, n)); out_delta(delta); out_delta_sign(delta >= 0.0 ? 1.0 : 0.0); out_total_volume(vpTotal(cells, n)); out_poc_volume(vpPocVolume(cells, n)); out_bucket_count(vpBucketCount(n)); } ``` The scans run in `onBar()` over the view the build filled before it: a module that reads the count once and computes many things from one block pays for the block once. ### One mark per price level Every output is one number per bar and every renderer draws one thing per bar, so the per-level picture is not a loop of marks. It is a declaration over the same cells: `plot.footprint({ name, cells: "profile" })` draws one footprint column per bar from the buckets, `plot.heatmap({ name, cells: "profile", value: "delta" })` paints them as a time by price heatmap, and `plot.profile({ name, cells: "profile", span: "session" })` sums them into a volume profile per session, range or visible window ([Price canvases](../presentation/price-canvases.md)). A profile the module computes itself (a scan that weights or filters the buckets) goes to a `plot.levels` frame docked on the price axis ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)); a fixed set of outputs (the point of control as a line, the top and bottom of the profile as two more, a `render.shape` at the level you care about) draws the levels you name. The [Volume profile and value area](../cookbook/volume-profile-value-area.md) recipe draws its levels that way. ### The worked footprint The `vp-buy-share-codefirst` starter is the footprint loop end to end: a celled input and the buy share of each bar's profile as a numeric output. The whole file and how to run it are on [Data sources](../core-concepts/data-sources.md#the-worked-footprint-example); in the editor it is the **VP Buy Share** card under **Order flow** in the template picker (the **Templates** icon beside **New indicator**). After a run on a market with profile data, type `last 5 buy_share` at the Console prompt to read the newest values. ## Book imbalance A `BookImbalance` reads one snapshot per bar: `begin()`, one `add(price, size, side)` per level with `side` exactly as the cell encodes it (`+1` bid, `-1` ask; any other value is ignored, so is a non-finite price or size), then `end()`. It keeps the `levels` highest bids and the `levels` lowest asks, each side in a small array sorted best price first, so the result is the same whatever order the levels arrive in. That matters: the chart hands the asks over from the highest price down, so the first ask tuple is the worst ask, never the best; `bestAsk()` is the lowest ask price whatever the order. After `end()`, `bidSize()` and `askSize()` are the kept sizes summed, `ratio()` is `bid / (bid + ask)` and `imbalance()` `(bid - ask) / (bid + ask)` (both NaN when both sums are 0), `bestBid()`, `bestAsk()` and `spread()` read the touch (NaN when a side is empty). ```typescript param("levels", 10, { min: 1, max: 500, description: "Levels kept per side, counted from the touch" }); param("smooth", 21, { min: 1, max: 200, description: "EMA window over the imbalance" }); input("close", ohlcv.close); input("book", book.cells, { max_cells: 1000, block_size: 10 }); output("imbalance", line, lower, { color: "#94a3b8", description: "(bids - asks) / (bids + asks) over the kept levels, -1..1" }); output("smoothed", line, lower, { color: "#2563eb", width: 2, description: "The imbalance smoothed" }); output("spread", none, lower, { description: "Best ask minus best bid" }); let imbalanceOf = new BookImbalance(10); let ema = new Ema(21); function onStart(): void { imbalanceOf = new BookImbalance(i32(p_levels())); ema = new Ema(i32(p_smooth())); } function onBar(): void { const n = in_book_cells(); if (n <= 0) return; // no snapshot this bar, or an empty one: nothing to measure const cells = in_book_view(); imbalanceOf.begin(); for (let i = 0; i + 2 < n; i += 3) { imbalanceOf.add(cells[i], cells[i + 1], i32(cells[i + 2])); } imbalanceOf.end(); const imbalance = imbalanceOf.imbalance(); const spread = imbalanceOf.spread(); const smoothed = isNaN(imbalance) ? NaN : ema.update(imbalance); out_imbalance(imbalance); out_smoothed(smoothed); out_spread(spread); } ``` The `Ema` from `./sdk/ta` is fed once per bar, in order; on a bar without a snapshot `onBar()` returns early, so the average is left untouched and the three outputs stay `NaN`. Size `max_cells` for the deepest book the market shows (a snapshot over the cap refuses the run); the cap is in tuples. ### Depth window scans by hand The class keeps a count of levels from the touch. A depth window keeps a price band instead: every scan takes a `depthPct` (`10` in the module below) and only levels within that percentage of the mid price count. The mid is the average of the best bid (the highest bid price) and the best ask (the lowest ask price), read from prices rather than positions so any level order works, and a level is inside the window when `abs(price - mid) <= mid * depthPct / 100`. Smaller percentages (1 to 5) focus on top-of-book activity; larger ones (10 to 20) read overall depth. | | `BookImbalance` | Depth window scan | | --- | --- | --- | | Levels kept | the `levels` best on each side | every level within `depthPct` of the mid | | Window | a count, the same whatever the price | a price band that scales with the mid | | Reads | sizes, ratio, imbalance, touch, spread | sums, the largest and smallest order, imbalance | Three scans parameterized by side cover six measures. The sums answer `0` on an empty window, `maxSide` and `minSide` answer `NaN` when no level of that side sits inside it, and all three answer `NaN` when a side of the book is missing (no mid): | Scan | Returns | | --- | --- | | `sumSide(cells, n, 1.0, depthPct)` | total bid size within the window | | `sumSide(cells, n, -1.0, depthPct)` | total ask size within the window | | `maxSide(cells, n, 1.0, depthPct)` | the largest single bid within the window | | `maxSide(cells, n, -1.0, depthPct)` | the largest single ask | | `minSide(cells, n, 1.0, depthPct)` | the smallest bid within the window | | `minSide(cells, n, -1.0, depthPct)` | the smallest ask | What the six measures serve: | Category | What the scans give you | | --- | --- | | Volume analysis | bid and ask size summed within the depth window, and their imbalance | | Order size analysis | the largest and smallest resting orders on each side, to spot size | | Market depth | how far liquidity reaches and where it clusters, for support and resistance reads | The module adds the imbalance the sums are usually combined into, `(bids - asks) / (bids + asks)`, smoothed with the shipped `Ema` so the per-snapshot noise reads as pressure. `depth_pct` is a param, so the window is a setting the chart user can change. ```typescript param("depth_pct", 10, { min: 0.1, max: 50, description: "Depth window as a percent of the mid price" }); param("smooth", 21, { min: 1, max: 200, description: "EMA window over the imbalance" }); input("close", ohlcv.close); input("book", book.cells, { max_cells: 1000, block_size: 10 }); output("bid_volume", line, lower, { color: "#26a69a", width: 2, description: "Bid size within the window" }); output("ask_volume", line, lower, { color: "#ef5350", width: 2, description: "Ask size within the window" }); output("max_bid", line, lower, { color: "#0f766e", width: 1, description: "Largest resting bid within the window" }); output("max_ask", line, lower, { color: "#be123c", width: 1, description: "Largest resting ask within the window" }); output("min_bid", line, lower, { color: "#5eead4", width: 1, description: "Smallest resting bid within the window" }); output("min_ask", line, lower, { color: "#fda4af", width: 1, description: "Smallest resting ask within the window" }); output("imbalance", line, lower, { color: "#94a3b8", width: 1, description: "(bids - asks) / (bids + asks), -1..1" }); output("imbalance_ema", line, lower, { color: "#2563eb", width: 2, description: "Smoothed imbalance" }); // The average of the best bid (the highest bid price) and the best ask (the lowest ask price), // or NaN when either side is missing. Reads prices, not positions, so any level order works. function bookMid(cells: StaticArray, n: i32): f64 { let bestBid = NaN; let bestAsk = NaN; for (let i = 0; i + 2 < n; i += 3) { const price = cells[i]; if (cells[i + 2] > 0.0) { if (isNaN(bestBid) || price > bestBid) bestBid = price; } else if (isNaN(bestAsk) || price < bestAsk) bestAsk = price; } return isNaN(bestBid) || isNaN(bestAsk) ? NaN : (bestBid + bestAsk) / 2.0; } // True when a level sits within depthPct percent of the mid. function inWindow(price: f64, mid: f64, depthPct: f64): bool { return Math.abs(price - mid) <= (mid * depthPct) / 100.0; } function sumSide(cells: StaticArray, n: i32, side: f64, depthPct: f64): f64 { const mid = bookMid(cells, n); if (isNaN(mid)) return NaN; let total = 0.0; for (let i = 0; i + 2 < n; i += 3) { if (cells[i + 2] == side && inWindow(cells[i], mid, depthPct)) total += cells[i + 1]; } return total; } function maxSide(cells: StaticArray, n: i32, side: f64, depthPct: f64): f64 { const mid = bookMid(cells, n); if (isNaN(mid)) return NaN; let best = NaN; for (let i = 0; i + 2 < n; i += 3) { if (cells[i + 2] == side && inWindow(cells[i], mid, depthPct)) { if (isNaN(best) || cells[i + 1] > best) best = cells[i + 1]; } } return best; } function minSide(cells: StaticArray, n: i32, side: f64, depthPct: f64): f64 { const mid = bookMid(cells, n); if (isNaN(mid)) return NaN; let best = NaN; for (let i = 0; i + 2 < n; i += 3) { if (cells[i + 2] == side && inWindow(cells[i], mid, depthPct)) { if (isNaN(best) || cells[i + 1] < best) best = cells[i + 1]; } } return best; } let depthPct: f64 = 10.0; let ema = new Ema(21); function onStart(): void { depthPct = p_depth_pct(); ema = new Ema(i32(p_smooth())); } function onBar(): void { const n = in_book_cells(); if (n <= 0) return; // no snapshot, or an empty one: nothing to measure const cells = in_book_view(); const bids = sumSide(cells, n, 1.0, depthPct); const asks = sumSide(cells, n, -1.0, depthPct); const imbalance = bids + asks > 0.0 ? (bids - asks) / (bids + asks) : NaN; const smoothed = isNaN(imbalance) ? NaN : ema.update(imbalance); out_bid_volume(sumSide(cells, n, 1.0, depthPct)); out_ask_volume(sumSide(cells, n, -1.0, depthPct)); out_max_bid(maxSide(cells, n, 1.0, depthPct)); out_max_ask(maxSide(cells, n, -1.0, depthPct)); out_min_bid(minSide(cells, n, 1.0, depthPct)); out_min_ask(minSide(cells, n, -1.0, depthPct)); out_imbalance(imbalance); out_imbalance_ema(smoothed); } ``` The `Ema` is fed in `onBar()` once per bar, in order, after the early return, so a bar without a snapshot never touches it. ## Absorption and liquidation bursts Both detectors are the cookbook recipes' tests, verbatim, so an indicator built on them flags exactly the bars [Absorption](../cookbook/absorption.md) and [Liquidation bursts](../cookbook/liquidation-bursts.md) flag. `Absorption(deltaWindow, atrLength, deltaSpike, maxRange)` answers, per `update(high, low, close, buy, sell)`: delta = `buy - sell`; norm = the `Sma(deltaWindow)` of `abs(delta)`; range = the `Atr(atrLength)`; heavy = norm > 0 and `abs(delta) >= deltaSpike * norm`; stuck = range > 0 and `high - low <= maxRange * range`; heavy and stuck give `+1` when delta >= 0 (buying absorbed) and `-1` otherwise (selling absorbed), else `0`. `delta()`, `norm()` and `range()` read the bar's three numbers. The answer is `0` while the average or the ATR is warming up. `LiquidationBurst(window, burstZ)` answers, per `update(longLiq, shortLiq)`, side by side: mean = `Sma(window)`, dev = `Stdev(window)`; burst = value > 0 and dev > 0 and `value >= mean + burstZ * dev`. A long burst answers `-1`, a short burst `+1`; when both sides burst the larger value wins, long on a tie; else `0`. `longZ()` and `shortZ()` read `(value - mean) / dev`, NaN while not warm or when dev is 0. The sample draws absorbed bars as dots (above the candle when buying was absorbed, below it when selling was) and writes both answers as data-only outputs an alert can read. ```typescript param("delta_spike", 2.0, { min: 1.0, max: 6.0, description: "Heavy when abs(delta) is this many times its rolling mean" }); param("delta_window", 48, { min: 10, max: 400, description: "Bars the mean of abs(delta) is taken over" }); param("max_range", 0.8, { min: 0.2, max: 2.0, description: "Stuck when the bar's range is under this many ATRs" }); param("atr_length", 14, { min: 2, max: 100, description: "The ATR's Wilder length" }); param("burst_z", 3.0, { min: 1.0, max: 8.0, description: "A burst sits this many deviations above the window's mean" }); param("window", 96, { min: 10, max: 500, description: "Bars the liquidation mean and deviation are taken over" }); input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero" }); input("sell", trades.volume, { side: "SELL", missing: "zero" }); input("long_liq", liquidations.liquidations, { side: "SELL", missing: "zero" }); input("short_liq", liquidations.liquidations, { side: "BUY", missing: "zero" }); output("absorbed_buying", shape, overlay, { color: "#f86800", description: "A dot above a candle where heavy buying went nowhere" }); output("absorbed_selling", shape, overlay, { color: "#f8c000", description: "A dot below a candle where heavy selling went nowhere" }); output("absorption", none, overlay, { description: "+1 buying absorbed, -1 selling absorbed, 0 none" }); output("burst", none, overlay, { description: "-1 a long burst, +1 a short burst, 0 none" }); let absorption = new Absorption(48, 14, 2.0, 0.8); let bursts = new LiquidationBurst(96, 3.0); function onStart(): void { absorption = new Absorption(i32(p_delta_window()), i32(p_atr_length()), p_delta_spike(), p_max_range()); bursts = new LiquidationBurst(i32(p_window()), p_burst_z()); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const absorbed = absorption.update(high, low, close, in_buy(), in_sell()); const burst = bursts.update(in_long_liq(), in_short_liq()); const range = absorption.range(); const dotAbove = absorbed == 1 ? high + range * 0.4 : NaN; const dotBelow = absorbed == -1 ? low - range * 0.4 : NaN; out_absorbed_buying(dotAbove); out_absorbed_selling(dotBelow); out_absorption(f64(absorbed)); out_burst(f64(burst)); } ``` A `shape` output written `NaN` draws nothing on that bar, so the dots appear only where the detector fired. The recipes add a box around the candle, a money tag on a burst and a notice when the market serves no sided prints or no liquidations; those are drawing objects on top of the same two answers. ## Where it runs The chart serves `volume_profile` and `book` over the loaded history and pushes the forming bar's profile and book live; a book module refreshes its newest bar at most about once a second. Cell alignment is an exact join: a primary bar with no observation gets a present empty block (`n == 0`), never a carried-forward one, so volume is never counted twice and a stale book never masquerades as a fresh read ([Data sources](../core-concepts/data-sources.md#celled-sources)). When the market has no profile data, the run stops with a toast instead of drawing zeros: "Volume profile data is unavailable for '' (the volume_profile source lane answered empty or was declined), so the indicator cannot compute." An alert on the indicator runs in OpenMarket's cloud; when it cannot evaluate a data source, saving the alert says so ("This Indicator reads a data source alerts cannot evaluate yet.", [Alerts](alerts.md)). ## Practices - **Scan once.** Read the count and the view once per bar and compute every measure from them. Nine scans over a bar's few hundred tuples is still cheap, but one is cheaper. - **Track the point of control.** The price with the most traded volume often acts as a magnet; `vpPoc` with `vpPocVolume` says how dominant the level is. - **Read delta for pressure.** `vpDelta` summarizes net aggressor flow per bar. Sustained positive delta is buy-side control; feed it to `Cvd` or `Cum` for cumulative delta, or to `Rsi` for delta-RSI ([TA library](ta-library.md)). - **Smooth the imbalance.** A large bid-over-ask imbalance often precedes an upward move and the reverse a downward one; a single snapshot is noisy, so smooth it before alerting on it. - **Watch large orders.** `max_bid` and `max_ask` jumping is size arriving; pair them with `min_bid` / `min_ask` to tell a thin book from a deep one. ## From Pine Nothing on this page maps one to one. Pine has no sided trades, volume profile bands, book levels or liquidations as script inputs, so there is no `ta.*` call to translate: the delta, the profile and the imbalance are computed from cells the chart serves to the indicator, and the detectors are recipes of this chart. Where Pine offers a volume profile, it is a chart-level drawing, not a series a script can read. <!-- source: https://openmarket.xyz/wrun/functions/levels-kit --> # Levels kit Levels are the prices a trader draws before the session starts: today's open, yesterday's high and low, last week's close, the session's range, the pivot point with its supports and resistances, the round numbers near price, and the swing levels price keeps returning to. A wrun indicator sees one bar at a time ([Execution model](../core-concepts/execution-model.md)), so the `./sdk/levels` module keeps the state for you. `PeriodLevels` and `SessionLevels` roll over on the clock from the [clock and sessions kit](time-and-sessions-kit.md), `PivotPoints` computes the standard, Fibonacci, Camarilla and Woodie sets from a previous range, `roundLevels` fills a grid of round numbers around a price, and `SupportResistance` clusters confirmed pivots into levels and counts how often each was touched. Everything is a class or a function you construct in `onStart()`, feed once per bar and read on the same bar; no call allocates after construction, so the module never grows memory per bar. | Export | Signature | Definition | | --- | --- | --- | | `PeriodLevels` | `new PeriodLevels(period, zone = "UTC")`; `.update(t, open, high, low, close)`; `.isNew()`, `.open()`, `.high()`, `.low()`, `.prevOpen()`, `.prevHigh()`, `.prevLow()`, `.prevClose()`, `.refused()`, `.refusedReason()`, `.reset()` | The running open, high and low of the current `"day"`, `"week"`, `"month"`, `"quarter"` or `"year"` in a time zone (or the period as Pine spells the timeframe: `"D"` / `"1D"`, `"W"` / `"1W"`, `"M"` / `"1M"`, `"3M"`, `"12M"`), and the open, high, low and close of the last completed one (`NaN` until one completes) | | `SessionLevels` | `new SessionLevels(spec, zone = "UTC", days = "0123456")`; `.update(t, open, high, low, close)`; `.isIn()`, `.isNew()`, `.open()`, `.high()`, `.low()`, `.prevOpen()`, `.prevHigh()`, `.prevLow()`, `.prevClose()`, `.refused()`, `.refusedReason()`, `.reset()` | The same over an `"HHMM-HHMM"` session on the listed weekdays (`0` = Sunday): the running levels while the bar is inside a session instance, the last completed instance as `prev*` | | `PivotPoints` | `new PivotPoints(kind = "standard")`; `.compute(high, low, close, open = NaN)`; `.pp()`, `.r1()`, `.r2()`, `.r3()`, `.s1()`, `.s2()`, `.s3()`, `.refused()`, `.refusedReason()` | The seven floor-trader levels from one range in the `"standard"`, `"fibonacci"`, `"camarilla"` or `"woodie"` form; every `compute()` overwrites them; any other kind refuses softly (Pine's `"Traditional"` is `"standard"`) | | `roundLevels` | `roundLevels(price, step, out): i32` | Fills `out` (a `StaticArray<f64>`) with the multiples of `step` around `price`, the first half at or below it and the rest above, nearest first; returns the count written (`0` for a step of `0` or below, a `NaN` step or a `NaN` price) | | `SupportResistance` | `new SupportResistance(left, right, tolerancePct, maxLevels)`; `.update(high, low, close)`; `.count()`, `.level(i)`, `.touches(i)`, `.kind(i)`, `.nearestAbove(price)`, `.nearestBelow(price)`, `.reset()` | Every confirmed `PivotHigh` / `PivotLow` (TradingView's pivots) merges into the nearest level within `tolerancePct` of its price or starts one; at most `maxLevels` are kept, the least touched dropped first | The first argument of `update()` on the two calendar classes is the bar's open time in UTC seconds: pass `bar.time()`. A `period`, `kind`, zone or session spec the module does not know never stops your indicator: the object refuses softly, `refused()` is true, `refusedReason()` names the rule and the words it takes, and every level reads `NaN`, so nothing draws from it. Written as a literal, the same argument fails the build on its line, in the same words. Every example constructs in `onStart()`, where the settings are read. ## Previous day, week and month levels `PeriodLevels(period, zone)` follows the `Clock` of the [clock and sessions kit](time-and-sessions-kit.md): a period is the run of bars sharing the clock's day, week (Monday start), month, quarter (from January, April, July or October 1st) or year key in the zone you name (`"UTC"` by default; `"America/New_York"`, `"Europe/London"` and the other names that page lists, or a fixed `"+05:30"`). `period` is one of the five words `"day"`, `"week"`, `"month"`, `"quarter"` and `"year"`, or the timeframe string a Pine script passes to `request.security`: `"D"` or `"1D"`, `"W"` or `"1W"`, `"M"` or `"1M"`, `"3M"` for the quarter and `"12M"` for the year. Anything else (a lowercase `"d"`, an intraday `"60"`, a `"2D"` the clock has no key for) refuses softly in the constructor; a span the clock has no key for is a [Bucket](higher-timeframe-kit.md#any-span-bucket). On each bar: - `isNew()` is true on the first bar of a period, and on the very first bar the object sees. - `open()` is the open of the period's first bar; `high()` and `low()` are the running extremes so far. - On the bar a new period starts, the period that just ended becomes `prevOpen()`, `prevHigh()`, `prevLow()` and `prevClose()` (the close of its last bar). They hold for the whole period and never repaint. - `prev*` are `NaN` until the first period boundary after construction or `reset()`. The period already running when the history starts counts as a period, however much of it the loaded bars cover, the same rule as the [Key levels](../cookbook/key-levels.md) recipe: on an intraday chart the first `prev*` may describe a partial day. - A non-finite `open` makes `open()` `NaN` for the period; a non-finite `high` or `low` makes that extreme `NaN` for the rest of the period (and the `prev*` it becomes); `prevClose()` is the last bar's close. The previous New York day's high and low as lines, with the running day open dashed and a data-only flag on the first bar of each day: ```typescript output("pdh", line, overlay, { color: "#f5a623", width: 1, description: "Previous New York day high" }); output("pdl", line, overlay, { color: "#f5a623", width: 1, description: "Previous New York day low" }); output("day_open", line, overlay, { color: "#94a3b8", width: 1, line_style: "dashed", description: "Open of the running day" }); output("new_day", none, overlay, { description: "1 on the first bar of a New York day" }); let day = new PeriodLevels("day"); function onStart(): void { // Construct in onStart(): an unknown period or zone refuses softly (day.refusedReason() says why). day = new PeriodLevels("day", "America/New_York"); } function onBar(): void { day.update(bar.time(), bar.open(), bar.high(), bar.low(), bar.close()); out_pdh(day.prevHigh()); out_pdl(day.prevLow()); out_day_open(day.open()); out_new_day(day.isNew() ? 1.0 : 0.0); } ``` The two level lines are `NaN` until the first New York midnight in the loaded history, then step on each midnight, daylight time included: the clock handles the 23-hour and 25-hour days. Four more `PeriodLevels` objects give the week, the month, the quarter and the year, or the same day in another zone; a yearly open is `new PeriodLevels("12M", zone)` read with `open()`. ## Session levels `SessionLevels(spec, zone, days)` follows the `Session` of the same kit: `spec` is `"HHMM-HHMM"` in the zone's local time, half-open (`"0930-1600"` holds 09:30 and excludes 16:00) and wrapping past midnight when the close is earlier than the open; `days` lists the weekday digits of the instance's opening day, `0` = Sunday through `6` = Saturday, so `"12345"` is Monday to Friday. Pine's session day string `"23456"` (Sunday = 1) is `"12345"` here. - `isIn()` is true while the bar sits inside an instance; `isNew()` on its first in-session bar. - `open()`, `high()` and `low()` describe the instance in progress and read `NaN` outside a session. - On the first bar after an instance ended (outside the hours, or already the first bar of the next instance when the bars skip the close) the ended instance becomes `prevOpen()`, `prevHigh()`, `prevLow()` and `prevClose()`; they hold until the next instance ends, so the previous session's range is available all night and through the weekend. - `prev*` are `NaN` until one instance has ended after construction or `reset()`; an instance already running when the history starts counts from its first loaded bar. A session no bar ever opens inside (a daily chart against an intraday session) never produces levels. `new SessionLevels("0930-1600", "America/New_York", "12345")` is the regular trading session of the US stock exchanges; feed it exactly as the example above feeds `PeriodLevels` and draw `prevHigh()` and `prevLow()` the same way. ## Pivot points `PivotPoints(kind).compute(high, low, close)` takes one range, normally the previous day's from `PeriodLevels`, and fills seven levels. With `H`, `L`, `C` and the range `R = H - L`: | Kind | Pivot | Resistances | Supports | | --- | --- | --- | --- | | `"standard"` | `PP = (H + L + C) / 3` | `R1 = 2 PP - L`, `R2 = PP + R`, `R3 = H + 2 (PP - L)` | `S1 = 2 PP - H`, `S2 = PP - R`, `S3 = L - 2 (H - PP)` | | `"fibonacci"` | `PP` as standard | `R1 = PP + 0.382 R`, `R2 = PP + 0.618 R`, `R3 = PP + R` | `S1 = PP - 0.382 R`, `S2 = PP - 0.618 R`, `S3 = PP - R` | | `"camarilla"` | `PP` as standard | `R1 = C + R * 1.1 / 12`, `R2 = C + R * 1.1 / 6`, `R3 = C + R * 1.1 / 4` | `S1 = C - R * 1.1 / 12`, `S2 = C - R * 1.1 / 6`, `S3 = C - R * 1.1 / 4` | | `"woodie"` | `PP = (H + L + 2 C) / 4` | the standard formulas from that `PP` | the standard formulas from that `PP` | `compute()` accepts a fourth `open` argument for kinds that read it; none of the four does. A non-finite high, low or close makes all seven levels `NaN`, and there is no `reset()`: every `compute()` overwrites every level, so `compute(NaN, NaN, NaN)` clears them. The kind is chosen at construction; to make it a setting, map a numeric param to the name in `onStart()`: ```typescript param("kind", 0, { min: 0, max: 3, description: "0 standard, 1 fibonacci, 2 camarilla, 3 woodie" }); output("pp", line, overlay, { color: "#94a3b8", width: 1, description: "Pivot point from the previous UTC day" }); output("r1", line, overlay, { color: "#dc2626", width: 1, description: "First resistance" }); output("r2", line, overlay, { color: "#dc2626", width: 1, line_style: "dashed", description: "Second resistance" }); output("r3", line, overlay, { color: "#dc2626", width: 1, line_style: "dotted", description: "Third resistance" }); output("s1", line, overlay, { color: "#16a34a", width: 1, description: "First support" }); output("s2", line, overlay, { color: "#16a34a", width: 1, line_style: "dashed", description: "Second support" }); output("s3", line, overlay, { color: "#16a34a", width: 1, line_style: "dotted", description: "Third support" }); function kindName(kind: i32): string { if (kind == 1) return "fibonacci"; if (kind == 2) return "camarilla"; if (kind == 3) return "woodie"; return "standard"; } let day = new PeriodLevels("day"); let pivots = new PivotPoints(); function onStart(): void { day = new PeriodLevels("day"); pivots = new PivotPoints(kindName(i32(p_kind()))); } function onBar(): void { day.update(bar.time(), bar.open(), bar.high(), bar.low(), bar.close()); // The previous day's range stands for the whole day: recompute once, when the day turns. if (day.isNew()) pivots.compute(day.prevHigh(), day.prevLow(), day.prevClose()); out_pp(pivots.pp()); out_r1(pivots.r1()); out_r2(pivots.r2()); out_r3(pivots.r3()); out_s1(pivots.s1()); out_s2(pivots.s2()); out_s3(pivots.s3()); } ``` Weekly pivots are the same file with `new PeriodLevels("week")` (or `"W"`, as Pine spells it); a session's pivots feed `compute()` from `SessionLevels` on the bar its `prev*` change. ## Round numbers `roundLevels(price, step, out)` fills a `StaticArray<f64>` you allocated once (at module level or in `onStart()`) with the multiples of `step` around `price`: with `base` the nearest multiple at or below `price`, the first `out.length / 2` slots (integer division) hold `base`, `base - step`, `base - 2 step`, ... and the remaining slots hold `base + step`, `base + 2 step`, ..., each half nearest first. It returns how many slots it wrote, `out.length` on success. A step of `0` or below, a `NaN` step or a `NaN` price write `NaN` into every slot and return `0`, so a stale grid never survives a bad bar. The values are floating-point products (`3 * 0.1` prints as `0.30000000000000004`): format them for display instead of comparing them with `==`. ```typescript const grid = new StaticArray<f64>(6); // 3 at or below the close, 3 above // In onBar(): grid[0] is the nearest round number at or below the close, // grid[3] the nearest above; count is 6, or 0 when the step was unusable. // const count = roundLevels(bar.close(), 100.0, grid); ``` A step of `100` on a five-figure price gives the hundreds; derive it from the price instead (`Math.pow(10.0, Math.floor(Math.log10(close)) - 1)`) for a grid that scales with the market. ## Clustered support and resistance `SupportResistance(left, right, tolerancePct, maxLevels)` is new: the shipped recipes take calendar extrema ([Key levels](../cookbook/key-levels.md)) or keep one zone per side ([Zone tracker](../cookbook/zone-tracker.md)); this class keeps a small ledger of levels built from every confirmed swing and remembers how often each was hit. It runs a `PivotHigh(left, right)` over the high and a `PivotLow(left, right)` over the low from `./sdk/ta` ([Series functions](series-functions.md)), so a pivot is reported `right` bars after its bar and never repaints. On each confirmed pivot: - It merges into the NEAREST existing level whose price is within `tolerancePct` percent of the pivot's price: the level's price becomes the touch-weighted mean of everything that merged into it and its `touches` grow by one. A tolerance of `0` merges exact matches only. - Otherwise it starts a new level with one touch. When that would exceed `maxLevels`, the existing level with the fewest touches is dropped first, the oldest on a tie; a new level always enters. - When a high and a low confirm on the same bar, the high merges first. `count()` is how many levels are kept, `level(i)` the price of the `i`-th by age (`0` the oldest kept), `touches(i)` its count and `kind(i)` `+1` when more pivot highs than lows merged into it (resistance), `-1` when more lows (support), the latest pivot's side on a tie; an index outside `0..count() - 1` reads `NaN`, `0` and `0`. `nearestAbove(price)` is the lowest level strictly above `price` and `nearestBelow(price)` the highest strictly below, `NaN` when there is none. `update(high, low, close)` takes the close for symmetry with the other kit classes and does not read it. `reset()` empties the ledger and the pivot windows. The levels as line handles, one per kept level, coloured by side and extended to the right, with the nearest level above and below the close as ordinary lines: ```typescript param("left", 5, { min: 1, max: 50, description: "Bars a swing must dominate on its left" }); param("right", 5, { min: 1, max: 50, description: "Bars that confirm the swing on its right" }); param("tolerance_pct", 0.3, { min: 0, max: 5, description: "Merge band as a percent of the pivot's price" }); param("max_levels", 6, { min: 1, max: 12, description: "Levels kept; the least touched goes first" }); output("nearest_above", line, overlay, { color: "#dc2626", width: 1, description: "The nearest level above the close" }); output("nearest_below", line, overlay, { color: "#16a34a", width: 1, description: "The nearest level below the close" }); output("level_count", none, overlay, { description: "Levels kept on this bar" }); handles.line({ color: "#94a3b8", width: 1, lineStyle: "dashed", extend: "right" }); let sr = new SupportResistance(5, 5, 0.3, 6); const lines = new Array<LineHandle>(); let firstT: f64 = NaN; function onStart(): void { sr = new SupportResistance(i32(p_left()), i32(p_right()), p_tolerance_pct(), i32(p_max_levels())); // One handle per kept level, made once here: ids are one space across the handle kinds. for (let i = 0; i < i32(p_max_levels()); i++) lines.push(draw.line(i)); } function onBar(): void { const t = bar.time(); if (isNaN(firstT)) firstT = t; const close = bar.close(); sr.update(bar.high(), bar.low(), close); const count = sr.count(); for (let i = 0; i < lines.length; i++) { if (i < count) { // Levels move as pivots merge, so every bar re-sets each line: same id, same line. const price = sr.level(i); const ink = sr.kind(i) > 0 ? rgba(220, 38, 38, 255) : rgba(22, 163, 74, 255); lines[i].set(firstT, price, t, price).color(ink).width(sr.touches(i) > 1 ? 2.0 : 1.0); } else { // A slot without a level: delete() on an id nobody holds is a no-op. lines[i].delete(); } } out_nearest_above(sr.nearestAbove(close)); out_nearest_below(sr.nearestBelow(close)); out_level_count(f64(count)); } ``` Levels with more than one touch draw thicker. Because a level's index is its age, a level that merges keeps its slot and its line; when a level is dropped the younger levels move down one index and the new level takes the last one, so several lines can change price on that bar. Read `last 20 level_count` at the editor's Console prompt to see the ledger fill, and `nearest_above` or `nearest_below` for the level price itself. ## From Pine - `request.security(syminfo.tickerid, "D", high[1])`: `new PeriodLevels("D")` (the same object as `"day"`) fed each bar, then `.prevHigh()` (and `.prevLow()`, `.prevOpen()`, `.prevClose()` for the other fields). - `request.security(syminfo.tickerid, "W", close[1])`, and the same with `"M"`, `"3M"` or `"12M"`: `new PeriodLevels("W")`, `("M")`, `("3M")`, `("12M")` and `.prevClose()`; the same request without `[1]` is the running period, `.open()`, `.high()` and `.low()`. - `timeframe.change("D")` (or `"W"`, `"M"`, `"3M"`, `"12M"`): `.isNew()` on the `PeriodLevels` built from that word, or `clock.isNewDay()` and its siblings on a `Clock` ([clock and sessions kit](time-and-sessions-kit.md)). - `ta.pivot_point_levels(type, anchor)`: `new PivotPoints(kind)` with `.compute()` called on the bar the anchor period turns, the previous period's high, low and close from `PeriodLevels` as its arguments. <!-- source: https://openmarket.xyz/wrun/functions/market-structure-kit --> # Market structure kit The `./sdk/structure` module reads price as a sequence of swings and gives you, in every file, the bookkeeping every market-structure indicator rewrites by hand: `Swings` finds confirmed swing highs and lows and says whether each is a higher or lower one, `MarketStructure` turns them into breaks of structure and changes of character with a trend, `FairValueGaps` keeps a ring of three-bar gaps and knows when a close filled each, `OrderBlocks` keeps the last opposite candle before every break until price trades back into it, `Divergence` compares price pivots with an oscillator, and the `candles` namespace answers doji, hammer, engulfing, inside, outside and pin bar as plain predicates. Nothing here repaints: a swing is confirmed `right` bars after it prints, exactly like the pivots on [Series functions](series-functions.md), and every other definition is built on that lag, so you do not keep the same state in arrays by hand. Authors disagree on almost every one of these definitions (how a pivot treats a tie, wick or close breaks, whether a change of character needs a prior trend, where an order block's edges sit), so each section below spells out the one definition its class implements, and that definition is the contract. ## What the module gives you | Export | Constructor and calls | In one line | | --- | --- | --- | | `Swings` | `new Swings(left, right)`; `.update(high, low)`; `.lastHigh()`, `.lastLow()`, `.barsSinceHigh()`, `.barsSinceLow()`, `.newHigh()`, `.newLow()`, `.hh()`, `.hl()`, `.lh()`, `.ll()`; `.reset()` | Pivots of the high and low as TradingView finds them, confirmed `right` bars late, each tagged higher or lower than the previous one | | `MarketStructure` | `new MarketStructure(left, right)`; `.update(high, low, close)`; `.trend()`, `.event()`, `.lastBreakLevel()`; `.reset()` | A close beyond the last unbroken swing: BOS (`1` / `-1`) or CHoCH (`2` / `-2`), each swing breakable once | | `FairValueGaps` | `new FairValueGaps(max, minSizePct = 0)`; `.update(high, low, close)`; `.count()`, `.newest()`, `.top(i)`, `.bottom(i)`, `.direction(i)`, `.age(i)`, `.filled(i)`; `.reset()` | Three-bar gaps in a ring of the newest `max`, filled by a close beyond the far edge | | `OrderBlocks` | `new OrderBlocks(max, left, right)`; `.update(open, high, low, close)`; `.count()`, `.newest()`, `.top(i)`, `.bottom(i)`, `.direction(i)`, `.age(i)`, `.mitigated(i)`; `.reset()` | The last opposite candle before each break, mitigated when a later bar trades into it | | `Divergence` | `new Divergence(left, right)`; `.update(price, osc): i32`; `.reset()` | `1` regular bullish, `2` hidden bullish, `-1` regular bearish, `-2` hidden bearish on a pivot's confirmation bar, else `0` | | `candles.doji(o, h, l, c, bodyPct = 10)` | | Body at most `bodyPct` percent of the range | | `candles.hammer(o, h, l, c)` | | Long lower wick, short upper wick, close in the top third | | `candles.shootingStar(o, h, l, c)` | | The hammer mirrored | | `candles.bullishEngulfing(prevO, prevC, o, c)` | | An up bar whose body covers the previous down bar's body | | `candles.bearishEngulfing(prevO, prevC, o, c)` | | A down bar whose body covers the previous up bar's body | | `candles.insideBar(prevH, prevL, h, l)` | | `h <= prevH` and `l >= prevL` | | `candles.outsideBar(prevH, prevL, h, l)` | | `h > prevH` and `l < prevL` | | `candles.pinBar(o, h, l, c, wickRatio = 2)` | | `1` for a dominant lower wick, `-1` for a dominant upper wick, `0` otherwise | The shared rules: construct in `onStart()` (every class allocates in its constructor only, so per-bar memory stays flat); call `update()` once per bar, then read the getters; `NaN` means "nothing yet" from every price getter and `-1` or `0` from the integer ones; `reset()` restores the freshly built state. Periods and ring sizes below 1 clamp to 1. Bad data never turns into a signal. A value that is `NaN` or an infinity is non-finite, and a bar with any non-finite field its class reads (the high, low or close; the open too for order blocks) breaks nothing, opens nothing, fills nothing and mitigates nothing, while ages still count that bar. Each section below says what that means for its class in one line. ## Swings ```text high[k] >= its `left` neighbours, > its `right` neighbours | . . . . H . . . . ^ ^ ^ ^ ^ ^ ^ ^ left = 4 right = 4 -> confirmed here, 4 bars late ``` `new Swings(left, right)` runs a `PivotHigh` over the high and a `PivotLow` over the low, TradingView's `ta.pivothigh` and `ta.pivotlow`. A swing high is a bar whose high is at least each of the `left` highs before it (a tie on the left still counts) and strictly above each of the `right` highs after it (a tie on the right does not); it is confirmed on the bar `right` bars later and never repainted. On that confirmation bar `newHigh()` is true, `lastHigh()` holds the swing's price, and `barsSinceHigh()` reads `right` (it counts from the swing bar, so it is `-1` before the first swing and grows by one every bar). `hh()` and `lh()` are true on the confirmation bar only, comparing the new swing high with the previous confirmed swing high (strictly higher or strictly lower; the first swing is neither); `hl()` and `ll()` do the same for swing lows. A non-finite high in the window ends the comparison on its side (the bars past it are not compared), and a non-finite candidate is no swing; the low side mirrors it. The sample tags every confirmed swing at its own bar with a label handle, HH / LH above and HL / LL below: ```typescript param("left", 5, { min: 1, max: 50, description: "Bars a swing must beat on its left" }); param("right", 5, { min: 1, max: 50, description: "Bars a swing must beat on its right: the confirmation lag" }); input("high", ohlcv.high); output("swing_high", none, overlay, { description: "The newest confirmed swing high" }); output("swing_low", none, overlay, { description: "The newest confirmed swing low" }); string("tag", { max_bytes: 24 }); handles.label({ size: 11 }); const MAX_TAGS = 16; // per side, the oldest tag is reused const RED: i32 = rgba(248, 113, 113, 255); const GREEN: i32 = rgba(74, 222, 128, 255); function makeLabels(first: i32, count: i32): LabelHandle[] { const out: LabelHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.label(first + i)); return out; } const highTags = makeLabels(0, MAX_TAGS); const lowTags = makeLabels(MAX_TAGS, MAX_TAGS); let swings = new Swings(5, 5); let right: i32 = 5; let highs: i32 = 0; let lows: i32 = 0; let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; function onStart(): void { right = i32(p_right()); swings = new Swings(i32(p_left()), right); } function onBar(): void { prevT = t; t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; swings.update(bar.high(), bar.low()); out_swing_high(swings.lastHigh()); out_swing_low(swings.lastLow()); if (!isNaN(width)) { // The swing printed `right` bars ago: place the tag on its own bar. const x = t - width * f64(right); if (swings.newHigh()) { const tag = highTags[highs % MAX_TAGS]; highs += 1; sb_clear(); sb_text(swings.hh() ? "HH " : swings.lh() ? "LH " : "H "); sb_f64(swings.lastHigh(), 2); tag.set(x, swings.lastHigh()).text(str_tag_sb).color(RED); } if (swings.newLow()) { const tag = lowTags[lows % MAX_TAGS]; lows += 1; sb_clear(); sb_text(swings.hl() ? "HL " : swings.ll() ? "LL " : "L "); sb_f64(swings.lastLow(), 2); tag.set(x, swings.lastLow()).text(str_tag_sb).color(GREEN); } } } ``` ## Break of structure and change of character ```text close above the last unbroken swing high swing high ---------------------- . <- BOS up (1) with the trend, or /\ / | CHoCH up (2) when the trend was down / \ / / \ / \/ <- swing low: a close below it breaks the other way ``` `new MarketStructure(left, right)` keeps its own `Swings`. The trend starts at `0`. Every confirmed swing can be broken once: a close strictly above the last unbroken swing high is an upward break, reported as BOS up (`event()` is `1`) while the trend is `0` or `+1` and as CHoCH up (`2`) while the trend is `-1`; after it the trend is `+1`. A close strictly below the last unbroken swing low is the mirror image: BOS down (`-1`) while the trend is `0` or `-1`, CHoCH down (`-2`) while it is `+1`, then the trend is `-1`. A newly confirmed swing replaces the previous one of its kind as the level to break. `event()` is non-zero on the breaking bar only, `trend()` holds between events, and `lastBreakLevel()` is the price of the swing the newest break went through. A bar with a non-finite high, low or close breaks nothing: the trend holds and the swing stays breakable by the next finite bar. The sample draws each event as a shape on the breaking bar and the broken level as a line: ```typescript param("left", 5, { min: 1, max: 50, description: "Bars a swing must beat on its left" }); param("right", 5, { min: 1, max: 50, description: "Bars a swing must beat on its right" }); input("high", ohlcv.high); output("bos_up", shape, overlay, { color: "#4ade80", description: "A mark under the bar that closed above the last swing high with the trend" }); output("choch_up", shape, overlay, { color: "#22d3ee", description: "A mark under the bar that turned a downtrend up" }); output("bos_down", shape, overlay, { color: "#f87171", description: "A mark over the bar that closed below the last swing low with the trend" }); output("choch_down", shape, overlay, { color: "#fb923c", description: "A mark over the bar that turned an uptrend down" }); output("level", line, overlay, { color: "#94a3b8", width: 1, description: "The price of the last broken swing" }); output("trend", none, overlay, { description: "1 up, -1 down, 0 before the first break" }); let structure = new MarketStructure(5, 5); function onStart(): void { structure = new MarketStructure(i32(p_left()), i32(p_right())); } function onBar(): void { const high = bar.high(); const low = bar.low(); structure.update(high, low, bar.close()); // A shape output draws where its value is a price and nothing where it is NaN. const event = structure.event(); out_bos_up(event == 1 ? low : NaN); out_choch_up(event == 2 ? low : NaN); out_bos_down(event == -1 ? high : NaN); out_choch_down(event == -2 ? high : NaN); out_level(structure.lastBreakLevel()); out_trend(f64(structure.trend())); } ``` ## Fair value gaps ```text bar 1 bar 2 bar 3 | | | <- low of bar 3 above the high of bar 1: | | ......| a bullish gap from high[1] (bottom) to | .....|.........| low[3] (top), open until a close drops | | below the bottom ``` `new FairValueGaps(max, minSizePct)` watches three bars at a time. A bullish gap opens on the bar whose low is strictly above the high two bars back (top = this low, bottom = that high, `direction(i)` is `1`); a bearish gap opens when this high is strictly below the low two bars back (top = that low, bottom = this high, `direction(i)` is `-1`). A gap whose height is under `minSizePct` percent of this bar's close is ignored. Each gap is created with `age(i)` `0` and ages one per bar; it is filled the first time a later close crosses the far edge (bullish: close below the bottom; bearish: close above the top) and `filled(i)` stays true. The ring keeps the newest `max` gaps, filled or not, dropping the oldest: index `0` is the oldest kept and `newest()` is `count() - 1` (`-1` while empty). A gap needs all three of its bars finite (high, low and close each), and a bar with a non-finite high, low or close fills nothing; every kept gap still ages on it. The sample draws every kept gap as a box handle from its middle bar, extended to the next bar while it is open and left where it was once filled: ```typescript param("min_size_pct", 0.1, { min: 0, max: 10, description: "Smallest gap kept, in percent of the close" }); input("high", ohlcv.high); output("open_gaps", none, overlay, { description: "Gaps kept in the ring that no close has filled yet" }); handles.box({ opacity: 0.15, borderWidth: 1 }); const MAX_GAPS = 12; // the ring size and the box count, so ring index and box stay aligned const GREEN: i32 = rgba(74, 222, 128, 255); const RED: i32 = rgba(248, 113, 113, 255); function makeBoxes(count: i32): BoxHandle[] { const out: BoxHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.box(i)); return out; } const boxes = makeBoxes(MAX_GAPS); let gaps = new FairValueGaps(MAX_GAPS, 0.1); let seen: i32 = 0; // gaps created so far: box (seen - count + i) % MAX_GAPS draws ring index i let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; function onStart(): void { gaps = new FairValueGaps(MAX_GAPS, p_min_size_pct()); } function onBar(): void { prevT = t; t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; gaps.update(bar.high(), bar.low(), bar.close()); const newest = gaps.newest(); if (newest >= 0 && gaps.age(newest) == 0) seen += 1; let open: f64 = 0.0; const count = gaps.count(); if (!isNaN(width)) { for (let i = 0; i < count; i += 1) { const box = boxes[(seen - count + i) % MAX_GAPS]; const filled = gaps.filled(i); if (!filled) open += 1.0; // The gap opened on the bar `age` bars ago; its middle bar is one earlier. const left = t - width * f64(gaps.age(i) + 1); const color = gaps.direction(i) > 0 ? GREEN : RED; if (filled) { box.opacity(0.05); // stops where it was } else { box.set(left, gaps.top(i), t + width, gaps.bottom(i)).color(color).fill(color).opacity(0.15); } } } out_open_gaps(open); } ``` ### Inverse fair value gaps An inverse fair value gap (IFVG) is a filled gap read the other way round: a filled bullish gap becomes a bearish zone, and the reverse. In `FairValueGaps` those are the kept gaps with `filled(i)` true, from `bottom(i)` to `top(i)`, pointing opposite to `direction(i)`. The kit does not record when a gap filled. ## Order blocks ```text swing high broken here -> close | | | | | | | | | B | B = the last bearish candle before the | breaking bar (searching back to the swing high's bar): its high and low are the bullish order block ``` `new OrderBlocks(max, left, right)` runs a `MarketStructure` of its own. On every BOS or CHoCH it looks back from the bar before the breaking bar to the broken swing's bar (inclusive) for the last bar whose close is against the break direction: a bearish candle (close strictly below open) for an upward break, a bullish candle for a downward break. That bar's high and low are the block's `top(i)` and `bottom(i)`, `direction(i)` is `1` for an upward break and `-1` for a downward one, and there is at most one block per event (none when no such bar exists in that span). A block is created with `age(i)` `0` and is mitigated the first time a later bar trades back into it: a bar's low at or below the top of a bullish block, or a bar's high at or above the bottom of a bearish block; `mitigated(i)` then stays true. The ring keeps the newest `max` blocks, mitigated or not, oldest first, like the gaps. A bar with a non-finite open, high, low or close is never a block's candle, mitigates nothing and breaks nothing (the break waits for the next finite bar that closes beyond the swing); every kept block still ages on it. Draw them like the gap boxes above: the kit keeps a block's edges, not its bar, so start each box on the breaking bar it was created on (`t - width * f64(age(i))`; the block's own candle sits between the broken swing and that bar) and stop extending a block once it is mitigated. ## Divergence ```text price . . <- lower low in price \ / \ . / \/ \ / \/ RSI . <- higher low in the oscillator on the same \ . two pivot bars: regular bullish (+1) \ / \ / \ / ``` `new Divergence(left, right)` finds the pivots of the price you feed it (the close, usually; the `Swings` rule) and remembers the oscillator's value on each pivot bar. On the bar a pivot is confirmed it compares the two most recent confirmed pivots of that kind with the oscillator on the same two bars: at pivot lows, a lower low in price with a higher low in the oscillator is regular bullish (`1`) and a higher low in price with a lower low in the oscillator is hidden bullish (`2`); at pivot highs, a higher high in price with a lower high in the oscillator is regular bearish (`-1`) and a lower high in price with a higher high in the oscillator is hidden bearish (`-2`). Every other bar, the first pivot of a kind, and any tie in price or oscillator give `0`. A non-finite oscillator value on either of the two pivot bars never diverges (the warm-up of an `Rsi` is the usual case), and that pivot still becomes the previous one for the next comparison. Beside a missing price a pivot high and a pivot low can confirm on the same bar: both are recorded, and the bar returns the high's verdict when it has one, else the low's. The sample runs it over the close and a 14-bar `Rsi` from `./sdk/ta` and marks the price bar; the marks carry `displacement_bars: -5` so they draw on the pivot bar itself at the default `right` of 5 (change both together): ```typescript param("rsi_period", 14, { min: 2, max: 200, description: "RSI length" }); param("left", 5, { min: 1, max: 50, description: "Bars a price pivot must beat on its left" }); param("right", 5, { min: 1, max: 50, description: "Bars a price pivot must beat on its right" }); output("rsi", line, lower, { color: "#a78bfa", description: "14-bar RSI of the close" }); output("bullish", shape, overlay, { color: "#4ade80", displacement_bars: -5, description: "Regular bullish: lower low in price, higher low in RSI" }); output("hidden_bullish", shape, overlay, { color: "#86efac", displacement_bars: -5, description: "Hidden bullish: higher low in price, lower low in RSI" }); output("bearish", shape, overlay, { color: "#f87171", displacement_bars: -5, description: "Regular bearish: higher high in price, lower high in RSI" }); output("hidden_bearish", shape, overlay, { color: "#fca5a5", displacement_bars: -5, description: "Hidden bearish: lower high in price, higher high in RSI" }); output("kind", none, overlay, { description: "1, 2, -1, -2 on the confirmation bar, else 0" }); let rsi = new Rsi(14); let divergence = new Divergence(5, 5); function onStart(): void { rsi = new Rsi(i32(p_rsi_period())); divergence = new Divergence(i32(p_left()), i32(p_right())); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const value = rsi.update(close); // A NaN oscillator on a pivot bar (the RSI warm-up) compares as no divergence. const kind = divergence.update(close, value); out_rsi(value); out_bullish(kind == 1 ? low : NaN); out_hidden_bullish(kind == 2 ? low : NaN); out_bearish(kind == -1 ? high : NaN); out_hidden_bearish(kind == -2 ? high : NaN); out_kind(f64(kind)); } ``` ## Candle patterns ```text doji hammer shooting star engulfing inside outside | | | | | | | -+- -+- | -+ | -+- -+- | | | | | | | | | | -+- |-+- | | | | | | -+- | ``` The `candles` namespace is stateless: each function takes the prices it needs and answers for that bar. Body is `abs(close - open)`, range is `high - low`, the lower wick is `min(open, close) - low` and the upper wick is `high - max(open, close)`. `doji` is true when the body is at most `bodyPct` percent of the range (a bar with no range counts). `hammer` needs a lower wick at least twice the body, an upper wick at most the body, and a close in the top third of the range; `shootingStar` is the mirror image with the close in the bottom third. `bullishEngulfing` needs this bar closing up, the previous bar closing down, and this body covering the previous body (`o <= prevC` and `c >= prevO`); `bearishEngulfing` is the mirror. `insideBar` is `h <= prevH` and `l >= prevL`; `outsideBar` is `h > prevH` and `l < prevL`. `pinBar` finds the dominant wick: at least `wickRatio` times the body and at least as long as the other wick, and answers `1` when that wick is below the body, `-1` when it is above, `0` otherwise (two equal qualifying wicks read `1`). Two rules keep degenerate bars out. `hammer`, `shootingStar` and `pinBar` need a positive range (`h > l`) and a positive dominant wick, so a flat bar (open, high, low and close all equal) is a doji and nothing else: not a hammer, not a shooting star, and `pinBar` answers `0`. And any non-finite argument, a `NaN` or an infinity in any price, in `bodyPct` or in `wickRatio`, makes every predicate answer false (`0` from `pinBar`). Feed the two-bar patterns the previous bar's values you keep yourself at module level, as the swings sample keeps `prevT`: ```typescript // In onBar(), with prevOpen / prevClose / prevHigh / prevLow kept from the last bar: // const engulfed = candles.bullishEngulfing(prevOpen, prevClose, open, close); // const pin = candles.pinBar(open, high, low, close, 2.5); // 1, -1 or 0 // const quiet = candles.insideBar(prevHigh, prevLow, high, low) && candles.doji(open, high, low, close, 15.0); ``` ## From Pine Only the pivot maps one to one: `ta.pivothigh(left, right)` and `ta.pivotlow(left, right)` are `PivotHigh` and `PivotLow` on the [TA library](ta-library.md) page, and `Swings` is the pair of them with the bookkeeping. Structure breaks, gaps, order blocks, divergence and the candle predicates have no Pine builtin; they are the definitions above. <!-- source: https://openmarket.xyz/wrun/functions/options-kit --> # Options kit The chart serves a coin's listed options as `options_chain` cells, one ten-value tuple per contract, on the live bar only ([Data sources](../core-concepts/data-sources.md)). The `./sdk/options` module is the arithmetic a gamma map runs over that block, with nothing to import: The numbers a card prints as net GEX, the dealer regime, the gamma flip and the expected move come from `GammaCurve` and `ExpectedMoves`, one rule each, loaded at the chain's as-of (`optionsAsOfMs`, the live bar's close) on the market's clock and kind, where a US stock or ETF expiry stays live and priced until 15 minutes past its stamp and a US index expiry until its stamp (`optionsLiveUntilMs`, `optionsYearsToGo`): read [The canonical numbers](#the-canonical-numbers) first. `OptionsChain` takes the chain, filters it by expiry and strike window, aggregates every contract into a strike table sorted ascending, and answers gamma exposure by strike, the call and put walls, max pain and the put/call open-interest ratio: the per-strike profile and the levels the [Strike matrix](../cookbook/strike-matrix.md) recipe draws beside its board. Its older totals keep their numbers for the packages that read them, under rules a card must not print as the canonical words: `totalNetGex()` sums the chain's served gammas at each contract's own underlying, and `zeroGamma()` is the first crossing of a running sum over the strikes, which can sit far from spot and contradict the regime. Construct the object in `onStart()`, load it once on the live bar, read it in the same bar; no call allocates after construction, so the module never grows memory per bar. The same module prices the chain too: `Greeks` for one contract's greeks, `IvTerm` for the at-the-money IV by expiry and at constant maturities, and the free functions for the normal curve, the expected move and the market's own date ([Pricing the chain](#pricing-the-chain)). | Export | Signature | Definition | | --- | --- | --- | | `OPTIONS_TUPLE` | `const OPTIONS_TUPLE: i32 = 10` | f64 values per contract in an `options_chain` block: `[strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega]`, `side` `+1` for a call and `-1` for a put | | `OptionsChain` | `new OptionsChain(maxStrikes)`; `.load(cells, count, nowMs, spot, nearest = 0, windowPct = 0.0): i32`; `.loadExpiry(cells, count, nowMs, spot, expiryMs, windowPct = 0.0): i32`; `.loadTable(cells, count, rowWidth, spot, windowPct = 0.0): i32`; `.strikes()`, `.strike(i)`, `.callOi(i)`, `.putOi(i)`, `.callGex(i)`, `.putGex(i)`, `.netGex(i)`, `.callPain(i)`, `.putPain(i)`; `.totalCallGex()`, `.totalPutGex()`, `.totalNetGex()`; `.zeroGamma()`, `.callWall()`, `.putWall()`, `.maxPain()`, `.putCallRatio()` | One chain measured by strike: `load()` keeps the contracts expiring after `nowMs` (the `nearest` soonest expiries when `nearest > 0`, the strikes within `windowPct` percent of `spot` when `windowPct > 0`), sums open interest and gamma exposure per strike and side, and returns the strike count kept; `loadExpiry()` keeps one expiry alone; the readers answer for the chain last loaded. `totalNetGex()` and `zeroGamma()` keep their older numbers; the canonical net GEX and flip are `GammaCurve`'s | | `Greeks` | `new Greeks()`; `.spot(side, s, strike, years, iv, rate = 0.04): f64`; `.forward(side, f, strike, years, iv, rate = 0.04): f64`; fields `price`, `delta`, `gamma`, `vega`, `theta`, `vanna`, `charm`, `d1`, `d2` | One contract priced by Black-Scholes on spot with no dividend, or by Black-76 on a forward; returns the price and fills every field ([Greeks](#greeks-one-contract-priced)) | | `IvTerm` | `new IvTerm(maxExpiries)`; `.load(cells, count, nowMs, spot, zone = 0, rate = 0.0): i32`; `.expiries()`, `.expiry(i)`, `.years(i)`, `.days(i)`, `.underlying(i)`, `.forward(i)`, `.atmStrike(i)`, `.callIv(i)`, `.putIv(i)`, `.atmIv(i)`, `.impliedMove(i)`; `.front()`, `.nearest(days)`, `.indexOf(expiryMs)`; `.iv(days)`; `.deltaStrike(i, side, delta)`, `.deltaIv(i, side, delta)` | The at-the-money IV of every live expiry and at a constant maturity and the strikes at a target delta ([The at-the-money term](#the-at-the-money-term)); `impliedMove(i)` keeps its older numbers, and the canonical expected move is `ExpectedMoves.expectedMove(i)` | | `GammaCurve` | `new GammaCurve(maxContracts, maxFlips = 8)`; `.load(cells, count, asOfMs, nearest = 0, spot = NaN, zone = 0, kind = 0): i32`; `.loadStrikes(cells, count, asOfMs, multiplier, nearest = 0, spot = NaN, zone = 0, kind = 0): i32`; `.contracts()`, `.spot()`, `.gexAt(x)`, `.netGex()`, `.regime()`, `.flip()`, `.flipCount()`, `.flipNear(k)` | Gamma exposure as a curve over hypothetical spot: the one rule behind net GEX, the dealer regime (its sign at spot) and the gamma flip (its root nearest spot) ([The canonical numbers](#the-canonical-numbers)) | | `ExpectedMoves` | `new ExpectedMoves(maxContracts, maxExpiries = 64)`; `.load(cells, count, asOfMs, spot = NaN, zone = 0, kind = 0): i32`; `.expiries()`, `.expiry(i)`, `.years(i)`, `.hours(i)`, `.forward(i)`, `.atmStrike(i)`, `.atmIv(i)`, `.expectedMove(i)`, `.oneSigma(i)`, `.indexOf(expiryMs)`; `.horizonIv(years)` | Per live expiry the forward, the at-the-money IV, the expected move and the 1σ range, and the at-the-money IV at any horizon ([The canonical numbers](#the-canonical-numbers)) | | `dealerRegime` | `dealerRegime(netGex: f64): f64` | The regime by the sign of net GEX: 1 long gamma, -1 short gamma, 0 neutral, NaN with no reading | | `bsGamma` | `bsGamma(s, strike, iv, years): f64` | Black-Scholes gamma with no rate, per 1 of the underlying; the rule the chart prices the chain's gammas by | | `straddleExpectedMove`, `oneSigmaMove` | `straddleExpectedMove(price, iv, years): f64`, `oneSigmaMove(price, iv, years): f64` | The expected move (0.85 of the at-the-money straddle) and the one-standard-deviation range, in price ([The expected move](#the-expected-move)) | | `GAMMA_FLIP_REACH`, `GAMMA_FLIP_STEP` | `const ...: f64` = 0.5, 0.0025 | The flip search's reach either side of spot and its step, fractions of spot | | `normCdf`, `normPdf` | `normCdf(x: f64): f64`, `normPdf(x: f64): f64` | The standard normal distribution and density | | `expectedMove`, `straddleMove` | `expectedMove(spot, iv, days): f64`, `straddleMove(spot, iv, days): f64` | The one-standard-deviation move under a deprecated name (read `oneSigmaMove`), and the straddle rule on calendar days ([The expected move](#the-expected-move)) | | `optionsTradeDay` | `optionsTradeDay(ms: f64, zone: i32): f64` | An instant's or an expiry stamp's trade date on the market's own clock, days since 1970-01-01 | | `optionsAsOfMs` | `optionsAsOfMs(barOpenMs: f64, intervalMs: f64): f64` | The as-of a bar's options data is read at: the bar's close time, `barOpenMs + intervalMs` (`bar.time() * 1000` and `chart.interval_sec() * 1000`), the bar's open where the host writes no interval; the chain and the strike rows of one bar read one clock ([The market's own date and the chain's clock](#the-markets-own-date-and-the-chains-clock)) | | `optionsLiveUntilMs` | `optionsLiveUntilMs(expiryMs: f64, zone: i32, kind: i32 = 0): f64` | The instant an expiry stops trading, its chain's last trade: 15 minutes past the stamp on a US stock or ETF chain (zone 1, OPRA: a PM expiry stamped 16:00 trades to 16:15), the stamp itself on a US index chain (`kind` 5, `market.kind()`), on Chicago and on UTC; a kind left out reads a stock; an expiry is live while it is after the as-of | | `optionsYearsToGo` | `optionsYearsToGo(expiryMs: f64, asOfMs: f64, zone: i32, kind: i32 = 0): f64` | The time a contract is priced at, in 365-day years: on a US stock or ETF chain every contract to `optionsLiveUntilMs`, never under a second while it trades; on a US index chain, Chicago and UTC to the stamp; 0 or less once it has stopped trading | | `chainPricedAtMs`, `pricedAtFromGamma` | `chainPricedAtMs(cells, count, barOpenMs): f64`, `pricedAtFromGamma(...)` | Deprecated as the chain's clock: a time solved back from one contract's gamma, kept with its numbers for the packages that call it. Read the chain at `optionsAsOfMs` | | `totalVarianceIv` | `totalVarianceIv(years1, iv1, years2, iv2, years): f64` | The IV `years` out between two expiries, interpolated in total variance: the constant maturity `IvTerm.iv(days)` reads between its two anchors ([The at-the-money term](#the-at-the-money-term)) | | `OPTIONS_YEAR_MS` | `const OPTIONS_YEAR_MS: f64 = 31536000000.0` | The 365-day year the chain's IV and greeks are quoted on | | `OPTION_PRINTS_TUPLE`, `OPTION_CONTRACT_FLOW_TUPLE`, `OPTION_CONTRACT_STATE_TUPLE`, `OPTION_SURFACE_TUPLE`, `OPTION_PRINTS_V2_TUPLE` | `const ...: i32` = 16, 17, 13, 9, 19 | f64 values per tuple in the `option_prints`, `option_contract_flow`, `option_contract_state`, `option_surface` and `option_prints_v2` blocks, on crypto, CME and US stock charts ([US listed options](../core-concepts/data-sources.md#us-listed-options-opra), [Option surface](../core-concepts/data-sources.md#option-surface), [Block and RFQ prints](../core-concepts/data-sources.md#option_prints_v2)), each ending with its `present` mask | | `OPTION_VIEW_ROW_CHAIN`, `OPTION_VIEW_ROW_STATE`, `VIEW_*` | `const ...: i32` = 11, 16; the row layouts `VIEW_CLASS_TUPLE` 0 to `VIEW_GEX_SUMS` 9 | f64 values per row of a view block on `options_chain` and on `option_contract_state`, and the layout column 0 of each row names ([Chain page views](#chain-page-views)) | | `viewTuples` | `viewTuples(cells, count, rowWidth, tuple, out): i32` | Copies a view block's class tuples out as a class block, so code that read the whole block reads a projection unchanged | | `ExposureTable`, `GexCurve`, `ChainTotals`, `OiBoard` | `new ExposureTable(maxStrikes, maxExpiries = 64)`, `new GexCurve(maxPoints)`, `new ChainTotals()`, `new OiBoard(maxContributions, maxStrikes = 4096)`; each `.load(cells, count, rowWidth)` | The fold views' readers: exposure by strike, day bucket and expiry; net GEX over a grid of spots; the chain summary's counts and sums; the open interest board's contributions and the change by strike ([Chain page views](#chain-page-views)) | | `BookStamp`, `OptionNumbers`, `VolTerm`, `SmileRows`, `SurfaceMatrix`, `StrikeProfile` | `new BookStamp()`, `new OptionNumbers(maxExpiries = 64)`, `new VolTerm(maxExpiries = 64)`, `new SmileRows(maxPoints)`, `new SurfaceMatrix(maxColumns = 16, maxRows = 64)`, `new StrikeProfile(maxStrikes, maxPoints = 1000)`; each `.load(cells, count, rowWidth)` | The book folds' readers: the stamp, the options numbers, the term structure, the smile, the surface matrix and the strike profile; `ExpectedMoves.loadNumbers(cells, count, rowWidth)` reads the numbers' expiry rows into `ExpectedMoves` ([Book folds](#book-folds)) | | `DayHistory` | `new DayHistory(capacity)`; `.push(day, value): bool`; `.count()`, `.capacity()`, `.span(window)`; `.value(ago)`, `.day(ago)`, `.agoOf(day)`; `.min(window)`, `.max(window)`, `.mean(window)`, `.stdev(window)`, `.rank(window)`, `.percentile(window)`, `.zscore(window)`, `.quantile(window, q)`; `.reset()` | One reading per trade day of a daily statistic, the newest last, and the readings of a window over it: the IV rank, the IV percentile, the z-score, the quantiles ([A history of daily statistics](#a-history-of-daily-statistics)) | | `NodeBoard`, `roleWord`, `NODE_ROLE_*` | `new NodeBoard(maxStrikes)`; `.load(strikes, values, count, spot, pct = 15.0): i32`; `.strikes()`, `.strike(i)`, `.value(i)`; `.top()`, `.gate()`, `.floor()`, `.ceiling()`; `.role(i)`, `.standout(i)`, `.isSignificant(i)`, `.pctOfTop(i)`; `.standoutCount()`, `.aboveNet()`, `.belowNet()`; `roleWord(code): string`; the role codes `NODE_ROLE_NORMAL` 0 to `NODE_ROLE_TOP` 7 | One signed reading per strike sorted into the nodes a strike board labels: the top, the gate, the floor, the ceiling, the standouts and the significant strikes ([Node roles](#node-roles)) | | `expiryPresetCount`, `thirdFridayMs`, `EXPIRY_PRESET_*` | `expiryPresetCount(expiries, count, nowMs, zone, preset, n): i32`; `thirdFridayMs(year, month, zone): f64`; the presets `EXPIRY_PRESET_FRONT` 0 to `EXPIRY_PRESET_COUNT` 7 | How many of the sorted live expiries a preset keeps, on the market's trade days ([Expiry presets](#expiry-presets)) | | `StrikeVelocity`, `VELOCITY_WINDOWS` | `new StrikeVelocity(maxKeys, maxBars)`; `.push(barMs, key, value): bool`; `.velocity(key, windowMin)`, `.velocityPct(key, windowMin)`; `.available(windowMin, hostIntervalMs): bool`; `.halo(key, w1, w2, w3): bool`; `.reset()`; `VELOCITY_WINDOWS` 1, 5, 10, 15, 60, 240, 1440 | How each strike's reading moved over a window of minutes ([Strike velocity](#strike-velocity)) | | `flowSideCode`, `flowScore` | `flowSideCode(aggressor, outside): i32`; `flowScore(side, cp, moneyness, dteDays, sizeVsOi, repeatHits): f64` | The side of the quote a print hit and the print's signed score, -100 to 100 ([Flow score](#flow-score)) | | `DERIVED_ROOTS`, `derivedRootCount`, `derivedRoot`, `derivedRatio` | `derivedRootCount(root): i32`, `derivedRoot(root, i): string`, `derivedRatio(close, rowUnderlying): f64` | The roots a chart's levels can be read through, and the ratio a derived level is drawn at ([Derived roots](#derived-roots)) | ![The strike table on a price axis: call exposure drawn to the right of each strike and put exposure to the left, the call wall above spot and the put wall below it, the running net sum climbing from the lowest strike and crossing the axis at the zero-gamma point, and max pain circled among the strikes](/wrun/images/diagrams/options-strike-table.svg) 1. **Strikes** on the price axis, ascending from the bottom: `strike(i)`, with `i` `0` the lowest. 2. **Call GEX** to the right of each strike and **put GEX** to the left: `callGex(i)` and `putGex(i)`, both stored positive. 3. **The running net sum**, calls minus puts from the lowest strike up: `zeroGamma()` is where it first crosses zero, placed between two strikes by the two sums' magnitudes. That is the older rule, kept for the packages that read it; the gamma flip a card prints is `GammaCurve.flip()` ([The canonical numbers](#the-canonical-numbers)). 4. **Call wall**, the strike at or above spot holding the most call open interest; **put wall**, the strike at or below spot holding the most put open interest. 5. **Max pain**, the listed strike that pays holders the least, circled among the strikes. Per contract, with `spot_c` the contract's `underlying` when above 0 and otherwise the `spot` you passed, and `mult` its `multiplier` when above 0 and otherwise 1: - `callGex(i)` and `putGex(i)` sum `gamma * oi * mult * spot_c * spot_c * 0.01` over the calls and the puts at the `i`-th strike: the dollar change of the open interest's delta for a 1% move of spot, in USD per 1% move. Both are stored positive (a listed option's gamma is positive). - `netGex(i)` is `callGex(i) - putGex(i)`: the dealer-naive sign convention, calls positive and puts negative, taking dealers as long the calls customers sold them and short the puts customers bought. `totalCallGex()`, `totalPutGex()` and `totalNetGex()` sum the table from the lowest strike up. `totalNetGex()` keeps that number for the packages that read it; it sums the chain's served gammas, so on a venue that serves its own greeks, or inside 15 minutes of an expiry, it can differ from the net GEX a card prints, `GammaCurve.netGex()`, which prices every gamma again at the chain's as-of. - `callOi(i)` and `putOi(i)` are the open interest summed per side at the strike, in the chain's own unit (coins on Deribit, contracts on CME). `putCallRatio()` is total put over total call open interest, `NaN` when the call side holds none. - `callWall()` is the strike at or above `spot` holding the most call open interest, `putWall()` the strike at or below `spot` holding the most put open interest; `NaN` when no strike on that side has any. Ties keep the lower strike. - `maxPain()` is the listed strike `S` minimising `sum(callOi * max(0, S - K)) + sum(putOi * max(0, K - S))` over the table's strikes `K`, the settlement price that pays holders the least; ties keep the lower strike, `NaN` on an empty table. - `zeroGamma()` walks the strikes upward summing `netGex`: the strike where the running sum lands on exactly 0, or the point between the two strikes where it changes sign, placed by the two sums' magnitudes (`prev + (next - prev) * |cum_prev| / (|cum_prev| + |cum_next|)`); `NaN` when the sum never changes sign. It keeps that number for the packages that read it, under a deprecated name: it is not the gamma flip. Print `GammaCurve.flip()` as the flip. - `strikes()` is the table size, `strike(i)` the `i`-th strike ascending (`0` the lowest); every indexed reader is `NaN` outside `0..strikes() - 1`. Before the first `load()` the table is empty: the totals read `0`, everything else `NaN`. ## Reading the chain on the live bar History bars carry an empty block and the chain arrives on the newest row, so the read sits under `bar.isLast()`: `in_chain_cells()` is the f64 count the bar carries (`-1` on a bar without a block), `in_chain_view()` is the block itself, read in place from the one buffer the build reserves at module start, and `load()` takes that array, the count, the chain's as-of in milliseconds (`optionsAsOfMs` over the bar's open and `chart.interval_sec()`: the live bar's close) and the chart's close as spot; `GammaCurve` also takes the market's zone (`market.zone()`) and kind (`market.kind()`, a stock when left out), on which a US stock or ETF expiry stays live until 15 minutes past its stamp and a US index expiry until its stamp. The numbers hold on the following bars, so an output or a card written in `onBar()` reads the same chain until the next live bar refreshes it. Net GEX and the flip come from a `GammaCurve` over the same expiries; the strike table gives the walls and max pain. ```typescript param("nearest_expiries", 0, { min: 0, max: 24, description: "Expiries counted: 0 = every listed expiry, N = the N nearest" }); param("window_pct", 0, { min: 0, max: 50, description: "Strikes the walls read: percent around spot each side, 0 = the whole chain" }); input("close", ohlcv.close); // the chart's own close: spot input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" }); market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp chart.interval_sec(); // the bar's length: the chain is read at the live bar's close output("net_gex", none, overlay, { description: "Net gamma exposure at spot over the counted expiries, USD per 1% move; live bar only" }); output("flip", none, overlay, { description: "The gamma flip over the counted expiries: the GEX curve's zero nearest spot" }); output("call_wall", none, overlay, { description: "The heaviest call strike at or above spot" }); output("put_wall", none, overlay, { description: "The heaviest put strike at or below spot" }); output("max_pain", none, overlay, { description: "The strike that pays option holders the least" }); let chain = new OptionsChain(1); let curve = new GammaCurve(1); let nearest: i32 = 0; let windowPct: f64 = 0.0; let zone: i32 = 0; let intervalMs: f64 = 0.0; function onStart(): void { // Construct here: the per-strike and per-contract buffers are the module's only allocation. chain = new OptionsChain(512); curve = new GammaCurve(in_chain_max_cells); nearest = i32(p_nearest_expiries()); windowPct = p_window_pct(); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; } function onBar(): void { if (bar.isLast()) { const n = in_chain_cells(); if (n >= OPTIONS_TUPLE) { const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer const asOfMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close chain.load(cells, n, asOfMs, bar.close(), nearest, windowPct); curve.load(cells, n, asOfMs, nearest, bar.close(), zone); } } out_net_gex(curve.netGex()); out_flip(curve.flip()); out_call_wall(chain.callWall()); out_put_wall(chain.putWall()); out_max_pain(chain.maxPain()); } ``` Read `last 1 net_gex` at the editor's Console prompt for the chain's net GEX, or loop `chain.strikes()` and draw `chain.netGex(i)` at `chain.strike(i)` into a frame for the docked profile the Greek exposure recipe shows. ## Expiries, the strike window and the table size ![The three load() filters as a funnel: every contract in the block enters at the top, about 1,550 on a BTC chain; the first cut drops the contracts whose expiry is not after now and keeps the N nearest expiries when asked; the second drops the strikes outside the window around spot; the third drops the strikes farthest from spot once the table holds maxStrikes; what comes out of the neck is the strike table, sorted ascending](/wrun/images/diagrams/options-load-funnel.svg) 1. **Every contract** in the block enters at the top, about 1,550 on a BTC chain. 2. **Expiry**: a contract whose `expiry_ms` is not after `nowMs` drops out; `nearest > 0` keeps only the N soonest expiries. 3. **Strike window**: `windowPct > 0` drops the strikes outside the window around `spot`. 4. **Table size**: once `maxStrikes` strikes are in, the strikes farthest from `spot` drop first. 5. **The strike table** comes out of the neck, sorted ascending; `load()` returns its size. `load(cells, count, nowMs, spot, nearest, windowPct)` applies three filters before anything is summed: - **Expiry.** Only contracts with `expiry_ms > nowMs` count; pass the chain's as-of, `optionsAsOfMs(bar.time() * 1000.0, chart.interval_sec() * 1000.0)`, the live bar's close: the chain is served inside the live bar, and a coarse bar's open lags it by up to the bar, so an expiry settled since would still count (on a daily bar the close runs ahead by as much, so read a same-day expiry on an intraday chart). `OptionsChain` keeps each expiry to its stamp; `GammaCurve` and `ExpectedMoves` take the market's zone and kind and keep a US stock or ETF expiry 15 minutes past it. `nearest > 0` keeps the `nearest` soonest of those expiries, so `nearest = 1` is the front expiry alone and `nearest = 2` the front two; asking for more expiries than the chain lists keeps them all, and `0` keeps every live expiry. There is no cap on distinct expiries. Whether an expiry is today is a calendar question, never the hours left: at 11:00 tomorrow's 10:00 expiry is 23 hours away and still 1 DTE. Compare the expiry's trade date with today's on the market's own clock: `sessionTradeDate()` with `market.zone()`, the calendar `time.trade_date` uses ([The market's own calendar](../core-concepts/time-and-sessions.md#the-markets-own-calendar)), as the [Strike matrix](../cookbook/strike-matrix.md) recipe does. - **Strike window.** `windowPct > 0` keeps the strikes within `windowPct` percent of `spot` on each side, bounds included (`spot * (1 - windowPct / 100)` to `spot * (1 + windowPct / 100)`); `0` keeps every strike. The window narrows the whole table: the walls, the totals, `zeroGamma()` and max pain are all measured over the strikes inside it. The Strike Matrix template narrows only its walls: its max pain is the reading of a chain loaded with `windowPct` `0`, its walls those of a chain loaded with its window, and its flip comes from a `GammaCurve` over every live expiry; an indicator that wants both tables constructs two `OptionsChain` objects in `onStart()` and loads each. - **Table size.** `maxStrikes` (clamped to at least 1) is the most distinct strikes the table holds; the Strike Matrix keeps 512. When a chain lists more, the strikes farthest from `spot` are dropped first, whatever order the contracts arrive in (two strikes at the same distance: the lower goes first), so the table is always the `maxStrikes` strikes nearest the chart. The template instead refuses the strikes that arrive after its table is full. A contract whose strike or open interest is not above 0 is skipped, so a strike only enters the table through live open interest; a contract whose expiry is not a number is skipped too. A gamma that is not a number poisons its strike's exposure and the totals, exactly as the template's sums do, and the walls, max pain and the open-interest ratio never read gamma, so they stay finite. ## A strike matrix on the price axis The per-strike readings are a table whose rows are prices, which is what `plot.matrix` draws: one row per strike docked on the price axis, one column per expiry, each cell filled from a diverging palette ([Price canvases](../presentation/price-canvases.md#strike-matrices)). Load one `OptionsChain` per expiry window on the live bar, write the board into a frame (prices ascending, one cell row per price, the ATM strike in `highlight`) and declare the matrix over it; the chart keeps the rows on their prices as you pan and zoom. The frame rides `wrun-4`, which a `frame(...)` declaration stamps for you. ```typescript input("close", ohlcv.close); input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" }); const board = frame("board", { max_bytes: 65536 }); plot.matrix({ name: "gex_board", frame: board, dock: "right", columns: ["Front", "Next", "Third"], price_column: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, format: "si", tooltip: "{{column}} net GEX {{value:usd}} at {{price}}" }); ``` The [Strike Matrix](../cookbook/strike-matrix.md) recipe is the whole file: net gamma exposure by strike across the four nearest expiries (a setting), the ATM row highlighted, rewritten on every live bar. ## Option strikes, bar by bar The `./sdk/option-strikes` module reads the `option_strikes` source ([Data sources](../core-concepts/data-sources.md#option-strikes)): every bar's own strike snapshot, twelve values per (expiry, strike) row, its exposures already in dollars and its open interest in the chain's own size (the coin on a crypto chain, contracts on US listed options and CME). `OptionStrikes` folds one block into a strike table sorted ascending and answers the questions `OptionsChain` answers, on every bar instead of the live one. | Export | Signature | Definition | | --- | --- | --- | | `OPTION_STRIKES_TUPLE` | `const OPTION_STRIKES_TUPLE: i32 = 12` | f64 values per row in an `option_strikes` block: `[strike, expiry_ms, net_gex, call_gex, put_gex, net_dex, net_vex, call_oi, put_oi, call_iv, put_iv, underlying]` | | `strikesPricedAtMs` | `strikesPricedAtMs(cells, count, multiplier, barOpenMs, intervalMs = 0): f64` | Deprecated as the rows' clock: a time solved back from the rows' gamma, kept with its numbers for the packages that call it and for the kit fold's curve row (`pricedAtMs()`). Read the rows at `optionsAsOfMs` | | `OPTION_STRIKES_KIT_ROW`, `KIT_STRIKE_ROW`, `KIT_LEVELS_ROW`, `KIT_CURVE_ROW` | `const ...: i32` = 14, 0, 1, 2 | f64 values per row of a strike kit fold (`fold: "kit"`), and its row layouts | | `OptionStrikes` | `new OptionStrikes(maxStrikes)`; `.load(cells, count, nearest = 0): i32`; `.loadLevels(cells, count): i32`; `.value(i)`; `.strikeCount()`, `.strike(i)`, `.netGex(i)`, `.callGex(i)`, `.putGex(i)`, `.netDex(i)`, `.netVex(i)`, `.callOi(i)`, `.putOi(i)`, `.callIv(i)`, `.putIv(i)`, `.iv(i)`; `.totalNetGex()`, `.totalCallGex()`, `.totalPutGex()`, `.totalNetDex()`, `.totalNetVex()`, `.totalCallOi()`, `.totalPutOi()`, `.putCallRatio()`; `.zeroGamma()`, `.callWall()`, `.putWall()`, `.maxPain()`, `.underlying()`; `.gexAtSpot()`, `.gammaRegime()`, `.gammaFlip()`, `.curveSpot()`, `.pricedAtMs()`; `.refused()`, `.refusedReason()` | One bar's snapshot by strike: `load()` keeps the rows of the `nearest` soonest expiries when `nearest > 0`, folds the rows of one strike into one table row and returns the strike count kept, or `-1` when the kept rows hold more distinct strikes than `maxStrikes`; the five curve readers read a kit fold's curve row (`NaN` without one) | Where it differs from `OptionsChain`, each because the rows arrive measured: - `netGex(i)`, `callGex(i)`, `putGex(i)`, `netDex(i)`, `netVex(i)`, `callOi(i)` and `putOi(i)` sum the strike's rows across its expiries; a NaN field (a side the strike does not list) counts as 0. `callIv(i)` and `putIv(i)` weight each row's IV by that side's open interest, and `iv(i)` weights both sides together, across every expiry: never a sum of percentages, `NaN` where no row reports one. - `callWall()` and `putWall()` are the strikes holding the largest call and put dollar gamma (`callGex(i)`, `putGex(i)`), at any distance from spot; ties keep the lower strike, `NaN` when no strike has any. - `zeroGamma()` is a strike: the first one, walking up from the lowest, where the running sum of `netGex` reaches zero or turns to the other sign. It is never a point between two strikes, and `NaN` when the sum never turns. It keeps that number for the packages that read it, under a deprecated name: the gamma flip of the rows is `GammaCurve.loadStrikes(...)` and then `flip()`, below. - `maxPain()` is the chain's definition over the table's open interest, `NaN` when the table holds none; `underlying()` is the underlying price of the soonest kept expiry. - The table never truncates: a block with more distinct kept strikes than `maxStrikes` is refused whole. `load()` returns `-1`, every reading is empty and `refused()` is true until the next load. `nearest` filters before the table fills, and a table built with the input's `in_<name>_max_cells` never overflows. - Every bar loads its own block, so a bar with no snapshot (an empty block, `count` 0) empties the readings: the totals read `0`, everything else `NaN`. The front expiry's net gamma, flip and walls on every bar. A bar's rows are its newest minute of strike rows, and that fold minute closes when the bar does, so `GammaCurve.loadStrikes()` prices the curve at the bar's close, `optionsAsOfMs(bar.time() * 1000, chart.interval_sec() * 1000)`, the clock a card reading the chain reads on the same bar, on the market's zone and kind (`market.zone()`, `market.kind()`: a US stock or ETF expiry stays live and priced until 15 minutes past its stamp, a US index expiry until its stamp); each row is a call and a put with that side's open interest and IV, and `market.option_multiplier()` declares the multiplier the curve reads: ```typescript input("close", ohlcv.close); input("strikes", option_strikes.cells, { max_cells: 1200, expiries: "nearest:1" }); market.option_multiplier(); // 100 on a US stock, the point value on CME, 1 on a coin market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp chart.interval_sec(); // the bar's length: the rows are read at the bar's close, when their fold minute closes output("net_gex", line, lower, { description: "Net gamma exposure of the front expiry at spot, USD per 1% move" }); output("flip", line, overlay, { description: "The gamma flip of the front expiry: the GEX curve's zero nearest spot" }); output("call_wall", line, overlay, { description: "The strike holding the most call gamma" }); output("put_wall", line, overlay, { description: "The strike holding the most put gamma" }); let strikes = new OptionStrikes(1); let curve = new GammaCurve(1); function onStart(): void { strikes = new OptionStrikes(in_strikes_max_cells); curve = new GammaCurve(in_strikes_max_cells * 2); // a call and a put per row } function onBar(): void { const n = in_strikes_cells(); if (strikes.load(in_strikes_view(), n > 0 ? n : 0) <= 0) return; const multiplier = p_market_option_multiplier(); const asOfMs = optionsAsOfMs(bar.time() * 1000.0, p_chart_interval_sec() * 1000.0); // the rows' as-of: the bar's close curve.loadStrikes(in_strikes_view(), n, asOfMs, multiplier, 0, bar.close(), i32(p_market_zone())); out_net_gex(curve.netGex()); out_flip(curve.flip()); out_call_wall(strikes.callWall()); out_put_wall(strikes.putWall()); } ``` ## Chain page views An input that names a view of the chain page ([Data sources](../core-concepts/data-sources.md#chain-page-views)) reads less than the whole chain. A projection's contracts arrive as the class's own tuples, so every reader on this page reads them as it reads the whole block. A fold arrives as a **view block**: rows of `OPTION_VIEW_ROW_CHAIN` (11) f64 values on `options_chain` and `OPTION_VIEW_ROW_STATE` (16) on `option_contract_state`, column 0 the row's layout and the layout's fields after it. Size the input's `max_cells` for those rows. A projection the same input names rides the same block, one `VIEW_CLASS_TUPLE` row per contract. | Layout | Row | Reader | | --- | --- | --- | | `VIEW_CLASS_TUPLE` (0) | `[0, the class tuple...]` | `viewTuples(cells, count, rowWidth, tuple, out)` copies them out as a class block | | `VIEW_STRIKE_TABLE` (7) | `[7, strike, call_oi, put_oi, call_gex, put_gex]` | `OptionsChain.loadTable(cells, count, rowWidth, spot, windowPct)`: every reader answers as after `load()` on the chain the view folded | | `VIEW_EXPOSURE_STRIKE` (4), `VIEW_EXPOSURE_BUCKET` (5), `VIEW_EXPOSURE_EXPIRY` (6) | `[4, strike, calls, puts, readings]`, `[5, strike, six day buckets]`, `[6, expiry_ms, days, net, counted]` | `ExposureTable`: `.strike(i)`, `.calls(i)`, `.puts(i)`, `.net(i)`, `.readings(i)`, `.bucket(i, b)`, `.expiries()`, `.expiry(e)`, `.days(e)`, `.expiryNet(e)`, `.counted(e)` | | `VIEW_GEX_POINT` (8), `VIEW_GEX_SUMS` (9) | `[8, point, gex]`, `[9, vex, dealer_delta, contracts]` | `GexCurve`: `.points()`, `.gex(p)`, `.vex()`, `.dealerDelta()`, `.contracts()` | | `VIEW_TOTALS` (1) | `[1, contracts, expiries, partial, low_strike, high_strike, traded, traded_volume, call_volume, put_volume, day_volume, total_oi, missing, counted, call_change, put_change]` | `ChainTotals`: one reader a field | | `VIEW_OI_CELL` (2), `VIEW_STRIKE_CHANGE` (3) | `[2, strike, column, a, b]`, `[3, strike, change]` | `OiBoard`: `.strike(i)`, `.column(i)`, `.a(i)`, `.b(i)` per contribution in the chain's order; `.changeStrike(k)`, `.change(k)` per strike | Each reader follows the module's contract: construct it in `onStart()` with the most rows it holds, `load()` it on the live bar, read it in the same bar; nothing allocates after construction, and a block larger than the reader holds is refused whole (`load()` returns `-1`). The fold's sums are the template's to the bit: the data plane sums in the chain's order with the template's operations. ```typescript input("close", ohlcv.close); input("chain", options_chain.cells, { max_cells: 2000, page_views: ["strike_table"] }); output("net_gex", line, lower, { description: "Net gamma exposure, USD per 1% move" }); let chain = new OptionsChain(1); function onStart(): void { chain = new OptionsChain(512); } function onBar(): void { const n = in_chain_cells(); if (!bar.isLast() || n <= 0) return; if (chain.loadTable(in_chain_view(), n, OPTION_VIEW_ROW_CHAIN, bar.close()) > 0) out_net_gex(chain.totalNetGex()); } ``` An `option_strikes` input declaring `fold: "kit"` reads each bar already measured with `OptionStrikes`' rules: rows of `OPTION_STRIKES_KIT_ROW` (14) values, one `KIT_LEVELS_ROW` with the bar's totals, walls, flip, max pain and spot when `levels` is set, then the `KIT_STRIKE_ROW` rows `[0, strike, value]` at the strikes the input's window draws, `value` the fold's lens. `OptionStrikes.loadLevels(cells, count)` reads them: every snapshot-wide reading as `load()` gives it, `strike(i)` and `value(i)` per strike (the other per-strike readers read `NaN`), and `-1` with `refused()` true when the bar held more rows than the input's `max_cells`. With `curve: true` beside `levels` a `KIT_CURVE_ROW` `[2, gex_at_spot, gamma_flip, curve_spot, priced_at_ms, contracts]` follows each levels row. With the curve the fold reads each bar as the example under [Option strikes, bar by bar](#option-strikes-bar-by-bar) reads it: at the bar's as-of (`optionsAsOfMs`, the bar's close), over the week of its rows (each expiry still trading then on the market's zone and kind, 7 or fewer trade days out), the levels row and the strike rows included; a bar whose week keeps no strike arrives empty. The curve row is `GammaCurve.loadStrikes(...)` over that week with `nearest`'s live expiries, each live and priced to its chain's last trade (15 minutes past the stamp on a US stock or ETF chain, the stamp on a US index chain, the CME Group and crypto). `gexAtSpot()`, `gammaRegime()` and `gammaFlip()` read the numbers `netGex()`, `regime()` and `flip()` give there, `curveSpot()` its S0 and `pricedAtMs()` the as-of, each `NaN` without a curve row. One difference stays: where the nearest live expiry reports no underlying, the curve reads `NaN`, not the chart's close (a stored row always carries one). ## Book folds An `options_chain` input that names a book fold (`numbers`, `vol_term`, `smile`, `surface`, `strike_profile`; [Data sources](../core-concepts/data-sources.md#chain-page-views)) reads the data plane's finished numbers over the chain page's whole book: the numbers the chart's own options panes draw. Its rows are as wide as its widest word (`OPTION_VIEW_ROW_NUMBERS` 12, `OPTION_VIEW_ROW_VOL_TERM` 16, `OPTION_VIEW_ROW_SMILE` 11, `OPTION_VIEW_ROW_SURFACE` 11, `OPTION_VIEW_ROW_STRIKE_PROFILE` 13): pass that width to every reader of the block, and size `max_cells` for the rows. Each reader reads its own layouts and skips the rest, so one block naming several words feeds every reader. A missing reading is NaN. | Layout | Row | Reader | | --- | --- | --- | | `VIEW_BOOK_STAMP` (12) | `[12, priced_at_ms, s0, family, oi_unit, greeks, contracts, expiries, dropped, book_kind, version]`, once a block | `BookStamp`: `.pricedAtMs()`, `.spot()` (`NaN` when no contract's expiry has an anchor, which a book holding contracts can answer beside its rows), `.family()` (1 US, 2 CME Group, 3 crypto), `.oiUnit()` (0 coin, 1 contracts), `.greeks()` (0 the venue's, 1 a model's), `.contracts()`, `.empty()` (a book with no contract: the stamp alone, no fold row, the pane clears; a `NaN` spot alone is not empty) | | `VIEW_NUMBERS` (10) | `[10, kind, ...]`: `NUMBERS_SCOPE` rows (scope, S0, net GEX, regime, flip, roots, four more roots), `NUMBERS_EXPIRY` rows (expiry, forward, ATM strike, ATM IV, years, expected move, one sigma, hours, both moves in percent), `NUMBERS_HORIZON` rows (years, ATM IV, both moves as fractions of 1) | `OptionNumbers`: `.scopeIndex(scope)`, `.netGex(i)`, `.regime(i)`, `.flip(i)`, `.expiryMs(e)`, `.atmIv(e)`, `.expectedMove(e)`, `.horizonIv(h)`; `ExpectedMoves.loadNumbers` answers `ExpectedMoves`' readers with the data plane's moves | | `VIEW_VOL_TERM` (13) | `[13, expiry_ms, days, forward, atm_iv, str25, str15, rr25, rr15, rr10, fly25, fly15, oi, call_oi, put_oi, flags]` | `VolTerm`: one reader a field, `.wingOutside(i)`, `.oneSidedAtm(i)`, `.noQuote(i)` | | `VIEW_SMILE_SERIES` (14), `VIEW_SMILE_POINT` (15) | `[14, series, expiry_ms, forward]`, `[15, strike, iv0, iv1, iv2]` | `SmileRows`: `.seriesPicked(s)`, `.seriesExpiryMs(s)`, `.points()`, `.strike(i)`, `.iv(i, s)` | | `VIEW_SURFACE_CELL` (16) | `[16, tag, at, value]`: tag -1 a column, -2 a row, -3 a column's summary, -4 the highlight, else a cell's row | `SurfaceMatrix`: `.columns()`, `.rows()`, `.columnExpiryMs(c)`, `.rowStrike(r)`, `.highlightRow()`, `.summary(c)`, `.value(r, c)` | | `VIEW_PROFILE_STRIKE` (17), `VIEW_PROFILE_LEVELS` (18), `VIEW_PROFILE_POINT` (19) | `[17, strike, call_oi, put_oi, call_gex, put_gex, net_gex, cum_net_gex, dex, vex]`, `[18, max_pain, call_wall, put_wall, call_oi, put_oi, oi_total, pc_oi, net_gex, net_dex, net_vex, strikes, clipped_right]`, `[19, x, gex]` | `StrikeProfile`: the strike rows, `.maxPain()`, `.callWall()`, `.putWall()`, `.putCallRatio()`, `.totalNetGex()`, `.points()`, `.pointX(p)`, `.pointGex(p)` | `SurfaceMatrix.highlightRow()` is the row nearest the book's spot S0, the median underlying of its nearest live expiry: the row the chart's built-in Options Surface bolds. That spot can sit off the chart's price (after hours, between chain snapshots), so a bold row that says where the price is reads the chart's close instead, where the close is in the strikes' units: the row whose `rowStrike(r)` is nearest `bar.close()` on a chart priced in the strikes' currency (`market.quote_is_usd()` on the US dollar chains) that is no option contract's own (`market.option_contract()`), with the close within half to twice `BookStamp.spot()`; otherwise `highlightRow()` ([Volatility surface](../cookbook/iv-surface.md) does this). ## Max pain's curve, one expiry at a time `loadExpiry(cells, count, nowMs, spot, expiryMs, windowPct)` is `load()` over the contracts of ONE expiry, the one whose `expiry_ms` is exactly `expiryMs`: every reader then answers for that expiry alone, its walls, its `zeroGamma()` and its max pain (that expiry's gamma flip is `GammaCurve.load(...)` with `nearest` set to the expiry's rank). Under max pain sits a curve, one point per listed strike `S`: - `callPain(i)` is `sum(callOi(k) * max(0, S - strike(k)))`: what the call holders collect if the expiry settles at the `i`-th strike; - `putPain(i)` is `sum(putOi(k) * max(0, strike(k) - S))`, the put holders' share; - `maxPain()` is the strike where the two summed are least. The unit is open interest times price, no multiplier (47 contracts 10 below the settle read 470); times the multiplier it is money. Loop `chain.strikes()` and draw the two values at `chain.strike(i)` for the curve under one expiry's max pain, or load each listed expiry in turn (`IvTerm`'s `expiry(i)` lists them) for max pain by expiry. ## Pricing the chain The chain carries each contract's mark IV, its gamma, its delta and its vega; everything else is priced from the IV. `mark_iv` rides the tuple in percentage points, so the IV every function below takes is `mark_iv / 100`, a decimal (`0.152` for 15.2%), and time to expiry is in 365-day years, `(expiry_ms - nowMs) / OPTIONS_YEAR_MS`, the year the IV is quoted on. ### Greeks: one contract priced `new Greeks()` once in `onStart()`; then per contract `greeks.spot(side, s, strike, years, iv, rate)` (Black-Scholes on the spot `s`, no dividend) or `greeks.forward(side, f, strike, years, iv, rate)` (Black-76 on the forward `f`), each returning the price and filling the fields. `side` above 0 is a call, else a put, as the tuple's `side`; `rate` is a decimal, `0.04` when left out. Pick the model by what the underlying is: a US stock chain's underlying is the stock's spot (Black-Scholes, with the rate), a futures chain's is the futures price and a crypto chain's the venue's own forward (Black-76; crypto chains are quoted at a rate of 0). | Field | Meaning | Unit | | --- | --- | --- | | `price` | the option's value | price | | `delta` | the price change for 1 of the underlying: a call 0 to 1, a put -1 to 0 (Black-76 discounts it by `e^(-rate * years)`) | per 1 of the underlying | | `gamma` | the delta change for 1 of the underlying | per 1 of the underlying | | `vega` | the price change for one vol point (the IV up 0.01) | per vol point | | `theta` | the price change as one calendar day passes; negative for a long option | per calendar day | | `vanna` | the delta change for one vol point | per vol point | | `charm` | the delta change as one calendar day passes, spot held: the delta a hedge sheds or gains overnight | per calendar day | | `d1`, `d2` | the two Black-Scholes terms | none | At or past expiry (`years` not above 0) the price is the intrinsic value, the delta 1 (or -1 for a put) in the money, 0 out of it and a half at the strike, and every other greek 0. A strike or an underlying that is not above 0, an IV that is not above 0 before expiry, or any input that is not a number reads NaN in every field. Nothing allocates: price as many contracts per bar as the chain holds. Exposure is a greek times open interest times the multiplier, signed by who holds it. With dealers long the calls and short the puts (the gamma map's convention), a strike's vanna exposure is the calls' `vanna * oi * multiplier` minus the puts': the shares the dealers' hedge must sell when the IV rises one point (buy, when the sum is negative). ### The at-the-money term `IvTerm` measures the chain's implied volatility the way volatility pages do. Per live expiry, the at-the-money IV is the mean of the call and the put IV at the strike nearest the expiry's forward (one side where the other has no IV), among the strikes within 20% of the expiry's underlying; the forward is the underlying times `e^(rate * years)`, so pass the rate on a US stock's chain and 0 where the underlying already is the forward. Between two expiries the IV is interpolated in total variance, IV squared times years, to a constant maturity: ```text w(T) = w1 + (w2 - w1) * (T - T1) / (T2 - T1), w = atm_iv^2 * years iv(days) = sqrt(w(days / 365) / (days / 365)) ``` An expiry that settles today is listed (`days(i)` reads 0) but never anchors the interpolation: its IV swings with the hours left. Before the first anchor `iv(days)` reads the first anchor's IV, past the last the last one's; with no anchor it reads NaN. The step between two anchors is `totalVarianceIv(years1, iv1, years2, iv2, years)`, exported on its own: an Indicator that builds its own curve over the expiries (the [Options sentiment](../cookbook/options-sentiment.md) recipe reads each expiry's at-the-money IV and wings from the surface) reads its constant maturities through the same arithmetic. It reads NaN when the variance it reaches or `years` is not above 0. - `load(cells, count, nowMs, spot, zone, rate)` keeps the contracts with a strike above 0 expiring after `nowMs`, the `maxExpiries` nearest expiries, and returns how many it kept, ascending. `zone` is the `market.zone()` code, the calendar `days(i)` counts on. - `expiry(i)`, `years(i)`, `days(i)` (its trade date minus today's, 0 on the expiry day), `underlying(i)`, `forward(i)`, `atmStrike(i)`, `callIv(i)`, `putIv(i)` and `atmIv(i)` read the `i`-th expiry, NaN outside `0..expiries() - 1`. - `iv(days)` is the constant-maturity IV `days` calendar days out. - `front()` is the first expiry after today, `nearest(days)` the anchor whose time to expiry is nearest `days` (the expiry a "30-day" skew reads), `indexOf(expiryMs)` an expiry's row; each -1 when there is none. - `deltaStrike(i, side, delta)` is the strike of the `i`-th expiry where the absolute delta equals `delta` (0.25 for the 25 delta wing) on the calls (`side` above 0) or the puts, the delta read off each contract's IV at the expiry's forward without discounting (the convention skew is quoted in), interpolated between the two listed strikes around it; `deltaIv(i, side, delta)` is the IV there. A risk reversal is `deltaIv(i, 1.0, 0.25) - deltaIv(i, -1.0, 0.25)`. - `impliedMove(i)` is `straddleMove(underlying(i), atmIv(i), years(i) * 365)`, in price. It keeps that number for the packages that read it, but it prices the straddle on the expiry's underlying and this term's own at-the-money pick, so it is not the expected move a card prints: read `ExpectedMoves.expectedMove(i)`, priced on the expiry's forward (its median underlying) at the mean of the IVs listed at the strike nearest it ([The canonical numbers](#the-canonical-numbers)). `load` keeps a reference to the block, never a copy: read `deltaStrike` and `deltaIv` on the bar that loaded it. ### The expected move The expected move is 0.85 times the at-the-money straddle, priced at the forward with no rate: the number flow desks quote and the one every OpenMarket surface prints as "Expected move". `straddleExpectedMove(price, iv, years)` is `0.85 * 2 * price * (2 * N(iv * sqrt(years) / 2) - 1)`, with `price` the expiry's forward or a horizon's anchor. The one-standard-deviation range is another number, `oneSigmaMove(price, iv, years)` = `price * iv * sqrt(years)`, about 1.47 times the expected move for any short expiry; a card names it "1σ range (68%)", never "Expected move". Both are in price; divide by the price for a percent. [`ExpectedMoves`](#the-canonical-numbers) reads both per expiry and at any horizon. The older names keep their numbers: `straddleMove(spot, iv, days)` is the straddle rule on calendar days (30 days at a 14.9% IV reads 2.9% of spot, 3 days at 11% reads 0.68%), and `expectedMove(spot, iv, days)` is the one-standard-deviation move, `iv * spot * sqrt(days / 365)`, under a name that says otherwise (deprecated: read `oneSigmaMove`). ### The market's own date and the chain's clock `optionsTradeDay(ms, zone)` is the trade date of an instant or an expiry stamp on the market's own clock, in days since 1970-01-01: New York's date on a US stock (zone 1), Chicago's on CME, whose trade day opens at 17:00 (zone 2), UTC on crypto (zone 0). A stamp at exactly 00:00 UTC is a date a venue stamped and reads as that date. Whether an expiry is today is a calendar question: `optionsTradeDay(expiry, zone) == optionsTradeDay(now, zone)`, never the hours left. `optionsAsOfMs(barOpenMs, intervalMs)` is the as-of a bar's options data is read at: the bar's close time, `bar.time() * 1000` plus `chart.interval_sec() * 1000`, the bar's open where the host writes no interval. The chain names the moment it was served to no module, and a bar's strike rows are its newest minute, which closes when the bar does, so a card reading the chain and a card reading the strike rows read one clock on one bar, never a time solved back from a gamma (two solves of one minute name two times, and a same-day gamma scales with 1 / sqrt(T)). Pass it as `nowMs` (or `asOfMs`) wherever the hours to expiry matter. `optionsLiveUntilMs(expiryMs, zone, kind)` is the instant an expiry stops trading, its chain's last trade, on the market's clock and kind: on a US stock or ETF chain (zone 1, OPRA) 15 minutes past the stamp, since a PM expiry is stamped 16:00 and its options trade to 16:15; on a US index chain (`kind` 5: SPX, NDX, XSP, VIX, RUT) the stamp itself, since index options stop at the close; on Chicago and UTC the stamp itself. A kind left out reads a stock, so pass `i32(p_market_kind())` (declare `market.kind();`) beside the zone wherever the chain can be an index's. An expiry is live while it is after the as-of. `optionsYearsToGo(expiryMs, asOfMs, zone, kind)` is the time a contract is priced at, in 365-day years: on a stock or ETF chain every contract to that instant, before the stamp as after it (no jump at 16:00), and never under a second while it trades, so the same-day book keeps its gamma until 16:15; on an index chain, Chicago and UTC to the stamp. `GammaCurve` and `ExpectedMoves` read both on the zone and kind their loads are handed; `IvTerm` and `OptionsChain` keep each expiry to its stamp. The data plane and the chart read the same rule. ```typescript // The term and the greeks on the live bar: 30-day at-the-money IV, the 25 delta risk reversal near 30 days, the front expiry's expected move and the dealers' vanna. input("close", ohlcv.close); input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" }); market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME) chart.interval_sec(); // the bar's length: the chain is read at the live bar's close output("iv30", none, overlay, { description: "30-day constant-maturity at-the-money IV, percent" }); output("rr25", none, overlay, { description: "25 delta risk reversal near 30 days: call IV minus put IV, vol points" }); output("front_move", none, overlay, { description: "The front expiry's expected move, percent of its forward" }); output("net_vanna", none, overlay, { description: "Dealers' delta change per vol point, long the calls and short the puts" }); let term = new IvTerm(1); let moves = new ExpectedMoves(1); let greeks = new Greeks(); let zone = 0; let intervalMs = 0.0; function onStart(): void { // Construct here: the per-expiry buffers are the only allocation. term = new IvTerm(64); moves = new ExpectedMoves(in_chain_max_cells); greeks = new Greeks(); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; } function onBar(): void { if (!bar.isLast()) return; const n = in_chain_cells(); if (n < OPTIONS_TUPLE) return; const cells = in_chain_view(); const spot = bar.close(); const nowMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close const rate = zone == 1 ? 0.04 : 0.0; // a stock's spot carries the rate to each forward; a futures or crypto underlying already is one term.load(cells, n, nowMs, spot, zone, rate); moves.load(cells, n, nowMs, spot, zone); // an OPRA expiry priced to 15 minutes past its stamp out_iv30(moves.horizonIv(30.0 / 365.0) * 100.0); const e = term.nearest(30.0); out_rr25((term.deltaIv(e, 1.0, 0.25) - term.deltaIv(e, -1.0, 0.25)) * 100.0); const today = optionsTradeDay(nowMs, zone); let front = -1; // the first expiry after today on the market's calendar for (let i = 0; i < moves.expiries() && front < 0; i += 1) if (optionsTradeDay(moves.expiry(i), zone) > today) front = i; out_front_move((moves.expectedMove(front) / moves.forward(front)) * 100.0); let vanna = 0.0; for (let i = 0; i + OPTIONS_TUPLE - 1 < n; i += OPTIONS_TUPLE) { if (!(cells[i + 3] > 0.0) || !(cells[i + 6] > 0.0)) continue; const years = optionsYearsToGo(cells[i + 1], nowMs, zone); // to the expiry's end: 0 or less once it stopped trading const under = cells[i + 7] > 0.0 ? cells[i + 7] : spot; if (zone == 1) greeks.spot(cells[i + 2], under, cells[i], years, cells[i + 6] / 100.0, rate); else greeks.forward(cells[i + 2], under, cells[i], years, cells[i + 6] / 100.0, rate); const multiplier = cells[i + 8] > 0.0 ? cells[i + 8] : 1.0; vanna += (cells[i + 2] > 0.0 ? 1.0 : -1.0) * greeks.vanna * cells[i + 3] * multiplier; } out_net_vanna(vanna); } ``` ## The canonical numbers Net GEX, the dealer regime, the gamma flip and the expected move each have one rule in the kit, so two cards on one chain never print two numbers for one word. Read them from `GammaCurve` and `ExpectedMoves` instead of summing, walking or pricing them in the Indicator. `GammaCurve` is gamma exposure as a curve over hypothetical spot. Over the live contracts of a scope (an expiry whose end, `optionsLiveUntilMs` on the load's zone, is after the as-of; open interest and IV above 0; `nearest` 0 counts every live expiry, 1 the front expiry alone, N the N soonest): - `spot()` is S0, the median underlying of the nearest live expiry's contracts. - `gexAt(x)` sums `side * oi * multiplier * bsGamma(u, strike, iv, years) * u * u * 0.01` with `u` the contract's own underlying times `x / S0`, so a dated future moves with the coin, and `years` the contract's `optionsYearsToGo` (to 15 minutes past the stamp on OPRA, at least a second). The unit is USD per 1% move, dealers long the calls and short the puts. - `netGex()` is `gexAt(S0)`, and `regime()` is its sign through `dealerRegime(netGex)`: 1 long gamma, -1 short gamma, 0 neutral. A flip never decides the regime. - `flip()` is the root of the curve nearest S0: the walk steps out from S0 by 0.25% on both sides at once, out to 50%, and bisects the first step that brackets a sign change to 1e-9 of S0. When both sides bracket at one step it takes the nearer root (the lower on a tie); it reads S0 when net GEX is 0 and NaN when no root lies within 50%. `flipCount()` and `flipNear(k)` read every root the walk brackets across the whole reach, nearest first. - A reading of exactly 0 brackets nothing: each side's bracket runs from its last nonzero reading. A curve that crosses 0 exactly at a step (a 0 between readings of opposite signs) is bisected across that step, and its root is found there. A curve that touches 0 and keeps its sign (a 0 between readings of the same sign) changes no regime, so it is no flip. That is the curve far from every strike, where each contract's gamma underflows to 0 and the curve fades out: a book of calls near spot has no flip, however far the walk goes. - The walk runs on the first `flip()`, `flipNear()` or `flipCount()` after a load, never inside it. A load of the same contracts at the same S0 (a bar that repeats its block, a live update between two reads of the chain) keeps every reading it already made, so a package walks the curve once per distinct block. The load keeps each contract's terms, so one `gexAt` costs one log of `x / S0` and one exp per contract. - `loadStrikes(...)` reads `option_strikes` rows instead of the chain, each row a call and a put with that side's open interest and IV, at the rows' as-of, `optionsAsOfMs(...)`: the bar's close, when their fold minute closes. Because the regime is the sign of the same curve the flip is the root of, a long-gamma card always has spot on the long side of its flip. The older `zeroGamma()` readers keep their numbers: the first crossing of a running sum over the strikes, which can sit far from spot and contradict the sign. Do not print it as the flip. `ExpectedMoves` reads each live expiry, nearest first. The forward is the median underlying of the expiry's contracts. The at-the-money IV is the mean of the call and the put mark IV at the strike nearest the forward (the lower on a tie). Then `expectedMove(i)` is `straddleExpectedMove(forward, atmIv, years)` and `oneSigma(i)` is `oneSigmaMove(forward, atmIv, years)`. `horizonIv(years)` is the at-the-money IV at any horizon: total-variance interpolation between the two expiries around it, the nearest expiry's IV before it and the farthest's after it. A horizon's move is `straddleExpectedMove(anchor, horizonIv(years), years)` on the price the horizon is anchored at: the next 24 hours is `years = 1 / 365`. Load both at `optionsAsOfMs(...)`, the live bar's close, and on the market's zone and kind (`market.zone()`, `market.kind()`), so a US stock or ETF expiry counts, and keeps its gamma, until 15 minutes past its stamp and a US index expiry until its stamp. Say what each number covers where you print it, "all expiries" or the expiry's date for the front one. ```typescript // The canonical numbers on the live bar: net GEX, the dealer regime and the gamma flip over every live expiry, and the front expiry's expected move and 1σ range. input("close", ohlcv.close); input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" }); market.zone(); // the market's clock: an OPRA expiry stays live and priced 15 minutes past its stamp chart.interval_sec(); // the bar's length: the chain is read at the live bar's close output("net_gex", none, overlay, { description: "Net GEX at spot, all expiries, USD per 1% move" }); output("regime", none, overlay, { description: "Dealer regime, all expiries: 1 long gamma, -1 short gamma, 0 neutral" }); output("gamma_flip", none, overlay, { description: "Gamma flip, all expiries: the root of the GEX curve nearest spot" }); output("expected_move", none, overlay, { description: "The front expiry's expected move, price: 0.85 of the at-the-money straddle" }); output("one_sigma", none, overlay, { description: "The front expiry's 1σ range, price" }); let curve = new GammaCurve(1); let moves = new ExpectedMoves(1); let zone = 0; let intervalMs = 0.0; function onStart(): void { // Construct here: the per-contract buffers are the only allocation. curve = new GammaCurve(in_chain_max_cells); moves = new ExpectedMoves(in_chain_max_cells); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; } function onBar(): void { if (!bar.isLast()) return; const n = in_chain_cells(); if (n < OPTIONS_TUPLE) return; const cells = in_chain_view(); const asOfMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the chain's as-of: the live bar's close curve.load(cells, n, asOfMs, 0, bar.close(), zone); // 0: every live expiry out_net_gex(curve.netGex()); out_regime(curve.regime()); out_gamma_flip(curve.flip()); moves.load(cells, n, asOfMs, bar.close(), zone); out_expected_move(moves.expectedMove(0)); out_one_sigma(moves.oneSigma(0)); } ``` ## A history of daily statistics The US listed options statistics (`option_daily`, and `option_stats_10m` every ten minutes) land one row per session: declared with `missing: "nan"`, a daily input lands its row on the session's own bar on a daily chart and on the first bar of its UTC day on an intraday chart, and every other bar reads `NaN`. `DayHistory` keeps those readings, one per day, the newest last, and answers what a history package asks of them: where today sits in its own past. - `push(day, value)` keeps `value` as day `day`'s reading: a day after the newest appends (the oldest drops once `capacity` readings are held), the newest day again replaces its reading (a revised row), and an earlier day, or a day or a value that is not finite, is skipped. It returns `true` when the reading was kept. Use the bar's UTC day, `Math.floor(bar.time() / 86400)`, so an intraday chart and a daily chart key the same sessions. - A window is the newest `window` readings, the newest among them; a window wider than the history reads the whole history, and `span(window)` says how many readings it holds. Compare `span` with the history the reading needs before you show it: a rank over five days is not a rank over a year. - `rank(window)`: `(newest - low) / (high - low) * 100`, where the newest sits between the window's low (0) and high (100); `NaN` with fewer than two readings or a flat window. - `percentile(window)`: the share of the window's earlier readings (every one but the newest) strictly below the newest, times 100. - `zscore(window)`: the newest against the mean and the sample standard deviation of the window's earlier readings; `NaN` with fewer than three of them or no spread among them. - `min`, `max`, `mean` and `stdev` (the sample deviation) read the window with the newest included; `quantile(window, q)` reads its `q` quantile (0 to 1, clamped), linear between the two closest ranks. - `value(ago)` and `day(ago)` read the history itself, `0` the newest and `NaN` outside it; `agoOf(day)` finds a day's reading (`-1` when it has none). Construct it once, at module level or in `onStart()`: its rings and its sort buffer are allocated there, and no call allocates after. ```typescript // The 30-day IV's rank and percentile over a year of sessions, once the history holds 60 of them. input("close", ohlcv.close); input("iv30", option_daily.atm_iv_30d, { missing: "nan" }); // the session's row on one bar, NaN elsewhere output("iv_rank", line, lower, { step: true, description: "Where the 30-day IV sits in its year, 0 to 100" }); output("iv_pct", line, lower, { step: true, description: "The share of the year's earlier sessions with a lower IV" }); const history = new DayHistory(260); let rank: f64 = NaN; let pct: f64 = NaN; function onBar(): void { const iv = in_iv30(); if (!isNaN(iv) && history.push(Math.floor(bar.time() / 86400.0), iv)) { const ready = history.span(252) >= 60; // a reading needs 60 sessions; until then say so instead of ranking rank = ready ? history.rank(252) : NaN; pct = ready ? history.percentile(252) : NaN; } out_iv_rank(rank); // held on every bar until the next session lands out_iv_pct(pct); } ``` The [IV rank](../cookbook/iv-rank.md), [Variance risk premium](../cookbook/vrp.md), [Skew history](../cookbook/skew-history.md), [Volatility regime](../cookbook/vol-regime.md), [Exposure history](../cookbook/exposure-history.md), [Options history](../cookbook/options-history.md), [Option stance](../cookbook/option-stance.md), [Options sentiment gauge](../cookbook/sentiment-gauge.md) and [Estimated dealer positioning](../cookbook/dealer-positioning.md) recipes build on it. ## The strike board A strike board (a heatmap of strikes against expiries or time) reads one signed number per strike: net GEX, net DEX, open interest or another lens, summed over the expiries it shows. The kit names the nodes on that board, picks its expiry columns, measures how each strike's number moves, scores the prints on a flow tape, and maps a chart's root to the roots its levels can be read through. Construct each class once, at module level or in `onStart()`: none allocates after, and every function is plain arithmetic. ### Node roles `NodeBoard.load(strikes, values, count, spot, pct)` takes ascending strikes, one signed value per strike, the price the board is read against and the significance percent (15 when left out). A strike's share is `pctOfTop(i)`, `100 * |value| / |top|`, multiplied before the divide: - **Top**: the largest `|value|`. A tie goes to the strike nearest spot, then to the lower strike. When every value is 0 there is no top (`top()` reads -1) and every strike is normal. - **Floor** and **ceiling**: the largest `|value|` strictly below spot, and strictly above it. - **Gate**: the largest `|value|` strictly between spot and the top's strike, kept only when its share is at least 35. - **Standouts**: every strike but the top whose `|value|` is at least each neighbour's (a missing neighbour counts as 0) and whose share is at least 50, positive or negative by the value's sign. - **Significant**: a share of at least `pct`. Every other strike is normal. `role(i)` is the strike's display role, the first that applies in the order top, gate, floor, ceiling, standout, significant, normal, as a code: 0 normal, 1 significant, 2 positive standout, 3 negative standout, 4 ceiling, 5 floor, 6 gate, 7 top (`NODE_ROLE_NORMAL` to `NODE_ROLE_TOP`). `standout(i)` (1, -1 or 0) and `isSignificant(i)` read the sets the order can hide: a standout that is also the floor shows the floor's role. `aboveNet()` and `belowNet()` sum the values above and below spot; a strike at spot counts in neither. `roleWord(code)` is the code's word for a label: top, gate, floor, ceiling, standout, significant or normal. ### Expiry presets `expiryPresetCount(expiries, count, nowMs, zone, preset, n)` returns how many of the leading expiries a preset keeps. The expiries are the live ones in epoch milliseconds, ascending, so every preset is a prefix. Days are trade days on the market's clock (`zone`, from `market.zone()`), read through `optionsTradeDay`, and a dated preset keeps the expiries on or before its last day: | Preset | Code | Keeps | | --- | --- | --- | | `EXPIRY_PRESET_FRONT` | 0 | The first expiry | | `EXPIRY_PRESET_TO_FRIDAY` | 1 | Through the first Friday on or after today | | `EXPIRY_PRESET_TO_NEXT_FRIDAY` | 2 | Through the Friday a week after that one | | `EXPIRY_PRESET_TO_OPEX` | 3 | Through this month's third Friday, or next month's once it has passed | | `EXPIRY_PRESET_TO_NEXT_OPEX` | 4 | Through the third Friday of the month after that one | | `EXPIRY_PRESET_TO_Q_OPEX` | 5 | Through the next third Friday of March, June, September or December | | `EXPIRY_PRESET_ALL` | 6 | Every expiry | | `EXPIRY_PRESET_COUNT` | 7 | The first `n` | `thirdFridayMs(year, month, zone)` is the instant a month's third Friday opens its trade day on the market's clock: 00:00 UTC on crypto, 00:00 New York on US listed options, 17:00 Chicago the evening before on CME. ### Strike velocity `new StrikeVelocity(maxKeys, maxBars)` keeps a ring of `maxBars` readings per key, where a key is an id from 0 the Indicator gives each strike (or each strike and expiry column). Push each key's reading once per bar with `push(barMs, key, value)`, bars in time order: - `velocity(key, w)`: the reading on the newest bar minus the reading on the newest bar at or before `w` minutes earlier; `NaN` when the key has no reading on the newest bar or its history does not reach that far. - `velocityPct(key, w)`: `100 * velocity / |the earlier reading|`; `NaN` when that reading is 0. - `available(w, hostIntervalMs)`: false for a window shorter than the chart's bar or beyond the bars held, so a picker hides it. - `halo(key, w1, w2, w3)`: the velocity has one sign on at least 2 of the windows given (0 leaves a window out). `VELOCITY_WINDOWS` lists the windows a board offers, in minutes: 1, 5, 10, 15, 60, 240 and 1440. The rings take `maxKeys * maxBars * 16` bytes, and a day of 1-minute bars needs 1441 of them. The movers (the significant strikes with the largest `|velocityPct|`) are the Indicator's to rank: it knows which strikes are significant. ### Flow score `flowSideCode(aggressor, outside)` reads an `option_prints` tuple's two side columns. On US listed options `aggressor` is +1 at the ask, -1 at the bid, 0 at the mid and 2 when no quote sided the print, and `outside` is +1 above the ask and -1 below the bid; on crypto and CME chains `aggressor` is the taker's side and `outside` reads 0. The code is +2 above the ask, -2 below the bid, +1 at the ask (or a taker's buy), -1 at the bid (or a taker's sale), and 0 at the mid or unsided. `flowScore(side, cp, moneyness, dteDays, sizeVsOi, repeatHits)` scores a print from -100 to 100, positive for a bought call or a sold put: - The base is `100 * s * cp`: `s` is 1, 0.8, 0, -0.8 or -1 for the codes +2 to -2, and `cp` is +1 for a call, -1 for a put. - The base times three factors, multiplied together first: moneyness (0 out of the money 1.0, 1 at the money 0.9, 2 in the money 0.6), days to expiry (up to 7 1.0, up to 30 0.85, up to 90 0.7, else 0.55) and size over open interest (above 1 1.0, an open interest of 0 included; above 0.5 0.9; else 0.75). - Plus 10 in the base's sign at 3 repeat hits or more, then clamped to -100 and 100. A side of 0 scores 0. ### Derived roots `DERIVED_ROOTS` maps a chart's root to the roots whose option chains its levels can be read through: ES to SPX and SPY, NQ to NDX and QQQ, GC to GLD, SI to SLV, YM to DIA, RTY to IWM, SPY to SPX and QQQ to NDX. `derivedRootCount(root)` and `derivedRoot(root, i)` read it (0 and the empty string for a root it does not list). A derived level is drawn at `derivedRatio(close, rowUnderlying)`, the chart's close over the row's underlying, so a derived strike is `strike * ratio`. ## Limits - **The chain is the live row's only.** `options_chain` fills the newest row and leaves every history row an empty block ([Limitations](../reference/limitations.md)); read it under `bar.isLast()` and keep the readings for the bars that follow. A gamma map over past bars reads `option_strikes` instead ([Option strikes, bar by bar](#option-strikes-bar-by-bar)), on crypto, CME and US stock charts, one book of the chain `venue` picks (`book`). - **The chains are the chart's.** `venue: "auto"` reads the chart's own options venue when it lists options (on a US stock or ETF chart its OPRA chain, on a CME futures chart its CME chain, each at your own tier), else the coin's Deribit chain; a venue's name (`deribit`, `cme`, ...) pins one. Open interest and the multiplier arrive as the venue reports them: Deribit in coins with a multiplier of 1, CME in contracts with the point value as the multiplier, OPRA in contracts with a multiplier of 100, which is why the exposure is in USD on all three. A venue the chart cannot serve is refused by name. - **One book per block.** The tuple names no symbol, so `GammaCurve` and `ExpectedMoves` read a block as one book of one chain and cannot tell two books apart: a block that carries a coin's two Deribit books (`BTC` and `BTC_USDC`) sums both books' open interest into net GEX and averages both surfaces' quotes at the at-the-money strike. - **Size `max_cells` for the chain.** A BTC chain is about 1,550 contracts; a crypto block over `max_cells` refuses the run instead of being truncated, and the `cells` array costs `max_cells * 10 * 8` bytes of module memory ([Limits](../reference/limits.md)). On a governed chain (OPRA, CME) `max_cells` is the budget the chart sizes the read to: the expiries that fit at 8 strikes each side of the money, then a wider window up to 80 strikes. - **Where the chain is served.** The chart serves `options_chain` when the indicator runs in your browser. A Protected indicator on OpenMarket's servers reads a coin's Deribit chain only (`venue: "auto"` or `"deribit"`): the US stock and CME chains and the other venue words are refused there by name. Alerts and your OpenMarket runner refuse an indicator that declares it, by name. `option_strikes` is served by the chart alone too; every other host refuses it by name. ## From Pine Nothing on this page maps to Pine. Pine cannot read an options chain, so there is no `request.*` call or `ta.*` function to translate: gamma exposure, the walls and max pain are computed from cells the chart serves to the indicator, and the class is this chart's arithmetic for them. <!-- source: https://openmarket.xyz/wrun/functions/alerts --> # Alerts An alert runs your published indicator in OpenMarket's cloud and tells you when a condition on one of its outputs, or a signal its file declares, comes true. You set it from the chart: pick an output or a declared signal, choose a condition, and OpenMarket's alerts engine evaluates it on the chart's market with the overlay's settings. There are two ways in: every drawn output is a value a condition can follow, and `alert(name, { when, message })` in the file names a ready-made signal. ## Set an alert from the chart 1. Publish the indicator. An alert needs a published version; on a draft the chart says "Publish the Indicator before adding an alert." ([Publishing](publishing.md)). 2. Add it to a chart and open the alert dialog from the indicator's bell in the legend, from the right-click menu, or from **Alert on** > **Indicators** in the sidebar's alert menu. 3. Pick the output or a declared signal, pick the condition, and save. The alert runs the version and the settings the overlay carries. The conditions on an output: ```text Crossing Crosses above, Crosses below, Greater than, Less than Channel Entering channel, Exiting channel, Inside channel, Outside channel Moving Moving up, Moving down, Moving up %, Moving down % ``` A data-only output (declared `none`) is not offered as a condition target; give it a declared signal instead, as below. ## When an alert checks and fires OpenMarket's alerts engine checks an indicator alert on the server, on every price tick of the chart's market, at most once a second for each indicator. The ticks that arrive inside that second fold into the bar that is still forming: its high and low keep every extreme, and its close is the latest price. The next check runs the indicator on the bar as it stands then, and every bar's close is checked. You pick when a fire counts: | Choice | Fires | | --- | --- | | Once | the first time the condition is met; then the alert is used up | | Once per bar | at most once on each bar, as soon as the condition is met on the forming bar | | Once per bar close | at most once on each bar, when the bar closes with the condition met | | Every time | each time the condition is met again after it was not | - A wick counts. A forming bar's high or low that reaches a level is seen on the next check, so a choice that fires on the forming bar catches a wick within about a second. Once per bar close waits for the bar to close. - A value that crosses a level and comes back inside the same second is not seen: a check reads the bar as it stands, not each tick inside the second. - A declared signal keeps its own rule (below): it turns on when its `when` output turns true, or on every bar it holds with `every_bar`, and the choice above says how often that counts as a fire. An indicator whose runs keep failing on the server (too slow, or stopping with an error) has its alerts paused: they show as paused (`paused_runtime`), the alert's owner gets a notice, and the engine tries the indicator again by itself and resumes the alerts once a run succeeds. The indicator keeps drawing on the chart; only its alerts pause. Price alerts and the alerts on a market's open interest, funding, liquidations or volume are not indicator alerts: the engine reads those series directly and never runs a package for them, so they need no port. ## Declare a signal in the file ```typescript param("fast", 21, { min: 1, max: 200, description: "Fast EMA length" }); param("slow", 55, { min: 2, max: 400, description: "Slow EMA length" }); output("fast", line, overlay, { color: "#2563eb", description: "Fast EMA of the close" }); output("slow", line, overlay, { color: "#f97316", description: "Slow EMA of the close" }); // Data-only: 1 on the bar the fast EMA crosses above the slow one, else 0. const goldenCross = output("golden_cross", none); // A ready-made signal in the chart's alert dialog: it fires when the gate turns from 0 to 1. alert("golden_cross_up", { when: goldenCross, message: "{{symbol}} golden cross at {{close}}", description: "Fast EMA crosses above slow EMA" }); let fast = new Ema(21); let slow = new Ema(55); let cross = new Cross(); function onStart(): void { fast = new Ema(i32(p_fast())); slow = new Ema(i32(p_slow())); cross = new Cross(); } function onBar(): void { const close = bar.close(); const fastValue = fast.update(close); const slowValue = slow.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; out_fast(fastValue); out_slow(slowValue); out_golden_cross(crossed == 1 ? 1.0 : 0.0); } ``` `alert(name, { when, message?, description?, text?, every_bar?, title? })` declares a signal over an output handle bound by a top-level `const`. It fires on the bar the `when` output turns from false to true (true is finite and nonzero; a `NaN` row is false and re-arms it), `message` is the text the alert sends (placeholders such as `{{symbol}}` and `{{close}}` fill in when it fires, and `{{<output>}}` reads a declared output's value on the fired bar), and `description` is the line under the signal in the alert dialog. Both are at most 200 characters. The `when` output may be data-only, as here: the file writes `golden_cross` from `onBar()` like any other output, and the declaration adds nothing to the compiled module. Declared signals appear in the chart's alert dialog beside the conditions, and an indicator that declares only signals offers only those. The grammar is on [Declarations and the sheet](../reference/declarations.md#alert). ### Sounds on the chart A declared signal can also play a sound on the chart, with no alert. When the file declares signals, the indicator's settings have a **Sounds** tab under **Chart**. The trader turns on **Play sounds**, picks a sound for each signal and sets one volume. The chart plays a signal's sound when its value rises during the live candle: when it turns true, or when it grows, so a count of prints sounds once per print. It plays one sound at a time and at most 4 a second, and when two signals rise together, the one declared first plays. Nothing plays on history, replay or a settings change. The choice is saved with the indicator on the chart; the file never sees it. Declare your most important signal first, and use `every_bar: true` for a count per bar. ## Alert words and every bar An alert can send words your file writes on the bar it fires, and it can fire on every bar its condition holds instead of only the first. Both are options on `alert(...)`, and both ride with the alert to the server: the alerts engine reads the `text` slot on the fired bar and applies `every_bar` there, so a fire carries the same words whether or not a chart is open. ```typescript // Two alerts on an EMA pair: one writes its own message on the cross, one fires on every bar the fast line stays above. param.int("fast", 21, { min: 1, max: 200 }); param.int("slow", 55, { min: 2, max: 400 }); output("fast", line, overlay, { color: "#2563eb" }); output("slow", line, overlay, { color: "#f97316" }); // Data-only gates: 1 on the bar the condition is true, else 0. const crossedUp = output("crossed_up", none); const above = output("above", none); // The slot the file writes the cross message into. const crossWords = string("cross_words", { max_bytes: 96 }); // Fires once, on the bar of the cross, with the words the file wrote on that bar. The dialog lists it as "EMA cross up". alert("cross_up", { when: crossedUp, text: crossWords, title: "EMA cross up", description: "Fast EMA crosses above slow EMA" }); // Fires on every bar the gate is true. {{fast}} and {{slow}} read those outputs on the fired bar. alert("still_above", { when: above, message: "{{symbol}}: fast {{fast}} is above slow {{slow}}", every_bar: true, description: "Every bar the fast EMA is above the slow EMA" }); let fast = new Ema(21); let slow = new Ema(55); let cross = new Cross(); function onStart(): void { fast = new Ema(i32(p_fast())); slow = new Ema(i32(p_slow())); cross = new Cross(); } function onBar(): void { const close = bar.close(); const fastValue = fast.update(close); const slowValue = slow.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; out_fast(fastValue); out_slow(slowValue); out_crossed_up(crossed == 1 ? 1.0 : 0.0); out_above(fastValue > slowValue ? 1.0 : 0.0); // Write the words on the bar the alert fires. On a bar that writes nothing, the alert sends its message, else its name. if (crossed == 1) { sb_clear(); sb_text("Fast EMA "); sb_auto(fastValue); sb_text(" crossed above slow EMA "); sb_auto(slowValue); str_cross_words_sb(); } } ``` - `cross_up` sends the words the file wrote into `cross_words` on the bar of the cross, such as "Fast EMA 103.71 crossed above slow EMA 103.7". - `still_above` fires on every bar the fast line is above the slow one, at most once per bar. Its message fills `{{fast}}` and `{{slow}}` with those outputs' values on the fired bar. ### Options | Option | What it does | Default | | --- | --- | --- | | `when` | the output that turns the alert on: true is finite and not 0 | required | | `text` | a string slot; its words on the fired bar are the message | none | | `message` | fixed words with placeholders: `{{symbol}}`, `{{exchange}}`, `{{interval}}`, `{{open}}`, `{{high}}`, `{{low}}`, `{{close}}`, `{{volume}}`, `{{value}}`, `{{time}}`, `{{alert.name}}`, and `{{<output>}}` for any output you declared | the alert's name | | `every_bar` | `true` fires on every bar `when` is true, once per bar at most; `false` fires only on the bar it turns true | `false` | | `description` | the line under the signal in the alert dialog | none | | `title` | the words the alert dialog, an armed alert and its notification show for the signal: any characters, spaces included, 1 to 120 of them on one line (the name itself takes letters, digits, `.`, `_` and `-` only); a newline, a control character or an invisible one (a bidi control, a zero-width space) is refused, as in a text setting's default | the alert's name | ### Which words are sent 1. The message the user types in the alert dialog, when there is one. Its placeholders fill in as always. 2. Otherwise the `text` slot's words on the fired bar. A bar that wrote nothing there, or an empty line, falls through. 3. Otherwise `message`. Each `{{<output>}}` becomes that output's value on the fired bar: a whole number as it is, any other number to 10 significant digits, `n/a` when the bar has no value. `{{close}}` and the other placeholders above keep their own meaning, even when an output has the same name. 4. Otherwise the alert's name. Words written by the file arrive as plain text. They are one line of at most 200 characters (longer words end with an ellipsis), a link in them is never clickable and never previewed, and mentions such as `@everyone` and `@here` are removed. They are never read as a template, so a `{{close}}` the file writes arrives exactly as written. ### Every bar, and the user's choice The alert dialog shows the file's choice under **Fire**: "When it turns true" or "Every bar while true". The user can change it for one alert there ("The script's author set the default; your choice applies to this alert."). The repeat and the tick-or-close choices still apply, so a tick alert can fire on the forming bar before it closes ([When an alert checks and fires](#when-an-alert-checks-and-fires)). ### Limits and refusals | Rule | What the build says | | --- | --- | | `text` names a string slot | `alert 'cross_up' option 'text' references output 'above' where a string slot is needed` | | `text` names something declared | `alert 'cross_up' option 'text' references 'ghost', which is neither a declared output nor a declared string slot; bind the output first (const h = output("...", ...)) or the slot (const s = string("...", { max_bytes: 32 })) and pass that const, or name it as a string literal` | | `every_bar` is `true` or `false` | `option 'every_bar' takes true or false` | | `message` and `description` are at most 200 characters | `message must be at most 200 characters` | | `title` is 1 to 120 characters | `alert 'cross_up' title is 121 characters; it takes at most 120`, `alert 'cross_up' title is empty; it names the alert in the dialog (leave it out to show the name)` | | `title` is one line of plain text | `alert 'cross_up' title carries a newline, a control or an invisible character; shown text is stripped of bidi controls, zero-width characters and control characters, so a title cannot carry them` | | 64 alerts per indicator | `alerts must declare at most 64 entries` | ## Strategy alerts An indicator that trades adds four choices of its own to the alert dialog: "Strategy order placed", "Strategy trade opened or closed", "Strategy position" and "Strategy equity" ([Strategies overview](../strategies/overview.md)). ## What an alert can evaluate One shared function decides whether an alert can be set on an indicator, on a market, and on which of its outputs: `wrunAlertability` in `@openmarket/sdk/wrun-host` (`@orangecharts/indicator-kit/host` in the kit). The alerts engine runs it as its door, and the chart runs it for the Create alert button and the output picker, so both give the same answer from the indicator file alone. It applies these rules in order, and the first refusal is the answer: 1. Indicator alerts are switched on (`WRUN_DISABLED` when they are not). 2. The market is not a CME Group venue (`VENUE_NOT_ALLOWED`). An alert on a US option contract (OPRA) is coming for real-time US options accounts with the feature turned on: until the alert server's OPRA lane serves the account, it is refused (`VENUE_NOT_ALLOWED: opra_lane_unavailable`), and once it does, an account the options feed serves delayed is refused there (`VENUE_NOT_ALLOWED: opra_realtime_required`). 3. The chart's interval is an alert interval (`UNSUPPORTED_INTERVAL`). 4. The alert server admits the file: its checks of the file's shape (`WRUN_PACKAGE_INVALID`, such as a tape floor read from a setting), then its `abi_version` (`WRUN_ABI_UNSUPPORTED`). 5. The alert server serves the market (`WRUN_FOREIGN_MARKET` for a venue it does not serve yet, such as `POLYGON_INDICES`), then every input, input by input in the file's order, planned the way the server plans them before it fetches anything: the source, its fields and views, the market it pins (`POLYGON_INDICES` refused) and its timeframe (`WRUN_SOURCE_UNSUPPORTED`, `WRUN_INTRABAR_UNSUPPORTED`, `WRUN_INTERVAL_PIN`, `WRUN_PACKAGE_INVALID`). Any input may pin another market, the first one included. The first input with a problem is the one named. 6. Every pinned timeframe fits: at or coarser than the chart's interval and a whole multiple of it, a weekly leg only on `ohlcv`, `funding` or `oi`, a `forming` view or a `1w` leg inside the 600 bars an alert keeps, and a `candles` stream no deeper than 2,000 candles and never weekly (checked with rule 5, input by input). Then no input that reads data pins a CME Group market (`VENUE_NOT_ALLOWED`); a `time` input or an `is_new_period` pulse of a `funding`, `oi` or `1w` leg reads no market, so its pin never counts there. On a US option contract an alert reads only the armed contract's own candles (`ohlcv` or a `candles` stream), judged with rule 5, input by input: another source is refused by name (`WRUN_SOURCE_UNSUPPORTED`), and so is a pin to any other market, a pulse's pin included (`WRUN_FOREIGN_MARKET`), as is a pin to an option contract from an alert armed anywhere else. A `candles` input is skipped on an interval its `chart_interval_below` is not finer than, as every chart skips it: no check above judges it and its pin never counts, so an hourly stream with `chart_interval_below: "1h"` arms on 4h and 1d. 7. The settings fit: every setting's default (or the value the alert carries) inside its own `min` and `max`, a strategy setting link inside its range, and a well-formed `displacement_bars_by` (`WRUN_PARAM_INVALID`, `WRUN_PACKAGE_INVALID`). 8. The market has the data every input reads (`VENUE_DATA_UNAVAILABLE`): a stock, forex, metal or index market (an ETF issuer such as `BLACKROCK` included) and Polymarket publish candles only (no order book, trades, funding, open interest, liquidations, volume profile or tape), a crypto spot venue has no funding, open interest or liquidations, and a quote-bar venue (`FX_OTC`, `POLYGON_FX`, `LBMA`, `LME`, `ICE`, `PLATTS`) has no volume either. Every input counts, one with `needed_by` included: the alert server reads no `needed_by` yet and asks every input's data on every market. An input pinned to another market is judged on that market, an `is_new_period` pulse of a `funding`, `oi` or `1w` leg reads no data, and a `volume_profile` input with `missing: "empty"` reads empty where a market has none. A `trades` input that follows the chart's coin is refused by name (`WRUN_SOURCE_UNSUPPORTED: <input>=trades follows the coin on <venue> (follow "coin")`): the alert server reads literal market pins only. An input's `when` gate counts as on: the alert server fetches every input whatever the settings. 9. Something can be watched (`NO_ALERTABLE_OUTPUT`): a plotted output, a strategy, or a declared alert. An output shifted by `displacement_bars` is listed but cannot be picked. Each refusal carries the server's own sentence, so the chart shows the same reason whichever side refused. The sections below say what each rule admits. An alert evaluates the indicator on the chart's market at the chart's interval, which must be 1m, 5m, 15m, 30m, 1h, 4h or 1d ("Alerts support 1m, 5m, 15m, 30m, 1h, 4h and 1d intervals. Switch the chart interval to arm this indicator."). It serves these inputs: | The indicator reads | An alert serves | | --- | --- | | Feeds | `ohlcv`, `trades`, `oi` (in dollars: `currency: "Coin"` is refused), `liquidations`, `funding` and `time`, plus `book` and `volume_profile` cells and live `tape` prints (`history: "0"`) | | An options summary | `implied_volatility` and `skew` pinned with the option coin as `symbol` and `exchange: "DERIBIT"` | | A published feed | `series` at `@scope/name`, where the alert server reads published feeds (production does not yet) | | Another market | its candles, through a secondary `ohlcv` input pinned with `symbol` and `exchange`: a crypto venue, a stock or ETF on `POLYGON`, forex, gold or silver on `FX_OTC` | | A coarser timeframe | a secondary `ohlcv`, `funding` or `oi` input pinned to `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d` or `1w`, a whole multiple of the chart's interval; a pinned candle counts only once it has closed | | A view of a pin | `confirmed` (the default), `forming` and `is_new_period` | | Candle history as an array | a `candles` stream (`candles.cells`): the closed candles of the chart's own market at the chart's interval, of another market pinned with `symbol` and `exchange` at the chart's interval, or of a coarser timeframe up to `1d`, as deep as the stream's `bars` up to 2,000 candles; plus its `forming` view (the live candle) and `forming_open` (the open of the candle holding each row) | An indicator it cannot evaluate is refused by name when you save the alert: - "This Indicator is pinned to a different interval than the chart." for a pin on the first input, a pin finer than the chart's interval or not a whole multiple of it, a custom timeframe such as `2h` or `45m`, and a `forming` view or `1w` candle too long for the 600 bars an alert keeps (below). - "This Indicator reads a data source alerts cannot evaluate yet." for every feed the table does not list, `odds` included, an `implied_volatility` or `skew` input without its `DERIBIT` pin, `trade_volume_by_size` cells, the `oi_candles` and `volume_profile_candles` streams (an open interest or volume profile history reads on the chart, not in an alert), and an `oi` input read in the venue's own units (`currency: "Coin"`: the alert server reads open interest in dollars only). - "Alerts cannot use the Timeframe setting yet. Set it back to its default to arm." for a source, timeframe or symbol setting moved off its default; the sentence names the setting. - "This Indicator reads a market alerts cannot evaluate yet (an index)." for an input pinned to an index (`POLYGON_INDICES`); pin an ETF on the same market instead (`SPY/USD`). - "Indicator alerts are not allowed on this venue." for an indicator whose input pins a CME market. On CME markets only price alerts are available for now ("Only price alerts are available on CME markets right now."), and where wrun indicator alerts are switched off the chart says "Indicator alerts are not enabled yet." - "Alerts can't run this Indicator yet: it reads candle history in a way the alert server doesn't provide." for a `candles` stream on `1w` or a custom timeframe such as `2h`, one finer than the chart's interval, one deeper than 2,000 candles, and for cells read off an `ohlcv` field. Pivot Points Standard (a weekly stream) and Timeframe Matrix (a `2h` stream) are refused this way today. - "This alert needs more history than alerts keep. Set the chart to 5m or higher, or use a shorter timeframe in the indicator's settings." for an indicator whose candle stream's timeframe spans more chart bars than the alert keeps (below): Anchored VWAP sums the chart's bars since the day's open, a day is 1,440 bars on a 1m chart and its alert keeps 504, so it arms on 5m and coarser. The sentence names the smallest chart interval that fits. - An indicator with no plotted output and no declared alert has nothing an alert can watch: no bell, no entry in the alert menus. `intrabar` cells, `options_chain` and `option_strikes` cells and an `offset` view are refused as well. A published stream deeper than the server keeps is refused when you save: "Alerts can't run this Indicator: it needs N candles of history and the alert server keeps 2000." ### How much history an alert reads An alert evaluates over at most 600 bars of the chart's interval. The window is the larger of the warm-up the file declares and the largest maximum among its settings, counted up to 500. A warm-up is one top-level line, `warmup({ terms: [{ param: length, times: 2 }], min: 40 })`: with `length` a setting's handle, it asks for twice that setting's value in bars, and at least 40. An indicator that reads a coarser pinned timeframe gets all 600 bars, even when it reads only that pin's `is_new_period` pulse; one that also reads `book` or `volume_profile` cells keeps the window its warm-up and settings give it. 600 chart bars hold 600 / (leg / chart) candles of a pin: a 4h pin holds 150 candles on a 1h chart, 37 on 15m and 12 on 5m. A higher-timeframe average longer than that arms but stays empty, so arm such alerts on a coarser chart: an average of 20 4h candles fills on 15m and stays empty on 5m. A `forming` view needs its whole candle inside the 600 bars, so a `1d` one needs a 5m chart or coarser and a `1w` one 30m or coarser, and a `1w` pin's closed candle needs 1h or coarser; on a finer chart the alert is refused with "This Indicator is pinned to a different interval than the chart." A `candles` stream is fetched on its own, as deep as its `bars` (up to 2,000 candles, one request), and never widens the 600-bar window. The window still bounds what the indicator sums over the chart's own bars: an indicator that anchors to the stream's timeframe needs one such period inside the window, so a daily anchor arms on 5m and coarser (288 bars a day) and is refused on 1m (1,440); a monthly anchor on a 1h chart (744 bars) arms and can differ from the chart late in the month. An indicator that builds a higher timeframe from the chart's own bars, with a `Resampler` and no pin, must declare `warmup()` long enough for it: 20 1h candles on a 5m chart are 20 x 12 = 240 bars. Otherwise its alert can arm and stay empty. ## Next - **Publishing:** the published version an alert runs ([Publishing](publishing.md)) - **Declarations and the sheet:** the full `alert(...)` grammar ([Declarations and the sheet](../reference/declarations.md#alert)) - **Multi-source:** pin a stock, forex or gold so an alert reads it ([Multi-source](../core-concepts/multi-source.md#stocks-forex-and-gold)) - **Execution model:** where each part of an indicator runs ([Execution model](../core-concepts/execution-model.md)) <!-- source: https://openmarket.xyz/wrun/functions/publishing --> # Publishing Publishing turns the wrun indicator in your editor into a versioned package on the OpenMarket registry, under your username, that you, the people you invite, or everyone can add to a chart. In the editor, **Publish** opens the **Publish Indicator** dialog once the current code runs with no errors (until then the editor says "Publish is available once the Indicator has no errors"); you need to be signed in, and the draft is saved first. Whether readers get the code, a compiled module, or neither is the dialog's **Code** choice, and it also decides where the indicator runs: on OpenMarket's servers, or in each person's browser. Publishing is also how code is reused between indicators: there is no import between them ([Reuse and libraries](#reuse-and-libraries)). Who can use it, inviting people and keeping a member list in sync from your own site are the [Sharing](../sharing/overview.md) section. ## The Publish Indicator dialog ```text Publish Indicator Name @yourname/ followed by the name: lowercase letters, digits and dashes Version 0.1.0 on the first release; Patch, Minor or Major after that What changed one line people read before they update (from the second version) Who can use it Everyone (Listed on OpenMarket on or off), Invite only, Just me Code Protected, Compiled, Open source Description what this Indicator shows Cover a picture of this pane, taken now ``` - **Name.** The scope is your OpenMarket username, lowercased, and the dialog sets it in front of the name; you type only the name part. After the first publish the name is read-only: a rename is a new indicator. The name shown in lists is the editor tab's title. - **Version.** The first release is always 0.1.0. Every later publish is **Publish a new version**: pick **Patch**, **Minor** or **Major** (the dialog starts on the next patch). A published version never changes, so revising an indicator means publishing the next version. - **What changed.** From the second version, one line of up to 280 characters that people read before they update. - **Description.** What the indicator shows, prefilled from the draft. - **Cover.** When the draft is on the active chart, publishing takes a picture of its pane and uses it as the package's cover. There is no picker; without a picture the registry shows a stock one. ![The Publish Indicator dialog on a first publish: the name after the scope, the 0.1.0 line, Who can use it with Invite only and Just me greyed without a direct session, Code, Description, Cancel and Publish](/wrun/images/publish-dialog.png) - The scope (`@yourname/`) is fixed in front of the name field; the name is prefilled from the tab's title. - "Version 0.1.0, the first release" replaces the version chips until the second publish. - **Everyone** is on with **Listed on OpenMarket**; **Invite only** and **Just me** are greyed here because this session was not a direct one. - **Code** shows the current choice, with its one-line meaning under the row. With a direct OpenMarket session the dialog publishes as you on the spot ("Publishing directly as @yourname: no popup."). Otherwise it opens a sign-in window that finishes by itself; if the browser blocks it, the dialog says "The publish window was blocked. Allow popups for this site and try again." A refusal from the registry, such as a version that already exists, reads "Publish failed:" followed by the registry's reason. ## Who can use it **Who can use it** picks **Everyone**, **Invite only** or **Just me**. A new publish starts on **Everyone**, listed. Invite only and Just me need a direct OpenMarket session; without one they are greyed out. You can change who can use a published indicator at any time without publishing a new version. What each choice means, how to invite people, and how to keep a member list in sync from your own site: [Sharing](../sharing/overview.md). ## Code: who reads it and where it runs | Choice | What the dialog says | Who gets what | | --- | --- | --- | | **Protected** | Runs on OpenMarket servers. Your code never leaves them: nobody can download, read or copy it. | the chart shows the result; nothing of yours downloads | | **Compiled** | Runs in each person's browser. They get a compiled module, never your source. | everyone with access downloads the compiled module, and a downloaded module can be copied | | **Open source** | Anyone who can use it can read the code and fork it. | everyone with access gets the code, in each person's browser | - The row opens the three choices; the tick marks the current one. - The sentence under the row changes with the choice and says who gets the code and where the indicator runs. - **Invite only** starts on **Protected**: the choice for anything you sell. Only Protected keeps the code on OpenMarket's servers; a Compiled module is downloaded by everyone with access and can be copied. Invite only greys out **Open source** ("Invite only keeps the code private."). A **Protected** indicator is marked Protected in the Indicators dialog. OpenMarket's servers compute it over the chart's candles and stream the result to the chart; its settings dialog is the file's own (a source, timeframe or symbol setting keeps its declared default there for now, and there is no Style page), and it cannot be forked. In the editor, once its current version is published, you can run the published indicator in the cloud instead of in your browser. Protected is free to run for your community within fair use ([Fair use](../sharing/overview.md#fair-use)). Open source code is capped at 256 KB. Protected is set at the first publish and cannot change later. A name first published as Compiled or Open source stays in the browser, and a name first published as Protected stays on OpenMarket's servers; Compiled and Open source can alternate from one version to the next. To move an indicator to the other side, publish it under a new name. ## After publishing - **Find it.** Published wrun indicators are in the chart's **Indicators** dialog, on its **Indicators** tab: **OpenMarket** (the built-in and official indicators), **Community**, and **Mine** (yours, drafts included, when you are signed in), with indicators others invited you to under **Shared with you**. The chart's search finds them too. - **Add it.** Add a row, or open it and press **Apply**. The overlay keeps the exact version it was added at and reloads that version, so a newer publish never changes a chart that already carries the older one. - **Indicator page.** In the detail panel, **Indicator page** opens the package's public page in a new tab. - **Fork.** On desktop, **Fork** copies an Open source indicator's code into a new draft in your editor, and publishing the draft records "Forked from" the original. A Compiled indicator has nothing to fork ("The author published this Indicator without its source, so there is nothing to fork."), and a Protected indicator offers no Fork. - **Alerts.** A published indicator can carry alerts from the chart; a draft cannot ([Alerts](alerts.md)). - **Invite people.** After an Invite only publish, **Invite people…** on the receipt opens the indicator's People panel ([Invite your community](../sharing/invite-your-community.md)). ## Manage a published indicator **Manage Indicator**, on the indicator's page under **Mine** in the Indicators dialog, is the owner's place for removal. **Delete Indicator** removes every version for good, and the name can never be used again. A chart that already carries it keeps an overlay that no longer loads and says so on its legend. On an Invite only indicator, **People · N** on the same page opens its People panel: the people with access, the invite link, imports and access keys ([Sharing](../sharing/overview.md)). ## Reuse and libraries Sharing code between wrun indicators is publishing one: the unit of reuse on OpenMarket is a whole indicator, `@yourname/name`, that people add to their charts, and an Open source one can be forked into a new draft in your editor. There is no source import between indicators, and no `import "@scope/lib"` from another indicator's source. Inside one indicator, shared code is ordinary AssemblyScript in the same file: an indicator is one file. ### Shared code in the one file Put functions, classes, and constants in the editor tab beside the declarations and `onBar()`. One file per indicator: the kit's classes and functions and the readers and writers Run generates from your declarations are simply there, with nothing to import, and there is no second file to import from (a second source file is refused: "one file per indicator for now: move src/helpers.ts into src/indicator.ts"). A set of normalization helpers, in the indicator that uses them, which owns the data, the TA objects, and the declarations, beside the kit's own `Sma` and `Stdev`: ```typescript param("period", 20, { min: 2, max: 400 }); output("z", line, lower, { color: "#4f8cff", description: "Z-score of the close" }); output("regime", line, lower, { color: "#f59e0b", description: "+1 stretched up, -1 down, 0 inside the band" }); // The shared logic: plain functions and a class, no declarations. function zscore(sample: f64, mean: f64, dev: f64): f64 { if (dev == 0.0) return 0.0; return (sample - mean) / dev; } // +1 stretched up, -1 stretched down, 0 neutral. function regime(z: f64, hi: f64, lo: f64): f64 { if (z > hi) return 1.0; if (z < lo) return -1.0; return 0.0; } class Band { top: f64; bottom: f64; constructor(top: f64, bottom: f64) { this.top = top; this.bottom = bottom; } contains(price: f64): bool { return price <= this.top && price >= this.bottom; } } let sma = new Sma(20); let stdev = new Stdev(20); function onStart(): void { sma = new Sma(i32(p_period())); stdev = new Stdev(i32(p_period())); } function onBar(): void { const close = bar.close(); const mean = sma.update(close); const dev = stdev.update(close); const z = zscore(close, mean, dev); const band = new Band(mean + dev, mean - dev); if (isNaN(mean) || isNaN(dev)) return; out_z(z); out_regime(band.contains(z) ? 0.0 : regime(z, 2.0, -2.0)); } ``` In the editor, open a **New indicator** tab, paste it in, and press **Run**: it builds like any other indicator. `Band` is a class the indicator constructs; a function is a function everywhere in the file, and there are no placement rules. The `new Band(...)` on every bar allocates a temporary the module frees once the bar drops it; keep one `Band` and update its fields when the history is long, which allocates nothing ([Collections](../core-concepts/collections.md)). ### Reuse across indicators What sharing code between indicators looks like on the chart: | You want | wrun form | | --- | --- | | use another indicator's functions | copy them into your tab, or add that indicator to the chart beside yours as its own overlay | | a shared type | a class in your tab | | reuse a series another indicator computed | not on the chart: each indicator runs its own module and cannot read another's outputs, so compute the series in the consumer | | a draft that resolves live in the editor | the editor builds the current source as you type, and **Run** puts it on the chart | | publish an immutable version | **Publish** in the editor; a published version never changes ([The Publish Indicator dialog](#the-publish-indicator-dialog)) | | pin an exact version | a chart keeps the exact version it added and reloads that version ([After publishing](#after-publishing)) | | start from someone else's code | **Fork** (on desktop) copies an Open source indicator's code into a new draft in your editor ([After publishing](#after-publishing)) | ## Good to know - Official indicators publish under `@om-core`: they list under **OpenMarket** with an **Official** tag. - The dialog has no price. Paid indicators show their price in the listing and cannot be added from the chart. - On CME markets an indicator runs in the reader's browser once they have accepted the CME market data terms; a Protected indicator does not run there. - The chart publishes to the OpenMarket registry; there is no other registry to choose. <!-- source: https://openmarket.xyz/wrun/sharing/overview --> # Who can use it When you publish, you choose who can use your indicator and who can read its code. This section is everything after that: inviting people, keeping a member list in sync from your own site, and what your members see. ```text Publish Indicator Who can use it Everyone Anyone on OpenMarket can find it and add it. Invite only Only the people you invite. Your community, your list. Just me Only on your charts. Nobody else sees it. Code Protected Runs on OpenMarket servers. Your code never leaves them: nobody can download, read or copy it. Compiled Runs in each person's browser. They get a compiled module, never your source. Open source Anyone who can use it can read the code and fork it. ``` ## Three choices | Choice | Who can find and add it | | --- | --- | | **Everyone** | anyone on OpenMarket | | **Invite only** | only the people you invite: your community, your list | | **Just me** | only you, on your own charts | **Everyone** comes with a **Listed on OpenMarket** switch. On, the indicator shows up when people search. Off, it stays out of search and opens from its link. **Invite only** is the one for a community you run, paid or not. You decide who is on the list, and nobody else can add it ([Invite your community](invite-your-community.md)). You can switch between the three at any time, without publishing a new version. Moving to **Just me** removes everyone who had access ([Switch to Just me](invite-your-community.md#switch-to-just-me)). ## Code: who can read it | Choice | Where it runs | What people get | | --- | --- | --- | | **Protected** | on OpenMarket's servers | the result on their chart; nothing of yours downloads | | **Compiled** | in each person's browser | a compiled module, never your source | | **Open source** | in each person's browser | the code, to read and fork | **Invite only** starts on **Protected**, the choice for anything you sell. A Compiled module is downloaded by everyone with access, and a downloaded module can be copied. Only Protected keeps the code on OpenMarket's servers. **Invite only** cannot be **Open source**: with Invite only picked, the dialog greys Open source out ("Invite only keeps the code private."). Where it runs is set at the first publish and cannot change later. A Protected indicator stays on OpenMarket's servers, and one first published Compiled or Open source stays in the browser. To move an indicator to the other side, publish it under a new name ([Publishing](../functions/publishing.md#code-who-reads-it-and-where-it-runs)). ## Fair use Protected is free to run for your community within fair use: 1,000 people with access per Protected indicator. Past that, the next person you add, from the chart or from your own site, is refused with: ```text Fair use is 1,000 people. Talk to us for more. ``` ## Where you manage people An Invite only indicator has a **People** panel: everyone with access, the invite link, imports and access keys. Three buttons open it: - **Invite people…** on the receipt, right after you publish. - **People · N** on the indicator's page in the Indicators dialog, under **Mine**, where N is how many people have access. - **People** beside **Publish** in the editor, on the indicator's tab. ## Move a community in three steps 1. Publish the indicator **Invite only**, with **Protected** code. 2. Bring your member list ([Import a list](invite-your-community.md#import-a-list)). 3. Hand out one invite link ([The invite link](invite-your-community.md#the-invite-link)). Your members sign in, press **Add to chart**, and your code stays on OpenMarket's servers. If you sell through your own site, it can keep the list in sync as people pay and cancel ([Access keys and the API](access-keys-and-api.md)). ## In this section - [Invite your community](invite-your-community.md): invite people by name, share one invite link, import a list you already have, and keep the people list tidy. - [Access keys and the API](access-keys-and-api.md): let your own site add and remove people as they pay and cancel. - [Connect Discord or Whop](connect-discord-or-whop.md): keep the list in sync with a Whop store or a paid Discord role, with a small script you run. - [What members see](what-members-see.md): your invite from the other side, from the link to **Add to chart**. <!-- source: https://openmarket.xyz/wrun/sharing/invite-your-community --> # Invite your community Add people to an Invite only indicator by name, with one invite link, or from a list you already keep, all from its **People** panel. The panel opens from the receipt after you publish, from the indicator's page, or from the editor ([Where you manage people](overview.md#where-you-manage-people)). ## Invite by name **Invite people…** opens a search: "Search followers, tiers or a username". Pick the people, add a note if you like, and press **Send invites**. Each one has access at once. Someone who does not follow you is found by their full username: "Someone else? Type their full username to find anyone on OpenMarket." **Tiers.** A tier is a named group, such as Premium, that you invite to several indicators at once. **Manage groups** keeps your tiers, and a tier holds at most 200 members. ## The invite link One link for your whole community: post it where your members already are, and everyone who opens it can get in. **Invite link** is in the People panel's corner menu, and **People who open it** decides what happens: | Choice | What happens | | --- | --- | | **Ask to join** (the default) | each person asks, and you approve each request in the People panel | | **Join right away** | anyone with the link gets access when they sign in | Either way, the link can carry a limit (how many people may join with it) and an end date (**Works until**). Both are optional. **Make a new link** retires the old one: the old link stops working, so a link that leaked is closed in one click. A request shows in the People panel as "maya asked to join", with **Approve** and **Ignore**. ## Import a list **Import a list** takes the list you already have. Paste names and emails into the search, or drop a .csv or .txt file on the sheet. A file names each person by **Username** or by **Email**, and **Ends** is the day their access ends: ```text Username,Email,Ends maya,,2026-12-31 ,sam@example.com,2026-11-04 ``` Rows with a username get access at once. Rows with only an email become personal links: the import gives you a CSV with one link per address, and you send each one yourself. ```text email,url,until sam@example.com,<the personal link>,2026-11-04 ``` OpenMarket never emails your customers, and never tells you whether an email has an account. Your own name is skipped. When the import is done it counts who was invited, who already had access, and who is not on OpenMarket yet. That last group can join with your invite link. A person who opens their personal link signs in or signs up and lands on **Add to chart** ([What members see](what-members-see.md)). ## The people list The People panel lists everyone with access, with a search box and three views: | View | Shows | | --- | --- | | **All** | everyone with access | | **Ending soon** | people whose access ends soon | | **Not joined yet** | people who have not opened their personal link yet | Each row says since when and how the person got access, or until when it lasts: ```text Since <date> · Invited by you Since <date> · Invite link Since <date> · Access key Until <date> · Imported ``` A row's menu sets an end date, removes it, or removes the person. The list follows the account, not the name, so a member who renames their account keeps access. The corner menu holds **Invite link**, **Access key**, **Export list** and **History**. **Export list** downloads the list as a CSV. **History** shows who added, changed and removed whom, and when someone joined. ## Remove people **Remove access** on a row ends that person's access. The indicator stops loading for them, a Protected one within about 15 minutes ([When access ends](what-members-see.md#when-access-ends)). ## Switch to Just me Switching an Invite only indicator to **Just me** removes everyone and retires its links. Before it does, the prompt counts the people and the personal links nobody has opened yet separately, so you see both numbers before you confirm. <!-- source: https://openmarket.xyz/wrun/sharing/access-keys-and-api --> # Access keys and the API Let your own site keep the people list: an access key lets your server add and remove people on one Invite only indicator as they pay and cancel. ## Make a key In the People panel's corner menu, **Access key** opens the key sheet. Give the key a label (where it lives: your site, a script) and press **Create key**. - The key belongs to your account and to this one indicator. It can add, remove and list people there, and nothing else. - It is shown once. Copy it into your server's secret store. - **Revoke** stops it at once: calls with it fail from then on. - Make as many as you need, one per system, so each can be revoked on its own. Keep the key on your server. Never put it in a web page, an app or a public repository. ## The calls Every call goes to your indicator's address on the registry and carries the key as a bearer token: ```text Base URL https://registry.openmarket.xyz/v1/packages/@you/your-indicator Authorization Bearer <access key> PUT /access/<username> add someone, or change their end date DELETE /access/<username> remove someone GET /access/<username> check one person GET /access everyone with access, a page at a time POST /access/batch up to 500 adds and removes in one call POST /access/links/batch a personal link for each of your members GET /access/links.csv the personal links nobody has opened yet ``` `@you/your-indicator` is your indicator's full name: your username, then the name you published it under. The key sheet shows the address under **Calls go to**. ## Add someone ```text curl -X PUT "https://registry.openmarket.xyz/v1/packages/@you/your-indicator/access/maya" \ -H "Authorization: Bearer $ACCESS_KEY" \ -H "Content-Type: application/json" \ -d '{"until": "2027-01-01T00:00:00Z"}' ``` The body is optional: leave it out and access has no end date. A second PUT replaces the end date, so a renewal sends the new one. The answer is `200` with the person's row: ```json { "username": "maya", "account_id": "<account id>", "until": "2027-01-01T00:00:00Z", "since": "2026-10-05T09:12:33Z", "via": "api" } ``` Keep the `account_id`. It still finds the person after they rename their account. ## Remove someone ```text curl -X DELETE "https://registry.openmarket.xyz/v1/packages/@you/your-indicator/access/maya" \ -H "Authorization: Bearer $ACCESS_KEY" ``` The answer is `204` whether or not they were on the list, so a cancellation that arrives twice does no harm. ## Check and list `GET /access/<username>` answers `200` with the person's row, or `404` when they are not on the list. `GET /access` reads everyone, 50 rows a page by default and up to 200 with `limit`. Pass a page's `next_cursor` back as `cursor` to read the next one. `q` filters by name, and `view` picks `all`, `ending` (access ending soon) or `waiting` (personal links nobody has opened yet). ```text curl "https://registry.openmarket.xyz/v1/packages/@you/your-indicator/access?limit=200&view=all" \ -H "Authorization: Bearer $ACCESS_KEY" ``` ## Many at once `POST /access/batch` takes up to 500 adds and removes in one call: the first import of your member list, or a nightly check that the list still matches yours. Each `add` row works like a PUT (an `until` of `null` means no end date), and each `remove` like a DELETE. ```text curl -X POST "https://registry.openmarket.xyz/v1/packages/@you/your-indicator/access/batch" \ -H "Authorization: Bearer $ACCESS_KEY" \ -H "Content-Type: application/json" \ -d '{"add":[{"subject":"maya","until":null}],"remove":["sam"]}' ``` ## Personal links A member with no OpenMarket account yet gets a personal link instead. Ask for one per member, keyed by your own id for them: ```text curl -X POST "https://registry.openmarket.xyz/v1/packages/@you/your-indicator/access/links/batch" \ -H "Authorization: Bearer $ACCESS_KEY" \ -H "Content-Type: application/json" \ -d '{"links":[{"ref":"member-1042","until":null}]}' ``` Send each member their link yourself. When they open it, they sign in or sign up and get access. `GET /access/links.csv` downloads the links nobody has opened yet. ## Naming a person Wherever a call takes a username, it also takes two other forms. In a batch they go in `subject`. | You write | Means | | --- | --- | | `maya` | an OpenMarket username | | `id:<account id>` | the `account_id` a call returned; it still works after a rename | | `ref:<your reference>` | your own id for a member you sent a personal link | ## Errors An error comes back as `{"error": {"code": "...", "message": "..."}}`: | Status | Code | What it means | | --- | --- | --- | | 404 | `user_not_found` | No one on OpenMarket has that username. | | 422 | `not_invite_only` | The indicator is not Invite only. | | 403 | `fair_use` | The Protected indicator is at 1,000 people ([Fair use](overview.md#fair-use)). | | 429 | `rate_limited` | More than 600 writes in a minute on this key. Wait the seconds the `retry-after` header names. | ## Wire it to your billing Two calls cover a membership, keyed by the OpenMarket username you collect at checkout: - **On signup**, `PUT /access/<username>`, with `until` set to the date they have paid through. Send it again on each renewal, and access lapses on its own if a renewal never comes. - **On cancellation or refund**, `DELETE /access/<username>`. No username at checkout? Make each customer a personal link instead, and send it with your welcome email. Selling through Whop, or behind a paid Discord role? [Connect Discord or Whop](connect-discord-or-whop.md) has a small script for each. Selling with Stripe, on Patreon or through a paid Telegram group? [Ready-made recipes](recipes.md) has a complete file for each, ready to run. Webhooks get missed now and then. A nightly batch that compares the list with your own member table catches whatever slipped through. <!-- source: https://openmarket.xyz/wrun/sharing/recipes --> # Ready-made recipes Sell your Invite only indicator through Stripe, Patreon or a paid Telegram group, and one small file keeps its people list in step with who pays. Each recipe is one file: copy it to any server with Node 20 or later, set a few variables, and run it, with nothing to install. It calls your indicator's Access API with an access key ([Access keys and the API](access-keys-and-api.md)) and gives each paying member a personal link, keyed by the service's own id for them ([Personal links](access-keys-and-api.md#personal-links)). They open it, sign in or sign up, and have the indicator. When they stop paying, the file takes it away. | Recipe | You sell through | It runs as | | --- | --- | --- | | [Stripe](#stripe) | a Payment Link or Checkout, one-time or as a subscription | a small web server | | [Patreon](#patreon) | your Patreon tiers | a small web server your patrons log in through | | [Telegram bot](#telegram-bot) | a paid Telegram group or channel | a bot, with no public address needed | The code on this page is the code OpenMarket's tests run, byte for byte. ## Stripe Sell through a Stripe Payment Link or Checkout, one-time or as a subscription, and each buyer gets your indicator as soon as they pay. Only the prices you name count, so the same Stripe account can sell other things too. ### What it does - **Pays**: after paying, Stripe sends the buyer to your server, which sends them on to their personal link. They sign in or sign up on OpenMarket and have the indicator. - **Renews**: each paid invoice moves their end date to the new paid-through date, plus 3 days in case a renewal runs late. - **Cancels**: when Stripe ends the subscription, the indicator goes with it, unless another subscription of theirs still holds one of your prices. A one-time payment keeps it for good. ### Set it up 1. In the People panel's corner menu, make an **Access key** for your indicator ([Make a key](access-keys-and-api.md#make-a-key)). 2. In Stripe, on the **API keys** page, click **Create restricted key** and give it **Read** on Checkout Sessions, Subscriptions and Invoices. 3. On your Payment Link, under **After the payment**, redirect customers to your website at `https://<your server>/thanks?session_id={CHECKOUT_SESSION_ID}`. If your own code makes the Checkout Session, use that address as its `success_url`. Then copy the id of each price that gives the indicator (`price_...`): **More** > **Product catalog**, the product, its price. 4. In Workbench (in the **Developers** menu), on the **Webhooks** tab, add a destination for the events `invoice.paid` and `customer.subscription.deleted`, of type **Webhook endpoint**, at `https://<your server>/webhook`. Click **Reveal secret** and copy the signing secret. 5. Save the code below as `stripe.mjs`, set the variables in the table, and run `node stripe.mjs` (Node 20 or later, nothing to install) on a server that Stripe and your buyers reach over HTTPS. | Variable | What it is | | --- | --- | | `STRIPE_SECRET_KEY` | the restricted key from step 2 (`rk_live_...`) | | `STRIPE_WEBHOOK_SECRET` | the signing secret from step 4 (`whsec_...`) | | `STRIPE_PRICE_IDS` | the price ids from step 3, comma separated (`price_...`); only these give the indicator | | `OPENMARKET_KEY` | the access key from step 1 | | `OPENMARKET_INDICATOR` | your indicator's full name, like `@you/your-indicator` | | `PORT` | the port to listen on (3000 if unset) | ```js // Stripe: sell your Invite only Indicator with a Payment Link or Checkout, // one-time or as a subscription. // // A buyer pays, Stripe sends them to /thanks, and this server sends them on // to their personal link. They sign in on OpenMarket and have the Indicator. // Each paid renewal moves their end date. A subscription that ends takes the // Indicator away. A one-time payment keeps it for good. Only the prices you // list count: anything else you sell on the same Stripe account never does. // // Set these, then run `node stripe.mjs` (Node 20 or later, nothing to install): // STRIPE_SECRET_KEY a restricted key that can read Checkout Sessions, // Subscriptions and Invoices // STRIPE_WEBHOOK_SECRET your webhook's signing secret (whsec_...) // STRIPE_PRICE_IDS the prices that give the Indicator, comma separated // (price_...) // OPENMARKET_KEY your Indicator's access key // OPENMARKET_INDICATOR your Indicator's full name, like @you/your-indicator // PORT the port to listen on (3000 if unset) // // In Stripe, redirect the Payment Link's buyers after payment to // https://<your server>/thanks?session_id={CHECKOUT_SESSION_ID} // and send the webhook events invoice.paid and customer.subscription.deleted to // https://<your server>/webhook import { createHmac, timingSafeEqual } from "node:crypto"; import { realpathSync } from "node:fs"; import { createServer } from "node:http"; import { fileURLToPath } from "node:url"; const GRACE_DAYS = 3; // a late renewal never cuts a paying member off const TOLERANCE_SECONDS = 5 * 60; // the replay window Stripe's own libraries use /** Subscription statuses that keep the Indicator (past_due: Stripe is retrying a renewal). */ const HOLDING = ["active", "trialing", "past_due"]; // ── Stripe ────────────────────────────────────────────────────────────── /** Answers the buyer's redirect after paying, and Stripe's webhook. */ export async function handle(request) { const url = new URL(request.url); if (request.method === "GET" && url.pathname === "/thanks") { return thanks(url.searchParams.get("session_id")); } if (request.method === "POST" && url.pathname === "/webhook") return webhook(request); return new Response("Not found.", { status: 404 }); } /** The buyer lands here after paying, and goes on to their personal link. */ async function thanks(sessionId) { const session = /^cs_\w+$/.test(sessionId ?? "") ? await stripe( `checkout/sessions/${sessionId}?expand[]=line_items&expand[]=subscription.latest_invoice`, ) : null; if (session === null) return page(404, "We could not find this payment."); const prices = configuredPrices(); const paid = session.status === "complete" && ["paid", "no_payment_required"].includes(session.payment_status) && (session.line_items?.data ?? []).some((item) => prices.has(item.price?.id)); // A one-time payment never ends. A subscription runs to what its latest invoice paid // for, and while that invoice is unpaid, /thanks gives out nothing. const subscription = session.subscription; // expanded, with its latest invoice let until; if (session.mode === "payment") until = null; else if (HOLDING.includes(subscription?.status)) until = paidThrough(subscription); if (!paid || until === undefined) { return page(402, "Payment not confirmed yet, or it has ended. Just paid? Reload in a minute."); } // A subscriber is their Stripe customer. A one-time payment through a Payment Link // usually has no customer (Stripe keeps a guest instead), so the session is the ref. const ref = `stripe-${session.customer ?? session.id}`; return Response.redirect(await personalLink(ref, until), 303); } /** A paid invoice moves the member's end date (and makes their link, if they closed * the tab before /thanks). An ended subscription takes the Indicator away. Both read * the subscription from Stripe now rather than trust the event: Stripe does not send * events in order, and a late one must not undo a newer one. */ async function webhook(request) { const body = await request.text(); if (!signedByStripe(request.headers.get("stripe-signature"), body)) { return new Response("Bad signature.", { status: 400 }); } const { type, data } = JSON.parse(body); const object = data.object; if (type === "invoice.paid") { // From API version 2025-03-31 (basil) on, an invoice names its subscription under // `parent`; before, at the top. Read both. Neither means a one-off invoice. const id = object.parent?.subscription_details?.subscription ?? object.subscription; const subscription = id ? await stripe(`subscriptions/${id}?expand[]=latest_invoice`) : null; if (subscription !== null && holds(subscription)) await moveEndDate(subscription); } if (type === "customer.subscription.deleted" && sells(object)) { // The customer may hold one of your prices on another subscription: then they keep it. const customer = encodeURIComponent(object.customer); const theirs = await stripe(`subscriptions?customer=${customer}&expand[]=data.latest_invoice`); const other = (theirs?.data ?? []).find((sub) => sub.id !== object.id && holds(sub)); if (other) await moveEndDate(other); else await removeMember(`stripe-${object.customer}`); } return new Response("OK"); // every other event is ignored } /** Moves the member's end date to what `subscription` is paid through. While its * latest invoice is unpaid, the end date stays where it is. */ async function moveEndDate(subscription) { const until = paidThrough(subscription); if (until !== undefined) await personalLink(`stripe-${subscription.customer}`, until); } /** What a subscription is paid through, plus the grace days: the end of the period its * latest invoice paid for. Undefined while that invoice is unpaid (a renewal Stripe is * still collecting, though it already opened the next period). */ function paidThrough(subscription) { const invoice = subscription.latest_invoice; if (invoice?.status !== "paid") return undefined; const ends = (invoice.lines?.data ?? []) .filter((line) => lineSubscription(line) === subscription.id) .map((line) => line.period?.end); return endDate(ends); } /** The subscription an invoice line bills for. From API version 2025-03-31 (basil) on it * sits under the line's `parent`; before, at the top of the line. */ function lineSubscription(line) { return ( line.parent?.subscription_item_details?.subscription ?? line.parent?.invoice_item_details?.subscription ?? line.subscription ); } /** A subscription that holds one of your prices, in a status that keeps the Indicator. */ function holds(subscription) { return HOLDING.includes(subscription.status) && sells(subscription); } /** Whether a subscription holds one of your prices. */ function sells(subscription) { const prices = configuredPrices(); return (subscription.items?.data ?? []).some((item) => prices.has(item.price?.id)); } /** STRIPE_PRICE_IDS: the prices that give the Indicator. Nothing else on the account counts. */ function configuredPrices() { const ids = (process.env.STRIPE_PRICE_IDS ?? "") .split(",") .map((id) => id.trim()) .filter(Boolean); if (ids.length === 0) throw new Error("Set STRIPE_PRICE_IDS to the prices that give the Indicator"); return new Set(ids); } /** GET from Stripe's API with the restricted key; null when Stripe has no such object. */ async function stripe(path) { const res = await fetch(`https://api.stripe.com/v1/${path}`, { headers: { authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` }, }); if (res.status === 404) return null; if (!res.ok) throw new Error(`Stripe ${path} answered ${res.status}: ${await res.text()}`); return res.json(); } /** Stripe's check, as its docs lay it out: Stripe-Signature holds `t=<unix seconds>` and * one `v1=<hex>` per active signing secret, each an HMAC-SHA256 of `<t>.<raw body>` * keyed by the whole whsec_ secret. A timestamp more than 5 minutes off is refused, so * a captured event cannot be replayed later. */ function signedByStripe(header, body) { const pairs = (header ?? "").split(",").map((part) => part.split("=")); const t = pairs.find(([key]) => key === "t")?.[1]; if (!(Math.abs(Date.now() / 1000 - Number(t)) <= TOLERANCE_SECONDS)) return false; const hmac = createHmac("sha256", process.env.STRIPE_WEBHOOK_SECRET).update(`${t}.${body}`); const expected = Buffer.from(hmac.digest("hex")); return pairs.some(([key, value = ""]) => { const given = Buffer.from(value); return key === "v1" && given.length === expected.length && timingSafeEqual(given, expected); }); } /** The latest of `periodEnds` (Unix seconds) plus the grace days, as an ISO date. */ function endDate(periodEnds) { const end = Math.max(...periodEnds.filter(Number.isFinite)); if (!Number.isFinite(end)) throw new Error("Stripe sent no period end"); return new Date((end + GRACE_DAYS * 24 * 60 * 60) * 1000).toISOString(); } /** A short page for a buyer with no link to go to. */ function page(status, text) { return new Response(`<!doctype html><meta charset="utf-8"><title>Payment

${text}

`, { status, headers: { "content-type": "text/html; charset=utf-8" }, }); } // ── OpenMarket ────────────────────────────────────────────────────────── // Your Indicator's Access API, called with its access key. function openmarketUrl(path) { const registry = process.env.OPENMARKET_REGISTRY ?? "https://registry.openmarket.xyz"; return `${registry}/v1/packages/${process.env.OPENMARKET_INDICATOR}${path}`; } async function openmarket(method, path, body) { const res = await fetch(openmarketUrl(path), { method, headers: { authorization: `Bearer ${process.env.OPENMARKET_KEY}`, ...(body === undefined ? {} : { "content-type": "application/json" }), }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!res.ok) throw new Error(`OpenMarket ${method} ${path} answered ${res.status}: ${await res.text()}`); return res.status === 204 ? null : res.json(); } /** The member's personal link, keyed by your own id for them. The same ref always * answers the same link, and a new `until` moves their end date, joined or not. */ async function personalLink(ref, until) { const { links } = await openmarket("POST", "/access/links/batch", { links: [{ ref, until }] }); return links[0].url; } /** Take the Indicator away from the member behind `ref` (harmless if they never joined). */ async function removeMember(ref) { await openmarket("DELETE", `/access/ref:${encodeURIComponent(ref)}`); } // ── Server ────────────────────────────────────────────────────────────── // `node .mjs` serves `handle` on $PORT (3000 by default). const MAX_BODY_BYTES = 1024 * 1024; // a webhook or a redirect is a few KB if (isMainModule()) { const port = Number(process.env.PORT ?? 3000); createServer(async (req, res) => { // Until the request is read and built, a failure is the caller's (400): a method // fetch refuses, a target it cannot parse, a caller who hung up midway. From then // on it is this server's (500). Either way the server stays up. let failure = 400; try { const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size <= MAX_BODY_BYTES) chunks.push(chunk); // past the cap, read on and keep nothing } if (size > MAX_BODY_BYTES) { res.writeHead(413).end("Too large."); return; } const hasBody = req.method !== "GET" && req.method !== "HEAD"; const request = new Request(`http://localhost${req.url}`, { method: req.method, headers: Object.entries(req.headers).flatMap(([k, v]) => Array.isArray(v) ? v.map((x) => [k, x]) : [[k, v]], ), body: hasBody ? Buffer.concat(chunks) : undefined, }); failure = 500; const response = await handle(request); res.writeHead(response.status, Object.fromEntries(response.headers)); res.end(Buffer.from(await response.arrayBuffer())); } catch (error) { console.error(error); if (res.headersSent) res.destroy(); else res.writeHead(failure).end(failure === 400 ? "Bad request." : "Something went wrong."); } }).listen(port, () => console.log(`Listening on :${port}`)); } /** Whether `node` was asked to run this file, by its own path or through a link * (on macOS, /tmp itself is a link to /private/tmp). */ function isMainModule() { try { return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; // no file to run: a REPL, or node -e } } ``` ### Try it before you go live 1. In a Stripe sandbox, repeat steps 2 and 3 with a test key and a test Payment Link that redirects to where the file runs. Run `stripe listen --forward-to localhost:3000/webhook`, and start the file with the `whsec_...` secret it prints. 2. Pay through the test link with the card `4242 4242 4242 4242`, any future date and any CVC. You land on your personal link: open it, and the indicator is yours. 3. `stripe trigger customer.subscription.created --override "subscription:items[0].price="` sends a test subscriber's first paid invoice, and the same with `customer.subscription.deleted` a cancellation. `stripe listen` shows your server answer `[200]` to each event. ### Good to know - A subscriber who closes the tab before the redirect still has a link waiting, made by their first paid invoice. It is under **Not joined yet** in the People panel and in `GET /access/links.csv`: send it to them. A one-time buyer's link comes only from the redirect, so add that buyer with **Invite people…** instead. - Each end date comes from an invoice Stripe has been paid, read when the event arrives, so events that come late or out of order change nothing, and a renewal still being collected moves nothing until it is paid. - Selling the indicator both one-time and as a subscription? A buyer who does both as the same Stripe customer gets one link, and the end of their subscription ends it. ## Patreon Give your Invite only indicator to your Patreon patrons: each one logs in with Patreon on a small server you run and lands on their own personal link. ### What it does - **Pledges**: a patron opens the link in your tier's welcome note, logs in with Patreon and lands on their personal link. They sign in or sign up on OpenMarket and have the indicator. - **Renews**: each charge moves their end date to 3 days past the next one. - **Stops paying**: a declined charge, an ended pledge or a deleted membership takes the indicator away. ### Set it up 1. In the Patreon Platform Portal, open **Clients & API Keys** and press **Create Client**. Set **Client API Version** to 2, add `https:///patreon/callback` under **Redirect URIs**, and copy the **Client ID** and **Client Secret**. 2. Find your campaign id with the new client's **Creator's Access Token**. The same call lists your tiers, for when only some of them come with the indicator: ```text curl -H "Authorization: Bearer " \ "https://www.patreon.com/api/oauth2/v2/campaigns?include=tiers&fields%5Btier%5D=title" ``` `data[0].id` is your campaign id, and each tier under `included` shows its `id` and `title`. 3. In **My Webhooks**, paste `https:///patreon/webhook` where it says "Create a new webhook by pasting your URL here" and press **+**. Turn on **Create Member**, **Update Member** and **Delete Member**, and copy the webhook's secret. 4. Save the code below as `patreon.mjs` on a server Patreon can reach over HTTPS, set the variables in the table, and run `node patreon.mjs` (Node 20 or later, nothing to install). 5. Add `https:///patreon` to the welcome note of each tier that comes with the indicator. | Variable | What it is | | --- | --- | | `PATREON_CLIENT_ID` | your client's **Client ID** | | `PATREON_CLIENT_SECRET` | your client's **Client Secret** | | `PATREON_CAMPAIGN_ID` | your campaign id, from step 2 | | `PATREON_WEBHOOK_SECRET` | your webhook's secret, from **My Webhooks** | | `PATREON_TIER_IDS` | optional: the ids of the tiers that come with the indicator, comma separated. Leave it out and every active patron gets it | | `PUBLIC_URL` | your server's HTTPS address, like `https://patrons.example.com` | | `OPENMARKET_KEY` | your indicator's access key, from **Access key** in its People panel | | `OPENMARKET_INDICATOR` | your indicator's full name, like `@you/your-indicator` | | `PORT` | the port to listen on (3000 if unset) | ```js // Patreon: give your Invite only Indicator to your patrons. // // Patreon does not know your patrons' OpenMarket accounts, so a patron // proves who they are with "Log in with Patreon" on this small server, and // it sends them on to their own personal link. A webhook keeps their end // date in step with Patreon: a renewal moves it, and a declined, ended or // deleted pledge takes the Indicator away. // // Put /patreon in your tier's welcome note. Patreon sends // patrons back to /patreon/callback, and your webhook points at // /patreon/webhook. // // Set: // PATREON_CLIENT_ID your client's Client ID (Clients & API Keys) // PATREON_CLIENT_SECRET your client's Client Secret // PATREON_CAMPAIGN_ID your campaign's id // PATREON_WEBHOOK_SECRET your webhook's secret (My Webhooks) // PATREON_TIER_IDS optional: only these tiers get the Indicator, // as a comma separated list of tier ids // PUBLIC_URL this server's https address // OPENMARKET_KEY your Indicator's access key // OPENMARKET_INDICATOR your Indicator's full name, @you/your-indicator // PORT 3000 by default // // Run: node patreon.mjs (Node 20 or later, nothing to install). import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { realpathSync } from "node:fs"; import { createServer } from "node:http"; import { fileURLToPath } from "node:url"; /** Days added to Patreon's next charge, so a late renewal never cuts a paying patron off. */ const GRACE_DAYS = 3; /** The patron's memberships, each with its campaign, its tiers, its status and its charges. */ const IDENTITY_URL = "https://www.patreon.com/api/oauth2/v2/identity" + "?include=memberships.campaign,memberships.currently_entitled_tiers" + "&fields%5Bmember%5D=patron_status,next_charge_date,last_charge_date,pledge_cadence"; /** Every request this server answers. */ export async function handle(request) { const { pathname } = new URL(request.url); if (request.method === "GET" && pathname === "/patreon") return logIn(); if (request.method === "GET" && pathname === "/patreon/callback") return callback(request); if (request.method === "POST" && pathname === "/patreon/webhook") return webhook(request); return new Response("Not found.", { status: 404 }); } // ── Log in with Patreon ───────────────────────────────────────────────── /** Send the patron to Patreon, with a one-time state kept in a cookie. */ function logIn() { const state = randomBytes(16).toString("hex"); const authorize = new URL("https://www.patreon.com/oauth2/authorize"); authorize.search = new URLSearchParams({ response_type: "code", client_id: process.env.PATREON_CLIENT_ID, redirect_uri: redirectUri(), scope: "identity identity.memberships", state, }).toString(); const secure = process.env.PUBLIC_URL?.startsWith("https:") ? "; Secure" : ""; return new Response(null, { status: 302, headers: { location: authorize.href, "set-cookie": `patreon_state=${state}; Path=/patreon; HttpOnly; SameSite=Lax; Max-Age=600${secure}`, }, }); } /** Patreon sends the patron back here: find their pledge and send them to their link. */ async function callback(request) { const url = new URL(request.url); const code = url.searchParams.get("code"); const cookie = /(?:^|;\s*)patreon_state=([0-9a-f]+)/.exec(request.headers.get("cookie") ?? ""); if (!code || !sameText(url.searchParams.get("state"), cookie?.[1])) { return page(400, "Patreon did not sign you in. Open the link from Patreon and try again."); } const token = await patreon("https://www.patreon.com/api/oauth2/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ code, grant_type: "authorization_code", client_id: process.env.PATREON_CLIENT_ID, client_secret: process.env.PATREON_CLIENT_SECRET, redirect_uri: redirectUri(), }), }); const identity = await patreon(IDENTITY_URL, { headers: { authorization: `Bearer ${token.access_token}` }, }); const member = identity.included?.find((item) => item.type === "member" && entitled(item)); if (member === undefined) { return page(403, "Your Patreon account has no active pledge that includes this Indicator."); } const ref = `patreon-${identity.data.id}`; const link = await personalLink(ref, await endDate(member, ref)); return new Response(null, { status: 303, headers: { location: link } }); } // ── Webhook ───────────────────────────────────────────────────────────── /** A renewal moves the end date; a declined, ended or deleted pledge removes the Indicator. */ async function webhook(request) { const body = Buffer.from(await request.arrayBuffer()); const secret = process.env.PATREON_WEBHOOK_SECRET; // Patreon signs the raw body: HMAC-MD5 keyed by the webhook's secret, as hex. const expected = secret ? createHmac("md5", secret).update(body).digest("hex") : ""; if (!sameText(request.headers.get("x-patreon-signature")?.toLowerCase(), expected)) { return new Response("Bad signature.", { status: 400 }); } const event = request.headers.get("x-patreon-event") ?? ""; const member = JSON.parse(body.toString()).data; const userId = member?.relationships?.user?.data?.id; if (!event.startsWith("members:") || !userId || !inCampaign(member)) { return new Response("Ignored."); } const ref = `patreon-${userId}`; if (event.endsWith(":delete") || !entitled(member)) await removeMember(ref); else await personalLink(ref, await endDate(member, ref)); return new Response("Done."); } // ── Patreon ───────────────────────────────────────────────────────────── async function patreon(url, init) { const res = await fetch(url, init); if (!res.ok) { throw new Error(`Patreon ${new URL(url).pathname} answered ${res.status}: ${await res.text()}`); } return res.json(); } /** A membership of your campaign. */ function inCampaign(member) { return member.relationships?.campaign?.data?.id === process.env.PATREON_CAMPAIGN_ID; } /** An active patron of your campaign, in one of PATREON_TIER_IDS when you set it. */ function entitled(member) { if (!inCampaign(member) || member.attributes?.patron_status !== "active_patron") return false; const tiers = (process.env.PATREON_TIER_IDS ?? "") .split(",") .map((id) => id.trim()) .filter(Boolean); const held = member.relationships?.currently_entitled_tiers?.data ?? []; return tiers.length === 0 || held.some((tier) => tiers.includes(tier.id)); } /** The end date to send, never none, so access always runs out without a renewal: * Patreon's next charge plus GRACE_DAYS. Without one (Patreon leaves it out on an * annual downgrade), the last charge plus one pledge cadence (in months) plus * GRACE_DAYS. Without either, a patron who already joined keeps the end date they * have (undefined leaves it as it is), and a new one gets a month plus GRACE_DAYS. */ async function endDate(member, ref) { const { next_charge_date: next, last_charge_date: last, pledge_cadence: cadence, } = member.attributes ?? {}; let paidThrough = next ? new Date(next) : null; if (!paidThrough && last && Number(cadence) > 0) { paidThrough = addMonths(new Date(last), Number(cadence)); } if (!paidThrough) { if (await joined(ref)) return undefined; paidThrough = addMonths(new Date(), 1); } return new Date(paidThrough.getTime() + GRACE_DAYS * 24 * 60 * 60 * 1000).toISOString(); } function addMonths(date, months) { const later = new Date(date); later.setUTCMonth(later.getUTCMonth() + months); return later; } /** Whether the patron behind `ref` already opened their link and holds the Indicator. */ async function joined(ref) { const path = `/access/ref:${encodeURIComponent(ref)}`; const res = await fetch(openmarketUrl(path), { headers: { authorization: `Bearer ${process.env.OPENMARKET_KEY}` }, }); if (res.status === 404) return false; if (!res.ok) throw new Error(`OpenMarket GET ${path} answered ${res.status}: ${await res.text()}`); return true; } function redirectUri() { return `${(process.env.PUBLIC_URL ?? "").replace(/\/+$/, "")}/patreon/callback`; } /** Compares two secrets in constant time. */ function sameText(a, b) { if (!a || !b) return false; const left = Buffer.from(a); const right = Buffer.from(b); return left.length === right.length && timingSafeEqual(left, right); } /** A short plain page for the patron. */ function page(status, message) { return new Response( `\n\nPatreon\n

${message}

\n`, { status, headers: { "content-type": "text/html; charset=utf-8" }, }, ); } // ── OpenMarket ────────────────────────────────────────────────────────── // Your Indicator's Access API, called with its access key. function openmarketUrl(path) { const registry = process.env.OPENMARKET_REGISTRY ?? "https://registry.openmarket.xyz"; return `${registry}/v1/packages/${process.env.OPENMARKET_INDICATOR}${path}`; } async function openmarket(method, path, body) { const res = await fetch(openmarketUrl(path), { method, headers: { authorization: `Bearer ${process.env.OPENMARKET_KEY}`, ...(body === undefined ? {} : { "content-type": "application/json" }), }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!res.ok) throw new Error(`OpenMarket ${method} ${path} answered ${res.status}: ${await res.text()}`); return res.status === 204 ? null : res.json(); } /** The member's personal link, keyed by your own id for them. The same ref always * answers the same link, and a new `until` moves their end date, joined or not. */ async function personalLink(ref, until) { const { links } = await openmarket("POST", "/access/links/batch", { links: [{ ref, until }] }); return links[0].url; } /** Take the Indicator away from the member behind `ref` (harmless if they never joined). */ async function removeMember(ref) { await openmarket("DELETE", `/access/ref:${encodeURIComponent(ref)}`); } // ── Server ────────────────────────────────────────────────────────────── // `node .mjs` serves `handle` on $PORT (3000 by default). const MAX_BODY_BYTES = 1024 * 1024; // a webhook or a redirect is a few KB if (isMainModule()) { const port = Number(process.env.PORT ?? 3000); createServer(async (req, res) => { // Until the request is read and built, a failure is the caller's (400): a method // fetch refuses, a target it cannot parse, a caller who hung up midway. From then // on it is this server's (500). Either way the server stays up. let failure = 400; try { const chunks = []; let size = 0; for await (const chunk of req) { size += chunk.length; if (size <= MAX_BODY_BYTES) chunks.push(chunk); // past the cap, read on and keep nothing } if (size > MAX_BODY_BYTES) { res.writeHead(413).end("Too large."); return; } const hasBody = req.method !== "GET" && req.method !== "HEAD"; const request = new Request(`http://localhost${req.url}`, { method: req.method, headers: Object.entries(req.headers).flatMap(([k, v]) => Array.isArray(v) ? v.map((x) => [k, x]) : [[k, v]], ), body: hasBody ? Buffer.concat(chunks) : undefined, }); failure = 500; const response = await handle(request); res.writeHead(response.status, Object.fromEntries(response.headers)); res.end(Buffer.from(await response.arrayBuffer())); } catch (error) { console.error(error); if (res.headersSent) res.destroy(); else res.writeHead(failure).end(failure === 400 ? "Bad request." : "Something went wrong."); } }).listen(port, () => console.log(`Listening on :${port}`)); } /** Whether `node` was asked to run this file, by its own path or through a link * (on macOS, /tmp itself is a link to /private/tmp). */ function isMainModule() { try { return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; // no file to run: a REPL, or node -e } } ``` ### Try it before you go live Patreon has no test mode, so use its test send and a real pledge of your own: 1. In **My Webhooks**, press **Send test** on **Update Member**. Patreon signs the sample event with your secret, and your server answers 200 when `PATREON_WEBHOOK_SECRET` matches it (400 when it does not). 2. From a second Patreon account, join your lowest tier. Open `https:///patreon`, log in with Patreon as that account, and sign in on OpenMarket with a second account: the indicator is under **Shared with you**. 3. Cancel that pledge. When Patreon ends it, the second account drops off your People list. ### Good to know - A patron who closed the tab opens `https:///patreon` again and lands on the same link. One who lost the indicator to a declined charge does the same after paying, and gets a fresh link. - Webhooks get missed now and then. The end date is your safety net: without a renewal, access ends 3 days after the charge that never came. - Logging in asks each patron to share their Patreon memberships, so the server can find the one in your campaign. It keeps nothing, and uses the Patreon login once. ## Telegram bot Sell access through a paid Telegram group or channel, and a small bot gives each member your indicator while they are in it. ### What it does - **Joins**: a member of your paid group or channel sends your bot `/start` and gets a personal link. Opening it gives them the indicator. - **Stays**: they keep it while they stay in the group or channel. - **Leaves**: they lose it when they leave or you remove them. ### Set it up 1. In Telegram, open @BotFather, send `/newbot`, and pick a name and a username. BotFather answers with your bot's token. Keep it secret: anyone with it controls your bot. 2. Add the bot to your paid group or channel and make it an admin. Only an admin sees who leaves, so this step matters. 3. Right after, open `https://api.telegram.org/bot/getUpdates` in your browser. The negative number after `"chat":{"id":`, like `-1001234567890`, is your chat's id. 4. In your indicator's People panel, open **Access key** in the corner menu and press **Create key**. 5. Save the code below as `telegram-bot.mjs`, set the variables in the table, and run `node telegram-bot.mjs` (Node 20 or later, nothing to install) on any computer or server that stays on. It needs no public address. | Variable | What it is | | --- | --- | | `TELEGRAM_BOT_TOKEN` | your bot's token, from @BotFather | | `TELEGRAM_CHAT_ID` | your paid group's or channel's id, like `-1001234567890` | | `OPENMARKET_KEY` | the access key from step 4 | | `OPENMARKET_INDICATOR` | your indicator's full name, like `@you/your-indicator` | ```js // Telegram bot: the members of your paid Telegram group or channel get your // Invite only Indicator, and lose it when they leave. // // A member sends your bot /start. While they are in the paid group or channel, // the bot answers with their personal link: they open it, sign in or sign up // on OpenMarket, and the Indicator is theirs. When they leave or are removed, // the bot takes it away. // // Set these, then run `node telegram-bot.mjs` (Node 20 or later): // TELEGRAM_BOT_TOKEN your bot's token, from @BotFather // TELEGRAM_CHAT_ID the paid group or channel, like -1001234567890 // (make the bot an admin there: only admins see who leaves) // OPENMARKET_KEY an access key on your Indicator // OPENMARKET_INDICATOR your Indicator's full name, like @you/your-indicator // // The bot asks Telegram for its updates (long polling), so it needs no public // address and runs anywhere. import { realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; // ── OpenMarket ────────────────────────────────────────────────────────── // Your Indicator's Access API, called with its access key. function openmarketUrl(path) { const registry = process.env.OPENMARKET_REGISTRY ?? "https://registry.openmarket.xyz"; return `${registry}/v1/packages/${process.env.OPENMARKET_INDICATOR}${path}`; } async function openmarket(method, path, body) { const res = await fetch(openmarketUrl(path), { method, headers: { authorization: `Bearer ${process.env.OPENMARKET_KEY}`, ...(body === undefined ? {} : { "content-type": "application/json" }), }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!res.ok) throw new Error(`OpenMarket ${method} ${path} answered ${res.status}: ${await res.text()}`); return res.status === 204 ? null : res.json(); } /** The member's personal link, keyed by your own id for them. The same ref always * answers the same link, and a new `until` moves their end date, joined or not. */ async function personalLink(ref, until) { const { links } = await openmarket("POST", "/access/links/batch", { links: [{ ref, until }] }); return links[0].url; } /** Take the Indicator away from the member behind `ref` (harmless if they never joined). */ async function removeMember(ref) { await openmarket("DELETE", `/access/ref:${encodeURIComponent(ref)}`); } // ── Telegram ──────────────────────────────────────────────────────────── // The Bot API, called with your bot's token. async function telegram(method, params) { const url = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}/${method}`; const res = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(params), }); const { ok, result, description } = await res.json(); if (!ok) throw new Error(`Telegram ${method}: ${description}`); return result; } /** Whether a chat member is in the chat now: the owner, an admin, a member, * or a restricted member who has not left. */ function isIn(member) { return ( ["creator", "administrator", "member"].includes(member.status) || (member.status === "restricted" && member.is_member) ); } // ── The bot ───────────────────────────────────────────────────────────── /** /start: the member's personal link, while they are in the paid chat. */ async function start(message) { const reply = (text, reply_markup) => telegram("sendMessage", { chat_id: message.chat.id, text, reply_markup }); try { const member = await telegram("getChatMember", { chat_id: process.env.TELEGRAM_CHAT_ID, user_id: message.from.id, }); if (isIn(member)) { const url = await personalLink(`telegram-${message.from.id}`, null); await reply("Open your personal link and sign in to OpenMarket to get the Indicator.", { inline_keyboard: [[{ text: "Get the Indicator", url }]], }); } else { await reply("Join the paid group or channel first, then send /start again."); } } catch (error) { // The member can send /start again, so a failure here holds up nothing behind it. console.error(error); await reply("Something went wrong. Send /start again in a minute.").catch(console.error); } } /** One update: answer /start in a private chat, and take the Indicator from * whoever leaves the paid chat or is removed from it. A removal that fails * throws, so Telegram hands the update over again on the next poll. */ export async function handleUpdate(update) { const { message, chat_member: change } = update; if (message?.chat.type === "private" && message.text?.startsWith("/start")) { await start(message); } if (change && String(change.chat.id) === process.env.TELEGRAM_CHAT_ID) { const { new_chat_member: member } = change; if (!isIn(member)) await removeMember(`telegram-${member.user.id}`); } } /** One long poll: waits up to 50 seconds for updates, handles each, and returns * the offset for the next poll. Leaves go first: a removal that fails throws * before any reply goes out, so the retry repeats nothing a member sees. */ export async function pollOnce(offset) { const updates = await telegram("getUpdates", { offset, timeout: 50, allowed_updates: ["message", "chat_member"], }); for (const update of updates) if (update.chat_member) await handleUpdate(update); for (const update of updates) if (!update.chat_member) await handleUpdate(update); return Math.max(offset, ...updates.map((update) => update.update_id + 1)); } // ── Run ───────────────────────────────────────────────────────────────── // `node telegram-bot.mjs` checks the bot is an admin of the paid chat, then // polls until you stop it. if (isMainModule()) { const bot = await telegram("getMe", {}); const self = await telegram("getChatMember", { chat_id: process.env.TELEGRAM_CHAT_ID, user_id: bot.id, }); if (self.status !== "administrator") { console.error(`Make @${bot.username} an admin of the paid chat: only admins see who leaves.`); process.exit(1); } console.log(`@${bot.username} is answering /start`); let offset = 0; for (;;) { try { offset = await pollOnce(offset); } catch (error) { console.error(error); await new Promise((resolve) => setTimeout(resolve, 5000)); } } } /** Whether `node` was asked to run this file, by its own path or through a link * (on macOS, /tmp itself is a link to /private/tmp). */ function isMainModule() { try { return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url); } catch { return false; // no file to run: a REPL, or node -e } } ``` ### Try it before you go live 1. Make a test group in Telegram, add your bot to it as an admin, and run the bot with `TELEGRAM_CHAT_ID` set to the test group's id. 2. From a second Telegram account, join the group and send your bot `/start`. Open the link signed in to a second OpenMarket account: the indicator is under **Shared with you** in the Indicators dialog. 3. Leave the group from that account. They drop off your People panel. ### Good to know - The Bot API cannot list a group's members, so the bot follows leaves as they happen. People already in the group when you start the bot send `/start` like anyone else. - While the bot is down, Telegram keeps its updates for up to 24 hours. Restart it within a day: anyone who left during a longer outage keeps the indicator until you remove them in the People panel. - A personal link works for the first OpenMarket account that opens it. Someone who leaves and comes back sends `/start` again. # Connect Discord or Whop Sell access through Whop or a paid Discord role, and a small script you run uses an access key to keep your indicator's people list in sync. There is no official connector. This is a small script you run yourself, on your own server, and OpenMarket's side is two calls. ## The idea When someone gains access on your side, add them. When they lose it, remove them: ```text Base URL https://registry.openmarket.xyz/v1/packages/@you/your-indicator Authorization Bearer PUT /access/ they paid, or got the role: 200 DELETE /access/ they left, or lost the role: 204, always ``` A PUT can carry `{"until": ""}` to end access on a date. Without it, access lasts until your DELETE. Both calls are safe to repeat, so an event that arrives twice does no harm. The key comes from the People panel ([Make a key](access-keys-and-api.md#make-a-key)). ## Collect each member's username The calls name a person by their OpenMarket username, so that is the one thing you must collect. Ask once, and keep it beside the customer: - **Whop**: add a custom field to your checkout that asks for it. The answer arrives with the membership. - **Discord**: members type `/openmarket ` in your server, and the bot below saves it. Or skip usernames: make each customer a personal link keyed by your own `ref` ([Personal links](access-keys-and-api.md#personal-links)) and send it to them yourself. They join by opening it, and `DELETE /access/ref:` removes them later. ## Whop Whop calls your server with a webhook when a membership changes. Subscribe it to `membership.updated`: Whop sends it when a membership activates and when it deactivates, with the membership's current `status`. The handler checks Whop's signature, adds the member while the status keeps access (`trialing`, `active`, `past_due`, `completed`), and removes them when it is `canceled` or `expired`. 1. In the Developer tab of your Whop dashboard, create a webhook for `membership.updated` that points at your server, and copy its secret. 2. Save the handler as `whop.mjs`. Set `OPENMARKET_ACCESS_KEY`, and `WHOP_WEBHOOK_SECRET` to the `ws_` secret exactly as Whop shows it. 3. Run `node whop.mjs` (Node 18 or later) where Whop can reach it. ```javascript import { createHmac, timingSafeEqual } from "node:crypto"; import { createServer } from "node:http"; const PACKAGE = "@you/your-indicator"; // your indicator's full name const QUESTION = "OpenMarket username"; // the label of your Whop checkout field const KEEP = ["trialing", "active", "past_due", "completed"]; // Whop statuses with access const END = ["canceled", "expired"]; // Whop statuses without it const ACCESS = `https://registry.openmarket.xyz/v1/packages/${PACKAGE}/access`; // PUT or DELETE one person. false: no OpenMarket account has that username. async function access(method, username) { const res = await fetch(`${ACCESS}/${encodeURIComponent(username)}`, { method, headers: { Authorization: `Bearer ${process.env.OPENMARKET_ACCESS_KEY}` }, }); if (res.ok) return true; const { error } = await res.json().catch(() => ({})); if (error?.code === "user_not_found") return false; throw new Error(`${method} ${username}: ${res.status} ${error?.code ?? ""}`); } // Whop signs ".." with HMAC-SHA256, keyed // by the whole ws_ secret, and sends "v1," in webhook-signature. function signedByWhop(headers, body) { const { "webhook-id": id, "webhook-timestamp": sent, "webhook-signature": signatures = "" } = headers; if (!id || !(Math.abs(Date.now() / 1000 - Number(sent)) <= 300)) return false; const hmac = createHmac("sha256", process.env.WHOP_WEBHOOK_SECRET).update(`${id}.${sent}.${body}`); const expected = Buffer.from(`v1,${hmac.digest("base64")}`); return signatures.split(" ").some((entry) => { const given = Buffer.from(entry); return given.length === expected.length && timingSafeEqual(given, expected); }); } // The member's answer to your checkout field. function usernameOf(membership) { return membership.custom_field_responses?.find((field) => field.question === QUESTION)?.answer.trim(); } createServer(async (req, res) => { const chunks = []; for await (const chunk of req) chunks.push(chunk); const body = Buffer.concat(chunks).toString(); if (!signedByWhop(req.headers, body)) return res.writeHead(401).end(); const { type, data } = JSON.parse(body); const username = type === "membership.updated" ? usernameOf(data) : undefined; try { if (username && KEEP.includes(data.status) && !(await access("PUT", username))) { console.warn(`${username} is not an OpenMarket username (Whop membership ${data.id})`); } if (username && END.includes(data.status)) await access("DELETE", username); res.writeHead(200).end(); } catch (error) { console.error(error); res.writeHead(500).end(); // Whop sends the event again later } }).listen(Number(process.env.PORT ?? 3000)); ``` If your webhook's payload carries no `custom_field_responses` (newer Whop API versions leave them out), `usernameOf` is the one function to change. A username that matches no OpenMarket account is logged, so you can ask that member again. Any other failure answers Whop with an error, and Whop sends the event again later. ## Discord A bot watches your paid role. A member who gets the role is added; one who loses it, or leaves the server, is removed. `/openmarket` saves the member's username and, if they already have the role, adds them at once. 1. In the Discord Developer Portal, on your app's **Bot** page, turn on **Server Members Intent**. The bot needs it to see role changes. 2. Run `npm install discord.js@14`, and save the bot as `bot.mjs`. 3. Set `OPENMARKET_ACCESS_KEY` and `DISCORD_TOKEN`, and run `node bot.mjs`. ```javascript import { Client, Events, GatewayIntentBits, MessageFlags, SlashCommandBuilder } from "discord.js"; const PACKAGE = "@you/your-indicator"; // your indicator's full name const PAID_ROLE = "Premium"; // the role your members pay for const ACCESS = `https://registry.openmarket.xyz/v1/packages/${PACKAGE}/access`; const usernames = new Map(); // Discord user id to OpenMarket username // PUT or DELETE one person. false: no OpenMarket account has that username. async function access(method, username) { const res = await fetch(`${ACCESS}/${encodeURIComponent(username)}`, { method, headers: { Authorization: `Bearer ${process.env.OPENMARKET_ACCESS_KEY}` }, }); if (res.ok) return true; const { error } = await res.json().catch(() => ({})); if (error?.code === "user_not_found") return false; throw new Error(`${method} ${username}: ${res.status} ${error?.code ?? ""}`); } const paid = (member) => member.roles.cache.some((role) => role.name === PAID_ROLE); const command = new SlashCommandBuilder() .setName("openmarket") .setDescription("Link your OpenMarket username") .addStringOption((option) => option.setName("username").setDescription("Your OpenMarket username").setRequired(true), ); const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] }); client.once(Events.ClientReady, async () => { for (const guild of client.guilds.cache.values()) { await guild.members.fetch(); // load everyone, so each role change arrives with the roles before it await guild.commands.set([command]); } }); client.on(Events.GuildMemberUpdate, async (before, after) => { const username = usernames.get(after.id); if (username && paid(before) !== paid(after)) await access(paid(after) ? "PUT" : "DELETE", username); }); client.on(Events.GuildMemberRemove, async (member) => { const username = usernames.get(member.id); if (username && paid(member)) await access("DELETE", username); }); client.on(Events.InteractionCreate, async (interaction) => { if (!interaction.isChatInputCommand() || interaction.commandName !== "openmarket") return; await interaction.deferReply({ flags: MessageFlags.Ephemeral }); const username = interaction.options.getString("username", true).trim(); const previous = usernames.get(interaction.user.id); usernames.set(interaction.user.id, username); let reply = `Saved. Your access starts when you get the ${PAID_ROLE} role.`; try { if (paid(interaction.member)) { if (previous && previous !== username) await access("DELETE", previous); reply = (await access("PUT", username)) ? "You're in. Find it under Shared with you in Indicators on OpenMarket." : "No OpenMarket account has that username. Check it and try again."; } } catch (error) { console.error(error); reply = "Something went wrong. Try again in a minute."; } await interaction.editReply(reply); }); process.on("unhandledRejection", console.error); client.login(process.env.DISCORD_TOKEN); ``` The sample keeps usernames in memory, so a restart forgets them. Keep them in a database. ## Checks and limits | Status | Code | What to do | | --- | --- | --- | | 404 | `user_not_found` | The username is wrong. Ask the member for it again. | | 403 | `fair_use` | The Protected indicator is at 1,000 people ([Fair use](overview.md#fair-use)). | | 429 | `rate_limited` | More than 600 writes in a minute on this key. Wait the seconds the `retry-after` header names. | Webhooks get missed and bots restart. Once a night, read the list with `GET /access`, a page at a time ([Check and list](access-keys-and-api.md#check-and-list)), compare it with your own, and PUT or DELETE the difference, or send it as one batch ([Many at once](access-keys-and-api.md#many-at-once)). The key works for this one indicator and nothing else. **Revoke** on its sheet in the People panel stops it at once. # What members see Your members never type a name or a code: they open your link, sign in, and land on **Add to chart**, or on a request you approve. ## Opening your link Signed out, your link opens sign-in, headed with your name: ```text @yourname invited you to an Indicator ``` After they sign in or sign up, a **Join right away** link or a personal link lands them on your indicator with **Add to chart**, without typing anything. The invite survives the sign-up, email check included. A personal link works for one account. Opened by a second account, it says "This personal link was already used by another account." ## An Ask to join link An **Ask to join** link, the default, shows a request card instead: ```text Invite only Only people @yourname invites can find and add it. Ask to join ``` They press **Ask to join** and see "Requested. You'll hear when @yourname says yes." You approve the request in the People panel ([The invite link](invite-your-community.md#the-invite-link)), and from then on they can add it. ## After they join The indicator is under **Shared with you** in the Indicators dialog, and the chart's search finds it. They add it like any other indicator ([After publishing](../functions/publishing.md#after-publishing)). With **Protected** code, OpenMarket's servers run the indicator over the chart's candles and send back only what it draws. Your members see the plots and nothing else: there is no code to download, read or fork. ## When access ends When you remove someone, or their end date passes, the indicator stops loading for them. A Protected one stops within about 15 minutes. A Compiled module their browser already downloaded cannot be called back: it stops updating, but it does not vanish from a page that is already open. That is one more reason to publish anything you sell as Protected. ## When the link cannot open An account that cannot use Indicators yet gets one sentence and nothing else: ```text This Indicator link isn't available on your account yet. ``` A wrong link, or one to an indicator you deleted, says "This Indicator isn't available. The link may be wrong, or the author removed it." # Cookbook Complete, working wrun indicators you can copy, run, and adapt, in six groups: what to draw on price, how to read order flow, prediction-market odds read against the markets they move with, HUD cards that read a market at a glance, views beyond the time axis (profiles, volatility curves and surfaces, fund flows, the order book, cross-market maps, calendars, the yield curve), and strategies that trade. Seventy-nine of them are also the templates the chart's **New indicator** starter list offers, one card each, under the same group names; the other six are shorter recipes that build up the loop one idea at a time, each with the indicator in full and the reasoning behind it. Every recipe page is a full indicator, not a snippet. Pick its card in the editor's starter list, or paste it into a blank indicator tab under the language marker, press **Run**, and it works. Then read "How it works" for the moving parts, "Where it runs" and "When data is missing" for the markets it serves and what it says on the ones it does not, and "Customize it" for the variations worth trying. Each recipe ends with the concept pages behind it, so you can go deeper wherever something catches your eye. Inside a group the shorter recipes come first, easy to advanced, then the picker's templates in the picker's order. The first one is the cleanest introduction to the loop: load a series, compute a number, draw it. ![The cookbook's six groups, one small drawing each: On price, candles with a zone boxed on them; Order flow, buyers up and sellers down on every bar; Prediction markets, an odds line over the market it moves with; HUDs, a card of readings; Beyond the time axis, a profile docked on the price axis; Strategies, the trades marked on price with equity rising above them](/wrun/images/diagrams/cookbook-map.svg) 1. **On price**: marks, zones and tints drawn on the chart's own bars. 2. **Order flow**: buyers and sellers, open interest, liquidations and options flow, bar by bar. 3. **Prediction markets**: a Polymarket market's odds against the market they move with. 4. **HUDs**: one reading of the whole market, kept beside the candles. 5. **Beyond the time axis**: profiles, curves, chains and fund flows on a second axis. 6. **Strategies**: packages that trade, replayed by the Strategy Tester. ## On price Marks, zones and tints drawn on the candles themselves, from the chart's own bars. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Volume spike detector](volume-spike.md) | Flags bars whose volume blows past its trailing average, scored as a z-score | one input, a TA class, a gated mark | | [Typed inputs tour](typed-inputs-tour.md) | Every kind of setting but text on one small channel indicator, with two pages, presets, a hover card, a HUD card and legend entries | fourteen of the fifteen setting kinds, the layout words and the "@name" bindings, the block kit | | [Anchored VWAP](anchored-vwap.md) | Weekly and daily VWAP that reset on UTC session boundaries, with a shaded band and a stretch readout | `bar.time()`, state that resets, a box as a channel | | [Regime filter](regime-filter.md) | A no-repaint 4h trend gate that tints a line by regime and marks entries only when the higher timeframe agrees | higher timeframes without lookahead, `color_by`, `shape_where` | | [Key levels](key-levels.md) | Prior-day and prior-week highs and lows plus the day open, as horizontal levels on any interval | segments as levels, a param as a gate | | [Zone tracker](zone-tracker.md) | Supply and demand zones drawn as boxes that switch off when price mitigates them | boxes with a `when` gate, ring-buffer windows | | [Session map](session-map.md) | Asia, London and New York each boxed around the session's high and low with a tag, the live session growing bar by bar | box and label handles keyed by the UTC clock, a ring of ids reused by day, one text slot for many tags | | [Volume heat hours](volume-heat-hours.md) | Every clock hour boxed over its range and tinted by its volume against the last day's average hour, hot hours tagged with their multiple | folding hours from the chart's own bars, a rolling baseline, opacity as the reading | | [Supply and demand zones](supply-demand-zones.md) | A zone at every confirmed swing, extended right until a close breaks it, with breakout marks and the nearest zone on each side tagged with its price | `PivotHigh` and `PivotLow`, zones as box handles that stop extending, right-anchored price tags | | [Trend alignment](trend-alignment.md) | The chart's EMA beside the 1h and 4h EMAs as steps, the background tinted while all three agree, a three-cell strip reading the state | closed 1h and 4h `candles` streams, `render.bgcolor` gated by a data-only output, an anchored strip | | [Trend candles](trend-candles.md) | The chart's own candles tinted by where the close sits against two averages, a dot on each flip, a counter of how long the state has held | `render.barcolor`, `shape` outputs for events, a counter in an anchored label | | [Strike matrix](strike-matrix.md) | The live options chain by strike across the four nearest expiries, net gamma exposure or another lens (delta, vega, vanna, charm, open interest), docked on the price axis with the ATM row outlined, the per-strike bars beside the board, and the largest GEX strike, the gamma flip, max pain and the put wall drawn across the chart as labelled levels | `options_chain.cells` on the live bar, a `plot.matrix` and a `plot.levels` docked on one side and kept apart by an `offset`, `draw.line` levels with plain label handles, the kit's `GammaCurve` for the flip and `OptionsChain` for the walls and max pain | | [Session OI levels](session-oi-levels.md) | Where open interest was built and unwound in each day, drawn as one profile per day, each anchored inside its own span of time | `plot.levels` with `span: "time"`, a spans frame, a colour per row | ## Order flow Who traded, who is positioned and who was forced out, from sided trades, open interest and liquidations, and where the options money went, from the US listed options flow of a stock's own options. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Aggregated CVD](aggregated-cvd.md) | Aggressive buying minus selling on the chart's market, accumulated, with volatility bands and sign coloring | the `trades` source, accumulators, `missing` policies, which inputs the chart pins to another market | | [CVD divergence](cvd-divergence.md) | Cumulative volume delta in its own pane, price swings dotted on it, and the evidence drawn when price and CVD disagree at two swings | side-split `trades.volume`, a displaced `shape` output, line and polyline handles across two panes | | [Positioning regimes](positioning-regimes.md) | Each bar's open-interest change in coins colored by who moved, a key card with each regime's share, a dot where the leading regime changed hands | `oi.close` reading NaN, one histogram output per regime, `draw.card` with text slots | | [Absorption](absorption.md) | Bars where heavy one-sided volume failed to move price, lit in the delta pane, boxed on the chart and dotted on the absorbed side | a ratio against a rolling norm, two histograms sharing a pane, sign palettes, a `plot.spans` box a bar | | [Liquidation bursts](liquidation-bursts.md) | Long and short liquidations in USD stacked in one column per bar in their own pane, a burst marked on price by a bubble sized and captioned by its USD size | the `liquidations` source by side, a z-score gate, a `plot.marks` bubble with a size law bound to a setting | | [Book heat](book-heat.md) | The order book painted as a heatmap behind the candles, resting size per level, the scale read off the run | `book.cells`, `plot.heatmap` over cells on the chart's one-ink ramp, a quantile scale | | [Liquidation heat](liquidation-heat.md) | Estimated liquidation levels as a grid of 64 rows around the close, hot rows lit, rewritten every bar | `out.grid`, `plot.heatmap` over a grid on the chart's one-ink ramp, with a floor | | [OI liquidation heat](liquidation-heat-oi.md) | The Liquidation Map's estimate drawn through time: positions opened from open interest, folded every bar onto a grid of 128 rows around the close and swept where price trades through | `oi.close` and side-split `trades.volume` read as positions, `out.grid` and `plot.heatmap` with a dollar tooltip, data-only outputs for alerts | | [Volume footprint](volume-footprint.md) | One footprint column per bar from the profile buckets, imbalances marked and stacked, the point of control per column | `volume_profile.cells`, `plot.footprint`, imbalance words | | [TPO letters](tpo-letters.md) | Thirty-minute letters per day on the chart's own candles, the initial balance bracketed, single prints lit | `plot.tpo`, the letter interval rule, `initial_balance` | | [Session volume profile](session-volume-profile.md) | A volume profile per session from the profile buckets, the value area shaded, each session boxed | `plot.profile` with `span: "session"`, `value_area_shade`, `background` | | [Option prints](option-prints.md) | The underlying's option prints on its chain (a US stock's on OPRA, a CME future's, a coin's on its venue), filtered by premium, calls or puts, the side of the quote, days to expiry and moneyness, newest first in a table whose rows name their contracts, each print a mark on price | `option_prints.cells` holding the window's newest prints and each bar's largest (`newest` beside `overflow: "largest"`), `options_flow` of scope `prints` for the per-bar sums, the `present` mask, a `panel.table` with `markets` written by `fb_contract`, `plot.marks` | | [Flow tape](flow-tape.md) | The underlying's option prints merged into orders (sweeps across venues, splits on one venue, blocks in one print, inferred) and tagged opening, volume over open interest and unusual against the chain summary, newest first | prints merged by contract, side and a time window, `option_contract_state.cells` on the live bar, tags as styled table cells | | [Flow marks](flow-marks.md) | The underlying's large option prints as marks on price, the up colour bullish and the down colour bearish, sized by premium, over a column of each bar's bullish minus bearish premium | `option_prints.cells` cut to each bar's 24 largest at the floor and types settings with `history: "90d"`, `options_flow` of scope `prints` for the per-bar sums, `plot.marks` with a size unit bound to a setting, a ladder-coloured histogram | | [Contract sides](contract-sides.md) | The underlying's option contracts by side of the quote (above the ask, at the ask, the mid, at the bid, below the bid, no side), calls beside puts over today or the last bars, with each bar's bullish minus bearish contracts as a column | `options_flow` sums by side of the quote kept in a ring of bars, `panel.bars` with a per-run title | | [Strike footprint](strike-footprint.md) | The underlying's option flow strike by strike and bar by bar behind the candles: bullish net premium, the calls' or the puts' alone, or contracts, around each bar's close | `option_contract_flow.cells` folded onto `out.grid` rows placed at strike prices, `plot.heatmap` with a diverging scale, a strike step learnt from the listed strikes | | [Premium tide](premium-tide.md) | The whole options market's net call and net put premium (every US listed underlying, the coin on every crypto venue, or CME's market) summed through the session (the regular session on a US stock, the whole trading day on CME), each print capped, with the net volume below; tides over every strike or the out-of-the-money ones and every expiry or the same-day ones, several at once as one net line each | `options_flow` market scope, a `param.multi` gating each tide's inputs through `when` and `when_bit`, a histogram in a named pane, a card | | [Options market stats](options-market-stats.md) | The whole market's put/call ratios by contracts and by premium through the day, a table of the day for every underlying, equities, ETFs, indices and the same-day expiries, and a card that says which side leads | `options_flow` market scopes summed by trade date, a `panel.table` over a frame, breakdown rows gated by a `param.multi` | | [Net flow](net-flow.md) | Net call premium and net put premium on the chart's underlying (bought at the ask minus sold at the bid) summed through each session as two lines, the whole market's on a toggle, a card with the session's lean | `options_flow` fields as scalar inputs with `missing: "nan"`, a `scope: "market"` input fetched only while a setting is on (`when`), sums restarting on `time.trade_date` | | [Flow VWAP](flow-vwap.md) | The chart's price weighted by the options premium bought at the ask since the session or the week, a line on the candles with dotted 1σ and 2σ bands lightly shaded, the premium of the chart's own chain or of another root (QQQ on an NQ chart), a card that reads where the close sits in σ | `options_flow` inputs on the chain a `param.choice` names (`underlying: "@chain"` over its `style_values`), a 0DTE set fetched only while a setting is on (`when`), a weighted Welford mean and deviation restarting on `time.trade_date` or its week, two `fill`s | | [Options volume](options-volume.md) | The contracts each bar traded as stacked columns, calls above zero and puts below, split by side or into bullish, neutral and bearish, a card with the put/call ratio | one `stack` of `bar` outputs, positives up and negatives down, two splits written by one setting | | [Greek flow](greek-flow.md) | The share delta and the vega the tape traded, bought at the ask minus sold at the bid, summed through each session in two panes, the out-of-the-money contracts on a toggle | sided `options_flow` model sums, a named `pane` for the second line, `moneyness: "otm"` behind `when` | | [NOPE](nope.md) | The session's option share delta as a percent of the stock's own volume, one line in the up colour above zero and the down colour below | `options_flow` beside the chart's `ohlcv.volume`, the session from `time.session` (the regular session on a US stock, the whole trading day on CME, by `market.zone()`), a `split` line | | [Interval flow](interval-flow.md) | The contracts one bar's interval traded, ranked by premium or volume in a table with ask and bid shares, fill, IV and share of the day, a histogram of every bar's busy contracts | `option_contract_flow.cells` read tuple by tuple, a session volume table by contract, `hasBit` for the VWAP and IV, a styled `panel.table` | | [Premium by strike](premium-by-strike.md) | Net premium strike by strike as a heat map behind the candles on the chain's strike spacing, the session's net by strike docked on the price axis, partial bars dotted | `option_contract_flow.cells` with `strike_window_pct`, `out.grid` and `plot.heatmap` with `center: 0`, `plot.levels` with per-row colours, `isPartial` | ## Prediction markets A Polymarket market's odds set against the market they move with. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Odds vs price](odds-vs-price.md) | A Polymarket market's odds against a pinned asset: rolling correlation, a divergence histogram, the asset's close in a window below the chart, a verdict card | a leg pinned to another market, `Correlation` and `Zscore`, a four-rung ladder on a histogram | ## HUDs One card pinned to the price pane, in the chart's default look, that answers one question first and reads the numbers behind it underneath, kept current on the live bar. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Market HUD](market-hud.md) | The trend in a word, then RSI, the taker buy share and the last closed bar's volume against its average on three rings, ATR percent and the open-interest change in coins as a sparkline | one `render.hud` card in the default look, a headline pill coloured by a ladder output, a rings tile, data-only outputs read by the tiles | | [Decision board](decision-board.md) | A headline written from six factors ("Buyers Ahead, 3 to 1"), the net score as a sparkline and each factor's reading in a row | each factor as a rule with its thresholds as settings, counts as data-only outputs, a headline written into a string slot | | [Order flow HUD](order-flow-hud.md) | Who is pushing price in a word, each bar's taker buy share as a sparkline, the window's buy share, the net taker delta in dollars and the liquidations on each side | side-split `trades` and `liquidations`, rolling windows kept as rings, a value tile with this bar's delta beside it | | [Order book HUD](order-book-hud.md) | The heavier side of the book in a word, the bid share within 1% of the mid on a meter, the dollars resting by distance and the biggest walls, dotted on price | `book.cells` read in two passes, depth bands summed by distance, line handles set on the live bar | | [Session HUD](session-hud.md) | The session trading now, how much of it has passed and the session up next, the share of an average day's range used, the close in today's range, the distance from the VWAP and the prior day's high and low | `param.session` windows read with `inSession`, a daily `candles` stream, a countdown written into a string slot | | [Greek exposure](greek-exposure.md) | The dealers' exposure one greek at a time (gamma, delta, vanna, charm, vega, IV times open interest, open interest) by strike on the price axis and by expiry under the chart, over every expiry, the same day, a week, a month, the nearest N or stacked by days to go, read in one plain line on a card | `options_chain.cells` on the live bar, the kit's `Greeks` for vanna and charm and `GammaCurve` for the regime and the flip, three `plot.levels` shapes and a `panel.bars` | | [Risk reversal skew](skew.md) | One expiry's risk reversal (the call's IV minus the put's) at nine deltas in bars under the chart, the 25 and 10 delta numbers, the four wing IVs and the smile's asymmetry, with puts rich, calls rich or flat as the card's headline | `options_chain.cells` on the live bar, the kit's `IvTerm` (`nearest`, `deltaIv`), a `panel.bars` with a per-run title | | [Expected move](expected-move.md) | The expected move by a horizon from 1 to 90 days or to the earnings expiry on a US stock or ETF (0.85 of the at-the-money straddle) beside the 1σ range, drawn as two pairs of rails from the prior session's close (today's 00:00 UTC open on crypto), each tagged on the price axis, with the at-the-money IV at seven constant maturities and the next six expiries' expected moves | the `numbers` and `vol_term` book folds read through `BookStamp`, `OptionNumbers`, `ExpectedMoves.loadNumbers` and `VolTerm`, timed from the book's priced instant, `time.trade_date` for the prior close, guide outputs with `axis_label` and `axis_look` for the rails | | [Volatility context](vol-context.md) | The term structure (contango, flat or backwardation from the 90-day over the 30-day at-the-money IV), the 25 delta skew over the 30-day IV (puts or calls rich) with the risk reversal, the 30-day IV against the realized volatility of the daily candles, and the front expiry's expected move, three verdicts in one line on a card | `options_chain.cells` on the live bar, the kit's `ExpectedMoves` (constant maturities, the expected move) and `IvTerm` (25 delta wings), a daily `candles` stream in a `CandleList` | | [Contract odds](contract-odds.md) | One contract of the chart's chain, named by its settings and held to expiry: the odds of profit, the breakeven, the most it can make and lose and Kelly's fractions | `options_chain.cells` on the live bar, the kit's `Greeks` and `normCdf`, `param.price` and `param.time` naming the contract | | [Options stats](options-stats.md) | Today's option activity of the underlying, calls against puts: who leads by the put/call ratio, contracts and premium with their ratios, the net premium, the bullish share and the open interest with its change | `options_flow` fields over every expiry and the same-day ones summed over today's bars, `option_contract_state.cells` on the live bar, a headline pill | | [Option stance](option-stance.md) | Where the chart's underlying's options stand (the IV rank and percentile, dealer gamma against the gamma flip, the walls, the put/call ratios, the skew, the front move, the next earnings date) and whether selling premium, selling vega, directional, long-dated and cheap option buying run with it, against it or neither | scalar `option_daily` inputs landing once per session, the kit's `DayHistory`, `market.earnings_next_ms()`, pill tiles written by the rules | | [Options sentiment gauge](sentiment-gauge.md) | Fear to greed from 0 to 100 over the underlying's own options and price: six inputs scored by their percentile against their own history and blended once four score, a step line under the chart with guides at the band edges, and a dial | `option_daily` per session, a daily `candles` stream for momentum, one `DayHistory` per input, `tile.gauge` | | [Day type](day-type.md) | The session's state from its 10-minute options statistics (pinned, trending, volatile or unsettled) and the counted odds that it holds 30 minutes to 2 hours on, the typical move, the forward range boxed ahead of the live bar and the levels on price | `option_stats_10m` samples on the bars holding them, outcomes counted per state and horizon, a box handle, a state ribbon | | [Estimated dealer positioning](dealer-positioning.md) | An estimate of option dealers' book every ten minutes: the gamma regime and its hedge per 1% move, the charm drift to the close, the vanna hedge, the delta today's signed flow left behind and net gamma against 10 to 30 minutes ago | `option_stats_10m` keyed by 10-minute slot in a `DayHistory`, `options_flow` at the ask and the bid summed per session, two named panes | | [Spot exposures](spot-exposures.md) | The dealers' exposure bar by bar: a headline over every expiry from the 10-minute chain statistics (open interest), or from the strike rows of the expiries still trading and 7 or fewer trade days out (Greek exposure's week) where the chart has none; the headline's net gamma, delta or vega exposure as a line, the week's gamma flip and walls as step lines on price, a heat map of the week's exposure by strike behind the candles (the level or its change), and the gamma regime on a card with the week's net gamma in its rows | `option_stats_10m` for the headline, `option_strikes.cells` as the strike kit fold with its curve row (`fold: "kit"`, `levels`, `curve`: the server measures each bar's week), the kit's `OptionStrikes.loadLevels`, `NodeBoard` and `dealerRegime`, an `out.grid` heat map, a split line | | [OI changes](oi-changes.md) | Where open interest built and unwound since its prior observation: a board of the change by strike and expiry on the price axis (or the change in percent, the open interest, the day's volume or the net volume), the largest increases and decreases in a table, the net change on a card | `option_contract_state.cells` on the live bar, its `present` bits, three `plot.matrix` boards, a `panel.table` | | [Top contracts](top-contracts.md) | The most active contracts by the day's volume, open interest, premium or gain in a table, the three most traded and the three most held strikes drawn across the chart, the top contract on a card | `option_contract_state.cells` on the live bar, a `panel.table` of styled cells, line and label handles | | [Options sentiment](options-sentiment.md) | One score from the volume-weighted strike offset of the day's volume and the 25 delta call IV minus put IV at 30 days, bullish at +20 and bearish at -20 on a meter, the IV gap as a line and the volume-weighted strike across the chart | `option_contract_state.cells` on the live bar, `option_surface.cells` on every bar (crypto, CME and US stock charts), the kit's `totalVarianceIv` | ## Beyond the time axis Views whose second axis is price, tenor or the calendar. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Volume profile and value area](volume-profile-value-area.md) | The rolling volume profile docked on the price axis with POC and the value area lit, the three levels drawn with price tags, a heatmap of volume by UTC hour below the chart | `volume_profile.cells` as a block, `plot.levels` docked on the axis, `panel.heatmap` | | [Open Interest Profile](open-interest-profile.md) | The current day, week or month's open interest change by price docked on the right as a two-sided column, the OI POC and value area tagged on the axis side, the period's bounds and its net change, the same rows on every chart finer than a week | `oi_candles` and `volume_profile_candles` streams a month deep, the forming hour from the chart's own bars, `plot.levels` with `baseline: "center"` and `tag_place: "axis"` | | [Options dashboard](options-dashboard.md) | Nine tiles over the chart's own option book (net GEX, the flip, the dealer regime, max pain, the put/call ratio, net VEX and net DEX over every live expiry, today's move in 1σ moves, the front expiry's 25-delta risk reversal), the gamma exposure curve over hypothetical spots with a signed fill and callouts, and a rolling CVD pane | one `options_chain` input naming three book folds (`numbers`, `strike_profile`, `vol_term`) read on the live bar through `BookStamp`, `OptionNumbers`, `StrikeProfile` and `VolTerm`, `panel.tiles` and `panel.line` over frames with markers and a caption, a named pane | | [Spot ETF flow](etf-flows.md) | The chart coin's daily spot-ETF net flow as one bar per day, the running sum in a strip on the price pane, a wash behind each day's candles, a card | `etf_flow.flow_usd` landing once per day, lower-pane box handles, `out.inset`, `render.bgcolor` | | [Liquidation map](liquidation-map.md) | An estimate of where open positions would be liquidated, docked on the price axis as a two-sided profile, the largest rows drawn across the chart with tags, a card | open interest split by taker side into leverage tiers, `plot.levels` with `baseline: "center"`, line and label handles | | [Options odds cloud](options-odds-cloud.md) | Where the options market expects price to settle at an expiry, docked on the price axis as one hump with the most likely row marked, the 68% and 95% bands drawn across the chart, a card | `options_chain.cells` turned into odds per price row, per-row colours and a `gradient` on `plot.levels`, declared `draw.line` and plain `draw.label` drawings | | [Who is trading](whos-trading.md) | The window's dollar volume shared out by trade size as a donut, bought against sold per size as bars with the verdict as the caption, a card with the whales' buy share | `trade_volume_by_size.cells` over a rolling window, `panel.pie`, `panel.bars` with a per-run caption | | [Rotation map](rotation-map.md) | Eight coins placed by strength against BTC and its momentum on a four-quadrant map with trails, the leader's label carrying its move against BTC, and a card | nine hourly `candles` streams on Binance Futures smoothed in days, `panel.scatter` with `guides`, `quadrants` and `trails`, `param.color` inks written into the frame | | [Correlation matrix](correlation-matrix.md) | How the chart's market moved with eight others as a market by market heatmap with an average row, a card with the most tied and most free markets | eight pins with `missing: "nan"`, Pearson correlation on the live bar, `panel.heatmap` on category axes with a palette scale, a `highlight` row and a `summary` row | | [Venue share](venue-share.md) | Each venue's share of the last 24 hours of BTC dollar volume as a donut, a table of venue, last, premium, volume and share, a card with the widest premium | pinned close and volume on four venues, `panel.pie`, a styled `panel.table`, `param.text` and `param.color` settings, `chart.interval_sec()` | | [Volatility surface](iv-surface.md) | Implied volatility by strike and expiry (the six nearest expiries, the 21 strikes nearest spot) as a heatmap with the row nearest the chart's price marked and an ATM summary row, the term structure as tiles, a card | the `surface` and `vol_term` book folds read through `SurfaceMatrix` and `VolTerm`, `panel.heatmap` with `row_title`, a `summary` row and a `highlight` row, `panel.tiles`, a `render.legend` entry | | [Volatility character](vol-character.md) | Realized volatility from the chart's own daily candles in one pane the View setting picks (historical volatility by window, the cone, the return structure, the seasonality or the character readings), a card naming the character with its half-life | one `candles` stream at `1d`, prefix sums, five frames of which one is written, `panel.line` on time and number axes, `panel.bars`, `panel.table`, `tile.pill` and `tile.meter` | | [Strike breakdown](strike-breakdown.md) | The underlying's options by strike, one chart per upcoming expiry, calls up and puts down: open interest, its change, contracts, premium or net premium today, totals in each chart's caption | `option_contract_state.cells` and `option_contract_flow.cells` summed by contract over today, three `panel.bars` on a number axis of strikes | | [Market share](market-share.md) | Each US options exchange's share of the market's contracts, today or over the newest sessions, nine exchanges by name (five picked by default) and the rest as Other, as a donut and a table, with the leader in a card | `options_flow` venue scope over the market scope's totals, nine exchanges gated by a `param.multi`, ten reads within a Plus chart's data budget, a ring of sessions, `panel.pie` and `panel.table` | | [Premium by expiry](premium-by-expiry.md) | The session's bullish minus bearish option premium per expiry as bars under the chart, or the two sides apart, labelled by date and days to go, a note at the top of the chart when a bar's contracts were cut down | `option_strike_flow.cells` summed per expiry, the kit's `fbExpiryLabel` for the dates, a `panel.bars` with a per-run caption | | [Options at price](options-at-price.md) | The options a stock traded over 1 to 30 sessions by the price it stood at, docked on the price axis as bullish, neutral and bearish (or calls and puts), in contracts or premium | `options_flow` rows kept in a ring at each bar's typical price, a stacked `plot.levels` with `series` and a `poc_price` | | [IV rank](iv-rank.md) | Where the 30-day implied volatility sits against its past year: the IV rank and the IV percentile as step lines with guides at the bands, a card with the window's low, high and sessions, and a clear wait while the history is short | `option_daily` with `missing: "nan"`, the kit's `DayHistory` (`rank`, `percentile`, `span`), step lines with guide outputs at the bands | | [Variance risk premium](vrp.md) | The 30-day IV against the realized volatility of the chart's daily closes: the spread now, and the premium completed 21 sessions later (never drawn before it is known) with its rank's sell and stand-down zones read on a card | `option_daily` beside a daily `candles` stream, a forward-aligned history in a second `DayHistory`, spread columns coloured by sign | | [Skew history](skew-history.md) | The 30-day 25 delta risk reversal per session with its percentile and z-score, one expiry's risk reversal per bar from the option surface with partial bars on their own dotted line, that expiry's put tail with its z-score in five steps, the candles tinted where the risk reversal moves against spot, and the term structure now against its median and quartiles | `option_daily` and `option_surface` (crypto, CME and US stock charts) cells read through `hasBit` and `isPartial`, `DayHistory.quantile`, a `Zscore` over solid bars, a buffer of past bars behind a `render.barcolor` gate, `panel.line` over category maturities | | [Volatility regime](vol-regime.md) | The 30-day IV's z-score against its earlier sessions as columns, the candles of stressed bars (the IV at its 80th percentile or above) dimmed, and the vol of vol with its own percentile | `DayHistory.zscore` and `percentile`, an exponentially weighted deviation, `render.barcolor` behind a gate | | [Exposure history](exposure-history.md) | Dealers' net gamma, delta, vega, charm or vanna per session as columns, the walls, the gamma flip and max pain on price as steps, with the change from the prior session and the percentile | eleven `option_daily` fields, a lens `param.choice`, sign-coloured columns, a value tile with its change | | [Options history](options-history.md) | Options volume, open interest or premium per session, the volume against its 30-session average, and a table of the newest sessions with the put/call ratio, the volume against its average, the open interest change and the IV | one `DayHistory` per field, stacked `bar` outputs, a `panel.table` written on the live bar | | [Seasonality grid](seasonality-grid.md) | A year by month grid of returns on daily charts, a weekday by hour grid of the average move on intraday charts, the best cell named, a card | two `candles` streams of the chart's own market (26 weeks of 1h, 12 years of 1d) picked by `chart.interval_sec()`, one `panel.heatmap` with a `highlight` and an Avg `summary` row, a signed scale | | [Depth curve](depth-curve.md) | The order book as two cumulative staircases meeting at the mid, the biggest walls called out, the heavier side in the caption, a card with the ratio, the wall and the spread | `book.cells` summed outward from the mid, `panel.line` step series with fills, `markers` with an exact `y`, a `caption` | | [Yield curve](yield-curve.md) | The Treasury curve today against a week and a month ago over a tenor axis, 2Y and 10Y callouts, the 2s10s spread on a card | nine `economic.value` pins, prints kept in a ring, days turned into bars with `chart.interval_sec()`, `panel.line` with three series | ## Strategies Packages that trade: orders placed in the file, replayed by the Strategy Tester under the chart. | Recipe | What it does | What it teaches | | --- | --- | --- | | [Moving-average cross](strategy-ma-cross.md) | Long when the fast average crosses above the slow one, flat when it crosses back under, with a tinted ribbon and a mark on each cross | `strategy(...)` in the source, orders in `onBar()`, a `range` ribbon | | [Risk-sized reversion](strategy-risk-reversion.md) | Buys the dip as RSI leaves oversold, protects it with an ATR-sized stop and target, leaves on recovery; each trade's rails drawn on price | an entry sized from its stop with `qty(...)` and `strategy.equity()`, a protective exit re-armed each bar, rails as line handles | ## How to use a recipe ![The loop every recipe shares: open the Editor, pick the recipe's card from Templates, press Run, change a setting and it reruns, read a value at the Console prompt, and Publish when it is yours; in the middle, the three verbs every recipe teaches: load a series, compute a number, draw it](/wrun/images/diagrams/cookbook-loop.svg) - **The ring** is the loop: the Editor, Templates, the recipe's card, Run, a setting changed, a value read at the Console prompt, and back to the editor. - **Publish** leaves the ring: the indicator goes to other charts, to readers and to alerts. - **The three verbs** in the middle are what every recipe does: load a series, compute a number, draw it. 1. Open the editor: the chart toolbar's **Editor** button, or the **Build** icon in the **Indicators** dialog. 2. For a recipe that is also a template, press the **Templates** icon ("Browse starter templates") in the editor's Explorer and pick the recipe's card under its group. The pick fills an untouched draft, or opens in a tab of its own, with the `//@lang=wrun-ts` line on top. For any other recipe, press **New indicator** in the Explorer, pick **Blank indicator** (a tab holding the `//@lang=wrun-ts` line alone), and paste the recipe's indicator block under that line. 3. Press **Run** on a liquid symbol. Run compiles the file in your browser and draws it on the chart. The order-flow recipes want a market where the venue reports buy and sell volume; each page's "Where it runs" names the markets it serves. 4. Open the overlay's settings. Every setting is a row there, labelled by its description and drawn as the control its kind names (a number field bounded by its `min` and `max` for `param(...)` and `param.int`, a toggle for `param.bool`, a menu for `param.choice`), so lookbacks and thresholds change without touching code, and a change reruns the indicator over the loaded bars. Colors are declared on the outputs, boxes, and segments, as theme words such as `theme.up` or as hex strings: edit them and Run again. 5. Read a value at the editor's Console prompt, which reads the last run without a new build (below). 6. Publish it from the editor to add it to other charts, share it, or put an alert on it ([Publishing](../functions/publishing.md), [Alerts](../functions/alerts.md)). A published indicator runs in each reader's browser, or on OpenMarket's servers when its code is **Protected**. What the Console prompt answers after a Run, with the [Volume spike detector](volume-spike.md)'s `z` as the output: ```text outputs every output with its value on the newest bar params the settings the last run used rows the bars the run covered, the first and last bar time, the warm-up bars z the output's value on the newest bar z[-3] the same output three bars back last 20 z its last 20 bars; a data-only output reads the same way ``` Most recipes read the chart's own market and interval ([Execution model](../core-concepts/execution-model.md)). The ones that pin say so on their page. The chart serves a pin on a secondary `ohlcv` input: an interval coarser than the chart's and a whole multiple of it ([Multi-timeframe](../core-concepts/multi-timeframe.md#the-interval-pin-a-real-coarser-feed)), or another market at the chart's interval ([Odds vs price](odds-vs-price.md)). A market pin on any other source is refused by name, which is why [Aggregated CVD](aggregated-cvd.md) reads the chart's own venue. Stocks, forex and gold pin the same way ([Multi-source](../core-concepts/multi-source.md#stocks-forex-and-gold)). On CME markets an indicator runs in the browser once you have accepted the CME market data terms, and the results stay on the chart. ## What the recipes share A few shapes come back in every recipe: - **State lives in module-level variables.** A value that must survive from bar to bar is a module-level `let`; a window of past values you index into is a `StaticArray` ring buffer, which `History` packages as a class ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). - **Decisions are numbers.** A condition the chart should act on is a data-only `none` output written as `1` or `0`; the declarations turn it into a look through `shape_where`, `color_by`, or a box's `when` gate. - **Calendar math comes from the bar's open time.** `bar.time()` is each bar's open in epoch seconds; dividing by 86400 gives the UTC day, and a boundary in that index is where sessions reset. - **An output can carry an alert.** Once the indicator is published and on a chart, the chart's alert dialog offers every drawn output with conditions such as **Crosses above** and **Greater than**, and a data-only gate becomes a ready-made signal through `alert(name, { when })` in the file ([Alerts](../functions/alerts.md)). # Typed inputs tour ![The tour's settings dialog open on its Signal page: the rail, the presets strip, a row of each kind](/wrun/images/wrun-dialog.svg) Every kind of setting the dialog can draw but text, on one small channel indicator: an average of a picked price field with percent bands, an offset in a picked unit, a reference close on a picked timeframe, a ratio against a picked market, a floor line and a session filter over picked weekdays. The dialog has two pages, **Signal** and **Bands**, a folded section and a section that carries its own toggle, two presets, and a Style page the chart adds by itself. On the chart, the basis line carries a hover card of four block kinds, a two-column HUD card of four tiles sits at the top left under the legend, clear of the newest candles, momentum and the ratio each draw in a pane of their own below the chart, and the legend reads the length setting after the indicator's name with the session's words beside it. The parts are fourteen of the fifteen setting kinds and the layout words ([Setting kinds](../settings/kinds.md), [Pages, sections, dividers, notes](../settings/layout.md)), the `"@name"` bindings that paint the basis line and pin two inputs, the session and unit helpers `inSession` and `unitToPrice` ([Sessions and units](../settings/sessions-and-units.md)), the block kit behind the hover card and the HUD ([HUD and hover cards](../presentation/hud-and-hover-cards.md)), and the `Sma`, `Ema`, `Atr` and `Roc` helpers ([TA library](../functions/ta-library.md)). Every setting is read once in `onStart()` and kept in a module variable. This is also the `typed-inputs-tour` template: the **Typed inputs tour** card under **Starters** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Typed inputs tour: every kind of setting the dialog can draw, on one small channel Indicator. Read the declarations top to bottom, then the two functions. // Each setting is declared by its kind, so the dialog knows the control to draw; the page, section, divider and note words lay the rows out in this order. page("Signal"); // the dialog's first page: the rows declared below land on it, in this order param.int("length", 20, { min: 2, max: 500, label: "Length in bars", hint: "Bars in the average" }); // a whole number: p_length() reads it in onStart() param.choice("kind", ["Simple", "Exponential"], "Simple", { label: "Average" }); // one of two choices: p_kind() reads the index, 0 for Simple param.source("src", ohlcv.close, { label: "Source" }); // the price field the average reads, picked in the dialog: in_src() reads it per bar param.bool("show_reference", true, { label: "Reference", row: "reference", hint: "The close on the timeframe picked beside it" }); // a toggle; rows naming the same row word share one line of the dialog param.timeframe("htf", "chart", { label: "Timeframe", row: "reference", when: "show_reference" }); // a timeframe pick on that line ("chart" follows the chart until a coarser one is picked), dimmed while the toggle it names is off ... input("close_htf", ohlcv.close, { interval: "@htf" }); // ... and bound to this input by name: the host fetches the picked timeframe param.symbol("pair", "BINANCE_FUTURES:ETHUSDT", { label: "Ratio against" }); // a market pick ... input("close_pair", ohlcv.close, { symbol: "@pair" }); // ... bound to this input the same way param.list("lookbacks", [5.0, 20.0], { max: 4, label: "Momentum lookbacks in bars" }); // a growable list of numbers, four at most: p_lookbacks() reads the filled slots param.time("since", "2024-01-01 00:00", { label: "Start", hint: "Earlier bars stay empty" }); // a point in time, pickable on the chart: p_since() reads epoch seconds param.price("floor", 0.0, { label: "Floor price", hint: "0 draws no floor" }); // a price level, pickable on the chart section("Session", { collapsed: true }); // a folded section: its header shows the row count param.session("rth", "09:30-16:00", { tz: "America/New_York", label: "Active hours" }); // a window and its zone: start, end and zone readers param.multi("days", ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], ["Mon", "Tue", "Wed", "Thu", "Fri"], { label: "Active days" }); // any number of picks: p_days() reads a bitmask page("Bands"); // the second page const showBands = param.bool("show_bands", true, { label: "Show bands" }); // a toggle, bound to a const so the section below can carry it in its header section("Bands", { toggle: showBands }); // the section's header carries the toggle param.range("band_pct", [0.5, 2.0], { min: 0, max: 10, step: 0.1, label: "Band width in percent" }); // a low..high pair on one slider: p_band_pct_lo() and p_band_pct_hi() param.number("offset", 0.0, { min: -100, max: 100, unit: ["price", "ticks", "%", "atr"], unit_default: "%", label: "Basis offset" }); // a number with a unit picker: p_offset_unit() reads the unit's code param.int("atr_length", 14, { min: 2, max: 50, slider: true, label: "ATR length", hint: "The ATR an atr-unit offset scales by" }); // a bounded whole number, drawn as a slider param.color("basis_color", "#2962ff", { label: "Basis colour" }); // a colour, painted onto the basis line below by name divider(); // a rule between rows note("Bands are **percent** distances from the basis: the low end below it, the high end above it."); // a line of words between rows market.tick_size(); // the host writes the market's tick size into a hidden setting: p_market_tick_size() reads it in onStart() const basisLine = output("basis", line, overlay, { color: "@basis_color", label: "Basis", format: "price", tooltip: "{{label}} {{value:price}}" }); // the colour setting paints this line; label, format and tooltip shape its legend entry; the handle names it below output("upper", line, overlay, { color: "#26a69a", label: "Upper band", format: "price" }); output("lower", line, overlay, { color: "#ef5350", label: "Lower band", format: "price" }); output("reference", line, overlay, { color: "#94a3b8", width: 1, line_style: "dashed", label: "Reference", format: "price" }); // the close on the picked timeframe: the chart's own until a coarser one is picked, then stepped output("floor", line, overlay, { color: "#f59e0b", label: "Floor", format: "price", legend: false }); // the picked price, kept out of the legend pane("momentum", { height_frac: 0.15 }); // a pane of its own below the chart, so the momentum never shares an axis with the ratio output("momentum", line, lower, { pane: "momentum", color: "#8b5cf6", label: "Momentum", format: "0.00", tooltip: "{{label}} {{value:0.00}} %" }); // the average rate of change over the listed lookbacks, in the pane declared above output("ratio", line, lower, { color: "#0ea5e9", label: "Ratio", format: "0.000" }); // the close over the picked market's close, in the default lower pane output("basis_chg", none); // data-only: the basis change per bar, the delta a tile shows beside the value output("band_pos", none); // data-only: where the close sits in the band, 0 at the lower band, 100 at the upper output("state", none); // data-only: 0 outside the session, 1 inside and under the basis, 2 inside and over it string("session", { max_bytes: 32 }); // the words the legend and the HUD show: the zone and whether the session is open legend({ title: "({{length}})" }); // the words after the Indicator's name in the legend: a setting read by name render.legend("session_entry", { text: "session", color_by: "state", colors: ["#94a3b8", "#ef5350", "#26a69a"] }); // a text entry in the legend, coloured by the state ladder render.hud("tour", { position: "top_left", safe_area: true, title: "Tour", columns: 2, tiles: [tile.value("Basis", "basis", { format: "price", delta: "basis_chg" }), tile.spark("Momentum", "momentum", { bars: 32 }), tile.gauge("Band position", "band_pos", { min: 0, max: 100, format: "int" }), tile.pill("Session", "session", { color_by: "state", colors: ["#94a3b8", "#ef5350", "#26a69a"] })] }); // a card of four tiles pinned under the legend, clear of the newest candles hover(basisLine, [block.value("Value", "basis", { format: "price", delta: "basis_chg" }), block.rows([["Upper", "upper", "price"], ["Lower", "lower", "price"], ["Reference", "reference", "price"]]), block.meter("Band position", "band_pos", { min: 0, max: 100, marks: [50] }), block.chips("session")]); // the card the basis shows on hover, titled by the line's label: four block kinds presets({ Scalp: { length: 9, kind: "Exponential", band_pct_lo: 0.2, band_pct_hi: 1, show_reference: false }, Swing: { length: 50, kind: "Simple", band_pct_lo: 1, band_pct_hi: 3, show_reference: true } }); // named settings sets the dialog offers as chips let basisSma = new Sma(20); // the two averages; onStart() rebuilds both at the chosen length and the kind picks one let basisEma = new Ema(20); let atr = new Atr(14); // the ATR an atr-unit offset scales by, rebuilt in onStart() at its own length let rocs: Roc[] = []; // one rate of change per listed lookback, built in onStart() let useEma = false; let bandsOn = true; let referenceOn = true; // the settings, read once in onStart() and kept here let lowPct = 0.5; let highPct = 2.0; let offset = 0.0; let offsetUnit = 0; let tick = 0.0; let since = 0.0; let floorPrice = 0.0; let dayMask = 0.0; let sessionStart = 570.0; let sessionEnd = 960.0; let zone = 0; let basis: f64 = NaN; // the basis, kept between bars: each bar measures its change against the last one // onStart() runs once before the first bar: every setting is read here, through its generated reader, and kept in module state. function onStart(): void { const n = i32(p_length()); basisSma = new Sma(n); basisEma = new Ema(n); useEma = p_kind() == 1.0; bandsOn = pb_show_bands(); referenceOn = pb_show_reference(); lowPct = p_band_pct_lo(); highPct = p_band_pct_hi(); offset = p_offset(); offsetUnit = i32(p_offset_unit()); atr = new Atr(i32(p_atr_length())); tick = p_market_tick_size(); // 0 where a host has no tick size: the helper then leaves a ticks value as it is since = p_since(); floorPrice = p_floor(); dayMask = p_days(); sessionStart = p_rth_start(); sessionEnd = p_rth_end(); zone = i32(p_rth_tz()); if (zone < 0 || zone >= SESSION_TZ_LABELS.length) zone = 0; const lookbacks = p_lookbacks(); rocs = []; for (let i = 0; i < lookbacks.length; i += 1) rocs.push(new Roc(i32(lookbacks[i]))); } // onBar() runs once per bar: read the bar, fold it into the averages, place it in the session; then write every output and the legend's words. function onBar(): void { const t = bar.time(); const close = in_src(); const reference = in_close_htf(); const pair = in_close_pair(); // the bar's open in epoch seconds, the picked price field and the two pinned closes const prevBasis = basis; const sma = basisSma.update(close); const ema = basisEma.update(close); basis = useEma ? ema : sma; const atrValue = atr.update(bar.high(), bar.low(), close); // the bar's high and low feed the ATR an atr-unit offset scales by if (isFinite(basis)) basis += unitToPrice(offset, offsetUnit, close, tick, atrValue); // the offset in the unit the dialog picked, as a price distance const ratio = isFinite(pair) && pair != 0.0 ? close / pair : NaN; let sum = 0.0; let count = 0; for (let i = 0; i < rocs.length; i += 1) { const r = rocs[i].update(close); if (isFinite(r)) { sum += r; count += 1; } } const momentum = count > 0 ? sum / f64(count) : NaN; const weekday = i32((Math.floor(t / 86400.0) + 3.0) % 7.0); // 0 = Monday, from the bar's UTC day: the bit the days setting is tested by const active = inSession(t, sessionStart, sessionEnd, zone) && multiHas(dayMask, weekday); // the window in its zone, daylight saving included const started = t >= since; if (!isFinite(basis) || !started) return; // nothing to draw yet (before Start, or while the average warms up): every output stays NaN on this bar const upper = basis * (1.0 + highPct / 100.0); const lowerBand = basis * (1.0 - lowPct / 100.0); out_basis(basis); out_basis_chg(basis - prevBasis); out_upper(bandsOn ? upper : NaN); out_lower(bandsOn ? lowerBand : NaN); // a hidden line is NaN: nothing is drawn out_reference(referenceOn ? reference : NaN); out_floor(floorPrice > 0.0 ? floorPrice : NaN); out_momentum(momentum); out_ratio(ratio); const span = upper - lowerBand; out_band_pos(span > 0.0 ? Math.min(100.0, Math.max(0.0, ((close - lowerBand) / span) * 100.0)) : NaN); out_state(active ? (close > basis ? 2.0 : 1.0) : 0.0); sb_clear(); sb_text(SESSION_TZ_LABELS[zone]); sb_text(active ? " open" : " closed"); str_session_sb(); // "New York open", coloured by the state ladder } ``` ## How it works Every setting is declared by its kind, and `onStart()` reads each one once through its reader and keeps it in a module variable ([Setting kinds](../settings/kinds.md#read-it-in-onstart)). The source, timeframe and symbol picks have no reader: the chart applies them, and `"@htf"` and `"@pair"` pin the two inputs ([Picks, lanes, the cap](../settings/picks-and-lanes.md#read-it-in-onstart)). `color: "@basis_color"` paints the basis line from the color setting ([The Style page](../settings/style-page.md#declare-it)). The unit code and the session's three parts are integers; `unitToPrice` and `inSession` turn them into a price distance and an in-session test per bar ([Sessions and units](../settings/sessions-and-units.md#read-it-in-onstart)). `basis_chg`, `band_pos` and `state` are data-only outputs. `pane("momentum", { height_frac: 0.15 })` gives momentum a pane of its own, so a ratio near 30 never flattens a momentum near 1 on a shared axis; the ratio keeps the default lower pane ([Plotting](../presentation/plotting.md#panes)). The hover card is titled by the basis line's label, so its first block reads `Value` rather than repeating `Basis`. Every tile and block reads the newest row, so a value written per bar is how a delta or a regime reaches the HUD card, the hover card and the legend's color ladder ([HUD and hover cards](../presentation/hud-and-hover-cards.md), [Legend](../presentation/legend.md)). ![The HUD card: a value with its delta, a sparkline, a gauge and a pill](/wrun/images/wrun-hud.svg) ![The legend: the title suffix read from the length setting, labelled values, the session entry colored by the state ladder](/wrun/images/wrun-legend.svg) ## Settings The dialog lays the rows out in source order: **Signal** and **Bands** on the rail, the folded **Session** section with its row count, the **Bands** section carrying its toggle, and **Scalp** and **Swing** as chips after **Default**. Each row is the control its kind names, shaped by `row`, `when`, `hint`, `slider` and `unit`. The **Style** page adds a row per drawn output; the basis line's color is the `basis_color` setting's row instead. What each control looks like and why: [Setting kinds](../settings/kinds.md#what-the-dialog-draws), [Options on a setting](../settings/options.md#what-the-dialog-draws), [Pages, sections, dividers, notes](../settings/layout.md#what-the-dialog-draws), [Presets](../settings/presets.md#what-the-dialog-draws), [The Style page](../settings/style-page.md#what-the-dialog-draws). ![The Signal page: a number field with a hint glyph, a menu, a source menu, a toggle and a timeframe sharing a line, a market button, a list, a time and a price with Pick, a folded Session section](/wrun/images/wrun-dialog.svg) ![The Bands page: a section carrying its toggle in the header, a two-handle slider, a number with a unit picker, a slider, a color picker, a divider and a note](/wrun/images/wrun-dialog-bands.svg) ![Style rows: visible, width, line style and color per output](/wrun/images/wrun-style-rows.svg) ## Where it runs Every market with candles, on any interval: the timeframe defaults to the chart's own. The source, timeframe and symbol picks are applied by the chart only when the indicator runs in your browser; on OpenMarket's servers the three keep their defaults and there is no Style page ([Picks, lanes, the cap](../settings/picks-and-lanes.md#where-a-setting-applies)). The legend, the HUD and the hover card are drawn where the indicator runs in the browser. ## When data is missing A hidden line is NaN and draws nothing: the bands while **Show bands** is off, the reference while **Reference** is off, the floor while **Floor price** is 0. Bars before **Start** return from `onBar()` before any output is written, so they stay empty. The ratio is NaN where the picked market has no close for the bar, and momentum stays NaN until the first lookback is warm. Where a host has no tick size the hidden setting reads 0 and `unitToPrice` leaves a ticks value as it is; an ATR of 0 does the same for an atr-unit offset. ## Customize it - **Pick a preset.** **Scalp** sets the length to 9, the average to Exponential, the band to 0.2 and 1 percent and hides the reference; **Swing** sets 50, Simple, 1 and 3 percent with the reference on. A range is set through its parts, `band_pct_lo` and `band_pct_hi` ([Presets](../settings/presets.md#declare-it)). - **Another reference.** Pick a coarser timeframe in the **Timeframe** menu and the reference line steps at that timeframe's closes; pick another market with **Ratio against** and the ratio pane follows it. - **Add a setting.** Declare it with its kind after the page it should land on and read it in `onStart()`, or name the page and section with `{ group: "Signal/Session" }` ([Pages, sections, dividers, notes](../settings/layout.md#declare-it)). - **Move the card.** `position` on `render.hud` is one of the nine anchors: `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right`. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Typed inputs tour** under **Starters**. 2. Press **Run**: the basis and its bands draw on price with the dashed reference, momentum and the ratio draw in two panes below, the legend reads `(20)` after the name, and the **Tour** card appears at the top left, under the legend. 3. Open the indicator's settings on the chart. **Signal** and **Bands** sit on the rail above the **Chart** caption, the presets strip offers **Default**, **Scalp** and **Swing**, and every row is the control its kind names. Switch **Average** to Exponential and the indicator reruns over the loaded bars without recompiling. 4. At the editor's Console prompt, type `outputs` to read the newest value of every output, the three data-only ones included. ## Concepts used - [Setting kinds](../settings/kinds.md) for the fifteen kinds, their controls and their readers - [Options on a setting](../settings/options.md) for `row`, `when`, `hint`, `slider` and `unit` - [Pages, sections, dividers, notes](../settings/layout.md) and [Presets](../settings/presets.md) for the layout words and the chips - [The Style page](../settings/style-page.md) for the rows the dialog adds and the `"@name"` binding - [Sessions and units](../settings/sessions-and-units.md) for `inSession`, the zone table and `unitToPrice` - [Picks, lanes, the cap](../settings/picks-and-lanes.md) for what the chart applies in the browser - [HUD and hover cards](../presentation/hud-and-hover-cards.md) and [Legend](../presentation/legend.md) for the three surfaces - [TA library](../functions/ta-library.md) for `Sma`, `Ema`, `Atr` and `Roc` # Volume spike detector Flag bars whose volume blows past its trailing average, scored as a z-score against a rolling mean and standard deviation. This recipe spots unusual volume. Instead of a fixed "alert above 1M" threshold that means nothing across different symbols, it measures how far the current bar's volume sits above its own recent average, in standard deviations. A reading of 3 means "three sigma above normal" whatever the symbol or timeframe. It is the cleanest possible introduction to the indicator loop: read one input, fold it into one class, write a few outputs. ## The wrun indicator ```typescript param("lookback", 50, { min: 10, max: 300, description: "Bars of history that define normal volume" }); param("threshold", 2.5, { min: 1, max: 6, description: "Z-score that counts as a spike" }); input("volume", ohlcv.volume); // the first input is the bar grid: the chart's own candles output("z", line, lower, { color: "#64748b", width: 1, description: "Volume z-score" }); output("threshold", line, lower, { color: "#ef4444", width: 1 }); output("spike", shape, lower, { color: "#ef4444", shape_where: "is_spike" }); output("is_spike", none); let zscore = new Zscore(50); let threshold: f64 = 2.5; function onStart(): void { zscore = new Zscore(i32(p_lookback())); threshold = p_threshold(); } function onBar(): void { const z = zscore.update(bar.volume()); if (isNaN(z)) return; out_z(z); out_threshold(threshold); out_spike(z); out_is_spike(z >= threshold ? 1.0 : 0.0); } ``` ## How it works **The data.** One `input("volume", ohlcv.volume)` names the chart's own volume as the first input, the grid the run walks, and `bar.volume()` reads it in `onBar()`, one value per bar. That is the only feed the detector needs, and `onBar()` sees this bar's value and nothing else. **The score.** A z-score answers "how surprising is this number?" You need two reference points: where volume usually sits, and how much it normally wobbles. `Zscore` is both reference points in one class: `update(x)` folds one bar into its window and returns `(x - mean) / stdev` over that window, or `0` when the window is flat. Because it is a ratio, it is comparable across any symbol or timeframe. A whale print on BTC and a thin altcoin both light up at the same number. **The warm-up guard.** Until `lookback` bars have loaded, the class returns `NaN`, and `onBar()` returns before writing anything: every output stays `NaN` on that bar, and a `NaN` is not drawn, so the pane stays empty there instead of drawing noise ([Execution model](../core-concepts/execution-model.md)). **The output.** `z` plots as a line in its own pane (`lower`). `threshold` is a line too, written to the same value on every bar, so you can see at a glance how close any bar is to firing. `spike` is a `shape` output whose value is the z-score (where the mark sits) and whose `shape_where` gate is the data-only `is_spike` output: the mark draws only on bars where the gate is `1`. Decisions are numbers here, and the sheet turns them into looks. ## Design notes - The mark is two outputs: its position (`spike`) and the decision that gates it (`is_spike`). An output cannot gate itself, so the gate is its own `none` output. - The threshold line is an output that never changes; its value is the param, written every bar. - Settings take any value inside `min`..`max`; the `description` is the label the settings dialog shows beside the field. - Every output has a value on every bar. After a Run the editor's Console prompt reads any of them (`last 20 z`, `is_spike`), and once the indicator is published, `z` can carry an alert set from the chart. ## Customize it - **Sensitivity.** `threshold` is the main knob. Drop it toward `1.5` to catch milder bursts, raise it toward `4` to keep only genuine anomalies. The red line moves with it. - **Memory.** `lookback` sets how much history "normal" is measured against. A short window (20) reacts to recent conditions and treats a busy session as the new baseline; a long window (200) compares against a calmer, broader average and flags more. - **Two-sided.** As written, only high-volume bars fire because the gate is `z >= threshold`. To catch unusually quiet bars too, add a second gate output (`z <= -threshold`) and a second `shape` output gated by it. - **Color and size.** The circle and line colors are hex strings on the declarations. `width` on the line output resizes it; `render.shape` picks a different mark kind than the chart's default ([Plotting](../presentation/plotting.md#text-labels-tables-strips-tints)). - **Turn it into an alert.** Publish it, add it to a chart, and set an alert from the chart on `z` with **Crosses above** at 3. OpenMarket's alerts engine evaluates it in the cloud with the overlay's settings; **Once per bar** lets it fire again on later spikes, at most once per bar ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run**. 3. At the editor's Console prompt, type `last 20 z` to read the score of the last 20 bars. ## Concepts used - [Series functions](../functions/series-functions.md) and [TA library](../functions/ta-library.md) for `Zscore` over a trailing window - [Setting kinds](../settings/kinds.md) for the `lookback` and `threshold` params - [Missing values (NaN)](../core-concepts/na-and-scalar-types.md) for the `NaN` warm-up rule - [Plotting](../presentation/plotting.md) and [Cards, frames and panels](../presentation/cards-frames-panels.md#marks-tints-and-fills) for the `line` outputs and the gated `shape` # Anchored VWAP Weekly and daily VWAP that reset on real UTC session boundaries, with a shaded band and a stretch readout for mean-reversion context. VWAP is the volume-weighted average price, the level large players benchmark fills against. A plain cumulative VWAP drifts: it averages from wherever the chart happened to start loading, so the line you see depends on how much history your browser fetched. This recipe pins VWAP to calendar sessions instead. The weekly line resets every Monday at 00:00 UTC and the daily line resets every midnight, so two traders looking at the same symbol see the same level. It adds a percentage band and a "stretch" number that tells you how far price has pulled from fair value. ## The wrun indicator ```typescript param("band_pct", 0.5, { min: 0.1, max: 3, description: "Band distance from the weekly VWAP, in percent" }); output("week_vwap", line, overlay, { color: "#f5a623", width: 2, description: "VWAP anchored to the UTC week" }); output("day_vwap", line, overlay, { color: "#4a90d9", width: 1, description: "VWAP anchored to the UTC day" }); const bandTop = output("week_upper", line, overlay, { color: "#f5a623", opacity: 0.3 }); const bandBottom = output("week_lower", line, overlay, { color: "#f5a623", opacity: 0.3 }); box("week_band", { top: bandTop, bottom: bandBottom, color: "#f5a623", opacity: 0.08, borderWidth: 0 }); output("stretch_pct", line, lower, { unit: "%", color: "#f5a623", description: "Close distance from the weekly VWAP" }); let bandPct: f64 = 0.5; let weekIdx: f64 = NaN; let weekPv: f64 = 0.0; let weekVol: f64 = 0.0; let weekComplete: bool = false; let dayIdx: f64 = NaN; let dayPv: f64 = 0.0; let dayVol: f64 = 0.0; let dayComplete: bool = false; function onStart(): void { bandPct = p_band_pct(); } function onBar(): void { const close = bar.close(); const typical = (bar.high() + bar.low() + close) / 3.0; const volume = bar.volume(); // UTC day index of this bar; epoch day 0 was a Thursday, so +3 makes weeks start on Monday 00:00 UTC. const day = Math.floor(bar.time() / 86400.0); const week = Math.floor((day + 3.0) / 7.0); if (week != weekIdx) { if (!isNaN(weekIdx)) weekComplete = true; weekIdx = week; weekPv = 0.0; weekVol = 0.0; } if (day != dayIdx) { if (!isNaN(dayIdx)) dayComplete = true; dayIdx = day; dayPv = 0.0; dayVol = 0.0; } weekPv += typical * volume; weekVol += volume; dayPv += typical * volume; dayVol += volume; // A session that was already running when the history starts is incomplete: stay NaN until the first boundary. const weekVwap = weekComplete && weekVol > 0.0 ? weekPv / weekVol : NaN; const dayVwap = dayComplete && dayVol > 0.0 ? dayPv / dayVol : NaN; out_week_vwap(weekVwap); out_day_vwap(dayVwap); out_week_upper(weekVwap * (1.0 + bandPct / 100.0)); out_week_lower(weekVwap * (1.0 - bandPct / 100.0)); out_stretch_pct(isNaN(weekVwap) || weekVwap <= 0.0 ? NaN : ((close - weekVwap) / weekVwap) * 100.0); } ``` ## How it works **The anchor is the whole trick.** `bar.time()` hands the module each bar's open time in epoch seconds. Divide by 86400 and you have a UTC day index; shift by three days and divide by seven and you have a week index whose boundary is Monday 00:00 UTC. When the index changes, the price-times-volume and volume sums reset. The reset is tied to the calendar, not to your scroll position or how much history loaded, which is exactly why the level is stable and shared. It is eight lines of arithmetic you can read. **Warm-up is honest.** A session that was already running when the loaded history starts is incomplete, so both lines stay `NaN` until their first boundary passes. The daily line fills in within the first day of loaded data, the weekly line needs about a week. `onBar()` still writes every output on those bars: the row exists, and the lines that are ready draw while the ones that are warming do not. That is the warm-up rule from the [Execution model](../core-concepts/execution-model.md): an output written `NaN` draws nothing on that bar, and the others draw as usual. **The band frames the move.** `week_upper` and `week_lower` are the weekly VWAP scaled by a percentage, drawn faint with `opacity: 0.3`, and `box("week_band", ...)` shades between them: with `from` and `to` left at `0` every bar contributes a one-bar-wide slice and the slices tile into a channel. Its `borderWidth: 0` keeps the slices from showing seams. The two band outputs are bound to consts because the box names them by handle. When price rides the upper band it is stretched rich versus the week's fair value; when it sags to the lower band it is cheap. **The stretch readout.** `(close - week_vwap) / week_vwap * 100` is the most actionable number, so it gets its own pane as `stretch_pct` with a `%` unit, `NaN` while the weekly line is warming. The indicator has it on every bar: a series you can read back in the legend, and a value an alert from the chart can compare. ## Design notes - There is no anchored-VWAP builtin: `bar.time()` and a reset-on-boundary sum are the building blocks, and they work for any anchor. - `color` is declared on each output, and the band tint is a box color with its own `opacity`. There is no color picker param: a `param(...)` declares a number, with a `min`, a `max` and a `description` ([Styling](../presentation/styling.md)). - The band is a box on every bar, one bar wide, tiling into a channel. `range("week_upper", "week_lower", { ... })` is the other form: the chart draws it as a filled band between the two outputs, with a colour ladder or a gradient when you want one ([Styling](../presentation/styling.md)). - The stretch readout is a lower-pane series: visible on every bar, and a value an alert from the chart can follow. A one-cell table is possible with a string slot and `render.table` ([Drawing objects](../presentation/drawing-objects.md)), at the cost of switching the file to the second runtime contract. ## Customize it - **Band width.** `band_pct` sets how far the band sits from the VWAP. Tighten it toward `0.2` on calm majors, widen it toward `2` on volatile names so the band actually contains the noise. - **Anchor period.** For a monthly anchor, compute the month index from the day index (a lookup over cumulative month lengths, leap years included); the reset logic does not change. Monthly needs about a month of loaded history before it shows anything. - **Band the daily line too.** Duplicate the two band outputs and the box against `day_vwap` if you trade the intraday session instead. - **Stretch as a signal.** Add a data-only gate output (`stretch_pct > 1.5`) and a `shape` output with `shape_where` on it, the way the [volume spike](volume-spike.md) marks its bars. Or skip the mark: publish the indicator, add it to a chart, and set an alert from the chart on `stretch_pct` with **Greater than** at 1.5; **Once only** fires it a single time ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run**. The daily line fills in within the first loaded day, the weekly line within the first loaded week. 3. At the editor's Console prompt, type `last 20 stretch_pct` to read the stretch of the last 20 bars. ## Concepts used - [Time and sessions](../core-concepts/time-and-sessions.md) for the day and week indexes from `bar.time()` - [Volume and VWAP](../functions/volume-indicators.md#vwap-anchors-side-by-side) for the anchored-VWAP pattern as a worked function - [Drawing objects](../presentation/drawing-objects.md) for the per-bar box that shades the band - [Missing values (NaN)](../core-concepts/na-and-scalar-types.md) for the `NaN` warm-up on each line # Regime filter (4h trend gate) A no-repaint higher-timeframe trend gate that tints a line by regime and only marks entries when the confirmed 4h trend agrees with the signal. The fastest way to cut false signals is to stop trading against the higher timeframe. This recipe reads a confirmed 4h trend, tints its 4h line green or red by that regime, and only marks an entry when a fast/slow EMA cross on your chart timeframe lines up with the 4h direction. The key word is confirmed: a 4h candle contributes only once it has closed, so a signal that shows up in history would have shown up live, at the same bar. No repaint, no hindsight. ## The wrun indicator ```typescript param("fast_len", 9, { min: 2, max: 100, description: "Fast EMA length, on the chart bars and on the 4h buckets" }); param("slow_len", 21, { min: 5, max: 200, description: "Slow EMA length" }); output("h4_fast", line, overlay, { width: 1, color_by: "regime", colors: ["#94a3b8", "#22d3a5", "#ff5b7f"], description: "Confirmed 4h fast EMA, tinted by regime", }); output("h4_slow", line, overlay, { color: "#94a3b8", width: 1, description: "Confirmed 4h slow EMA" }); output("regime", none, overlay, { description: "0 warming, 1 bull, 2 bear" }); output("long", shape, overlay, { color: "#22d3a5", shape_where: "is_long" }); output("short", shape, overlay, { color: "#ff5b7f", shape_where: "is_short" }); output("is_long", none); output("is_short", none); let h4Fast = new Ema(9); let h4Slow = new Ema(21); let fast = new Ema(9); let slow = new Ema(21); let cross = new Cross(); let bucket: f64 = NaN; let bucketClose: f64 = NaN; let h4FastValue: f64 = NaN; let h4SlowValue: f64 = NaN; function onStart(): void { h4Fast = new Ema(i32(p_fast_len())); h4Slow = new Ema(i32(p_slow_len())); fast = new Ema(i32(p_fast_len())); slow = new Ema(i32(p_slow_len())); cross = new Cross(); } function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); // 4h buckets on UTC boundaries. A bucket's close folds into the 4h EMAs only once the NEXT bucket // has started, so the regime never uses a 4h candle that is still forming: no repaint. const b = Math.floor(bar.time() / 14400.0); if (b != bucket) { if (!isNaN(bucketClose)) { h4FastValue = h4Fast.update(bucketClose); h4SlowValue = h4Slow.update(bucketClose); } bucket = b; } bucketClose = close; const regime = isNaN(h4FastValue) || isNaN(h4SlowValue) ? 0.0 : h4FastValue > h4SlowValue ? 1.0 : h4FastValue < h4SlowValue ? 2.0 : 0.0; const crossed = cross.update(fast.update(close), slow.update(close)); if (isNaN(h4SlowValue)) return; out_h4_fast(h4FastValue); out_h4_slow(h4SlowValue); out_regime(regime); out_long(low); out_short(high); out_is_long(crossed == 1 && regime == 1.0 ? 1.0 : 0.0); out_is_short(crossed == -1 && regime == 2.0 ? 1.0 : 0.0); } ``` ## How it works **The higher-timeframe view.** `Math.floor(bar.time() / 14400)` puts every chart bar in a UTC 4h bucket. The module remembers the last close it saw in the current bucket, and when a bar from the NEXT bucket arrives it folds that remembered close into the two 4h EMAs. A 4h candle therefore contributes exactly once, after it closed. That is what makes the gate trustworthy: the tints you see on old bars are what you would have seen live. The promise is fourteen lines you can read, and the [Execution model](../core-concepts/execution-model.md) explains why an indicator cannot break it by accident. **The regime.** Fast 4h EMA above slow is bull (`1`), below is bear (`2`), and warming is `0`. It is a data-only output, and the `h4_fast` line indexes its three-entry palette with it: grey, green, red. Both 4h EMAs are guarded with `isNaN` so the warm-up region counts as neither regime, rather than a coin flip. **The trigger.** Separately, the module computes the same fast/slow EMAs on the chart timeframe and detects the moment they cross. `Cross.update(fast, slow)` returns `+1` on the one bar where the fast EMA moves from at-or-below to above the slow one, `-1` for the opposite, `0` otherwise, including on any bar where either side is still `NaN`. That is the entry idea on its own. **The gate.** `is_long` is `1` only when the cross and the regime agree; `long` is a `shape` output at the bar's low, gated by it. A bullish cross during a 4h downtrend is silently dropped, which is the whole point: most chop happens when you fight the higher timeframe. **Two ways to see the state.** The 4h line carries the regime through `color_by`, so the context is always visible, and the two `shape` outputs drop a mark only on confirmed, gated entries. The 4h EMA lines are drawn even before a single cross fires, so there is always something on screen. ## Design notes - The higher timeframe is built in the module from the chart's own bars, and the confirm-on-next-bucket rule is the no-repaint contract written out. The chart also serves the direct form, an `interval: "4h"` pin on a second `close` input: a 4h leg of closed candles fetched on its own, read as of each row's close, on any chart whose interval divides 4h evenly. It sees each 4h close one bar earlier than the bucketing does, on the bar whose close ends the 4h candle, and both are causal ([Multi-timeframe](../core-concepts/multi-timeframe.md)). - The regime tint is a choice. This indicator tints the 4h line through `color_by`; `render.barcolor` tints the candles themselves with the same gate and ladder options, and a background tint per bar is `render.bgcolor` ([Plotting](../presentation/plotting.md#text-labels-tables-strips-tints)). - A `shape` output's value is where its mark sits: `long` is written the bar's low, so the mark hangs below the candle, and `short` the bar's high, so it sits above. - The colors are `colors` and `color` on the declarations: a palette on the line that `color_by` indexes, one color on each mark. ## Customize it - **EMA speed.** `fast_len` and `slow_len` drive both the regime and the trigger. Widen the gap (21 / 55) for fewer, slower signals, tighten it for more. Because the same lengths feed the 4h regime, changing them reshapes the whole gate. - **Regime timeframe.** Change `14400.0` to `86400.0` for a daily regime (stricter, fewer entries) or `3600.0` for a looser gate on lower-timeframe charts. Bucketing works for any multiple of the chart interval. - **Loaded history.** The 4h regime needs enough loaded bars for its slow EMA to warm up, roughly `slow_len * 4` chart hours on a 1h chart. If the line never tints, pan back: the indicator reruns over the longer window. - **Different trigger.** Swap the cross for an RSI level or a breakout and keep the `regime == 1.0` / `regime == 2.0` gates to filter it by trend. - **Make it actionable.** `is_long` is data-only, so the alert dialog does not offer it as a condition. Bind it to a `const` (`const isLong = output("is_long", none);`) and declare `alert("trend_long", { when: isLong, message: "{{symbol}} trend-aligned long" })`: once the indicator is published and on a chart, that signal is in the chart's alert dialog and fires only on trend-aligned entries ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run** on a chart finer than 4h, such as 15m or 1h. 3. At the editor's Console prompt, type `last 20 regime` to read the regime of the last 20 bars. ## Concepts used - [Multi-timeframe](../core-concepts/multi-timeframe.md) for the no-repaint bucket fold and the `interval` pin the chart serves - [Moving averages](../functions/moving-averages.md) for `Ema` and [Series functions](../functions/series-functions.md) for `Cross` - [Styling](../presentation/styling.md) for `color_by` over a data-only output - [Repainting](../core-concepts/repainting.md) for why a bucket folds in only on the next bucket's first bar # Key levels Prior-day and prior-week highs and lows plus the running day open, drawn as horizontal levels that are calendar-correct on any chart interval. Yesterday's high and low, last week's high and low, and today's open are the levels the market keeps reacting to, and half the annotations on any trading chart are someone maintaining them by hand. This recipe maintains them for you: five levels computed from calendar-anchored sessions, drawn as thin lines that are exactly the same on a 1-minute chart and a 4-hour chart, and that never repaint: a prior day high is always the prior completed UTC day. ## The wrun indicator ```typescript param("show_open", 1, { min: 0, max: 1, description: "1 draws the running day open, 0 hides it" }); input("open", ohlcv.open); // the first input is the bar grid: the chart's own candles const pdh = output("pdh", none, overlay, { description: "Prior UTC day high" }); const pdl = output("pdl", none, overlay, { description: "Prior UTC day low" }); const pwh = output("pwh", none, overlay, { description: "Prior UTC week high" }); const pwl = output("pwl", none, overlay, { description: "Prior UTC week low" }); const dayOpen = output("day_open", none, overlay, { description: "Open of the running UTC day" }); const openVisible = output("open_visible", none); // Each bar draws its level from itself to the next bar; consecutive bars chain into one line that // steps to the new level on the first bar of each period. segment("pdh_line", { yFrom: pdh, yTo: pdh, from: 0, to: 1, color: "#f5a623", width: 1 }); segment("pdl_line", { yFrom: pdl, yTo: pdl, from: 0, to: 1, color: "#f5a623", width: 1 }); segment("pwh_line", { yFrom: pwh, yTo: pwh, from: 0, to: 1, color: "#4a90d9", width: 1 }); segment("pwl_line", { yFrom: pwl, yTo: pwl, from: 0, to: 1, color: "#4a90d9", width: 1 }); segment("open_line", { yFrom: dayOpen, yTo: dayOpen, from: 0, to: 1, when: openVisible, color: "#f5a623", width: 1, lineStyle: "dashed" }); let showOpen: f64 = 1.0; let dayIdx: f64 = NaN; let dayHigh: f64 = NaN; let dayLow: f64 = NaN; let runningOpen: f64 = NaN; let priorDayHigh: f64 = NaN; let priorDayLow: f64 = NaN; let weekIdx: f64 = NaN; let weekHigh: f64 = NaN; let weekLow: f64 = NaN; let priorWeekHigh: f64 = NaN; let priorWeekLow: f64 = NaN; function onStart(): void { showOpen = p_show_open(); } function onBar(): void { const open = bar.open(); const high = bar.high(); const low = bar.low(); const day = Math.floor(bar.time() / 86400.0); const week = Math.floor((day + 3.0) / 7.0); if (day != dayIdx) { // The day that just closed becomes the prior day. A day already running when the history // starts is incomplete and never becomes a level. if (!isNaN(dayIdx)) { priorDayHigh = dayHigh; priorDayLow = dayLow; } dayIdx = day; dayHigh = high; dayLow = low; runningOpen = open; } else { if (high > dayHigh) dayHigh = high; if (low < dayLow) dayLow = low; } if (week != weekIdx) { if (!isNaN(weekIdx)) { priorWeekHigh = weekHigh; priorWeekLow = weekLow; } weekIdx = week; weekHigh = high; weekLow = low; } else { if (high > weekHigh) weekHigh = high; if (low < weekLow) weekLow = low; } out_pdh(priorDayHigh); out_pdl(priorDayLow); out_pwh(priorWeekHigh); out_pwl(priorWeekLow); out_day_open(runningOpen); out_open_visible(showOpen != 0.0 ? 1.0 : 0.0); } ``` ## How it works **The levels come from completed sessions.** The module keeps the running high and low of the current UTC day and week from the day index of `bar.time()`. On the first bar of a new day, the day that just closed becomes the prior day: `pdh` and `pdl` step to its high and low, and hold there for the whole day. Weeks work the same way. A day or week already running when the loaded history starts is incomplete and never becomes a level. This is the same no-repaint contract as the [Regime filter](regime-filter.md): a level is only ever built from bars that have closed. **The day open is the one level that should move.** It is the open of the first bar of the running day, refreshed once at the boundary and held: a variable assigned on the boundary bar. **Drawing is a segment per bar.** Each level is a segment from this bar to the next (`from: 0, to: 1`) with both ends on the same output. The pieces chain into one horizontal line that steps to the new level on the first bar of each period. Every level output is `none`: the numbers are computed and readable at the editor's Console prompt, but the segments are what draws, so the levels never appear twice. The `open_line` segment is gated by `open_visible`, which is the `show_open` param turned into an output: a setting becomes a gate. **Nothing waits for the last bar.** There is no last-bar special case: the level exists on every bar it applies to, so each level has a value on every bar. ## Design notes - The levels are per-bar segments. Offsets clamp to the loaded range, so a line ends at the newest bar, never past it. A line handle drawn under `bar.isLast()` and extended right is the other form, the one [Volume profile and value area](volume-profile-value-area.md) draws its three levels with ([Drawing objects](../presentation/drawing-objects.md)). - The levels carry no price tags. A tag per level is a `render.label` over a string slot ([Drawing objects](../presentation/drawing-objects.md)), which switches the file to the second runtime contract; the level values themselves are readable at the editor's Console prompt. - The show-open switch is a numeric param (`0` or `1`), and each level's color is a `color` option on its segment. - There is no history depth to declare: state lives in a few module-level variables, however much history is loaded. ## Customize it - **Add monthly levels.** Compute a month index from the day index and keep a third running high and low; two more outputs and two more segments (7 of the 16 allowed). - **Prior close and midpoint.** Keep the last close of each day for a `pdc` level; `(pdh + pdl) / 2` is the day's midpoint, a favorite mean-reversion magnet. - **Style per period.** `lineStyle: "dotted"` on the weekly segments keeps them quieter than the daily ones; `width: 2` makes a level louder. - **Alert on a level.** The levels are data-only, so the alert dialog does not offer them as conditions. Read `bar.close()` and write a data-only gate `1` on the bar the close crosses above `pdh`, bind the gate to a `const`, and declare `alert("pdh_break", { when: ... })`: once the indicator is published and on a chart, the signal is in the chart's alert dialog ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run** on any interval. The prior-day levels appear once a full UTC day has loaded, the prior-week ones once a full week has. 3. At the editor's Console prompt, type `pdh` for the prior day's high on the newest bar, or `last 5 pwh` for the prior week's high over the last five bars. ## Concepts used - [Time and sessions](../core-concepts/time-and-sessions.md) for the day and week indexes and why the prior day is always a completed UTC day - [Drawing objects](../presentation/drawing-objects.md) for segments with `from: 0, to: 1` as horizontal levels - [Options on a setting](../settings/options.md) for the boolean-as-param that becomes a `when` gate - [Core variables](../core-concepts/core-variables.md) for the running highs and lows kept in module-level variables # Zone tracker Supply and demand zones drawn as boxes that switch themselves off when price mitigates them, with a live count of the zones still active. Supply and demand zones are price areas where a strong move began. They stay interesting until price trades back through them, at which point they are mitigated and no longer matter. Tracking them by hand means juggling a list of rectangles and remembering to remove each one when it gets invalidated. This recipe does it for you: it finds zones at confirmed pivots, draws each one as a box, and switches the box off the moment price mitigates the zone. It is a tour of the wrun drawing model: state in module-level variables, boxes that read their bounds from outputs, and a gate that switches a drawing off. ## The wrun indicator ```typescript param("lookback", 20, { min: 5, max: 100, description: "Bars a swing must dominate to count as a pivot" }); input("open", ohlcv.open); // the first input is the bar grid: the chart's own candles const demandTop = output("demand_top", none); const demandBottom = output("demand_bottom", none); const demandLive = output("demand_live", none); const supplyTop = output("supply_top", none); const supplyBottom = output("supply_bottom", none); const supplyLive = output("supply_live", none); output("active_zones", none, overlay, { description: "Zones alive on this bar, 0 to 2" }); // One bar wide (from 0 to 0) on every bar the zone is alive: the bars tile into a band that starts // at the pivot and stops on the bar that mitigates it. box("demand_zone", { top: demandTop, bottom: demandBottom, when: demandLive, color: "#22d3a5", opacity: 0.18, borderWidth: 0 }); box("supply_zone", { top: supplyTop, bottom: supplyBottom, when: supplyLive, color: "#ff5b7f", opacity: 0.18, borderWidth: 0 }); const MAX_LOOKBACK = 100; const highs = new StaticArray(MAX_LOOKBACK); const lows = new StaticArray(MAX_LOOKBACK); let n: i32 = 20; let cursor: i32 = 0; let count: i32 = 0; let windowHigh: f64 = NaN; let windowLow: f64 = NaN; let prevOpen: f64 = NaN; let prevHigh: f64 = NaN; let prevLow: f64 = NaN; let prevClose: f64 = NaN; let dTop: f64 = NaN; let dBottom: f64 = NaN; let dLive: f64 = 0.0; let sTop: f64 = NaN; let sBottom: f64 = NaN; let sLive: f64 = 0.0; function onStart(): void { n = i32(p_lookback()); } function onBar(): void { const open = bar.open(); const high = bar.high(); const low = bar.low(); const close = bar.close(); // A pivot is confirmed one bar after it prints: the previous bar led its window and this bar turned back. const pivotHigh = !isNaN(windowHigh) && prevHigh >= windowHigh && high < prevHigh; const pivotLow = !isNaN(windowLow) && prevLow <= windowLow && low > prevLow; // One live zone per side: a new pivot is ignored while the side's zone is still alive. if (pivotHigh && sLive == 0.0) { sTop = prevHigh; sBottom = Math.max(prevOpen, prevClose); sLive = 1.0; } if (pivotLow && dLive == 0.0) { dTop = Math.min(prevOpen, prevClose); dBottom = prevLow; dLive = 1.0; } // Mitigation: a close through the far edge retires the zone. if (dLive == 1.0 && close < dBottom) dLive = 0.0; if (sLive == 1.0 && close > sTop) sLive = 0.0; // Push this bar into the window and recompute the window extremes. highs[cursor] = high; lows[cursor] = low; cursor = (cursor + 1) % n; if (count < n) count += 1; windowHigh = NaN; windowLow = NaN; if (count == n) { let h = -Infinity; let l = Infinity; for (let i = 0; i < n; i++) { if (highs[i] > h) h = highs[i]; if (lows[i] < l) l = lows[i]; } windowHigh = h; windowLow = l; } prevOpen = open; prevHigh = high; prevLow = low; prevClose = close; out_demand_top(dTop); out_demand_bottom(dBottom); out_demand_live(dLive); out_supply_top(sTop); out_supply_bottom(sBottom); out_supply_live(sLive); out_active_zones(dLive + sLive); } ``` ## How it works **State shaped like the problem.** Each side has three numbers: the zone's top, its bottom, and whether it is alive. They are outputs, so the sheet can draw from them, and they are module-level variables, so they survive from bar to bar. The indicator spreads them over named outputs because the box has to read them by name. **Birth.** The window's highest high and lowest low come from a ring buffer of highs and lows plus a scan: the two `StaticArray` buffers are allocated once, at module start, sized from the param's `max`, and `cursor` walks them. A pivot is confirmed one bar after it prints: the previous bar led its window and the current bar turned back. When a pivot fires and that side has no live zone, the zone takes its bounds from the pivot bar's body and wick and its `live` flag flips to `1`. **Death is a gate turning off.** Every bar checks whether the close went through the zone's far edge. A mitigated zone sets `live` to `0`, and the box's `when` gate stops drawing from that bar on. Nothing is deleted: the bars the zone was alive on keep their slices. **The box.** `box("demand_zone", ...)` with `from` and `to` at `0` draws one bar-wide slice on every bar where `demand_live` is `1`; the slices tile into a band that starts at the pivot and ends on the mitigation bar. `borderWidth: 0` keeps the slices seamless. The coordinates are output handles bound to consts, which is how a box names an output. **The dashboard.** `active_zones` is `demand_live + supply_live`, a data-only count. Every bar carries it, readable at the editor's Console prompt. ## Design notes - The zones are a fixed set of declared boxes gated per bar: what a bar draws is decided on that bar ([Drawing objects](../presentation/drawing-objects.md)). That is why this indicator keeps one zone per side. More zones are more declared boxes, up to 16 per sheet. Box handles, which the file creates, moves and deletes by id, are the other form: [Supply and demand zones](supply-demand-zones.md) keeps a ring of them per side. - A mitigated zone stays visible on the bars it was alive on. For a zone that vanishes from the chart when it breaks, draw it as a box handle and delete the handle on the mitigation bar. - Each zone's facts are module-level variables and its mitigation check is one `if` line. An AssemblyScript `class` would carry the same fields ([User-defined types](../core-concepts/user-defined-types.md)); the outputs are the reason the flat form is simpler here. ## Customize it - **Zone frequency.** `lookback` controls how significant a swing must be to spawn a zone. A small value (10) marks many minor pivots, a large one (50) keeps only major swing points. This is the main dial between "lots of zones" and "only the big ones". - **Mitigation rule.** Right now a single close beyond the zone mitigates it. For a stricter definition, require the close to pass fully through to the far edge, or two consecutive closes, by adding a counter beside each `live` flag. - **Zone thickness.** The bounds come from the pivot bar's body (`open`/`close`) and wick (`high`/`low`). Use the full candle range for thicker zones by reading `prevHigh` and `prevLow` for both edges, or the body only for tighter ones. - **More zones.** Duplicate the three outputs and the box per extra slot and fill the first free slot at each pivot; 16 boxes per sheet is the ceiling. - **Alert on a mitigation.** `active_zones` is data-only, so the alert dialog does not offer it as a condition. Add a data-only gate written `1` on the bar a zone dies, bind it to a `const`, and declare `alert("zone_died", { when: ... })`: once the indicator is published and on a chart, the signal is in the chart's alert dialog ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run**. 3. At the editor's Console prompt, type `last 20 active_zones` to read how many zones were alive on each of the last 20 bars. ## Concepts used - [Collections](../core-concepts/collections.md) for the `StaticArray` ring buffers sized from a param's `max` - [Series functions](../functions/series-functions.md) for `Highest` and `Lowest`, the one-call form of the window scan - [Drawing objects](../presentation/drawing-objects.md) for boxes with a `when` gate and why nothing is deleted - [User-defined types](../core-concepts/user-defined-types.md) for the `class` that carries a zone's fields when you want one - [Core variables](../core-concepts/core-variables.md) for the module-level state that survives from bar to bar # Session map ![Asia, London and New York session boxes on a BTC chart](/wrun/images/session-map.png) Asia, London and New York each drawn as a box around the session's high and low, with a small tag inside the box's left edge naming the session; every box and tag is in the muted colour, so the tags tell the sessions apart. The live session's box grows with every bar. Where two sessions overlap (London into New York, Asia into London) the boxes overlap too. The last five days stay on the chart; older boxes are reused. The parts are box and label handles in chart time and price ([Drawing objects](../presentation/drawing-objects.md)), one bounded text slot every tag is written through, and the bar's open time, `bar.time()`, placed in each window's own zone by a session setting ([Time and sessions](../core-concepts/time-and-sessions.md), [Sessions and units](../settings/sessions-and-units.md)). Nothing is drawn per bar beyond moving the open session's box, so a closed day costs nothing. This is also the `session-map` template: the **Session Map** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Session Map: Asia, London and New York boxed around each session's high and low, a small tag on each box, the live session growing bar by bar. // The trader sees which session set the range, where the overlaps traded, and how far the live session has run. Each session is a window in its own zone. section("Sessions"); // the dialog's first section: a window and its zone per session; daylight saving follows the zone, bar by bar param.session("asia", "00:00-08:00", { tz: "UTC", label: "Asia" }); param.session("london", "07:00-16:00", { tz: "UTC", label: "London" }); param.session("new_york", "13:30-20:00", { tz: "UTC", label: "New York" }); section("Boxes"); param.int("days_kept", 5, { min: 1, max: 10, label: "Days kept", description: "Days of sessions kept on the chart; the oldest box is reused" }); param.bool("show_tags", true, { label: "Show tags", description: "Tag each box with its session name" }); input("high", ohlcv.high); // the bar's high and low grow the open session's box output("sessions_open", none, overlay, { description: "Sessions open on this bar: 0, 1, or 2 where two sessions overlap" }); // data-only, so the Console can read it string("tag", { max_bytes: 48 }); // one bounded slot every tag is written through handles.box({ opacity: 0.08, borderWidth: 1 }); // boxes in chart time and price: one per session per day handles.label({ size: 11, align: "left" }); // the tags, and the one line of words on a coarse chart const SESSIONS = 3; // Asia, London, New York const MAX_DAYS = 10; // the ring's ceiling: 30 boxes and 30 tags at most, ids in one space const NAMES = ["Asia", "London", "New York"]; const inks: i32[] = [theme.MUTED, theme.MUTED, theme.MUTED]; // one muted ink per session: the tags name them const MUTED_INK: i32 = theme.MUTED; // the one line of words, in the chart's muted text const starts = new StaticArray(SESSIONS); // each window's start and end in minutes from midnight, and its zone, read from the settings in onStart() const ends = new StaticArray(SESSIONS); const zones = new StaticArray(SESSIONS); const dayKey = new StaticArray(SESSIONS); // the day the open instance's window opened, in its zone (NaN = none yet): a new day opens a new box whatever bars the feed has let clocks: Clock[] = []; // one bar clock per session, built in onStart() for the zone each window is set in const slot = new StaticArray(SESSIONS); // the ring slot that instance sits in const instances = new StaticArray(SESSIONS); // instances seen so far, per session const startT = new StaticArray(SESSIONS); // the open instance's first bar open const endT = new StaticArray(SESSIONS); // the open instance's right edge (the newest bar's close) const hiP = new StaticArray(SESSIONS); // the open instance's high and low so far const loP = new StaticArray(SESSIONS); const touched = new StaticArray(SESSIONS); // 1 when this bar sits inside the session const fresh = new StaticArray(SESSIONS); // 1 on the bar that opens a new instance const grew = new StaticArray(SESSIONS); // 1 when this bar lifted the instance's high (a top tag moves up) const sank = new StaticArray(SESSIONS); // 1 when this bar pushed the instance's low down (a bottom tag moves down) function makeBoxes(first: i32, count: i32): BoxHandle[] { const out: BoxHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.box(first + i)); return out; } function makeLabels(first: i32, count: i32): LabelHandle[] { const out: LabelHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.label(first + i)); return out; } const boxes = makeBoxes(0, SESSIONS * MAX_DAYS); // handle objects allocate once, at module load const tags = makeLabels(SESSIONS * MAX_DAYS, SESSIONS * MAX_DAYS); const words = draw.label(90); // the one line of words when the chart is too coarse let daysKept = 5; let showTags = true; let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; // width = the smallest gap between bar opens seen, so a weekend gap never widens a box let wordsShown = false; // onStart() runs once before the first bar: read the settings, three readers per session, and build a clock per zone. function onStart(): void { starts[0] = p_asia_start(); ends[0] = p_asia_end(); zones[0] = i32(p_asia_tz()); starts[1] = p_london_start(); ends[1] = p_london_end(); zones[1] = i32(p_london_tz()); starts[2] = p_new_york_start(); ends[2] = p_new_york_end(); zones[2] = i32(p_new_york_tz()); daysKept = i32(p_days_kept()); if (daysKept < 1) daysKept = 1; if (daysKept > MAX_DAYS) daysKept = MAX_DAYS; showTags = pb_show_tags(); clocks = [new Clock(SESSION_TZ_IDS[zones[0]]), new Clock(SESSION_TZ_IDS[zones[1]]), new Clock(SESSION_TZ_IDS[zones[2]])]; for (let s = 0; s < SESSIONS; s += 1) dayKey[s] = NaN; } // onBar() runs once per bar: place the bar in its sessions, open a new instance on a new day, grow the open ones; // then write the output, move the boxes this bar touched, and place a tag when a box opens or grows past its tag's edge. function onBar(): void { prevT = t; t = bar.time(); const high = bar.high(); const low = bar.low(); if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; for (let s = 0; s < SESSIONS; s += 1) { touched[s] = 0; fresh[s] = 0; grew[s] = 0; sank[s] = 0; } if (isNaN(width)) return; // the first bar has no width yet: nothing to draw const coarse = width >= 14400.0; // 4h and coarser: a session is one or two bars, the boxes would say nothing if (coarse) { out_sessions_open(0.0); if (!wordsShown) { // once: the handle stays sb_clear(); sb_text("Session Map needs a chart finer than 4h"); words.set(56, 14).text(str_tag_sb).anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).color(MUTED_INK); wordsShown = true; } return; } let openCount = 0; for (let s = 0; s < SESSIONS; s += 1) { clocks[s].update(t); // the bar in the window's zone, daylight saving included // A bar counts when its span reaches into the window: its open inside it, or the window opening before its close (New // York's 13:30 open inside the 13:00 bar of a 1h chart); lead = minutes from the bar's open to the window's start. const early = !inSession(t, unchecked(starts[s]), unchecked(ends[s]), unchecked(zones[s])); const lead = (unchecked(starts[s]) - f64(clocks[s].hour() * 60 + clocks[s].minute()) + 1440.0) % 1440.0; if (early && !(lead > 0.0 && lead * 60.0 < width)) continue; openCount += 1; touched[s] = 1; const key = Math.floor((t + (early ? lead * 60.0 : 0.0) + f64(clocks[s].offsetSec()) - unchecked(starts[s]) * 60.0) / 86400.0); // the local day the window opened, read at its open (a wrapped window keeps its opening day) if (key != unchecked(dayKey[s])) { // a new session day: the next ring slot (the oldest box moves here) dayKey[s] = key; slot[s] = unchecked(instances[s]) % daysKept; instances[s] = unchecked(instances[s]) + 1; startT[s] = t; hiP[s] = high; loP[s] = low; fresh[s] = 1; } else { if (high > unchecked(hiP[s])) { hiP[s] = high; grew[s] = 1; } if (low < unchecked(loP[s])) { loP[s] = low; sank[s] = 1; } } endT[s] = t + width; // the box ends at this bar's close } out_sessions_open(f64(openCount)); for (let s = 0; s < SESSIONS; s += 1) { if (unchecked(touched[s]) == 0) continue; const id = s * MAX_DAYS + unchecked(slot[s]); const box = boxes[id]; box.set(unchecked(startT[s]), unchecked(hiP[s]), unchecked(endT[s]), unchecked(loP[s])); if (unchecked(fresh[s]) == 1) box.color(inks[s]).fill(inks[s]).opacity(0.08).border(1.0); // the session's colour, set when the box is (re)opened const bottom = s == 1; // the tag sits inside its box's left edge, clear of the chart's High and Low labels: London's on the bottom, Asia's and New York's under the top, so overlapping sessions never share an edge if (showTags && (unchecked(fresh[s]) == 1 || (bottom ? unchecked(sank[s]) : unchecked(grew[s])) == 1)) { sb_clear(); sb_text(NAMES[s]); const tag = tags[id]; tag.set(unchecked(startT[s]), bottom ? unchecked(loP[s]) : unchecked(hiP[s])).text(str_tag_sb); if (unchecked(fresh[s]) == 1) tag.color(inks[s]).size(11).align(ALIGN_LEFT).valign(bottom ? VALIGN_BOTTOM : VALIGN_TOP); } } } ``` ## How it works **Sessions are cut from the clock.** `bar.time()` gives each bar's open in epoch seconds, UTC. Each session is a `param.session` (Asia 00:00 to 08:00, London 07:00 to 16:00, New York 13:30 to 20:00, all in UTC by default), read in `onStart()` as a start, an end and a zone; per bar, a bar belongs to a session when its span reaches into the window in that zone, daylight saving included: `inSession(...)` says whether the bar's open falls inside the window, and a `Clock` in that zone says whether the window opens before the bar closes, so on a 1h chart New York's 13:30 open puts the 13:00 bar in its box. The same clock keys each day's instance, read at the window's open. The bar's high and low grow the open session's box; a box is created on the session's first bar and moved with `set()` on every bar after that, so the live session's box grows as the bars arrive. **A ring of boxes, reused.** `days_kept` (5, up to 10) times three sessions is the number of box handles in play; each day's session takes the slot of the same session `days_kept` days earlier, so the oldest box is reused rather than a new one made. The handle objects are made once, at module start. **Tags sit inside their box.** Each tag hangs inside its box's left edge, so the chart's own High and Low labels, drawn outside the candles' extremes, never sit on one: Asia's and New York's under the top edge (`valign(VALIGN_TOP)`), London's on the bottom edge (`valign(VALIGN_BOTTOM)`), so the two sessions that overlap London never put their tags on the same edge. A tag moves when its edge does: up with a new session high, down with a new session low. **One slot, many tags.** `string("tag", { max_bytes: 48 })` is the one bounded slot; each tag is built with the allocation-free builder (`sb_clear`, `sb_text`, `str_tag_sb`) and sent to its label handle in turn, so the three session names never allocate a string on the live bar. `show_tags` off leaves the boxes bare. **The count is data.** `sessions_open` is a data-only output: 0, 1, or 2 where two sessions overlap. It draws nothing; the editor's Console prompt reads it after a Run. ## Where it runs Every market with candles, on charts finer than 4h. Sessions are cut in the zone each one is set to, UTC by default. ## When data is missing On a 4h or coarser chart a session is one or two bars, so the example draws one muted line of words at the top-right ("Session Map needs a chart finer than 4h") and nothing else. At 1h a session is eight or nine bars wide, and a box starts on the bar its session opens in (New York's at 13:00 for the 13:30 open). ## Customize it - **Other sessions.** The three windows are settings, each with its own zone; a window that crosses midnight (`22:00-04:00`) wraps on its own. - **More days.** `days_kept` goes up to 10; past that, raise the ring's ceiling where the handles are made (each day is three box and three label ids). - **Quieter boxes.** `handles.box({ opacity: 0.08, borderWidth: 1 })` sets the fill and the border for every box; each session's ink (`inks`, the muted colour for all three) is set where its box is created, so a colour per session goes there. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Session Map** under **On price**. 2. Press **Run** on a chart finer than 4h, such as 15m: the boxes draw on the chart and the live session's box grows as bars arrive. 3. At the editor's Console prompt, type `last 60 sessions_open` to read how many sessions were open on each of the last 60 bars. ## Concepts used - [Drawing objects](../presentation/drawing-objects.md) for box and label handles, chart coordinates and ids reused by slot - [Time and sessions](../core-concepts/time-and-sessions.md) for `bar.time()` and UTC day math - [Execution model](../core-concepts/execution-model.md) for module-level state and where `onStart()` and `onBar()` run # Volume heat hours ![Hour boxes tinted by volume with hot-hour multiplier tags](/wrun/images/volume-heat-hours.png) Every clock hour boxed over its high and low, tinted by that hour's volume against the average of the last day's completed hours: quiet hours are nearly invisible, busy hours wash stronger in the text colour, and an hour past the hot multiple gets a border in the same colour and a muted tag such as "2.3x" above it (whole numbers from 10x up). The live hour fills in as its bars arrive. The parts are one box handle per clock hour and a label handle for the tag ([Drawing objects](../presentation/drawing-objects.md)), the bar's open time, `bar.time()`, for the hour boundary ([Time and sessions](../core-concepts/time-and-sessions.md)), and a rolling average of completed hours kept in module-level state. Hours are folded from the chart's own bars, so no pinned leg is needed and the example runs on stocks too. This is also the `volume-heat-hours` template: the **Volume Heat Hours** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volume Heat Hours: every clock hour boxed over its range and tinted by its volume against the average of the last day's hours, // one ramp of the text ink from near-invisible (quiet) to a bright wash (hot); hot hours get a border and a muted "2.3x" tag. Hours are // folded from the chart's own bars. param.int("baseline_hours", 24, { min: 6, max: 168, label: "Baseline in hours", description: "Completed hours the average volume is taken over" }); param.number("hot_multiple", 2.0, { min: 1.2, max: 5, step: 0.1, label: "Hot multiple", description: "An hour at this multiple of the average is hot: it gets a border and a tag" }); param.int("hours_kept", 60, { min: 6, max: 60, label: "Hours kept", description: "Hours kept on the chart; the oldest box is reused" }); legend({ title: "({{baseline_hours}}h)" }); // the words after the name in the legend: the baseline, read by name input("high", ohlcv.high); // the hour's box spans its high and low output("hour_ratio", none, overlay, { description: "This hour's volume so far against the average completed hour" }); // data-only, so the Console can read it string("tag", { max_bytes: 48 }); // one bounded slot every tag is written through handles.box({ opacity: 0.04, borderWidth: 0 }); // boxes in chart time and price: one per hour, quiet by default handles.label({ size: 11 }); // the "2.3x" tags (centred over their box) and the one line of words when the example cannot run const MAX_HOURS = 60; // the ring's ceiling: 60 boxes and 60 tag ids (only hot hours draw theirs) const MAX_BASE = 168; // the baseline ring's ceiling: a week of hours const HOT_INK: i32 = theme.TEXT; // the hours' ramp and a hot hour's border: the chart's text ink const MUTED_INK: i32 = theme.MUTED; // the tags and the one line of words function makeBoxes(first: i32, count: i32): BoxHandle[] { const out: BoxHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.box(first + i)); return out; } function makeLabels(first: i32, count: i32): LabelHandle[] { const out: LabelHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.label(first + i)); return out; } const boxes = makeBoxes(0, MAX_HOURS); // handle objects allocate once, at module load const tags = makeLabels(MAX_HOURS, MAX_HOURS); // tag i belongs to box i, so a recycled hour never leaves a stale tag behind const words = draw.label(200); // the one line of words const hourVolumes = new StaticArray(MAX_BASE); // completed hours' volumes, the baseline ring let baselineHours = 24; let hot = 2.0; let hoursKept = 60; let baseHead = 0; let baseCount = 0; let baseSum = 0.0; // the baseline ring's cursor, fill and running sum let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; // width = the smallest gap between bar opens seen let hourKey: f64 = NaN; let hourSlot = 0; let hours = 0; // the hour being drawn, its ring slot, hours seen let hStart: f64 = NaN; let hEnd: f64 = NaN; let hHi: f64 = NaN; let hLo: f64 = NaN; let hVol = 0.0; // the open hour let bars = 0; let sawVolume = false; let wordsShown = false; let wordsText = ""; // the line of words to show function showWords(): void { sb_clear(); sb_text(wordsText); words.set(56, 14).text(str_tag_sb).anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).color(MUTED_INK); wordsShown = true; } // onStart() runs once before the first bar: read the settings. function onStart(): void { baselineHours = i32(p_baseline_hours()); if (baselineHours < 1) baselineHours = 1; if (baselineHours > MAX_BASE) baselineHours = MAX_BASE; hot = p_hot_multiple(); if (hot < 1.01) hot = 1.01; hoursKept = i32(p_hours_kept()); if (hoursKept < 1) hoursKept = 1; if (hoursKept > MAX_HOURS) hoursKept = MAX_HOURS; } // onBar() runs once per bar: fold the bar into its hour (when a new hour opens, the finished one joins the baseline), write the output, // then paint this hour's box from its ratio; a hot hour gets a border and a tag. function onBar(): void { prevT = t; t = bar.time(); const high = bar.high(); const low = bar.low(); const volume = bar.volume(); if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; bars += 1; if (isNaN(width)) return; // the first bar has no width yet const coarse = width >= 3600.0; // an hourly or coarser chart: an hour is one bar, the boxes would say nothing new if (coarse) { if (!wordsShown) { wordsText = "Volume Heat Hours needs a chart finer than 1h"; showWords(); } return; } const key = Math.floor(t / 3600.0); let fresh = false; if (key != hourKey) { if (!isNaN(hourKey)) { // the finished hour joins the baseline ring (its oldest entry drops out of the sum) baseSum += hVol - unchecked(hourVolumes[baseHead]); hourVolumes[baseHead] = hVol; baseHead = (baseHead + 1) % baselineHours; if (baseCount < baselineHours) baseCount += 1; } hourKey = key; hourSlot = hours % hoursKept; hours += 1; hStart = t; hHi = high; hLo = low; hVol = 0.0; fresh = true; } else { if (high > hHi) hHi = high; if (low < hLo) hLo = low; } if (!isNaN(volume) && volume > 0.0) { hVol += volume; sawVolume = true; } hEnd = t + width; const average = baseCount >= 3 ? baseSum / f64(baseCount) : NaN; // three completed hours before the first tint const ratio = average > 0.0 ? hVol / average : NaN; out_hour_ratio(ratio); if (!sawVolume) { if (bar.isLast() && bars >= 8 && !wordsShown) { wordsText = "No volume on this market"; showWords(); } return; } if (wordsShown) { words.delete(); wordsShown = false; } // volume arrived after all if (fresh) tags[hourSlot].delete(); // a recycled slot starts without the old hour's tag if (isNaN(ratio)) return; // no baseline yet: nothing drawn for this hour let u = (ratio - 0.75) / (hot - 0.75); if (u < 0.0) u = 0.0; if (u > 1.0) u = 1.0; // 0 at three quarters of the average and below, 1 at the hot multiple const isHot = ratio >= hot; boxes[hourSlot].set(hStart, hHi, hEnd, hLo).fill(HOT_INK).opacity(0.04 + 0.41 * u * u).color(HOT_INK).border(isHot ? 1.0 : 0.0); // one ink, alpha 0.04 to 0.45, rising with the square so average hours stay faint if (isHot) { // the tag sits over the box and re-reads its multiple while the hour is still filling sb_clear(); sb_f64(ratio, ratio >= 10.0 ? 0 : 1); sb_text("x"); // "2.3x", "220x" tags[hourSlot].set((hStart + hEnd) * 0.5, hHi + (hHi - hLo) * 0.35).text(str_tag_sb).color(MUTED_INK).size(11); } } ``` ## How it works **An hour is folded from the bars.** `bar.time()` gives each bar's open; a new hour starts when the bar's hour of day changes. The hour's box spans its high and low (`bar.high()`, `bar.low()`) and its volume is the sum of its bars' `bar.volume()`. On the live bar the open hour's box is moved with `set()` so it fills in as the bars arrive. **The baseline is the completed hours.** `baseline_hours` (24, 6 to 168) completed hours feed the average; the ratio of this hour's volume so far against that average is `hour_ratio`, a data-only output the editor's Console prompt reads after a Run. The first three completed hours are the warm-up, so nothing is tinted before them. **Tint by ratio, border past the multiple.** The box fills in the text colour and its opacity follows the ratio: nearly invisible for a quiet hour, a stronger wash as the ratio climbs. An hour at or past `hot_multiple` (2.0) gets a border in the text colour and a muted tag ("2.3x", whole numbers from 10x up) written through the one bounded slot with the allocation-free builder (`sb_clear`, `sb_f64`, `sb_text`, `str_tag_sb`). **A ring of hours.** `hours_kept` (60, the ceiling the handle ring allows) boxes stay on the chart; the oldest is reused. The handle objects are made once, at module start. ## Where it runs Every market with volume, on charts finer than 1h. ## When data is missing On an hourly or coarser chart it draws one muted line of words at the top-right ("Volume Heat Hours needs a chart finer than 1h"). A market without volume (gold on the FX venue) gets "No volume on this market" and nothing else. ## Customize it - **A longer baseline.** `baseline_hours` up to 168 (a week of hours) smooths the average over the weekly cycle. - **Stricter tags.** Raise `hot_multiple` to tag only the busiest hours; the tint still grades every hour. - **Session hours only.** Gate the fold on the hour of day (the [Session map](session-map.md) recipe's window test) to box the cash session alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volume Heat Hours** under **On price**. 2. Press **Run** on a chart finer than 1h, such as 5m or 15m. 3. At the editor's Console prompt, type `last 24 hour_ratio` to read, for each of the last 24 bars, its hour's volume so far against the average completed hour. ## Concepts used - [Drawing objects](../presentation/drawing-objects.md) for box and label handles and ids reused by slot - [Time and sessions](../core-concepts/time-and-sessions.md) for `bar.time()` and the hour boundary - [Execution model](../core-concepts/execution-model.md) for module-level state and where `onStart()` and `onBar()` run # Supply and demand zones ![Supply and demand zone boxes with nearest level price tags](/wrun/images/supply-demand-zones.png) A zone at every confirmed swing high (supply, in the down colour) and swing low (demand, in the up colour), one zone height of ATR deep, anchored on the swing's own bar and extended right bar by bar until a close breaks through it. A broken zone fades to the muted colour, stops extending, and a small rose mark sits on the breakout bar (under the bar that closed up through a supply zone, over the bar that closed down through a demand zone). At the right edge the nearest live zone above and below the close is tagged with its price in muted text: "S 84,210" above, "D 82,950" below (four decimals on sub-dollar markets: "S 0.1398"). The parts are the `PivotHigh`, `PivotLow` and `Atr` helpers from the TA library ([TA library](../functions/ta-library.md)), box handles for the zones and right-anchored label handles for the two price tags ([Drawing objects](../presentation/drawing-objects.md)), and two `shape` outputs for the breakout marks. This is also the `supply-demand-zones` template: the **Supply and Demand Zones** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Supply and Demand Zones: a zone at every confirmed swing high (supply, the down colour) and swing low (demand, the up colour), extended right // until a close breaks through it; a broken zone fades to the muted ink and stops; a rose mark sits on the breakout bar; the nearest live zone // above and below is tagged with its price in plain muted text. param.int("swing_strength", 8, { min: 2, max: 30, label: "Swing strength in bars", description: "Bars on each side a swing high or low must beat" }); param.number("zone_atr", 0.25, { min: 0.05, max: 2, step: 0.01, label: "Zone height in ATR", description: "Zone height in ATR(14) measured at the swing" }); param.int("zones_per_side", 6, { min: 1, max: 12, label: "Zones per side", description: "Zones kept per side; the oldest is replaced" }); param.color("mark_color", "#fb7185", { label: "Break mark" }); // a colour setting: painted onto both break marks below by name, so the Style page shows one control for it legend({ title: "({{swing_strength}})" }); // the words after the name in the legend: the swing strength, read by name input("high", ohlcv.high); // swing highs come from the highs, swing lows from the lows output("break_up", shape, overlay, { color: "@mark_color", description: "A mark at the bar's low on a bar that closed up through a supply zone" }); // a rose mark under the breakout bar, in the colour setting output("break_down", shape, overlay, { color: "@mark_color", description: "A mark at the bar's high on a bar that closed down through a demand zone" }); // and over the breakdown bar output("supply_near", none, overlay, { description: "Bottom of the nearest live supply zone above the close" }); // data-only, for the Console output("demand_near", none, overlay, { description: "Top of the nearest live demand zone below the close" }); string("tag", { max_bytes: 48 }); // one bounded slot both tags are written through handles.box({ opacity: 0.14, borderWidth: 1 }); // zones in chart time and price handles.label({ anchor: "right", size: 11, align: "right" }); // the two price tags: pixels from the right edge, price on the y axis const MAX_ZONES = 12; // per side: 24 boxes at most, ids 0..23 const RING = 64; // bars of history kept for the swing's own time and ATR (swing_strength is at most 30) const SUPPLY_INK: i32 = theme.DOWN; const DEMAND_INK: i32 = theme.UP; const MUTED_INK: i32 = theme.MUTED; // the chart's own colours: a spent zone, the tags and the words muted const TAG_X = 56.0; // the tags end 56 px from the pane's right edge, clear of the price-axis pills function makeBoxes(first: i32, count: i32): BoxHandle[] { const out: BoxHandle[] = []; for (let i = 0; i < count; i += 1) out.push(draw.box(first + i)); return out; } const supplyBoxes = makeBoxes(0, MAX_ZONES); const demandBoxes = makeBoxes(MAX_ZONES, MAX_ZONES); // handle objects allocate once const supplyTag = draw.label(30); const demandTag = draw.label(31); const words = draw.label(32); // the one line of words while no swing has confirmed // One zone per ring slot, per side: its top and bottom, its first bar, whether it is still live, and what changed this bar. const sTop = new StaticArray(MAX_ZONES); const sBottom = new StaticArray(MAX_ZONES); const sStart = new StaticArray(MAX_ZONES); const sLive = new StaticArray(MAX_ZONES); const sUsed = new StaticArray(MAX_ZONES); const sEvent = new StaticArray(MAX_ZONES); // event: 1 opened, 2 broke const dTop = new StaticArray(MAX_ZONES); const dBottom = new StaticArray(MAX_ZONES); const dStart = new StaticArray(MAX_ZONES); const dLive = new StaticArray(MAX_ZONES); const dUsed = new StaticArray(MAX_ZONES); const dEvent = new StaticArray(MAX_ZONES); const times = new StaticArray(RING); const atrs = new StaticArray(RING); // the last bars' opens and ATRs, so a swing is anchored on its own bar let strength = 8; let zoneAtr = 0.25; let zonesPerSide = 6; let pivotHigh = new PivotHigh(8, 8); let pivotLow = new PivotLow(8, 8); const atr = new Atr(14); let head = 0; let supplyCount = 0; let demandCount = 0; let bars = 0; let wordsShown = false; // the history ring's cursor, the zones seen per side, bars seen let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; // A price in words: thousands grouped, cents on small prices, four decimals under one. function sbGrouped(n: i64): void { 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 { const a = Math.abs(v); if (a >= 1000.0) sbGrouped(i64(Math.round(a))); else if (a >= 1.0) sb_f64(a, 2); else sb_f64(a, 4); } // onStart() runs once before the first bar: read the settings and size the swing helpers. function onStart(): void { strength = i32(p_swing_strength()); if (strength < 1) strength = 1; if (strength > RING - 2) strength = RING - 2; zoneAtr = p_zone_atr(); zonesPerSide = i32(p_zones_per_side()); if (zonesPerSide < 1) zonesPerSide = 1; if (zonesPerSide > MAX_ZONES) zonesPerSide = MAX_ZONES; pivotHigh = new PivotHigh(strength, strength); pivotLow = new PivotLow(strength, strength); } // onBar() runs once per bar: fold the bar into the helpers, open a zone on a confirmed swing, break zones the close went through, write the outputs; // then open or fade the zones that changed, extend the live ones to this bar, and tag the nearest two on the live bar. function onBar(): void { prevT = t; t = bar.time(); const high = bar.high(); const low = bar.low(); const close = bar.close(); bars += 1; if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; const atrNow = atr.update(high, low, close); times[head] = t; atrs[head] = atrNow; head = (head + 1) % RING; const swingHigh = pivotHigh.update(high); const swingLow = pivotLow.update(low); // reported on the bar that confirms them, strength bars after the swing for (let i = 0; i < MAX_ZONES; i += 1) { sEvent[i] = 0; dEvent[i] = 0; } if (isNaN(width)) return; // the first bar has no width yet const at = (head - 1 - strength + RING) % RING; // the swing's own bar in the ring let swingAtr = unchecked(atrs[at]); if (isNaN(swingAtr)) swingAtr = atrNow; // early in the run the ATR at the swing may not exist yet if (!isNaN(swingHigh) && !isNaN(swingAtr) && swingAtr > 0.0) { // a supply zone hangs down from the swing high let overlaps = false; for (let i = 0; i < MAX_ZONES; i += 1) if (unchecked(sUsed[i]) == 1 && unchecked(sLive[i]) == 1 && swingHigh <= unchecked(sTop[i]) && swingHigh >= unchecked(sBottom[i])) overlaps = true; if (!overlaps) { const k = supplyCount % zonesPerSide; supplyCount += 1; sTop[k] = swingHigh; sBottom[k] = swingHigh - zoneAtr * swingAtr; sStart[k] = unchecked(times[at]); sLive[k] = 1; sUsed[k] = 1; sEvent[k] = 1; } } if (!isNaN(swingLow) && !isNaN(swingAtr) && swingAtr > 0.0) { // a demand zone stands up from the swing low let overlaps = false; for (let i = 0; i < MAX_ZONES; i += 1) if (unchecked(dUsed[i]) == 1 && unchecked(dLive[i]) == 1 && swingLow <= unchecked(dTop[i]) && swingLow >= unchecked(dBottom[i])) overlaps = true; if (!overlaps) { const k = demandCount % zonesPerSide; demandCount += 1; dBottom[k] = swingLow; dTop[k] = swingLow + zoneAtr * swingAtr; dStart[k] = unchecked(times[at]); dLive[k] = 1; dUsed[k] = 1; dEvent[k] = 1; } } let breakUp: f64 = NaN; let breakDown: f64 = NaN; let supplyNear: f64 = NaN; let demandNear: f64 = NaN; for (let i = 0; i < MAX_ZONES; i += 1) { if (unchecked(sUsed[i]) == 1 && unchecked(sLive[i]) == 1 && unchecked(sEvent[i]) == 0) { if (close > unchecked(sTop[i])) { sLive[i] = 0; sEvent[i] = 2; breakUp = low; } // closed up through supply: spent, marked under the bar else if (unchecked(sBottom[i]) > close && (isNaN(supplyNear) || unchecked(sBottom[i]) < supplyNear)) supplyNear = unchecked(sBottom[i]); } if (unchecked(dUsed[i]) == 1 && unchecked(dLive[i]) == 1 && unchecked(dEvent[i]) == 0) { if (close < unchecked(dBottom[i])) { dLive[i] = 0; dEvent[i] = 2; breakDown = high; } // closed down through demand else if (unchecked(dTop[i]) < close && (isNaN(demandNear) || unchecked(dTop[i]) > demandNear)) demandNear = unchecked(dTop[i]); } } out_break_up(breakUp); out_break_down(breakDown); out_supply_near(supplyNear); out_demand_near(demandNear); const right = t + width; for (let i = 0; i < MAX_ZONES; i += 1) { if (unchecked(sUsed[i]) == 1) { const box = supplyBoxes[i]; const e = unchecked(sEvent[i]); if (e == 1 || unchecked(sLive[i]) == 1) box.set(unchecked(sStart[i]), unchecked(sTop[i]), right, unchecked(sBottom[i])); // a live zone grows to the newest bar if (e == 1) box.color(SUPPLY_INK).fill(SUPPLY_INK).opacity(0.14).border(1.0); if (e == 2) { box.set(unchecked(sStart[i]), unchecked(sTop[i]), right, unchecked(sBottom[i])).color(MUTED_INK).fill(MUTED_INK).opacity(0.04); } // spent: ends on the breakout bar } if (unchecked(dUsed[i]) == 1) { const box = demandBoxes[i]; const e = unchecked(dEvent[i]); if (e == 1 || unchecked(dLive[i]) == 1) box.set(unchecked(dStart[i]), unchecked(dTop[i]), right, unchecked(dBottom[i])); if (e == 1) box.color(DEMAND_INK).fill(DEMAND_INK).opacity(0.14).border(1.0); if (e == 2) { box.set(unchecked(dStart[i]), unchecked(dTop[i]), right, unchecked(dBottom[i])).color(MUTED_INK).fill(MUTED_INK).opacity(0.04); } } } if (bar.isLast() && supplyCount + demandCount == 0 && bars > 2 * strength + 20) { // a flat market (a tie on a swing's right never confirms it): say so instead of an empty pane if (!wordsShown) { sb_clear(); sb_text("No confirmed swings on this chart yet"); words.set(56, 14).text(str_tag_sb).anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).color(MUTED_INK); wordsShown = true; } } else if (wordsShown) { words.delete(); wordsShown = false; } if (bar.isLast()) { // the two tags: the nearest live zone above and below the close, on the live bar only if (!isNaN(supplyNear)) { sb_clear(); sb_text("S "); sbPrice(supplyNear); supplyTag.set(TAG_X, supplyNear).text(str_tag_sb).color(MUTED_INK).size(11).anchor(ANCHOR_RIGHT).align(ALIGN_RIGHT); } else supplyTag.delete(); if (!isNaN(demandNear)) { sb_clear(); sb_text("D "); sbPrice(demandNear); demandTag.set(TAG_X, demandNear).text(str_tag_sb).color(MUTED_INK).size(11).anchor(ANCHOR_RIGHT).align(ALIGN_RIGHT); } else demandTag.delete(); } } ``` ## How it works **A swing confirms late.** `swing_strength` (8, 2 to 30) is the number of bars on each side a swing high or low must beat, so a swing is known `swing_strength` bars after it happened; the zone is anchored back on the swing's own bar through `bar.time()`. The swings are TradingView's pivots: a swing must beat the bars after it strictly, while a tie with a bar before it still counts. **One zone height of ATR.** `zone_atr` (0.25, in ATR(14) measured at the swing) sets the zone's depth: a supply zone hangs from the swing high, a demand zone stands on the swing low. Every bar the live zones are extended right with `set()`; a close through a zone breaks it, the box fades to the muted colour and stops extending, and the bar's low or high is written to `break_up` or `break_down`, the two rose `shape` outputs (NaN on every other bar, so nothing is drawn there). **A ring per side.** `zones_per_side` (6, up to 12) zones stay per side; the oldest is replaced. The handle objects are made once, at module start. **The nearest zone is data.** `supply_near` (the bottom of the nearest live supply zone above the close) and `demand_near` (the top of the nearest live demand zone below it) are data-only outputs, one value per bar, readable at the editor's Console prompt. The same two prices are the tags at the right edge, written through the one bounded slot with the allocation-free builder; the tag's decimals follow the price (four on sub-dollar markets). ## Where it runs Every market with candles. The first zones appear once a swing has confirmed (about twice the swing strength in bars) and the ATR has warmed up (14 bars). ## When data is missing A swing must beat the bars after it strictly, so a flat, tick-quantized market (a prediction market pinned at one price) may confirm none: the example then says "No confirmed swings on this chart yet" at the top-right instead of leaving the pane empty. ## Customize it - **Bigger structures.** Raise `swing_strength`; the zones confirm later and there are fewer of them. - **Deeper zones.** `zone_atr` up to 2 ATRs; a zone is broken by a close through its far edge. - **Keep broken zones out.** Delete a broken zone's handle instead of fading it to the muted colour, and its slot frees for the next swing. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Supply and Demand Zones** under **On price**. 2. Press **Run**. The first zones appear once a swing has confirmed and the ATR has warmed up. 3. At the editor's Console prompt, type `supply_near` and `demand_near` to read the two tagged prices on the newest bar. ## Concepts used - [TA library](../functions/ta-library.md) for `PivotHigh`, `PivotLow` and `Atr` - [Drawing objects](../presentation/drawing-objects.md) for box handles, right-anchored labels and chart coordinates - [Plotting](../presentation/plotting.md) for `shape` outputs that draw only where they are finite # Trend alignment ![Three EMAs, regime tint and the 15m/1h/4h state strip](/wrun/images/trend-alignment.png) Three averages on the price pane: the chart's own EMA (sky) beside the 1h EMA (violet) and the 4h EMA (teal), the higher-timeframe ones drawn as steps that move only when their candle closes. The background tints in the chart's default up colour while price and both higher timeframes point up, in its default down colour while all three point down, and stays clear when they disagree; a new state has to hold for two bars before the tint flips, so there are no one-bar stripes. A three-cell strip at the top-right reads the state in words: "15m up 1h up 4h down", each word in the up, down or muted colour. The parts are two `candles` streams of closed 1h and 4h candles with the history to seed their averages ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)), a `render.bgcolor` tint gated and coloured by a data-only output ([Styling](../presentation/styling.md)), and a strip of anchored box and label handles at the top-right corner ([Drawing objects](../presentation/drawing-objects.md)). This is also the `trend-alignment` template: the **Trend Alignment** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Trend Alignment: the chart's EMA beside the 1h and 4h EMAs as stepped lines; the background tints only while price and both higher // timeframes agree (the up colour up, the down colour down, held two bars before it flips); a three-cell strip at the top-right reads // "15m up 1h up 4h down", each word in the up, down or muted colour. param.int("ema_chart", 21, { min: 2, max: 200, label: "Chart EMA", row: "chart", description: "EMA length on the chart's own bars" }); // each length shares a dialog line with its line's colour: rows naming the same row word sit side by side param.color("chart_color", "#38bdf8", { label: "Chart line", row: "chart" }); // a colour setting, painted onto the output below by name param.int("ema_1h", 21, { min: 2, max: 200, label: "1h EMA", row: "1h", description: "EMA length on 1h closes" }); param.color("color_1h", "#a78bfa", { label: "1h line", row: "1h" }); param.int("ema_4h", 9, { min: 2, max: 200, label: "4h EMA", row: "4h", description: "EMA length on 4h closes" }); param.color("color_4h", "#2dd4bf", { label: "4h line", row: "4h" }); input("close", ohlcv.close); // the chart's own close: the primary grid input("h1", candles.cells, { interval: "1h", bars: 200 }); // the closed 1h candles: the first bar carries the 200 before it, so the 1h EMA is warm from the first bar; each later bar the ones that closed since input("h4", candles.cells, { interval: "4h", bars: 200 }); // the same for 4h const chartLine = output("ema_chart", line, overlay, { color: "@chart_color", width: 2, label: "Chart EMA", format: "price", description: "EMA on the chart's bars" }); // the colour setting paints it; the handle names it for the hover card output("ema_1h", line, overlay, { color: "@color_1h", width: 2, label: "1h EMA", format: "price", description: "EMA on 1h closes; steps once per hour" }); output("ema_4h", line, overlay, { color: "@color_4h", width: 2, label: "4h EMA", format: "price", description: "EMA on 4h closes; steps once per four hours" }); output("aligned", none, overlay, { description: "+1 while all three point up, -1 while all three point down, 0 mixed; a new state must hold two bars" }); // data-only, for the Console hover(chartLine, [block.value("Chart EMA", "ema_chart", { format: "price" }), block.rows([["1h EMA", "ema_1h", "price"], ["4h EMA", "ema_4h", "price"], ["Aligned", "aligned", "int"]])]); // the card the chart EMA opens under the cursor: its value, then the other two averages and the state render.bgcolor("alignment", { where: "aligned", color_by: "aligned", colors: ["#ef53501a", "#26a69a1a"] }); // the chart's default down and up hues at alpha 0.10 (a tint carries its own alpha); -1 clamps to colors[0] (down), +1 reads colors[1] (up); 0 draws nothing string("cell", { max_bytes: 80 }); // one bounded slot every strip cell is written through handles.box({ anchor: "top_right", color: "theme.bg", opacity: 0.85, borderWidth: 0 }); // the strip's backdrop in the chart's background colour, no frame, in pane pixels from the top-right corner handles.label({ anchor: "top_right", align: "right", color: "theme.text", size: 11 }); // the strip's cells, right-aligned in pane pixels const UP_INK: i32 = theme.UP; const DOWN_INK: i32 = theme.DOWN; const MUTED_INK: i32 = theme.MUTED; // the chart's own colours: a direction's sign, flat or unknown muted const CELL_W = 74.0; const RIGHT = 56.0; // cell width in pixels; the strip stays clear of the price-axis tags (about 46 px into the pane) const backdrop = draw.box(0); // handle objects allocate once const cells: LabelHandle[] = [draw.label(1), draw.label(2), draw.label(3)]; // chart, 1h, 4h const words = draw.label(4); // the one line of words on an hourly or coarser chart let emaChart = new Ema(21); let avg1h = new Ema(21); let avg4h = new Ema(9); // each higher-timeframe average folds one closed candle at a time: NaN until it has folded its length let ema1h: f64 = NaN; let ema4h: f64 = NaN; let close1h: f64 = NaN; let close4h: f64 = NaN; // the two averages and the newest closed 1h and 4h closes let t: f64 = NaN; let prevT: f64 = NaN; let width: f64 = NaN; let foldedClose: f64 = NaN; // fold()'s second answer: the newest close it folded let candidate = 0; let candidateRun = 0; let held = 0; // the alignment state, and the state waiting two bars to take over function direction(price: f64, average: f64): i32 { return isNaN(price) || isNaN(average) ? 0 : price > average ? 1 : price < average ? -1 : 0; } // The chart interval in words from the bar width: 15m, 1h, 4h, 1d. function sbInterval(): void { if (width < 3600.0) { sb_int(i64(Math.round(width / 60.0))); sb_text("m"); } else if (width < 86400.0) { sb_int(i64(Math.round(width / 3600.0))); sb_text("h"); } else { sb_int(i64(Math.round(width / 86400.0))); sb_text("d"); } } function sbDirection(dir: i32, known: bool): void { sb_text(!known ? " -" : dir > 0 ? " up" : dir < 0 ? " down" : " flat"); } // "-" while the average warms // Fold a block of closed candles into an average, oldest first: returns the average after the newest (the one before when the block is empty) and leaves that candle's close in foldedClose. function fold(block: StaticArray, cells: i32, avg: Ema, value: f64, close: f64): f64 { const n = cells < block.length ? cells : block.length; // -1 (no candle yet) and 0 fold nothing let v = value; foldedClose = close; for (let i = 0; i + 6 <= n; i += 6) { const c = unchecked(block[i + 4]); if (!isFinite(c)) continue; v = avg.update(c); foldedClose = c; } // [offset_ms, open, high, low, close, volume] per candle return v; } function tone(dir: i32): i32 { return dir > 0 ? UP_INK : dir < 0 ? DOWN_INK : MUTED_INK; } // onStart() runs once before the first bar: read the settings. function onStart(): void { emaChart = new Ema(i32(p_ema_chart())); avg1h = new Ema(i32(p_ema_1h())); avg4h = new Ema(i32(p_ema_4h())); } // onBar() runs once per bar: feed the chart EMA every bar, fold the 1h and 4h candles that closed by this bar into their averages, read the // three directions, then write the lines and the state; on the live bar only, redraw the strip. function onBar(): void { prevT = t; t = bar.time(); const close = bar.close(); if (!isNaN(prevT) && t > prevT && (isNaN(width) || t - prevT < width)) width = t - prevT; const fast = emaChart.update(close); ema1h = fold(in_h1_view(), in_h1_cells(), avg1h, ema1h, close1h); close1h = foldedClose; // a candle arrives on the bar whose close is at or after its own, so each average steps once per candle ema4h = fold(in_h4_view(), in_h4_cells(), avg4h, ema4h, close4h); close4h = foldedClose; const dirChart = direction(close, fast); const dir1h = direction(close1h, ema1h); const dir4h = direction(close4h, ema4h); // +1 above its average, -1 below, 0 unknown const next = dirChart != 0 && dirChart == dir1h && dir1h == dir4h ? dirChart : 0; if (next == candidate) candidateRun += 1; else { candidate = next; candidateRun = 1; } if (candidateRun >= 2) held = candidate; // a state has to hold two bars before the tint flips: no one-bar stripes if (isNaN(fast)) return; out_ema_chart(fast); out_ema_1h(ema1h); out_ema_4h(ema4h); out_aligned(f64(held)); if (bar.isLast()) { backdrop.set(RIGHT + 3.0 * CELL_W + 16.0, 12.0, RIGHT, 36.0); // pixels from the top-right corner: left, top, right, bottom sb_clear(); sbInterval(); sbDirection(dirChart, true); cells[0].set(RIGHT + 8.0 + 2.0 * CELL_W, 24.0).text(str_cell_sb).color(tone(dirChart)).align(ALIGN_RIGHT); sb_clear(); sb_text("1h"); sbDirection(dir1h, !isNaN(ema1h)); cells[1].set(RIGHT + 8.0 + CELL_W, 24.0).text(str_cell_sb).color(tone(dir1h)).align(ALIGN_RIGHT); sb_clear(); sb_text("4h"); sbDirection(dir4h, !isNaN(ema4h)); cells[2].set(RIGHT + 8.0, 24.0).text(str_cell_sb).color(tone(dir4h)).align(ALIGN_RIGHT); if (width >= 3600.0) { sb_clear(); sb_text(width > 3600.0 ? "Made for charts finer than 1h" : "Made for charts finer than 1h: here the 1h average is the chart's own"); words.set(RIGHT, 50.0).text(str_cell_sb).color(MUTED_INK).align(ALIGN_RIGHT); } } } ``` ## How it works **Closed candles step the averages.** `input("h1", candles.cells, { interval: "1h", bars: 200 })` and its 4h twin are streams of closed candles: the first bar carries the 200 that closed before it, and every later bar carries the candles that closed since, on the bar whose close is at or after the candle's own. `fold()` feeds each candle's close, oldest first, to a kit `Ema` of the setting's length, so each higher-timeframe EMA steps once per closed candle and is flat in between, and it is already warm on the chart's first bar: on a 1m chart the 1h EMA (21) has folded about 190 hourly closes before the first minute, so it reads the same value as an EMA over the market's whole history. An `Ema` is NaN until it has folded its length (its first value is the average of those closes), so a length deeper than the history served draws nothing rather than a guess, and the strip reads "-" for that timeframe. The chart's own EMA (`ema_chart`, 21) reads the bar's close. **Agreement is a number.** `aligned` is +1 while the close sits above all three averages and every average points up, -1 while all three point down, 0 otherwise; a new state must hold two bars before it is written, which is what keeps one-bar stripes off the chart. It is data-only: the tint reads it, and so does the editor's Console prompt. **The tint reads the number.** `render.bgcolor("alignment", { where: "aligned", color_by: "aligned", colors: [down, up] })` gates on the output and picks its colour from it: -1 clamps to the first entry, +1 reads the second, 0 draws nothing. The two entries are the chart's default down and up colours as hex at alpha 0.10, since a tint carries its own alpha. **The strip is three cells.** A backdrop box and three right-aligned labels are anchored to the pane's top-right corner in pixels; each cell is written through the one bounded slot on the live bar and names the chart interval from the bar spacing. ## Where it runs Crypto and prediction markets on charts finer than 1h, such as 1m, 5m, 15m or 30m: the chart fetches each stream on its own, 200 closed candles deep, so the averages are right from the first bar on every one of them. On a 1h chart the 1h stream holds the chart's own candles; a chart coarser than 1h still runs, reading every 1h candle inside each of its bars, and says the example is made for finer charts. OpenMarket's alerts engine does not read `candles` streams yet, so an alert on this indicator is refused when you save it ([Alerts](../functions/alerts.md)). ## When data is missing On an hourly chart the 1h average is the chart's own, so the example adds one muted line of words under the strip ("Made for charts finer than 1h: here the 1h average is the chart's own") and keeps the lines and the tint; on a coarser chart the line reads "Made for charts finer than 1h". Where a market's history is shorter than an average's length, that average stays empty and its strip cell reads "-". ## Customize it - **Other timeframes.** Change the two `interval` words (declaration literals, not settings) and the strip's two labels; raise `bars` for an average longer than 200 candles. - **Slower flips.** Raise the two-bar hold where `aligned` is written to demand a longer agreement. - **Lines only.** Delete the `render.bgcolor` line to keep the three averages and the strip without the tint. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Trend Alignment** under **On price**. 2. Press **Run** on a chart finer than 1h, such as 15m: the three averages draw, the background tints while they agree, and the strip reads the state. 3. At the editor's Console prompt, type `last 20 aligned` to read the state of the last 20 bars. ## Concepts used - [Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream) for the `candles` stream, its `bars` depth and when a candle arrives - [Styling](../presentation/styling.md) for `render.bgcolor`, gates and colour ladders - [Drawing objects](../presentation/drawing-objects.md) for anchored box and label handles in pane pixels # Trend candles ![Candles tinted by two averages with flip dots and bar counter](/wrun/images/trend-candles.png) The chart's own candles tinted by where the close sits against two moving averages. Above both averages the candle takes the up tint, below both the down tint (two colour settings, the chart's default up and down colours to start), and between them it keeps the chart's own colours. The two averages are lines: the fast one in the text colour, the slow one fainter. A dot marks each bar where the close crossed from one side of both averages to the other: under the bar for a flip up (in the up tint), over it for a flip down (in the down tint); crossing into the gap between the lines and back to the same side is not a flip. A counter at the top right reads how long the current state has held: "12 bars up", "7 bars down", "3 bars between". The parts are `render.barcolor`, the per-bar candle tint gated and coloured by two data-only outputs ([Styling](../presentation/styling.md)), two `shape` outputs for the flip dots, and one label handle anchored to the top-right corner for the counter ([Drawing objects](../presentation/drawing-objects.md)). This is also the `trend-candles` template: the **Trend Candles** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Trend Candles: the chart's own candles tinted by where the close sits against two moving averages. Above both, // the candle takes the up tint; below both, the down tint (two colour settings, the chart's default up and down hues); // between them it keeps the chart's own colours. The two averages are drawn as lines (fast in the text ink, slow // fainter), a dot marks each bar where the trend flipped from one side to the other // (under the bar for a flip up, over it for a flip down), and a counter at the top right reads how long the current // state has held ("12 bars up"). param.int("fast_len", 21, { min: 2, max: 200, label: "Fast EMA", row: "lengths", description: "Fast EMA length in bars" }); // two whole numbers on one dialog line param.int("slow_len", 50, { min: 2, max: 400, label: "Slow EMA", row: "lengths", description: "Slow EMA length in bars" }); param.color("up_color", "#26a69a", { label: "Up tint", row: "tints" }); // two colour settings on one line: each paints the dot and the candle tint of its side below, by name param.color("down_color", "#ef5350", { label: "Down tint", row: "tints" }); const fastLine = output("fast_ema", line, overlay, { color: "theme.text", width: 2, label: "Fast EMA", format: "price", description: "EMA of the close over fast_len bars" }); // the handle names it for the hover card output("slow_ema", line, overlay, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Slow EMA", format: "price", description: "EMA of the close over slow_len bars" }); output("trend", none, overlay, { description: "+1 above both averages, -1 below both, 0 between" }); output("tinted", none, overlay, { description: "1 when the candle is tinted (above or below both averages): the tint's gate" }); output("tint", none, overlay, { description: "1 above both averages (the up tint), 0 below both (the down tint): the tint's colour index" }); output("run", none, overlay, { description: "Bars the current state has held" }); output("flip_up", shape, overlay, { color: "@up_color", description: "A dot under the bar where the trend turned up" }); // the up tint setting paints it output("flip_down", shape, overlay, { color: "@down_color", description: "A dot over the bar where the trend turned down" }); string("text", { max_bytes: 24 }); // the counter's one line handles.label({ anchor: "top_right", align: "right", size: 12 }); // the counter, in pane pixels from the chart's top-right corner render.barcolor("trend_tint", { where: "tinted", color_by: "tint", colors: ["@down_color", "@up_color"] }); // the bar's own candle, body and wick, in the two tint settings hover(fastLine, [block.value("Fast EMA", "fast_ema", { format: "price" }), block.rows([["Slow EMA", "slow_ema", "price"], ["Trend", "trend", "int"], ["Run", "run", "int"]])]); // the card the fast average opens under the cursor const MUTED_INK = theme.MUTED; // the counter between the averages: the chart's muted text const counter = draw.label(0); let fastLen = 21; // settings, read in onStart() let slowLen = 50; let upInk = rgba(38, 166, 154, 255); // the two tint settings: the counter reads in the side's tint let downInk = rgba(239, 83, 80, 255); let fastEma = new Ema(21); // rebuilt in onStart() let slowEma = new Ema(50); let trend = 0; // +1 above both, -1 below both, 0 between let lastTinted = 0; // the last side the close was on (+1 or -1): a flip is a change of side let run = 0; // bars the current state has held let rangeAvg: f64 = NaN; // a running mean of high - low: the dot's distance from the bar function onStart(): void { fastLen = i32(p_fast_len()); slowLen = i32(p_slow_len()); fastEma = new Ema(fastLen); slowEma = new Ema(slowLen); upInk = fromPacked(p_up_color()); downInk = fromPacked(p_down_color()); } // onBar() runs once per bar: feed both averages, place the close against them, count the run, catch a flip; // then write the averages, the state and the dots on every bar, and the counter on the live bar only. function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const fast = fastEma.update(close); const slow = slowEma.update(close); const range = high - low; rangeAvg = isNaN(rangeAvg) ? range : rangeAvg + (range - rangeAvg) * 0.1; let flipUpY: f64 = NaN; // this bar's dots, NaN when the side held let flipDownY: f64 = NaN; if (isNaN(fast) || isNaN(slow)) return; // warm-up rows draw nothing const next = close > fast && close > slow ? 1 : close < fast && close < slow ? -1 : 0; run = next == trend ? run + 1 : 1; trend = next; if (trend != 0 && trend != lastTinted) { // the close crossed to the other side of both averages if (lastTinted != 0) { if (trend > 0) flipUpY = low - rangeAvg * 0.6; else flipDownY = high + rangeAvg * 0.6; } lastTinted = trend; } out_fast_ema(fast); out_slow_ema(slow); out_trend(f64(trend)); out_tinted(trend != 0 ? 1.0 : 0.0); out_tint(trend > 0 ? 1.0 : 0.0); out_run(f64(run)); out_flip_up(flipUpY); out_flip_down(flipDownY); if (bar.isLast()) { sb_clear(); sb_int(run); sb_text(run == 1 ? " bar " : " bars "); sb_text(trend > 0 ? "up" : trend < 0 ? "down" : "between"); counter.set(60, 14).text(str_text_sb).align(ALIGN_RIGHT).color(trend > 0 ? upInk : trend < 0 ? downInk : MUTED_INK); // inward past the price-axis tags, in the side's tint } } ``` ## How it works **Two averages, three states.** `fast_len` (21) and `slow_len` (50) are the EMA lengths; `trend` is +1 while the close sits above both averages, -1 below both, 0 between. It is data-only; the editor's Console prompt reads it after a Run. **The candle reads two numbers.** `render.barcolor("trend_tint", { where: "tinted", color_by: "tint", colors: ["@down_color", "@up_color"] })` tints the bar's own candle, body and wick: `tinted` (1 above or below both averages) is the gate, `tint` (1 above, 0 below) picks the colour. Between the lines the gate is 0 and the candle keeps the chart's own colours. **A flip is a change of side.** `flip_up` carries the bar's low on a bar where `trend` went from -1 to +1 (a dot in the up tint under the bar), `flip_down` the bar's high on the way back (a dot in the down tint over it); both are NaN elsewhere. Crossing into the gap and back to the same side is not a flip. **The counter is a slot.** `run` counts the bars the current state has held; on the live bar it is written through the one bounded slot ("12 bars up") to a label anchored at the top-right corner in pixels. It reads in the side's tint: `onStart()` turns the **Up tint** and **Down tint** settings into colours with `fromPacked(p_up_color())` and `fromPacked(p_down_color())`, so a changed tint recolours the candles, the dots and the counter together (the muted text colour between the averages). ## Where it runs Every market with candles: crypto, stocks, FX, prediction markets, and CME futures once you have accepted the CME market data terms (the results stay on the chart). ## When data is missing The first `slow_len` bars are warm-up and draw nothing; a bar without a close keeps the chart's own colours. ## Customize it - **Other averages.** Swap `Ema` for `Sma` from the TA library; the lengths stay settings. - **A one-line filter.** Drop the slow average and the "between" state to tint by one line. - **Tint the wick only.** `render.barcolor` colours body and wick together; for the body alone, draw the tint as a `render.bgcolor` band instead. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Trend Candles** under **On price**. 2. Press **Run**: the candles take the tint, and the counter appears at the top right. 3. At the editor's Console prompt, type `last 20 trend` to read the state of the last 20 bars. ## Concepts used - [Styling](../presentation/styling.md) for `render.barcolor`, gates and colour ladders - [Plotting](../presentation/plotting.md) for `shape` outputs that draw only where they are finite - [Drawing objects](../presentation/drawing-objects.md) for the anchored label and the text slot # Strike Matrix ![Two charts side by side. On the left, BTCUSDT 5m with the strike board docked on the price axis. Its coloured boxes print signed dollars, with a bar per strike beside them. Dashed level lines with labels cross the chart. On the right sit the Options Dashboard's tiles, gamma curve and pane of buys minus sells](/wrun/images/style-anything/overview.png) To find levels price may respect, a price-axis board shows strikes (option price levels) down and expiry dates across. Each box shows dealer gamma, how fast dealers (the market makers who hedge options) must hedge as price moves. Up-colour boxes lean to calls (bets on a rise), down-colour boxes to puts (bets on a fall). One dashed line marks the gamma flip (Flip), where dealers switch from calming price to pushing it. Three others mark max pain (MP), where option holders collect least, and the strikes heaviest in gamma and in puts. Under the hood: it reads `options_chain.cells` as one block on the live bar ([Data sources](../core-concepts/data-sources.md)). It writes two frames from the frame buffer: a `plot.matrix` over the board and a `plot.levels` over the bars. Both dock right, kept apart by an `offset` ([Price canvases](../presentation/price-canvases.md), [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)). **Layout** net writes its one column to a `plot.matrix` of its own. `fbExpiryLabel` writes the column dates ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)). `GammaCurve` gives the flip, and `optionsAsOfMs` and `optionsLiveUntilMs` the as-of and the expiries still trading ([The market's own date](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). `OptionsChain` gives max pain and the walls ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)). `NodeBoard`, `expiryPresetCount` and `StrikeVelocity` give the nodes, the columns and the velocity ([The strike board](../functions/options-kit.md#the-strike-board)). `draw.line` drawings are placed from the newest bar, with label handles pinned in pixels from the price axis ([Drawing objects](../presentation/drawing-objects.md)). This is also the `strike-matrix` template: the **Strike Matrix** card under **On price** in the editor's starter list. It compiles as written. It is the left chart of the options desk that [Style anything](../presentation/style-anything.md) walks through part by part, beside the [Options Dashboard](options-dashboard.md). ## The wrun indicator ```typescript // Strike Matrix: this symbol's live options as a board on the price axis, strikes down and expiry dates across. A // strike is an option's price level, and an expiry is the date an option ends. Each box shows dealer gamma at that // strike and date. Dealers are the market makers who hedge what they sell. Gamma is how fast dealers must hedge as // price moves. A box in the up colour means calls (bets on a rise) carry the strike. A box in the down colour means // puts (bets on a fall) do. Deeper colour means a bigger number. Bars beside the board total each strike. Four dashed // lines mark key prices. The gamma flip is where dealers switch from calming moves to feeding them. Max pain is the // strike where option buyers collect the least at expiry. The put wall is the strike with the heaviest puts at or below // the price. The last line marks the strike with the most positive gamma. Big strikes often act as magnets or walls for // price. Use it to see where dealer hedging may slow a move or speed it up. // // Under the hood: the chart's own live option chain as a strike by expiry board docked on the price axis (one lens per // cell, in the chart's up colour where calls carry the strike and its down colour where puts do, the tint deepening // with size), a column of per-strike bars beside it, and four dashed level lines across the chart, each labelled just // left of the bars: the strike inside the board's window holding the largest positive net GEX, the gamma flip over all // expiries (the options kit's GammaCurve, the level every options card reads), max pain and the put wall inside the // window. The Lens setting picks what the board and the bars read: net gamma exposure (the default), delta held, vega, // vanna or charm, in dollars with dealers long the calls and short the puts (delta keeps each option's own sign), or // the open interest by strike and expiry, calls and puts together, in whole contracts (coins to a tenth on crypto); the // four levels always read gamma. The chain is read at its as-of (optionsAsOfMs: the live bar's close time), each expiry // live until it stops trading (optionsLiveUntilMs: 16:15 New York on OPRA, so today's OPRA expiry keeps its column // until then); a column is headed by its expiry's date on the market's clock (16 Oct, or 15 Jan '27 in another year), // the front one 0DTE on its own trade date. The chain is live only: history bars cost one read and draw nothing; the // boards, the levels and their labels are rewritten on the last bar as the chain moves. // // The reading layer names the board's nodes (the options kit's NodeBoard over each strike's reading summed across the // board's columns, read against the close): the top node's cell is starred, the gate, the floor and the ceiling carry // G, F and C, a cell reads its value or the node's percent of the top, the strikes under the significance share are // shown, hidden, dimmed or faded, and the legend reads the net above and below spot. Expiry preset picks the columns by // the calendar (the kit's expiryPresetCount), Palette paints the cells on a viridis, cividis, inferno or plasma ramp, // and Centre on top moves the strike window onto the top node. Velocity reads how each cell's reading moved over a // window (the kit's StrikeVelocity, one reading a bar for each strike and expiry, the strikes nearest the board's // centre first), on every bar that carries the chain: a badge after the cell's text, a filter, a bold halo where the // neighbouring windows that can be read agree, and the largest movers among the significant nodes in the legend. Layout // net folds each board into one wider column: every strike's reading summed over the expiries the preset keeps (the // reading its node is measured on), headed by the count it sums, its velocity keyed by the strike and the kept // expiries, so a roll of them starts the ring over. A setting a host leaves out (a list written for an older version) // reads its default. param.choice("lens", ["gamma", "delta", "vega", "vanna", "charm", "oi"], "gamma", { label: "Lens", description: "What the boxes show: gamma (how fast dealers must hedge) by default, per 1% move. delta, vega, vanna and charm show other dealer risks in dollars, vega and vanna per volatility point, charm per day. oi shows open interest (contracts still held open)." }); param.number("window_pct", 7, { min: 1, max: 30, label: "Strike window, percent", description: "Which strikes (option price levels) the board shows, in percent each way from the price. Under Centre on top, it centres on the strongest strike instead." }); param.int("expiries", 4, { min: 1, max: 12, label: "Expiry columns", description: "How many expiry dates get a column when Expiry preset is count, nearest first" }); param.number("rate_pct", 4, { min: 0, max: 20, step: 0.25, label: "Rate, percent", when: "lens in 2,3,4", description: "The interest rate used to price vega, vanna and charm on US stocks and CME futures. Crypto options use 0." }); input("close", ohlcv.close); // the chart's own close: the grid, and spot for the strike window input("chain", options_chain.cells, { max_cells: 4000, venue: "auto", description: "The chart's own option chain (venue auto: OPRA on a US stock or ETF, CME on a futures chart, else the coin's Deribit chain)" }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega] per contract input("trade_date", time.trade_date); // the bar's trade date, the day an expiry must fall on to read 0DTE: the UTC date on crypto, the New York date on a US stock (a 1W or 1M bar's first day, so the chain's as-of moves it on) market.zone(); // the market's own clock, written by the chart: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME, whose trade day opens at 17:00) chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The reading layer's settings, declared after the market's clock and the bar's length (the chart fills those two), so // every setting above keeps its slot. param.choice("expiry_preset", ["front", "to_friday", "to_next_friday", "to_opex", "to_next_opex", "to_q_opex", "all", "count"], "count", { label: "Expiry preset", description: "front is the nearest date. to_friday and to_next_friday reach this or next Friday, to_opex and to_next_opex this or next monthly expiry (opex, a third Friday). to_q_opex reaches the next quarterly one, all shows up to 12, and count follows Expiry columns." }); section("Nodes"); param.choice("node_labels", ["off", "value", "pct"], "pct", { label: "Node labels", description: "A node is one strike's total across the board. off prints nothing, value each box's own number, and pct a node's share of the strongest. pct shows on each strike's biggest box, its number elsewhere." }); param.choice("node_pct_mode", ["off", "focus", "top"], "focus", { label: "Node %", when: "node_labels", description: "Where the shares print: off none, top the strongest strike only, focus every key strike. focus also tags the floor (F), the biggest strike below the price, and the ceiling (C) above. The gate (G) is the biggest between the price and the strongest." }); param.number("significance_pct", 15, { min: 5, max: 60, label: "Significant at, percent of the top", description: "A strike counts as key when its total reaches this share of the strongest strike's. The rest are low strikes." }); param.choice("low_nodes", ["show", "hide", "dim", "fade"], "dim", { label: "Low nodes", description: "How to draw strikes below the key share. Show them as they are, hide them, dim their text, or fade their colour to a fifth." }); param.number("hide_under_pct", 0, { min: 0, max: 50, label: "Hide strikes under, percent of the top", description: "Blanks every strike whose total is under this share of the strongest strike's. 0 hides none." }); param.choice("palette", ["classic", "viridis", "cividis", "inferno", "plasma"], "classic", { label: "Palette", description: "The box colours. Classic uses the chart's own down and up colours. The other choices are colour-blind-safe scales, dark at zero." }); param.choice("center", ["spot", "top"], "spot", { label: "Centre on", description: "Where the strike window centres: on the price (spot) or on the strongest strike (top)" }); section("Velocity"); param.choice("velocity_window", ["off", "1m", "5m", "10m", "15m", "1h", "4h", "1d"], "off", { label: "Velocity window", description: "How far back each box is compared, shown as a change badge after its text. Gamma, delta, vega and oi get badges, but vanna and charm do not. A window shorter than one bar, or longer than the data so far, shows none." }); param.choice("velocity_filter", ["all", "increasing", "decreasing"], "all", { label: "Velocity filter", description: "Keeps every box, or only the boxes whose number rose or fell over the window" }); param.bool("halo", false, { label: "Halo", description: "Bolds a box's text when its move points the same way over at least two of three windows. Those are the Velocity window and the next shorter and longer ones." }); param.int("movers", 0, { min: 0, max: 10, label: "Movers", description: "Lists this many key strikes with the biggest percent move over the window in the legend. 0 lists none." }); // The layout follows the reading layer's settings, so each of those keeps its slot too. section("Layout"); param.choice("layout", ["matrix", "net"], "matrix", { label: "Layout", description: "Matrix shows one column per expiry date. Net shows one column, each strike summed over the chosen dates." }); output("spot", none, overlay, { description: "The chart's last close, the price the board and the lines centre on" }); output("net_gex", none, overlay, { description: "Dealers' net gamma exposure over the board, in USD per 1% price move. Newest bar only." }); output("net_lens", none, overlay, { description: "The Lens total over the board, in dollars, or in contracts on the oi choice. Newest bar only." }); output("t_prev", none, overlay, { description: "The previous bar's open time in epoch seconds, where the level lines start" }); output("t_last", none, overlay, { description: "This bar's open time in epoch seconds, the level lines' second point" }); output("wall_price", none, overlay, { description: "The strike on the board with the largest positive net gamma exposure. Newest bar only." }); output("flip_price", none, overlay, { description: "The gamma flip over all expiry dates, where dealers switch from calming moves to feeding them. Empty when none lies within 50% of the price. Newest bar only." }); output("pain_price", none, overlay, { description: "Max pain: the strike where option holders collect the least at expiry, over all of this symbol's options. Newest bar only." }); output("put_wall_price", none, overlay, { description: "The put wall: the strike with the heaviest puts at or below the price on the board. Newest bar only." }); string("spot_text", { max_bytes: 32 }); // the legend entry: "live spot $84.6K" string("wall_text", { max_bytes: 32 }); // the level labels, one slot each, written on the live bar string("flip_text", { max_bytes: 48 }); // "#1 $86K | Flip · all expiries $85.7K" string("pain_text", { max_bytes: 32 }); string("put_wall_text", { max_bytes: 32 }); string("nodes_text", { max_bytes: 64 }); // the Above/Below chip: "Above +$84.3M | Below -$12.1M" string("movers_text", { max_bytes: 192 }); // "Movers 103 +25%, 110 -12%" string("board_text", { max_bytes: 48 }); // the columns the board shows: "4 expiries", "3 expiries, to Friday" legend({ title: "±{{window_pct}}%" }); // the words after the name in the legend: the strike window, read from the settings by name; the columns ride the first entry, which counts them on the live bar render.legend("board_entry", { text: "board_text", color: "theme.muted" }); render.legend("spot_entry", { text: "spot_text", color: "theme.muted" }); render.legend("nodes_entry", { text: "nodes_text", color: "theme.muted" }); render.legend("movers_entry", { text: "movers_text", color: "theme.muted" }); const board = frame("board", { max_bytes: 98304 }); // the matrix: one row per strike, one column per expiry, a dollar lens; cells carry their node text and style const gexRows = frame("gex_rows", { max_bytes: 16384 }); // the bars: the dollar lens per strike, the board's row sums const oiBoard = frame("oi_board", { max_bytes: 98304 }); // the same two on the open interest lens; only the pair the lens picks is written const oiRows = frame("oi_rows", { max_bytes: 16384 }); const netBoard = frame("net_board", { max_bytes: 98304 }); // Layout net's board: one column, each strike's reading summed over the board's expiries, on a dollar lens const oiNetBoard = frame("oi_net_board", { max_bytes: 98304 }); // and on the open interest lens; a layout writes its own boards only, the bars the same under both // The strike by expiry board against the price axis: a diverging palette centred on zero, puts in the chart's down // colour and calls in its up colour, the tint by the square root of the cell's size, signed dollars in every cell, the // at-the-money row outlined in the text ink. The open interest lens has a board of its own: one ramp, counts unsigned, // printed as written ("auto": the whole contracts the frame carries read 995, never 995.0). A cell carrying its own // text prints that instead, and one carrying a colour (a ramp's) is filled with it. plot.matrix({ name: "gex_board", frame: board, dock: "right", column_width: 66, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "usd", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Exposure by expiry", tooltip: "{{column}}: {{value:usd}} at {{price}}" }); plot.matrix({ name: "oi_matrix", frame: oiBoard, dock: "right", column_width: 66, row_max_px: 22, price_column: true, header: true, palette: ["theme.bg", "theme.up"], scale: "sqrt", opacity: 0.95, format: "auto", font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Open interest by expiry", tooltip: "{{column}}: {{value}} open at {{price}}" }); // Layout net's two boards: the same cells in one column, 96 px wide so a summed reading's text fits whole, headed by // the count of expiries it sums. plot.matrix({ name: "gex_net", frame: netBoard, dock: "right", column_width: 96, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "usd", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Net exposure by strike", tooltip: "{{column}}: {{value:usd}} at {{price}}" }); plot.matrix({ name: "oi_net", frame: oiNetBoard, dock: "right", column_width: 96, row_max_px: 22, price_column: true, header: true, palette: ["theme.bg", "theme.up"], scale: "sqrt", opacity: 0.95, format: "auto", font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Net open interest by strike", tooltip: "{{column}}: {{value}} open at {{price}}" }); // The per-strike net GEX bars beside the board: zero mid-dock, positives one way and negatives the other, each row // in its own colour from the frame, a hover card per row, pushed inward past the board (both dock right), 100 px wide. // The push is a pixel offset for now: in the sheet, beside names another level only; once it can name a matrix (the // chart docks a level beside one), beside naming the board replaces the offset and tracks the board's own width. // Layout net's board (one 96 px column) is narrower, so there the bars keep the same offset a little apart from it. plot.levels({ name: "gex_by_strike", frame: gexRows, dock: "right", width_px: 100, baseline: "center", labels: false, opacity: 0.95, thickness_px: 10, format: "usd", signed: true, hover: true, offset: [340, 0] }); // offset: the board's width (4 columns of 66 px plus the price column), so the bars sit left of it instead of under it plot.levels({ name: "oi_by_strike", frame: oiRows, dock: "right", width_px: 100, baseline: "edge", labels: false, opacity: 0.95, thickness_px: 10, format: "auto", hover: true, offset: [340, 0] }); // the open interest lens's bars, all one way, whole contracts as written // Four dashed levels across the whole pane, placed from the newest bar: the largest positive GEX strike in the chart's // up colour, the put wall in its down colour, the gamma flip in the text ink and max pain in the muted ink. Their // labels, plain text in the muted ink, are label handles placed in pixels from the price axis (x) at the level's price // (y), their right edge just left of the bars, so a label never covers a cell of the board or runs into the axis. draw.line("wall_line", { x1: "t_prev", y1: "wall_price", x2: "t_last", y2: "wall_price", color: "theme.up", width: 1, line_style: "dashed", extend: "both" }); draw.line("flip_line", { x1: "t_prev", y1: "flip_price", x2: "t_last", y2: "flip_price", color: "theme.text", width: 1, line_style: "dashed", extend: "both" }); draw.line("pain_line", { x1: "t_prev", y1: "pain_price", x2: "t_last", y2: "pain_price", color: "theme.muted", width: 1, line_style: "dashed", extend: "both" }); draw.line("put_wall_line", { x1: "t_prev", y1: "put_wall_price", x2: "t_last", y2: "put_wall_price", color: "theme.down", width: 1, line_style: "dashed", extend: "both" }); handles.label({ anchor: "right", align: "right", style: "plain", font_weight: "medium" }); const MAX_ROWS = 128; // strikes on the board (the frame's cap) const MAX_COLS = 12; // expiries on the board (the setting's cap) const MAX_CELLS = 1536; // a board's cells at most: 128 rows of 12 columns const TUPLE = 10; // f64s per contract: strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega const MAX_EXPIRIES = 64; // distinct live expiries the chain may list const MIN_T_MS = 900000.0; // 15 minutes: a contract nearer its expiry's end prices no time left, as the chart's greeks do const GAMMA = 0; // the lenses, in the setting's order const DELTA = 1; const VEGA = 2; const VANNA = 3; const CHARM = 4; const OPEN_INTEREST = 5; const LENS_TITLES: String[] = ["GEX by expiry", "DEX by expiry", "Vega by expiry", "Vanna by expiry", "Charm by expiry", "OI by expiry"]; const NET_TITLES: String[] = ["Net GEX", "Net DEX", "Net vega", "Net vanna", "Net charm", "Net OI"]; // Layout net's, by lens const NET_HEADERS: String[] = ["Net · 0 exp", "Net · 1 exp", "Net · 2 exp", "Net · 3 exp", "Net · 4 exp", "Net · 5 exp", "Net · 6 exp", "Net · 7 exp", "Net · 8 exp", "Net · 9 exp", "Net · 10 exp", "Net · 11 exp", "Net · 12 exp"]; // Layout net's header, by the expiries its column sums (the 12 columns at most) const LABELS_OFF = 0; // Node labels, in the setting's order const LABELS_PCT = 2; const PCT_FOCUS = 1; // Node %, in the setting's order (0 off) const PCT_TOP = 2; const LOW_HIDE = 1; // Low nodes, in the setting's order (0 show) const LOW_DIM = 2; const LOW_FADE = 3; const LAYOUT_NET = 1; // Layout, in the setting's order (0 matrix) const FILTER_UP = 1; // Velocity filter, in the setting's order (0 all) const FILTER_DOWN = 2; const FADE = 0.2; // a faded low node's fill: a fifth of its reading const TEXT_MAX = 16; // characters a cell's text holds const PREFIX_NONE = 0; // the mark a node's cell starts with const PREFIX_TOP = 1; // the star const PREFIX_GATE = 2; // G, F and C, each with a space after it const PREFIX_FLOOR = 3; const PREFIX_CEILING = 4; let netSetKey = 0.0; // Layout net's velocity key in an expiry's place: the kept expiries summed, each weighted by its rank, so it moves whenever the kept set does (a roll, a shrink, a listing) and the strike's ring starts over const CELL_BYTES = 94208.0; // a board frame's 96 KiB, less its prices, columns, title and highlight: the cells' share const VEL_READINGS = 81920; // readings the velocity rings hold in all: 1.25 MiB at 16 bytes a reading, inside the module's 4 MiB beside the chain's tables // The ramps, dark theme stops from low to high (contract E), one run per palette after classic, which has none: a // signed board reads them on |value| (the mirrored ramp, its dark end at zero), the open interest board on the count. const RAMPS: StaticArray = [0x440154, 0x3b528b, 0x21918c, 0x5ec962, 0xfde725, 0x00224e, 0x35456c, 0x666970, 0x948e77, 0xc8b866, 0xfee838, 0x000004, 0x420a68, 0x932667, 0xdd513a, 0xfca50a, 0xfcffa4, 0x0d0887, 0x6a00a8, 0xb12a90, 0xe16462, 0xfca636, 0xf0f921]; const RAMP_FIRST: StaticArray = [0, 0, 5, 11, 17]; // each palette's first stop in RAMPS, in the setting's order const RAMP_STOPS: StaticArray = [0, 5, 6, 6, 6]; // and its stop count const strikePrice = new StaticArray(MAX_ROWS); // the strike table, sorted ascending, one row per strike inside the window const cellValue = new StaticArray(MAX_ROWS * MAX_COLS); // the lens per row and column const cellSeen = new StaticArray(MAX_ROWS * MAX_COLS); // 1 where a contract with a reading for the lens landed in the cell const cellKey = new StaticArray(MAX_ROWS * MAX_COLS); // each cell's velocity key on the bar last measured, -1 for none const rowCall = new StaticArray(MAX_ROWS); // the row's calls on the lens across the board's columns (the hover card), signed as they count const rowPut = new StaticArray(MAX_ROWS); // the row's puts on the lens, signed as they count (negative dollars of gamma, positive open interest) const rowGex = new StaticArray(MAX_ROWS); // the row's net GEX whatever the lens: the net_gex output sums the rows the board keeps const rowOrder = new StaticArray(MAX_ROWS); // the rows nearest the board's centre first: the order cells take velocity keys in const rowSum = new StaticArray(MAX_ROWS); // each strike's node reading: the lens summed across the board's columns const rowMove = new StaticArray(MAX_ROWS); // each significant strike's move over the velocity window, percent (the movers) const rowTaken = new StaticArray(MAX_ROWS); // the movers already listed const greeks = new Greeks(); // prices vega, vanna and charm per contract; allocated once const expiryMs = new StaticArray(MAX_EXPIRIES); // the live expiries, sorted ascending const tags: LabelHandle[] = [draw.label(0), draw.label(1), draw.label(2), draw.label(3)]; // the wall, the flip, max pain, the put wall; handle objects allocate once let chain = new OptionsChain(1); // the whole chain measured by strike: max pain and the strikes the levels rank on let windowChain = new OptionsChain(1); // the strikes inside the board's window: the two walls, as Gamma Map reads them let curve = new GammaCurve(1); // every live expiry's gamma curve: the flip; built in onStart() let nodes = new NodeBoard(1); // the board's nodes over each strike's reading; built in onStart() let velocity = new StrikeVelocity(1, 2); // each cell's readings, a ring per strike and expiry; sized in onStart() let keyCap = 0; // the rings: one key a cell, handed to the cells nearest the board's centre let mapExpiry = new StaticArray(1); // the pairs holding a key, sorted by expiry then strike let mapStrike = new StaticArray(1); let mapKey = new StaticArray(1); let mapCount = 0; let keyStrike = new StaticArray(1); // by key: the pair holding it, the bar it last read and the bar the pair took it on let keyExpiry = new StaticArray(1); let keySeen = new StaticArray(1); let keyBorn = new StaticArray(1); let freeKeys = new StaticArray(1); // the keys no pair holds let freeCount = 0; let keysLeft = true; // false once a cell on this bar found every key read by a nearer one let velNowMs: f64 = NaN; // the bar the rings last read let lens = GAMMA; // settings, read in onStart() let windowPct = 0.07; let columns = 4; let rate = 0.04; let preset = EXPIRY_PRESET_COUNT; let labels = LABELS_PCT; let pctMode = PCT_FOCUS; let significancePct = 15.0; let lowNodes = LOW_DIM; let hideUnderPct = 0.0; let palette = 0; // 0 classic, else the ramp's index in RAMP_FIRST let centerOnTop = false; let velOn = false; // a velocity window on a lens with velocity (vanna and charm have none) let velMin = 0; // the window, minutes, and its two neighbours among the kit's windows (0 for none) let velBelow = 0; let velAbove = 0; let velFilter = 0; let haloOn = false; let moverCount = 0; let net = false; // Layout net: one column a board, each strike's reading summed over the preset's expiries let cellBytes = 25.0; // the most bytes one cell takes in the frame at these settings let intervalMs = 0.0; // the bar's length in milliseconds, read in onStart(); 0 where the host writes none let close: f64 = NaN; // this bar let t: f64 = NaN; let prevT: f64 = NaN; let nowMs: f64 = 0.0; // the chain's as-of, read on every bar that carries the chain let today = 0; // today, days since 1970-01-01: the live bar's trade date, or the as-of's date on a bar longer than a day let marketZone = 0; // the market's clock, read in onStart() let oiDecimals = 0; // open interest in the frames: whole contracts on OPRA and CME, coins to a tenth on crypto let rowCount = 0; // strikes in the table let rowCap = MAX_ROWS; // strikes the table keeps on this board: fewer when its cells would outgrow the frame let boardCentre: f64 = NaN; // the strike window's centre: the close, or the top node's strike let expiryCount = 0; // live expiries seen let shownCols = 0; // the board's columns: the leading live expiries the preset keeps let boardCols = 0; // the columns the board draws: shownCols, or one under Layout net let netGex: f64 = NaN; // the board's net GEX, measured on the live bar let netLens: f64 = NaN; // the board's net on the lens let wallPrice: f64 = NaN; // the levels, measured on the live bar let wallGex: f64 = NaN; let flipPrice: f64 = NaN; let flipStrike: f64 = NaN; let painPrice: f64 = NaN; let putWallPrice: f64 = NaN; let flipRank = 0; let painRank = 0; let putWallRank = 0; function choiceOf(value: f64, count: i32, fallback: i32): i32 { // a choice's index, or its default when it is missing or outside the words if (!isFinite(value) || value < 0.0 || value >= f64(count)) return fallback; return i32(value); } function numberOf(value: f64, lo: f64, hi: f64, fallback: f64): f64 { // a number setting inside its range, or its default when it is missing if (!isFinite(value)) return fallback; return value < lo ? lo : value > hi ? hi : value; } function onStart(): void { chain = new OptionsChain(512); windowChain = new OptionsChain(512); curve = new GammaCurve(in_chain_max_cells); // a slot per contract the block can carry, so a load is never refused nodes = new NodeBoard(MAX_ROWS); // the per-strike buffers are its only allocation lens = i32(p_lens()); windowPct = p_window_pct() / 100.0; columns = i32(p_expiries()); if (columns > MAX_COLS) columns = MAX_COLS; marketZone = i32(p_market_zone()); const intervalSec = p_chart_interval_sec(); intervalMs = isFinite(intervalSec) && intervalSec > 0.0 ? intervalSec * 1000.0 : 0.0; rate = marketZone == 0 ? 0.0 : p_rate_pct() / 100.0; // crypto chains are quoted at a rate of 0 oiDecimals = marketZone == 0 ? 1 : 0; // The reading layer's settings follow the chart's two, so a host that sends the older, shorter list reads NaN for // them: each, and a choice outside its words, reads its declared default. preset = choiceOf(p_expiry_preset(), 8, EXPIRY_PRESET_COUNT); // the choices are the kit's EXPIRY_PRESET_* codes, in order labels = choiceOf(p_node_labels(), 3, LABELS_PCT); pctMode = choiceOf(p_node_pct_mode(), 3, PCT_FOCUS); significancePct = numberOf(p_significance_pct(), 5.0, 60.0, 15.0); lowNodes = choiceOf(p_low_nodes(), 4, LOW_DIM); hideUnderPct = numberOf(p_hide_under_pct(), 0.0, 50.0, 0.0); palette = choiceOf(p_palette(), 5, 0); centerOnTop = choiceOf(p_center(), 2, 0) == 1; velFilter = choiceOf(p_velocity_filter(), 3, 0); haloOn = numberOf(p_halo(), 0.0, 1.0, 0.0) > 0.5; moverCount = i32(numberOf(p_movers(), 0.0, 10.0, 0.0)); net = choiceOf(p_layout(), 2, 0) == LAYOUT_NET; const pick = choiceOf(p_velocity_window(), 8, 0); // 0 off, else the kit's VELOCITY_WINDOWS[pick - 1] velOn = pick > 0 && lens != VANNA && lens != CHARM; if (velOn) { const j = pick - 1; velMin = VELOCITY_WINDOWS[j]; velBelow = j > 0 ? VELOCITY_WINDOWS[j - 1] : 0; velAbove = j + 1 < VELOCITY_WINDOWS.length ? VELOCITY_WINDOWS[j + 1] : 0; // The rings reach the window, and the halo's wider neighbour too, in the chart's bars: the newest bar, the bar the // reach goes back to and one more. A cell takes a ring while the readings last: every cell of a full board on a // short window; on a long one the cells nearest the board's centre (a 1h window with its halo on a 1m chart keeps // 338, a 1d window there 56), the farthest strikes showing no badge. const reach = haloOn && velAbove > velMin ? velAbove : velMin; const bars = i32(Math.ceil((f64(reach) * 60000.0) / (intervalMs > 0.0 ? intervalMs : 60000.0))) + 2; let keys = VEL_READINGS / bars; const keyMax = net ? MAX_ROWS : MAX_CELLS; // a ring a cell: under Layout net, one a strike if (keys > keyMax) keys = keyMax; if (keys < 1) keys = 1; velocity = new StrikeVelocity(keys, bars); mapExpiry = new StaticArray(keys); mapStrike = new StaticArray(keys); mapKey = new StaticArray(keys); keyStrike = new StaticArray(keys); keyExpiry = new StaticArray(keys); keySeen = new StaticArray(keys); keyBorn = new StaticArray(keys); freeKeys = new StaticArray(keys); for (let k = 0; k < keys; k += 1) freeKeys[k] = keys - 1 - k; // key 0 is taken first freeCount = keys; keyCap = keys; } // A cell's bytes at most: its value, its text, a ramp colour, the dimmed ink and the halo's weight, as these // settings write them; the board keeps the strikes whose cells fit the frame. cellBytes = 25.0 + (labels == LABELS_OFF ? 10.0 : 28.0) + (palette > 0 ? 18.0 : 0.0) + (lowNodes == LOW_DIM ? 27.0 : 0.0) + (haloOn && velOn ? 21.0 : 0.0); } // ── The expiry list: sorted insertion of a distinct live expiry, the nearest kept when full ── function noteExpiry(ms: f64): void { let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryMs[mid] < ms) lo = mid + 1; else hi = mid; } if (lo < expiryCount && expiryMs[lo] == ms) return; if (expiryCount >= MAX_EXPIRIES) { if (lo >= expiryCount) return; // later than every kept expiry expiryCount -= 1; // the latest makes room } for (let i = expiryCount; i > lo; i -= 1) expiryMs[i] = expiryMs[i - 1]; expiryMs[lo] = ms; expiryCount += 1; } function columnOf(ms: f64): i32 { // the board column of an expiry: its rank among the columns the preset keeps, or -1 for (let c = 0; c < shownCols; c += 1) if (expiryMs[c] == ms) return c; return -1; } function keptSetKey(): f64 { // the kept expiries summed, each weighted by its rank: exact in f64 (12 expiries of 1.8e12 ms at most), and a different set sums differently let key = 0.0; for (let c = 0; c < shownCols; c += 1) key += expiryMs[c] * f64(c + 1); return key; } // ── The strike table: sorted insertion, one row per strike; when full, the end farther from the centre gives way ── function clearRow(row: i32): void { for (let c = 0; c < MAX_COLS; c += 1) { cellValue[row * MAX_COLS + c] = 0.0; cellSeen[row * MAX_COLS + c] = 0; } rowCall[row] = 0.0; rowPut[row] = 0.0; rowGex[row] = 0.0; } function moveRow(from: i32, to: i32): void { strikePrice[to] = strikePrice[from]; rowCall[to] = rowCall[from]; rowPut[to] = rowPut[from]; rowGex[to] = rowGex[from]; for (let c = 0; c < MAX_COLS; c += 1) { cellValue[to * MAX_COLS + c] = cellValue[from * MAX_COLS + c]; cellSeen[to * MAX_COLS + c] = cellSeen[from * MAX_COLS + c]; } } function strikeSlot(strike: f64): i32 { // the row of this strike, inserted when new; -1 when the table is full and this strike is the farthest from the centre let lo = 0; let hi = rowCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } if (lo < rowCount && strikePrice[lo] == strike) return lo; if (rowCount >= rowCap) { // full: the end farther from the centre is dropped, unless this strike is farther still const lowGap = Math.abs(strikePrice[0] - boardCentre); const highGap = Math.abs(strikePrice[rowCount - 1] - boardCentre); if (Math.abs(strike - boardCentre) >= Math.max(lowGap, highGap)) return -1; if (lowGap >= highGap) { // drop the lowest row: every row shifts down one for (let i = 0; i < rowCount - 1; i += 1) moveRow(i + 1, i); if (lo > 0) lo -= 1; } rowCount -= 1; if (lo > rowCount) lo = rowCount; } for (let i = rowCount; i > lo; i -= 1) moveRow(i - 1, i); strikePrice[lo] = strike; clearRow(lo); rowCount += 1; return lo; } function atmStrike(): f64 { // the strike nearest spot: the highlighted row let best = strikePrice[0]; for (let r = 1; r < rowCount; r += 1) if (Math.abs(strikePrice[r] - close) < Math.abs(best - close)) best = strikePrice[r]; return best; } // ── One contract on the lens, signed as it counts: dealers long the calls and short the puts, delta in its own sign ── function lensValue(cells: StaticArray, i: i32, spot: f64, multiplier: f64, signedGex: f64): f64 { if (lens == GAMMA) return signedGex; const side = cells[i + 2] > 0.0 ? 1.0 : -1.0; const oi = cells[i + 3]; if (lens == OPEN_INTEREST) return oi; // calls and puts together, in the chain's own amount if (lens == DELTA) return cells[i + 5] * oi * multiplier * spot; // delta dollars held if (lens == VEGA && cells[i + 9] > 0.0) return side * cells[i + 9] * oi * multiplier; // the venue's vega: dollars per IV point const left = optionsLiveUntilMs(cells[i + 1], marketZone) - nowMs; // the time to the expiry's end: 16:15 New York on OPRA const years = left < MIN_T_MS ? 0.0 : left / OPTIONS_YEAR_MS; const sigma = cells[i + 6] / 100.0; // mark IV rides the chain in percentage points if (marketZone == 1) greeks.spot(side, spot, cells[i], years, sigma, rate); // a US stock: Black-Scholes on spot else greeks.forward(side, spot, cells[i], years, sigma, rate); // futures and crypto: the underlying is the forward if (lens == VEGA) return side * greeks.vega * oi * multiplier; return side * (lens == VANNA ? greeks.vanna : greeks.charm) * oi * multiplier * spot; // dollars per IV point, per day } // ── The board, measured on every bar that carries the chain ── function fillBoard(n: i32, centre: f64): void { // the strikes inside the window around `centre`, the preset's columns const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer rowCount = 0; boardCentre = centre; const lo = centre * (1.0 - windowPct); const hi = centre * (1.0 + windowPct); for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const strike = cells[i]; const oi = cells[i + 3]; if (!(strike > 0.0) || !(oi > 0.0) || strike < lo || strike > hi) continue; const col = columnOf(cells[i + 1]); if (col < 0) continue; // an expiry past the board's columns, or already expired const multiplier = cells[i + 8] > 0.0 ? cells[i + 8] : 1.0; // Deribit open interest is in coin units (multiplier 1); CME open interest is contracts times the point value const spot = cells[i + 7] > 0.0 ? cells[i + 7] : close; const gexUsd = cells[i + 4] * oi * multiplier * spot * spot * 0.01; // the USD delta change of the open interest for a 1% move of spot const isCall = cells[i + 2] > 0.0; const signed = isCall ? gexUsd : -gexUsd; // calls positive, puts negative: the dealer-naive sign convention const row = strikeSlot(strike); if (row < 0) continue; rowGex[row] += signed; const v = lensValue(cells, i, spot, multiplier, signed); if (!isFinite(v)) continue; // no reading on this lens (no IV to price, a NaN greek): the cell stays as it was cellValue[row * MAX_COLS + col] += v; cellSeen[row * MAX_COLS + col] = 1; if (isCall) rowCall[row] += v; else rowPut[row] += v; } // The nets over the rows the board keeps: a row the table dropped for a nearer strike takes its contracts with it. netGex = 0.0; netLens = 0.0; for (let r = 0; r < rowCount; r += 1) { netGex += rowGex[r]; netLens += rowCall[r] + rowPut[r]; } } function loadNodes(): void { // the nodes over each strike's reading summed across the columns, read against the close for (let r = 0; r < rowCount; r += 1) rowSum[r] = rowCall[r] + rowPut[r]; nodes.load(strikePrice, rowSum, rowCount, close, significancePct); } function measureChain(n: i32): void { // n = f64 cells in the block const cells = in_chain_view(); rowCount = 0; expiryCount = 0; shownCols = 0; netGex = 0.0; netLens = 0.0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) if (optionsLiveUntilMs(cells[i + 1], marketZone) > nowMs) noteExpiry(cells[i + 1]); // the live expiries, nearest first if (expiryCount > 0) { // The columns: the leading live expiries the preset keeps on the market's trade days at the as-of (count keeps // Expiry columns), 12 at most; then the strikes whose cells fit the frame at these settings. const kept = expiryPresetCount(expiryMs, expiryCount, nowMs, marketZone, preset, columns); shownCols = kept < MAX_COLS ? kept : MAX_COLS; } boardCols = net && shownCols > 0 ? 1 : shownCols; // Layout net draws one column, so its frame fits every row if (shownCols > 0) { rowCap = i32(Math.min(f64(MAX_ROWS), Math.max(1.0, Math.floor(CELL_BYTES / (f64(boardCols) * cellBytes))))); fillBoard(n, close); } loadNodes(); if (centerOnTop && nodes.top() >= 0) { // Centre on top: the window again, around the top node's strike const topStrike = nodes.strike(nodes.top()); if (topStrike != close) { fillBoard(n, topStrike); loadNodes(); } } if (net) foldColumns(); } function foldColumns(): void { // Layout net: each strike's cells summed into its one column, the reading its node is measured on for (let r = 0; r < rowCount; r += 1) { let seen = 0; for (let c = 0; c < shownCols; c += 1) if (cellSeen[r * MAX_COLS + c] != 0) seen = 1; cellValue[r * MAX_COLS] = rowSum[r]; cellSeen[r * MAX_COLS] = seen; } } // ── Velocity: one reading a bar for each cell, keyed by its strike and expiry (the column moves when an expiry rolls) ── // A cell keeps its key while it stays on the board; a pair that leaves frees its key for a cell that arrives, and a key // taken over reads its new pair from the bar it was taken on. Keys go to the strikes nearest the board's centre first, // so when the cells outnumber them the farthest strikes show no badge, and no ring starts over. Under Layout net a cell // is its strike's one column, keyed by the strike and the kept expiries (netSetKey): its reading summed over them, a // bar; when the kept set rolls the key changes and the ring starts over, as a new matrix column's does, so a badge never // compares a sum over one set with a sum over another. function mapAt(strike: f64, expiry: f64): i32 { // the first keyed pair at or after this one let lo = 0; let hi = mapCount; while (lo < hi) { const mid = (lo + hi) >> 1; const e = mapExpiry[mid]; if (e < expiry || (e == expiry && mapStrike[mid] < strike)) lo = mid + 1; else hi = mid; } return lo; } function keyOf(strike: f64, expiry: f64): i32 { // the pair's key, -1 for none const at = mapAt(strike, expiry); return at < mapCount && mapExpiry[at] == expiry && mapStrike[at] == strike ? mapKey[at] : -1; } function mapPut(strike: f64, expiry: f64, key: i32): void { const at = mapAt(strike, expiry); for (let i = mapCount; i > at; i -= 1) { mapExpiry[i] = mapExpiry[i - 1]; mapStrike[i] = mapStrike[i - 1]; mapKey[i] = mapKey[i - 1]; } mapExpiry[at] = expiry; mapStrike[at] = strike; mapKey[at] = key; mapCount += 1; } function mapDrop(strike: f64, expiry: f64): void { const at = mapAt(strike, expiry); if (at >= mapCount || mapExpiry[at] != expiry || mapStrike[at] != strike) return; for (let i = at; i + 1 < mapCount; i += 1) { mapExpiry[i] = mapExpiry[i + 1]; mapStrike[i] = mapStrike[i + 1]; mapKey[i] = mapKey[i + 1]; } mapCount -= 1; } function rowOf(strike: f64): i32 { // the board's row of a strike, -1 when the board has none let lo = 0; let hi = rowCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } return lo < rowCount && strikePrice[lo] == strike ? lo : -1; } function onBoard(key: i32): bool { // whether the key's pair is a cell of this bar's board const r = rowOf(keyStrike[key]); if (r < 0) return false; const c = net ? (keyExpiry[key] == netSetKey ? 0 : -1) : columnOf(keyExpiry[key]); // Layout net: the strike's one column, while the kept set its ring sums stands return c >= 0 && cellSeen[r * MAX_COLS + c] != 0; } function takeKey(barMs: f64): i32 { // a key for a cell that arrives: a free one, else the one a pair off the board holds longest, else the one of the cell farthest from the centre not read on this bar; -1 for none if (freeCount > 0) { freeCount -= 1; return freeKeys[freeCount]; } if (!keysLeft) return -1; let best = -1; let bestOff = false; let bestSeen = 0.0; let bestGap = 0.0; let bestExpiry = 0.0; for (let k = 0; k < keyCap; k += 1) { const seen = keySeen[k]; if (seen >= barMs) continue; // read on this bar: a nearer cell keeps it const off = !onBoard(k); const gap = Math.abs(keyStrike[k] - boardCentre); const expiry = keyExpiry[k]; let better = best < 0; if (!better) { if (off != bestOff) better = off; else if (off) better = seen < bestSeen || (seen == bestSeen && gap > bestGap); else better = gap > bestGap || (gap == bestGap && expiry > bestExpiry); } if (better) { best = k; bestOff = off; bestSeen = seen; bestGap = gap; bestExpiry = expiry; } } if (best < 0) { keysLeft = false; // every key is read by a nearer cell: the rest of this bar's cells go without return -1; } mapDrop(keyStrike[best], keyExpiry[best]); return best; } function orderRows(): void { // the rows nearest the board's centre first, the lower strike first on a tie let right = 0; while (right < rowCount && strikePrice[right] < boardCentre) right += 1; let left = right - 1; for (let n = 0; n < rowCount; n += 1) { if (right >= rowCount || (left >= 0 && boardCentre - strikePrice[left] <= strikePrice[right] - boardCentre)) { rowOrder[n] = left; left -= 1; } else { rowOrder[n] = right; right += 1; } } } function pushVelocity(barMs: f64): void { // this bar's cells into the rings, the nearest strikes first keysLeft = true; velNowMs = barMs; if (net) netSetKey = keptSetKey(); orderRows(); for (let i = 0; i < rowCount; i += 1) { const r = rowOrder[i]; for (let c = 0; c < boardCols; c += 1) { const at = r * MAX_COLS + c; cellKey[at] = -1; if (cellSeen[at] == 0) continue; const strike = strikePrice[r]; const expiry = net ? netSetKey : expiryMs[c]; let key = keyOf(strike, expiry); if (key < 0) { key = takeKey(barMs); if (key < 0) continue; // no key left for this cell: it shows no badge mapPut(strike, expiry, key); keyStrike[key] = strike; keyExpiry[key] = expiry; keyBorn[key] = barMs; } keySeen[key] = barMs; velocity.push(barMs, key, cellValue[at]); cellKey[at] = key; } } } function readable(key: i32, windowMin: i32): bool { // whether the key's ring holds its pair's reading windowMin minutes back return key >= 0 && windowMin > 0 && velNowMs - f64(windowMin) * 60000.0 >= keyBorn[key]; } function moveOf(at: i32, velActive: bool): f64 { // the cell's move over the window in its unit; NaN for none if (!velActive) return NaN; const key = cellKey[at]; return readable(key, velMin) ? velocity.velocity(key, velMin) : NaN; } function haloWindow(key: i32, windowMin: i32): i32 { // a halo window the chart can read for this cell, 0 for one it cannot return windowMin > 0 && velocity.available(windowMin, intervalMs) && readable(key, windowMin) ? windowMin : 0; } function haloOf(key: i32): bool { // one sign over at least two of the windows that can be read (contract C) return velocity.halo(key, haloWindow(key, velBelow), haloWindow(key, velMin), haloWindow(key, velAbove)); } // ── The levels through the options kit: the flip over all expiries, max pain over the whole chain, the walls inside the window ── function nearestStrikeIndex(price: f64): i32 { // the kit table's strike nearest a price, -1 on an empty table const n = chain.strikes(); let best = -1; let bestGap = Infinity; for (let i = 0; i < n; i += 1) { const gap = Math.abs(chain.strike(i) - price); if (gap < bestGap) { bestGap = gap; best = i; } } return best; } function rankOf(value: f64, a: f64, b: f64): i32 { // 1 when this level carries the most |net GEX| of the three, 3 the least let rank = 1; if (a > value) rank += 1; if (b > value) rank += 1; return rank; } function measureLevels(n: i32): void { // OptionsChain keeps the contracts whose stamp is after the clock it is handed: a millisecond before the front live // expiry keeps every live one (an OPRA expiry trades 15 minutes past its stamp) and none that has stopped trading. const liveFrom = expiryCount > 0 ? expiryMs[0] - 1.0 : nowMs; chain.load(in_chain_view(), n, liveFrom, close, 0, 0.0); // every live expiry, every strike: max pain windowChain.load(in_chain_view(), n, liveFrom, close, 0, windowPct * 100.0); // the board's window: the walls a chart of this range trades against curve.load(in_chain_view(), n, nowMs, 0, close, marketZone); // every live expiry at the as-of: the flip is the curve's zero nearest S0 const count = windowChain.strikes(); wallPrice = NaN; wallGex = NaN; for (let i = 0; i < count; i += 1) { const g = windowChain.netGex(i); if (g > 0.0 && (isNaN(wallGex) || g > wallGex)) { wallGex = g; wallPrice = windowChain.strike(i); } } flipPrice = curve.flip(); painPrice = chain.maxPain(); putWallPrice = windowChain.putWall(); const fi = isNaN(flipPrice) ? -1 : nearestStrikeIndex(flipPrice); const pi = isNaN(painPrice) ? -1 : nearestStrikeIndex(painPrice); const wi = isNaN(putWallPrice) ? -1 : nearestStrikeIndex(putWallPrice); flipStrike = fi < 0 ? NaN : chain.strike(fi); const fg = fi < 0 ? 0.0 : Math.abs(chain.netGex(fi)); const pg = pi < 0 ? 0.0 : Math.abs(chain.netGex(pi)); const wg = wi < 0 ? 0.0 : Math.abs(chain.netGex(wi)); flipRank = rankOf(fg, pg, wg); painRank = rankOf(pg, fg, wg); putWallRank = rankOf(wg, fg, pg); } // ── Text: the legend entries and the level labels, built without allocating ── function sbUsd(v: f64): void { // "+$84.3M", "-$4.5M", "+$950.0K" if (!isFinite(v)) { sb_text("n/a"); return; } sb_text(v < 0.0 ? "-$" : "+$"); const a = Math.abs(v); if (a >= 1.0e9) { sb_f64(a / 1.0e9, 2); sb_text("B"); } else if (a >= 1.0e6) { sb_f64(a / 1.0e6, 1); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 1); sb_text("K"); } else sb_f64(a, 0); } function sbCount(v: f64): void { // "12.3K", "995": an open interest, whole contracts under 1,000 const a = Math.abs(v); if (a >= 1.0e6) { sb_f64(a / 1.0e6, 1); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 1); sb_text("K"); } else sb_f64(a, oiDecimals); } function sbStrike(p: f64): void { // "$86K", "$2.4K", "$0.42": the strike as a short price sb_text("$"); if (p >= 10000.0) { sb_f64(p / 1000.0, 0); sb_text("K"); } else if (p >= 1000.0) { sb_f64(p / 1000.0, 1); sb_text("K"); } else sb_f64(p, 2); } function sbPrice(p: f64): void { // "$85.7K", "$2.44K", "$0.42" sb_text("$"); if (p >= 1000.0) { sb_f64(p / 1000.0, 1); sb_text("K"); } else sb_f64(p, 2); } function clearTags(): void { for (let k = 0; k < 4; k += 1) tags[k].delete(); // no-ops when never drawn } function clearNodeTexts(): void { // the columns, the chip and the movers write nothing without a board sb_clear(); str_board_text_sb(); sb_clear(); str_nodes_text_sb(); sb_clear(); str_movers_text_sb(); } function writeBoardText(): void { // the legend's first entry: the columns the board shows, and the preset's word sb_clear(); if (shownCols > 0 && rowCount > 0) { sb_int(shownCols); sb_text(shownCols == 1 ? " expiry" : " expiries"); if (preset == EXPIRY_PRESET_FRONT) sb_text(", front"); else if (preset == EXPIRY_PRESET_TO_FRIDAY) sb_text(", to Friday"); else if (preset == EXPIRY_PRESET_TO_NEXT_FRIDAY) sb_text(", to next Friday"); else if (preset == EXPIRY_PRESET_TO_OPEX) sb_text(", to opex"); else if (preset == EXPIRY_PRESET_TO_NEXT_OPEX) sb_text(", to next opex"); else if (preset == EXPIRY_PRESET_TO_Q_OPEX) sb_text(", to quarterly opex"); else if (preset == EXPIRY_PRESET_ALL) sb_text(", all"); } str_board_text_sb(); } function writeTexts(): void { // the legend entries, then each label built in the line buffer and sent with its handle writeBoardText(); sb_clear(); sb_text("live spot "); sbPrice(close); str_spot_text_sb(); const boardPx = net ? 96.0 + 76.0 : 66.0 * f64(shownCols) + 76.0; // the board: 66 px a column (Layout net's one 96 px) plus the price column const inset = Math.max(boardPx, 340.0) + 108.0; // past the board (the bars' offset at least) and the 100 px of bars left of it if (isNaN(wallPrice)) tags[0].delete(); else { sb_clear(); sbUsd(wallGex); tags[0].set(inset, wallPrice).text(str_wall_text_sb).color(theme.MUTED).valign(VALIGN_BOTTOM); // each tag's box rests on its line, the words above it, so the line never runs through them } if (isNaN(flipPrice)) tags[1].delete(); else { sb_clear(); sb_text("#"); sb_int(flipRank); sb_text(" "); sbStrike(flipStrike); sb_text(" | Flip · all expiries "); sbPrice(flipPrice); tags[1].set(inset, flipPrice).text(str_flip_text_sb).color(theme.MUTED).valign(VALIGN_BOTTOM); } if (isNaN(painPrice)) tags[2].delete(); else { sb_clear(); sb_text("#"); sb_int(painRank); sb_text(" "); sbStrike(painPrice); sb_text(" | MP "); sbPrice(painPrice); tags[2].set(inset, painPrice).text(str_pain_text_sb).color(theme.MUTED).valign(VALIGN_BOTTOM); } if (isNaN(putWallPrice)) tags[3].delete(); else { sb_clear(); sb_text("#"); sb_int(putWallRank); sb_text(" "); sbStrike(putWallPrice); tags[3].set(inset, putWallPrice).text(str_put_wall_text_sb).color(theme.MUTED).valign(VALIGN_BOTTOM); } } function sbLensNet(v: f64): void { // the chip's net in the lens's unit: signed dollars, or an open interest if (lens == OPEN_INTEREST) sbCount(v); else sbUsd(v); } function sbStrikeExact(k: f64): void { // a strike as listed: "103", "6652.5", "0.42" sb_f64(k, k == Math.floor(k) ? 0 : k * 10.0 == Math.floor(k * 10.0) ? 1 : 2); } function badgeSize(p: f64): f64 { // a move's percent as the badge prints it: no decimals from 10 up, one below const a = Math.min(Math.abs(p), 99999.0); return Math.abs(p) < 9.95 ? Math.round(a * 10.0) / 10.0 : Math.round(a); } function sbBadge(p: f64): void { // "+25%", "-3.4%" sb_text(p < 0.0 ? "-" : "+"); sb_f64(badgeSize(p), Math.abs(p) < 9.95 ? 1 : 0); sb_text("%"); } function writeNodeTexts(velActive: bool): void { // the Above/Below chip, then the movers sb_clear(); if (rowCount > 0 && nodes.top() >= 0) { sb_text("Above "); sbLensNet(nodes.aboveNet()); sb_text(" | Below "); sbLensNet(nodes.belowNet()); } str_nodes_text_sb(); sb_clear(); if (moverCount > 0 && velActive) { // A significant strike's move: its cells' moves summed over its reading back then, so every cell needs a reading. for (let r = 0; r < rowCount; r += 1) { rowTaken[r] = 0; rowMove[r] = NaN; if (!nodes.isSignificant(r)) continue; let move = 0.0; let then = 0.0; let cells = 0; for (let c = 0; c < boardCols; c += 1) { const at = r * MAX_COLS + c; if (cellSeen[at] == 0) continue; const d = moveOf(at, true); if (!isFinite(d)) { cells = -1; break; } move += d; then += cellValue[at] - d; cells += 1; } if (cells > 0 && then != 0.0) rowMove[r] = (100.0 * move) / Math.abs(then); } let listed = 0; for (let k = 0; k < moverCount; k += 1) { let best = -1; let bestSize = -1.0; for (let r = 0; r < rowCount; r += 1) { if (rowTaken[r] != 0 || !isFinite(rowMove[r]) || rowMove[r] == 0.0) continue; // a strike that did not move is no mover const size = Math.abs(rowMove[r]); if (size > bestSize) { best = r; bestSize = size; } } if (best < 0) break; rowTaken[best] = 1; sb_text(listed == 0 ? "Movers " : ", "); sbStrikeExact(strikePrice[best]); sb_text(" "); sbBadge(rowMove[best]); listed += 1; } } str_movers_text_sb(); } // ── Frames: the board and the bars, appended as JSON text without allocating ── function tradeDayOf(sec: f64): f64 { // an instant's trade date on the market's own clock, days since 1970-01-01: CME's trade day opens at 17:00 Chicago (zone 2), every other market's at midnight return sessionTradeDate(sec, marketZone, marketZone == 2 ? 1020.0 : 0.0); } function expiryDayKey(ms: f64): i32 { // the expiry's trade date on the market's own clock, days since 1970-01-01; a stamp at exactly 00:00 UTC is the date a venue stamped if (ms % 86400000.0 == 0.0) return i32(ms / 86400000.0); return i32(tradeDayOf(Math.floor(ms / 1000.0))); } function todayKey(tradeDate: f64, clockMs: f64, intervalSec: f64): i32 { // today on the same calendar: the bar's trade date, or the trade date of the chain's as-of when that is later on a bar longer than a day (a 1W or 1M bar carries its first day's date) const clockDay = tradeDayOf(Math.floor(clockMs / 1000.0)); if (!isFinite(tradeDate)) return isFinite(clockDay) ? i32(clockDay) : 0; const tradeDay = Math.floor(tradeDate / 86400.0); return i32(intervalSec > 86400.0 && clockDay > tradeDay ? clockDay : tradeDay); } function fbColumnLabel(ms: f64, nearest: bool): void { // "0DTE" for the front expiry on the bar's trade date, else its date as the kit's fbExpiryLabel spells it ("27 Jun", "15 Jan '27" in another year), never the hours left to it fb_text("\""); if (nearest && expiryDayKey(ms) <= today) fb_text("0DTE"); else fbExpiryLabel(ms, nowMs, marketZone); fb_text("\""); } function fbUsd(v: f64): void { // "+$84.3M" inside a frame string if (!isFinite(v)) { fb_text("n/a"); return; } fb_text(v < 0.0 ? "-$" : "+$"); const a = Math.abs(v); if (a >= 1.0e9) { fb_f64(a / 1.0e9, 2); fb_text("B"); } else if (a >= 1.0e6) { fb_f64(a / 1.0e6, 1); fb_text("M"); } else if (a >= 1.0e3) { fb_f64(a / 1.0e3, 1); fb_text("K"); } else fb_f64(a, 0); } function priceDecimals(v: f64): i32 { // decimals follow the price's size: strikes at 84,000 / 2,437.5 / 12.5 / 0.42 return v >= 1000.0 ? 1 : v >= 10.0 ? 2 : v >= 1.0 ? 3 : 5; } function fbCount(v: f64): void { // "12.3K", "995" inside a frame string: an open interest, whole contracts under 1,000 const a = Math.abs(v); if (a >= 1.0e6) { fb_f64(a / 1.0e6, 1); fb_text("M"); } else if (a >= 1.0e3) { fb_f64(a / 1.0e3, 1); fb_text("K"); } else fb_f64(a, oiDecimals); } // A cell's own text, at most 16 characters: a node's mark, then its share of the top or the cell's value as the board's // number words spell it, then the velocity badge. Each piece's length is counted before it is written, so a long one // drops the mark's space, then the badge's, then the badge. function digitsOf(x: f64): i32 { // the integral digits of a number at or above 0 let d = 1; let v = Math.floor(x); while (v >= 10.0) { v = Math.floor(v / 10.0); d += 1; } return d; } function unitOf(a: f64, top: i32): i32 { // the value's unit for one decimal, the way the board's number words round: 0 none, 1 K, 2 M, 3 B, 4 T if (a < 999.95 || top < 1) return 0; if (a < 999950.0 || top < 2) return 1; if (a < 999950000.0 || top < 3) return 2; if (a < 999950000000.0 || top < 4) return 3; return 4; } function unitSize(unit: i32): f64 { return unit == 1 ? 1.0e3 : unit == 2 ? 1.0e6 : unit == 3 ? 1.0e9 : unit == 4 ? 1.0e12 : 1.0; } function scaledOf(a: f64, unit: i32): f64 { // the value in its unit, rounded to one decimal return Math.round((a / unitSize(unit)) * 10.0) / 10.0; } function valueTextLength(v: f64): i32 { const a = Math.abs(v); if (lens == OPEN_INTEREST) { const unit = unitOf(a, 2); if (unit > 0) return digitsOf(scaledOf(a, unit)) + 3; return oiDecimals > 0 ? digitsOf(Math.round(a * 10.0) / 10.0) + 2 : digitsOf(Math.round(a)); } if (a < 0.05) return 4; // "$0.0" const unit = unitOf(a, 4); return 2 + digitsOf(scaledOf(a, unit)) + 2 + (unit > 0 ? 1 : 0); } function fbUnit(unit: i32): void { if (unit == 1) fb_text("K"); else if (unit == 2) fb_text("M"); else if (unit == 3) fb_text("B"); else if (unit == 4) fb_text("T"); } function fbValueText(v: f64): void { // "+$84.3M", "-$60.0", "$0.0" (usd, signed, one decimal), or "12.3K", "995" on open interest const a = Math.abs(v); if (lens == OPEN_INTEREST) { const unit = unitOf(a, 2); if (unit > 0) { fb_f64(scaledOf(a, unit), 1); fbUnit(unit); } else fb_f64(oiDecimals > 0 ? Math.round(a * 10.0) / 10.0 : Math.round(a), oiDecimals); return; } if (a < 0.05) { fb_text("$0.0"); return; } const unit = unitOf(a, 4); fb_text(v < 0.0 ? "-$" : "+$"); fb_f64(scaledOf(a, unit), 1); fbUnit(unit); } function fbBadge(p: f64): void { // "+12%", "-3.4%" fb_text(p < 0.0 ? "-" : "+"); fb_f64(badgeSize(p), Math.abs(p) < 9.95 ? 1 : 0); fb_text("%"); } function fbCellText(prefix: i32, showPct: bool, pct: f64, v: f64, badge: f64): void { const markLength = prefix == PREFIX_TOP ? 1 : prefix != PREFIX_NONE ? 2 : 0; const bodyLength = showPct ? digitsOf(Math.round(pct)) + 1 : valueTextLength(v); let badgeLength = isFinite(badge) ? 3 + digitsOf(badgeSize(badge)) + (Math.abs(badge) < 9.95 ? 2 : 0) : 0; let markSpace = prefix >= PREFIX_GATE; let badgeSpace = badgeLength > 0; let total = markLength + bodyLength + badgeLength; if (total > TEXT_MAX && markSpace) { markSpace = false; total -= 1; } if (total > TEXT_MAX && badgeSpace) { badgeSpace = false; total -= 1; } if (total > TEXT_MAX) badgeLength = 0; if (prefix == PREFIX_TOP) fb_text("★"); else if (prefix == PREFIX_GATE) fb_text("G"); else if (prefix == PREFIX_FLOOR) fb_text("F"); else if (prefix == PREFIX_CEILING) fb_text("C"); if (markSpace) fb_text(" "); if (showPct) { fb_f64(Math.round(pct), 0); fb_text("%"); } else fbValueText(v); if (badgeLength > 0) { if (badgeSpace) fb_text(" "); fbBadge(badge); } } function fbHexDigit(d: i32): void { if (d < 10) fb_int(d); else if (d == 10) fb_text("a"); else if (d == 11) fb_text("b"); else if (d == 12) fb_text("c"); else if (d == 13) fb_text("d"); else if (d == 14) fb_text("e"); else fb_text("f"); } function fbRampColor(drawn: f64, range: f64): void { // "#21918c": the palette's stops at the square root of the cell's share of the range, the dark end at zero const first = RAMP_FIRST[palette]; const stops = RAMP_STOPS[palette]; const t = range > 0.0 ? Math.sqrt(Math.min(1.0, Math.abs(drawn) / range)) : 0.0; const pos = t * f64(stops - 1); let i = i32(Math.floor(pos)); if (i > stops - 2) i = stops - 2; const f = pos - f64(i); const a = RAMPS[first + i]; const b = RAMPS[first + i + 1]; fb_text("#"); for (let shift = 16; shift >= 0; shift -= 8) { const ca = f64((a >> shift) & 0xff); const cb = f64((b >> shift) & 0xff); const ch = i32(Math.round(ca + (cb - ca) * f)); fbHexDigit(ch >> 4); fbHexDigit(ch & 15); } } function prefixOf(r: i32): i32 { // the mark a node's cell starts with: the star on the top, G, F and C under Node % focus const role = nodes.role(r); if (role == NODE_ROLE_TOP) return PREFIX_TOP; if (pctMode != PCT_FOCUS) return PREFIX_NONE; if (role == NODE_ROLE_GATE) return PREFIX_GATE; if (role == NODE_ROLE_FLOOR) return PREFIX_FLOOR; if (role == NODE_ROLE_CEILING) return PREFIX_CEILING; return PREFIX_NONE; } function pctShown(r: i32): bool { // whether the strike's node prints its share of the top if (labels != LABELS_PCT) return false; if (pctMode == PCT_FOCUS) return nodes.isSignificant(r); if (pctMode == PCT_TOP) return nodes.role(r) == NODE_ROLE_TOP; return false; } function rowHidden(r: i32): bool { // a strike under Hide strikes under, or a low node under Low nodes hide if (hideUnderPct > 0.0 && nodes.pctOfTop(r) < hideUnderPct) return true; return lowNodes == LOW_HIDE && !nodes.isSignificant(r); } function cellFiltered(at: i32, velActive: bool): bool { // a cell the velocity filter leaves out: its move has the other sign, or none if (!velActive || (velFilter != FILTER_UP && velFilter != FILTER_DOWN)) return false; const move = moveOf(at, true); return velFilter == FILTER_UP ? !(move > 0.0) : !(move < 0.0); } function dominantCol(r: i32): i32 { // the row's largest cell, where its node's text goes (the nearer expiry on a tie); -1 for none let best = -1; let bestSize = -1.0; for (let c = 0; c < boardCols; c += 1) { const at = r * MAX_COLS + c; if (cellSeen[at] == 0) continue; const size = Math.abs(cellValue[at]); if (size > bestSize) { best = c; bestSize = size; } } return best; } function writeCell(r: i32, c: i32, node: i32, low: bool, velActive: bool, range: f64, valueDecimals: i32): void { const at = r * MAX_COLS + c; if (cellSeen[at] == 0 || cellFiltered(at, velActive)) { fb_text("null"); // no open interest (or no reading on the lens) in this cell, or the velocity filter leaves it out return; } const v = cellValue[at]; const faded = low && lowNodes == LOW_FADE; const drawn = faded ? v * FADE : v; // a faded low node keeps its reading in its text const prefix = c == node && labels != LABELS_OFF ? prefixOf(r) : PREFIX_NONE; const showPct = c == node && pctShown(r); const key = velActive ? cellKey[at] : -1; const badge = labels != LABELS_OFF && readable(key, velMin) ? velocity.velocityPct(key, velMin) : NaN; const texted = labels == LABELS_OFF || prefix != PREFIX_NONE || showPct || isFinite(badge) || faded; const dim = low && lowNodes == LOW_DIM; const bold = haloOn && key >= 0 && haloOf(key); if (!texted && !dim && !bold && palette == 0) { // a plain cell: the number, printed by the board's own words fb_f64(drawn, valueDecimals); return; } fb_text("{\"value\":"); fb_f64(drawn, valueDecimals); if (texted) { fb_text(",\"text\":\""); if (labels != LABELS_OFF) fbCellText(prefix, showPct, nodes.pctOfTop(r), v, badge); fb_text("\""); } if (palette > 0) { fb_text(",\"color\":\""); fbRampColor(drawn, range); fb_text("\""); } if (dim) fb_text(",\"text_color\":\"theme.muted\""); if (bold) fb_text(",\"font_weight\":\"bold\""); fb_text("}"); } function fbNetLabel(): void { // Layout net's one header, the expiries its column sums: "Net · 5 exp" fb_text("\""); fb_text(NET_HEADERS[shownCols]); fb_text("\""); } function writeBoard(velActive: bool): void { // strikes ascending, one cell per expiry column (Layout net: one column), the row of the strike nearest spot highlighted const cols = boardCols; const decimals = priceDecimals(close); const valueDecimals = lens == OPEN_INTEREST ? oiDecimals : 0; let range = 0.0; // a ramp's top: the largest |value| the board draws if (palette > 0) { for (let r = 0; r < rowCount; r += 1) { if (rowHidden(r)) continue; const fade = !nodes.isSignificant(r) && lowNodes == LOW_FADE ? FADE : 1.0; for (let c = 0; c < cols; c += 1) { const at = r * MAX_COLS + c; if (cellSeen[at] == 0 || cellFiltered(at, velActive)) continue; const a = Math.abs(cellValue[at] * fade); if (a > range) range = a; } } } fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(strikePrice[r], decimals); } fb_text("],\"cells\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_text("["); const hidden = rowHidden(r); const low = !nodes.isSignificant(r); const node = dominantCol(r); for (let c = 0; c < cols; c += 1) { if (c > 0) fb_text(","); if (hidden) fb_text("null"); else writeCell(r, c, node, low, velActive, range, valueDecimals); } fb_text("]"); } fb_text("],\"cols\":["); for (let c = 0; c < cols; c += 1) { if (c > 0) fb_text(","); if (net) fbNetLabel(); else fbColumnLabel(expiryMs[c], c == 0); } fb_text("],\"title\":\""); fb_text(net ? NET_TITLES[lens] : LENS_TITLES[lens]); fb_text("\",\"highlight\":{\"price\":"); // the row alone: a col here would outline the whole column too fb_f64(atmStrike(), decimals); fb_text("}}"); writeFrameBuffer(lens == OPEN_INTEREST ? (net ? oiNetBoard : oiBoard) : net ? netBoard : board); } function writeBars(): void { // the board's row sums as bars, positive in the chart's up colour and negative in its down colour, a hover hint per row const decimals = priceDecimals(close); fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(strikePrice[r], decimals); } fb_text("],\"values\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(rowCall[r] + rowPut[r], lens == OPEN_INTEREST ? oiDecimals : 0); } fb_text("],\"colors\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_text(rowCall[r] + rowPut[r] >= 0.0 ? "\"theme.up\"" : "\"theme.down\""); } fb_text("],\"tooltips\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_text("\"C "); if (lens == OPEN_INTEREST) fbCount(rowCall[r]); else fbUsd(rowCall[r]); fb_text(" | P "); if (lens == OPEN_INTEREST) fbCount(rowPut[r]); else fbUsd(rowPut[r]); fb_text("\""); } fb_text("]}"); writeFrameBuffer(lens == OPEN_INTEREST ? oiRows : gexRows); } function noReadings(): void { // a bar without the chain, or a history bar: the readings are the live bar's out_net_gex(NaN); out_net_lens(NaN); out_wall_price(NaN); out_flip_price(NaN); out_pain_price(NaN); out_put_wall_price(NaN); } // onBar() runs once per bar: a bar without the chain costs one read; a bar that carries it is measured, its cells read // into the velocity rings; the live bar writes the readings, places the labels and writes the two boards. function onBar(): void { prevT = t; t = bar.time(); close = bar.close(); out_spot(close); out_t_prev(prevT); out_t_last(t); const last = bar.isLast(); const n = isNaN(close) || isNaN(t) ? 0 : in_chain_cells(); if (n < TUPLE) { if (last) { clearTags(); clearNodeTexts(); } noReadings(); return; } nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the bar's close time measureChain(n); if (velOn && rowCount > 0) pushVelocity(t * 1000.0); if (!last) { noReadings(); return; } today = todayKey(in_trade_date(), nowMs, intervalMs > 0.0 ? intervalMs / 1000.0 : t - prevT); // the day the 0DTE label asks for measureLevels(n); out_net_gex(rowCount > 0 ? netGex : NaN); out_net_lens(rowCount > 0 ? netLens : NaN); out_wall_price(wallPrice); out_flip_price(flipPrice); out_pain_price(painPrice); out_put_wall_price(putWallPrice); writeTexts(); const velActive = velOn && rowCount > 0 && velocity.available(velMin, intervalMs); writeNodeTexts(velActive); if (rowCount > 0) { writeBoard(velActive); writeBars(); } } ``` ## How it works **The chain is live only.** `input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" })` delivers the chart's own listed contracts as `[strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega]` tuples on the live row (a BTC chain is about 1,550; on a governed chain, OPRA or CME, the chart serves as many strikes each side of every expiry's money as 4,000 contracts fit, 27 on SPY's 36 expiries); history bars carry an empty block and cost one read, so the boards and the levels are measured on the last bar and rewritten as the chain moves. `venue: "auto"` reads the chart's own market when it lists options, else the coin's Deribit chain. **The lens per cell.** On the default gamma lens each cell is gamma times open interest times the multiplier times spot squared times 0.01 (Deribit open interest is in coin units with multiplier 1; CME open interest is contracts times the point value), calls positive and puts negative; each contract lands in the cell of its strike row and its expiry column. `window_pct` (7) keeps the strikes within that percent of spot each side and `expiries` (4) the nearest expiries; a strike table of 128 rows holds the window, and when a window is wider than that the strike farthest from spot gives way. Each row also keeps its call and put halves for the bars' hover card, and `net_gex` sums the net GEX of the rows the board keeps as a data-only output, live bar only, whatever the lens (a strike the table drops for a nearer one takes its contracts with it, so the nets always match the cells). The other lenses follow [Greek exposure](greek-exposure.md)'s definitions in dollars, with the dealers long the calls and short the puts: delta is delta times open interest times the multiplier times spot, each option in its own sign; vega is the venue's vega (or the model's, where the venue serves none) times open interest times the multiplier, per IV point; vanna and charm are priced from each contract's mark IV (Black-Scholes on spot on a US stock at the **Rate** setting, Black-76 on the forward elsewhere, a crypto chain at a rate of 0), times open interest, the multiplier and spot, per IV point and per calendar day; the open interest lens sums both sides' open interest in the chain's own amount (contracts, or coins on Deribit) and prints it on a board of its own, one ramp from the background to the up colour: the frame carries whole contracts on OPRA and CME (coins to a tenth on Deribit) and `format: "auto"` prints a number as written, so a cell of 995 contracts reads `995`, never `995.0`, and 12,345 reads `12,345`; the bars and both hovers print the same way. `net_lens` sums the board's rows on the lens. A contract with no reading on the lens (no IV to price) leaves its cell as it was. **The chain's as-of.** The chain is read as of the live bar's close time, `optionsAsOfMs(t * 1000, intervalMs)` with the bar's length from `chart.interval_sec()`: the chart serves the snapshot as of a moment inside the live bar and names it to no module, so the close is the clock every options card reads on that bar, never a time solved back from a gamma. An expiry is live while `optionsLiveUntilMs(expiry, zone)` is after the as-of: on OPRA 15 minutes past its stamp, since a US listed PM expiry stamped 16:00 New York trades to 16:15, so on the 5-minute bar opening at 16:00 (read as of 16:05) today's expiry still heads the board as `0DTE`, and from the bar opening at 16:15 tomorrow's leads; on CME and crypto the stamp itself. Vega, vanna and charm price each contract to that end. `OptionsChain` keeps the contracts stamped after the clock it is handed, so it is handed a millisecond before the front live expiry: max pain and the walls read the same live expiries as the board and the flip. On a bar of a day or longer the close is the bar's end, so an expiry that settles inside the live bar is already off the board. **The date decides 0DTE.** The front column reads `0DTE` when its expiry's trade date is today's, never when it is under 24 hours away: at 11:00, tomorrow's 10:00 expiry is 23 hours off and still reads `16 Oct`. Both dates are read on the market's own clock, `sessionTradeDate()` on `market.zone()`, the calendar `time.trade_date` uses: the UTC date on crypto, New York's on a US stock, and on CME the trade date, which opens at 17:00 Chicago (`tradeDayOf()`). Today is the bar's trade date, and on a 1W or 1M bar, which carries its first day's date all period, the later of that and the trade date of the as-of (`todayKey()`). `expiryDayKey()` reads a stamp at exactly 00:00 UTC as the date a venue stamped and every other stamp at its instant, so Binance's metals expiry at 21:00 UTC stays today's. The header's dates are the same reading, written by the frame buffer's `fbExpiryLabel(expiryMs, nowMs, zone)`: the day and the month (`16 Oct`), and the year's last two digits once the expiry's trade date falls in another year than the as-of's (`15 Jan '27`), at most ten characters inside a column's 16, so the 66 px column holds every label whole. **The columns.** `expiry_preset` (count by default) picks how many of the live expiries the board shows with the kit's `expiryPresetCount(expiryMs, expiryCount, nowMs, zone, preset, columns)`, on the market's trade days at the as-of: front keeps the first expiry, to_friday every expiry through the first Friday on or after today, to_next_friday a week further, to_opex through this month's third Friday (next month's once it has passed), to_next_opex through the month after that, to_q_opex through the next third Friday of March, June, September or December, all every live expiry, and count the `expiries` setting's N. The board holds 12 columns at most, so all keeps the nearest 12; a preset that keeps none (a chain whose nearest expiry falls after this Friday, read to Friday) writes no board. The headers keep their dates, the front one `0DTE` on its own trade date. **The nodes.** Each strike's reading is its row summed across the board's columns (calls plus puts, the bar's value), loaded into the kit's `NodeBoard` against the close at `significance_pct` (15): the top is the largest `|reading|`, the gate the largest strictly between spot and the top, kept at 35% of the top or more, the floor and the ceiling the largest strictly below and above spot, the standouts the other local peaks at 50% of the top or more, and a significant strike one at `significance_pct` of the top or more. A strike's text goes on its largest cell (the nearer expiry on a tie): the top's starts with the star, and under **Node %** focus the gate's, the floor's and the ceiling's with G, F and C. Under **Node labels** pct that cell prints the strike's share of the top (`★100%`, `G 36%`, `55%`) where **Node %** asks for one (focus: every significant strike; top: the top alone; off: none), and every other cell prints its own value through the board's number words; under value a marked cell prints its own value after the mark (`★+$60.0`); under off no cell prints anything, the fills alone. A cell carrying a text, an ink or a weight is written as an object, `{ "value": 60, "text": "★100%" }`, every other cell as its number. The legend's chip reads `aboveNet()` and `belowNet()`: the readings of the strikes above the close and below it, summed (`Above +$179 | Below -$60`; an open interest reads unsigned). **Low nodes and hidden strikes.** The strikes under the significance share are low nodes: **Low nodes** shows them as they are, hides them (empty cells), dims them (`text_color: "theme.muted"`, the value kept) or fades them (the value at a fifth, so the fill fades, the text keeping the reading). **Hide strikes under** empties every strike whose share of the top is under the setting, 0 hiding none. **Centre on** top measures the board again around the top node's strike, so a node away from spot sits in the middle of the window; the highlight still marks the strike nearest the close. **The palettes.** Classic keeps the sheet's palette, the chart's down, background and up colours. Viridis, cividis, inferno and plasma colour each cell in the module: the ramp's stops (dark theme hex, low to high) interpolated at the square root of the cell's `|value|` over the largest one the board draws, so the dark end sits at zero on both sides of the signed board (the ramp mirrored) and at the smallest count on the open interest board, and the largest cell takes the top stop (`#fde725` on viridis). The colour rides the cell as `color`. **Velocity.** With `velocity_window` on and a lens that has velocity (gamma, delta, vega and open interest; vanna and charm show none), every bar that carries the chain pushes each cell's reading into the kit's `StrikeVelocity`, keyed by the cell's strike and expiry, so a column that moves when an expiry rolls keeps its readings. On the live bar a cell's text ends with its move over the window in percent (`+12%`, `-3.4%`: no decimals from 10 up, one below); `velocity_filter` increasing or decreasing empties the cells that did not rise or fall; `halo` bolds the cells whose move has one sign over at least two of the window and its two neighbours among 1m, 5m, 10m, 15m, 1h, 4h and 1d, counting only the windows the chart can read (a 1m neighbour on a 5m chart casts no vote); `movers` lists the significant strikes with the largest move in the legend (`Movers 103 +25%, 110 -12%`), a strike's move being its cells' moves over its reading back then. A window shorter than the chart's bar, or longer than the bars that carried the chain reach back, is unavailable: no badge, and the filter keeps every cell. The chart serves the chain on the live bar, so a window reads once the bars that carried it reach that far back. The rings reach the window (and, with the halo, its wider neighbour) in the chart's bars, and hold 81,920 readings in all (1.25 MiB inside the module's 4 MiB). A cell keeps its ring while it stays on the board, a pair that leaves frees its ring for a cell that arrives (read from the bar it arrived on), and the rings go to the strikes nearest the board's centre first: every cell of a full board on a short window; on a long one the nearest cells (a 1h window with its halo on a 1m chart keeps 338, a 1d window there 56), the farthest strikes showing no badge. A move of spot keeps every ring of the cells that stay on the board. **The net layout.** `layout` net (matrix by default) draws each board as one column: a strike's cell is its reading summed over the columns the preset or the count keeps, the row sum the nodes and the bars already read, so the column, the bars and the Above/Below chip agree. It rides a board of its own, the `net_board` frame on the `gex_net` matrix (`oi_net_board` on `oi_net` for open interest), declared after the frames and matrices that were there so every earlier slot stays, with `column_width: 96` so a summed value's text fits whole inside the 16 characters a cell holds. The header reads `Net` and the count of expiries it sums (`Net · 5 exp`), the title names the lens (`Net GEX`, `Net OI`). Every node rule reads that one column: the star on the top, G, F and C under **Node %** focus, the share or the value under **Node labels**, **Low nodes**, **Hide strikes under** and **Centre on**. The velocity rings key the strike alone and read its summed value each bar, so a strike whose expiries move apart shows its net move (`+25%`) where the matrix shows each cell's own (`+50%` and `+0.0%`). The levels and their labels (placed past the narrower board), the highlight row, the bars (at their 340 px `offset`, a little apart from the board) and the legend read as the matrix layout's. A host that sends the settings list from before **Layout** existed reads it as matrix, byte for byte the board it drew before. **The frame's size.** A board frame holds 96 KiB. Each cell's bytes at most follow the settings (its text, a ramp colour, the dimmed ink, the halo's weight), so the board keeps the strikes nearest its centre whose cells fit: all 128 rows at four columns, 98 at twelve on the defaults, 65 at twelve with every option on; **Layout** net's one column keeps all 128. **The levels.** The gamma flip is the options kit's `GammaCurve` over every live expiry at the as-of, `curve.load(in_chain_view(), n, nowMs, 0, close, marketZone)` pricing each contract to its expiry's end: gamma exposure priced again at each hypothetical spot with every contract's own underlying moved with it, and the flip the curve's zero nearest S0 (the nearest expiry's median underlying), walked out in 0.25% steps up to 50% each side and bisected, the level Gamma Map and the Options Dashboard read too ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)); with no zero within 50% it reads NaN and draws no line. The chain goes through the `OptionsChain` kit twice: the whole chain, every live expiry and every strike, gives `maxPain()`, and a second load with the board's `window_pct` gives the walls a chart of this range trades against, read as Gamma Map reads them: `netGex(i)` finds the strike inside the window holding the largest positive net GEX and `putWall()` the heaviest put strike at or below spot inside it, so the two templates name the same put wall on the same chain. The labels rank the flip, max pain and the put wall 1 to 3 by the absolute net GEX at the strike nearest each (`#1 $86K | Flip · all expiries $85.7K`, the flip's label naming its scope), so the heaviest level reads first. The level prices are data-only outputs, NaN on history bars, and `t_prev` and `t_last` carry the two newest bar times the lines are placed from. **Two frames, two canvases.** A dollar lens writes the `board` and `gex_rows` frames, the open interest lens the `oi_board` and `oi_rows` frames, so the pair the lens does not pick stays absent; **Layout** net writes `net_board` or `oi_net_board` in place of the lens's board, and the matrix board stays absent then. The board frame carries `prices` (the strikes, ascending), `cells` (one row per price, one entry per column: a number, `null` where the expiry lists no open interest at the strike or a setting empties the cell, or an object carrying the number beside its text, colour, ink and weight), `cols` (the expiry labels, `0DTE` for the front expiry on the bar's trade date, else its date: `27 Jun`, or `15 Jan '27` in another year), a `title` naming the lens (`GEX by expiry`, `OI by expiry`) and a `highlight` naming the price of the strike nearest spot, so the board outlines that one row. The bars frame carries the same `prices`, the row sums as `values`, a colour per row (`theme.up` for a positive sum, `theme.down` for a negative one) and a `tooltips` entry naming the call and put halves. Both are appended with `fb_text` and `fb_f64` into the generated frame buffer and sent with `writeFrameBuffer`, so the live bar allocates nothing. `plot.matrix({ frame: board, dock: "right" })` docks the board at the price axis, each row on its strike's price, the header sticky at the top; `palette: ["theme.down", "theme.bg", "theme.up"]` with `center: 0` and `scale: "sqrt"` tints the cells on a diverging ramp from the chart's down colour through its background to its up colour, `format: "usd"` with `signed: true` prints them as signed dollars, `grid_lines: "all"` rules every cell, `highlight_color: "theme.text"` outlines the at-the-money row in the text ink and `tooltip` puts a readout under the cursor. `plot.levels({ frame: gexRows, dock: "right", baseline: "center" })` draws the bars from a zero line mid-dock, `width_px: 100` and `thickness_px: 10` size them, and `hover: true` opens the row's card. Two canvases docked on the same side overprint and no word stacks them: `offset: [340, 0]`, the board's width (four columns of 66 px plus the price column), pushes the bars inward so they sit left of the board instead of under it. In the sheet `beside` names another level only; once it can name a matrix, `beside` naming the board replaces this pixel offset and follows the board's own width, and until then the offset stays. **The legend.** `legend({ title: "±{{window_pct}}%" })` puts the strike window after the indicator's name (`±7%`), filled from the setting of that name, so the words stay true on every coin; a title reads settings alone, so the columns the board shows ride the first entry instead, `render.legend("board_entry", { text: "board_text" })`, written on the live bar from the columns the preset kept (`4 expiries`, `3 expiries, to Friday`, `12 expiries, all`). `render.legend("spot_entry", { text: "spot_text" })` adds the live spot from a string slot written on the live bar (`live spot $86.5K`: the live bar's reading, which a crosshair on an older bar leaves as it is). Two more entries read the `nodes_text` and `movers_text` slots: the Above/Below chip and, with **Movers** above 0 and a velocity window that reads, the movers; each is empty otherwise. **The lines and their labels.** Each `draw.line` runs from `t_prev` to `t_last` at its level's price with `extend: "both"`, so the dashed line spans the whole pane. The labels are label handles declared once with `handles.label({ anchor: "right", align: "right", style: "plain", font_weight: "medium" })`: `tags[k].set(inset, price)` puts a label's right edge `inset` pixels in from the price axis at its level's price, and `inset` is the board's width (66 px a column plus the 76 px price column, at least the bars' 340 px `offset`) plus the 100 px of bars and an 8 px gap, so a label never covers a cell or a bar or runs into the axis whatever `expiries` reads. Its text is built with `sb_text`, `sb_f64` and `sb_int` and sent with its own slot's sender (`.text(str_flip_text_sb)`), and `.color(theme.MUTED)` inks every label as plain text in the muted colour, whatever its line's colour. A level that is NaN deletes its label and draws no line. ## What the settings do - **Lens**: What the boxes show: gamma (how fast dealers must hedge) by default. delta shows how much of the asset dealers must hold to hedge. vega shows how much they gain or lose when option prices rise. vanna and charm show how that hedge changes with option prices (vanna) or with time (charm). oi shows open interest (contracts still held open). - **Strike window, percent**: How far above and below the price the board's strikes reach, in percent. - **Expiry columns**: How many expiry dates get a column when Expiry preset is count, nearest first. - **Rate, percent**: The interest rate used to price vega, vanna and charm on US stocks and CME futures. - **Expiry preset**: Picks the columns: front keeps the nearest expiry date. to_friday and to_next_friday reach this or next Friday. to_opex and to_next_opex reach this or next monthly expiry (opex, its third Friday). to_q_opex reaches the next quarterly one, all shows up to 12, and count follows Expiry columns. - **Node labels**: A node is one strike's total across the board. off prints nothing in the boxes, and value prints each box's number. pct prints a node's share of the strongest node on its biggest box. - **Node %**: focus prints the shares on every key node (see Significant at), top on the strongest only, and off nowhere. focus also tags the floor (F), the biggest node below the price, and the ceiling (C), the biggest above it. The gate (G) is the biggest node between the price and the strongest one. - **Significant at, percent of the top**: A strike is key when its total reaches this share of the strongest strike's. - **Low nodes**: Shows, hides, dims or fades the strikes below the key share. - **Hide strikes under, percent of the top**: Blanks every strike whose total is under this share of the strongest, 0 hiding none. - **Palette**: Uses the chart's own down and up colours, or a colour-blind-safe scale that is dark at zero. - **Centre on**: Centres the strike window on the price (spot) or on the strongest strike (top). - **Velocity window**: How far back each box is compared, shown as a percent badge after its text. - **Velocity filter**: Keeps every box, or only the boxes whose number rose or fell. - **Halo**: Bolds a box whose move points the same way in at least two of three windows. Those are the Velocity window and the next shorter and longer ones. - **Movers**: Lists this many key strikes with the biggest moves in the legend. - **Layout**: Matrix shows one column per expiry date, and net folds them into one summed column. ## Where it runs It works on any chart with listed options. On crypto, that is any coin Deribit lists options for, such as BTC, ETH and SOL, on any exchange. For example, Binance Futures BTCUSDT and Binance spot ETHUSDT both work. On a US stock or ETF chart, every indicator can read that symbol's US listed options. On a futures chart from CME, the Chicago exchange, it reads that future's own options. US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless you have real-time CME data. A copy you run from the editor (where you write and run indicators) reads crypto, US stock and CME options. On a CME chart, accept the CME market data terms first. The chart sends the newest options snapshot on the live bar only, about every 30 seconds. Older bars get no options data. On a 1-minute or 5-minute chart, the candles span only a few strikes. Drag the price axis to zoom out, and the board shows more strikes. The picture above is a 5-minute chart zoomed out that way. ## When data is missing On a market with no listed options, it stops before loading anything. The error names the problem and the way out. On HYPERLIQUID_FUTURES/PURR, for example, it says PURR is not listed on Deribit. It then suggests a CME futures chart or a coin Deribit lists, such as BTC, ETH or SOL. Until the options data arrives, the chart shows only the candles. If no expiry is still trading, no board and no bars appear. A box with no open interest (contracts still open) prints nothing and stays uncoloured. A level it cannot find draws no line and no label. That happens with no gamma flip, or no put strike at or below the price on the board. An Expiry preset that keeps no date draws no board. A Velocity window shorter than one bar, or longer than the data so far, shows no badge. The Velocity filter then keeps every box. A chart saved with an older version opens on the same columns. Every setting that version lacked starts at its default, and Layout starts on matrix. A choice the setting does not list also falls back to its default. ## Customize it - **Another lens.** Set **Lens** to delta, vega, vanna, charm or oi; the board, the bars and their hover cards follow, the levels stay gamma's. - **A narrower board.** Lower `window_pct` for the strikes nearest spot, or `expiries` to 2 for the front of the curve. - **More columns.** Raise `expiries` (up to 12) and add 66 px to the `offset` of `plot.levels` for every added column, so the bars keep clear of the wider board; the labels move left with the board on their own. - **Bars on the other side.** `dock: "left"` on `plot.levels` puts the bars at the left edge of the pane; drop the `offset` then. - **Fewer levels.** Delete a `draw.line`, its label's block in `writeTexts()`, the output the line reads and the string slot the label sends; the rest keeps drawing. - **Pin the venue.** Change `venue: "auto"` to `"deribit"` and Run again to read the coin's Deribit chain even where the chart's market lists options of its own; `"cme"` reads a CME futures chart's chain. - **A calendar of columns.** Set **Expiry preset** to to_friday for this week's expiries, to_opex through the monthly, or all for every live one (12 at most). - **One net column.** Set **Layout** to net: each board folds into one 96 px column, every strike's reading summed over the expiries **Expiry preset** keeps (`Net · 5 exp`), the star and the marks on that column. - **Fewer labels.** **Node %** top labels the top node alone; **Node labels** off leaves the fills. - **Less noise.** **Low nodes** hide, or **Hide strikes under** 20, keeps the strikes that matter. - **A colour-blind-safe board.** **Palette** viridis or cividis paints the cells on a ramp dark at zero. - **Velocity.** On a 1m chart, **Velocity window** 5m with **Halo** on and **Movers** 5 marks the cells moving fastest. - **Your own colours.** The palette's two ends, the bars and the four levels are theme words (`theme.up`, `theme.down`, `theme.text`, `theme.muted`), so they follow the chart's theme and the user's up and down colours; a hex word in their place fixes a colour ([Style anything](../presentation/style-anything.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Strike Matrix** under **On price**. 2. Press **Run** on a BTC or ETH chart: the board docks at the price axis once the chain arrives, the bars beside it, the four dashed levels across the chart with their labels just left of the bars. Drag the price axis to zoom it out if the board shows only a few rows. 3. Hover a cell for its net GEX or a bar for the row's call and put halves; at the editor's Console prompt, type `net_gex` to read the board's sum, or `flip_price` for the gamma flip. 4. In the settings, set **Expiry preset**, **Node labels**, **Velocity window** or **Layout**: the board is rewritten on the next bar, the star on the top node. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `options_chain` celled class, its tuple and the `venue` word - [Price canvases](../presentation/price-canvases.md) for `plot.matrix`, the matrix frame, the colour scale and the hover readout - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels` over a frame, `baseline`, `hover` and `offset` - [Drawing objects](../presentation/drawing-objects.md) for `draw.line` placed from the newest bar and label handles pinned in pixels from the price axis - [Options kit](../functions/options-kit.md#the-canonical-numbers) for `GammaCurve` and the flip and `OptionsChain` for max pain and the walls, and [The market's own date and the chain's clock](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsAsOfMs` and `optionsLiveUntilMs` - [The strike board](../functions/options-kit.md#the-strike-board) for `NodeBoard`, `expiryPresetCount` and `StrikeVelocity`: the nodes, the columns and the velocity - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel`, the column dates - [Style anything](../presentation/style-anything.md) for the whole desk, part by part # Session OI Levels ![Open-interest profiles anchored to each day's span with the bar change below](/wrun/images/session-oi-levels.png) Where open interest was built and unwound in each day, as a profile anchored to the day's own time span. Each bar's change in open interest is spread over the price rows its range covered, so a row grows where positions were opened or closed while price traded there: the up colour where they were opened on balance, the down colour where they were closed, muted where nothing moved. Every day gets its own profile, its rows scaled to that day's biggest and drawn from the day's first bar, and hovering a row reads the open interest moved there. Under the chart, the bar's open-interest change as a histogram. The trader sees the prices the positioning was decided at, day by day. The parts are an `oi.close` feed input beside the chart's candles ([Data sources](../core-concepts/data-sources.md)), a frame of time spans feeding `plot.levels` with `span: "time"` ([Drawing primitives](../presentation/cards-frames-panels.md)), one histogram output under the chart ([Plotting](../presentation/plotting.md)), and a label handle for the one sentence shown on a market without open interest ([Drawing objects](../presentation/drawing-objects.md)). This is also the `session-oi-levels` template: the **Session OI Levels** card under **On price** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Session OI Levels: where open interest was built and unwound in each day, as a profile anchored to the day's own time // span. Each bar's change in open interest is spread over the price rows its range covered, so a row grows where // positions were opened (the up colour) or closed (the down colour) while price traded there; every day gets its own // profile, its rows scaled to that day's biggest row and drawn by the chart from the day's first bar. The bar's // open-interest change rides along as a histogram under the chart. section("Sessions"); // the dialog's one section param.int("sessions", 10, { min: 2, max: 30, label: "Days shown", description: "Days drawn, the newest last" }); param.int("rows", 32, { min: 8, max: 64, label: "Rows per day", description: "Price rows per day" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("oi", oi.close, { missing: "nan" }); // open interest at the bar's close; a bar without a reading, or a market without open interest, reads NaN output("oi_change", histogram, lower, { color_by: "oi_tone", colors: ["theme.down", "theme.up"], description: "Open interest change on the bar" }); // the up colour where positions were opened, the down colour where they were closed output("oi_tone", none, overlay, { description: "1 while open interest rose on the bar, 0 while it fell" }); // data-only: the histogram's colour index const oi_spans = frame("oi_spans", { max_bytes: 65536 }); // one span per day: its start and end, a price per row, the open interest moved on the row, a colour per row plot.levels({ name: "oi_by_price", frame: oi_spans, dock: "left", span: "time", width_frac: 0.5, labels: false, color: "theme.muted", opacity: 0.85, format: "si", hover: true }); // each day's profile grows from the day's first bar; hover a row for the open interest moved there string("note", { max_bytes: 40 }); // the one sentence shown when the market has no open interest handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 12, style: "plain", safe_area: true }); // that sentence: plain muted words at the pane's top right, clear of the chart's buttons const MAX_BARS = 8192; const MAX_ROWS = 64; const MAX_DAYS = 30; // the bar ring (8192 bars is 28 days of 5m bars) and the finished days kept, for the largest settings const barT = new StaticArray(MAX_BARS); const barLo = new StaticArray(MAX_BARS); const barHi = new StaticArray(MAX_BARS); const barOi = new StaticArray(MAX_BARS); // each ring bar's open time, price span and open-interest change const dayStart = new StaticArray(MAX_DAYS + 1); const dayLo = new StaticArray(MAX_DAYS + 1); const dayStep = new StaticArray(MAX_DAYS + 1); // each folded day's span start (NaN: it draws nothing), bottom and row height; slot MAX_DAYS is the open day const dayNet = new StaticArray((MAX_DAYS + 1) * MAX_ROWS); const dayMoved = new StaticArray((MAX_DAYS + 1) * MAX_ROWS); // per day and row: the net open-interest change, and the open interest moved, built or unwound const note = draw.label(0); // the one muted sentence; a handle allocates once at module load let sessions = 10; let rows = 32; // the params, read in onStart() let seq = -1; let openSeq = 0; let openDay: i64 = -1; let doneHead = -1; let doneCount = 0; // the bars counted (bar s sits in ring slot s % MAX_BARS), the open day and its first bar, the finished days' ring: its newest slot and the days in it let prevOi: f64 = NaN; // the last open-interest reading let t: f64 = NaN; // this bar's open time function dayOf(time: f64): i64 { return i64(Math.floor(time / 86400.0)); } // the UTC day number of an open time function priceDecimals(step: f64): i32 { // enough decimals that the rounded row prices stay evenly spaced (the docked grid is contiguous only within 0.1% of its step) const d = i32(Math.ceil(Math.log(2000.0 / step) / Math.LN10)); return d < 2 ? 2 : d > 9 ? 9 : d; } // ── One day's profile: its bars folded into `rows` price rows across the day's span, kept in a day slot ── function spread(a: f64, b: f64, amount: f64, gridLo: f64, width: f64, base: i32): void { // [a, b]'s open-interest change over the rows it overlaps, in proportion let first = i32(Math.floor((a - gridLo) / width)); let last = i32(Math.floor((b - gridLo) / width)); if (first < 0) first = 0; if (last > rows - 1) last = rows - 1; if (first > rows - 1) first = rows - 1; if (last < 0) last = 0; if (first >= last || b - a <= 0.0) { dayNet[base + first] += amount; dayMoved[base + first] += Math.abs(amount); return; } // one row, or a bar thinner than the grid for (let k = first; k <= last; k += 1) { const cellLo = gridLo + f64(k) * width; const cellHi = cellLo + width; const overlap = Math.min(b, cellHi) - Math.max(a, cellLo); if (overlap > 0.0) { const share = (amount * overlap) / (b - a); dayNet[base + k] += share; dayMoved[base + k] += Math.abs(share); } } } function foldDay(from: i32, to: i32, slot: i32): void { // the bars from..to (counted, oldest first) are one day: its rows into day slot `slot` if (to - from >= MAX_BARS) from = to - MAX_BARS + 1; // bars older than the ring are gone let lo = Infinity; let hi = -Infinity; for (let s = from; s <= to; s += 1) { const i = s % MAX_BARS; if (barLo[i] < lo) lo = barLo[i]; if (barHi[i] > hi) hi = barHi[i]; } dayStart[slot] = NaN; if (!(hi > lo)) return; // a day with no price span const rowHeight = (hi - lo) / f64(rows); const base = slot * MAX_ROWS; for (let r = 0; r < rows; r += 1) { dayNet[base + r] = 0.0; dayMoved[base + r] = 0.0; } let moved = 0.0; for (let s = from; s <= to; s += 1) { const i = s % MAX_BARS; const change = barOi[i]; if (isNaN(change) || change == 0.0) continue; spread(barLo[i], barHi[i], change, lo, rowHeight, base); moved += Math.abs(change); } if (moved <= 0.0) return; // a day with no open-interest change dayStart[slot] = f64(dayOf(barT[from % MAX_BARS])) * 86400.0; dayLo[slot] = lo; dayStep[slot] = rowHeight; // the span: the UTC day the bars belong to, in epoch seconds } function writeDay(slot: i32, first: bool): bool { // one folded day appended to the frame as a span; false when the day draws nothing const start = dayStart[slot]; if (isNaN(start)) return false; const lo = dayLo[slot]; const rowHeight = dayStep[slot]; const base = slot * MAX_ROWS; const decimals = priceDecimals(rowHeight); if (!first) fb_text(","); fb_text("{\"start\":"); fb_num(start); fb_text(",\"end\":"); fb_num(start + 86400.0); fb_text(",\"prices\":["); // row centres, strictly increasing for (let r = 0; r < rows; r += 1) { if (r > 0) fb_text(","); fb_f64(lo + (f64(r) + 0.5) * rowHeight, decimals); } fb_text("],\"values\":["); // the open interest moved on the row (0 where nothing moved, so the grid stays whole) for (let r = 0; r < rows; r += 1) { if (r > 0) fb_text(","); fb_f64(dayMoved[base + r], 0); } fb_text("],\"colors\":["); // up where positions were opened on balance, down where they were closed, muted where nothing moved for (let r = 0; r < rows; r += 1) { if (r > 0) fb_text(","); const net = dayNet[base + r]; fb_text(net > 0.0 ? "\"theme.up\"" : net < 0.0 ? "\"theme.down\"" : "\"theme.muted\""); } fb_text("]}"); return true; } function writeSpans(): void { // the newest `sessions` days, oldest first, as one spans frame: the finished days as folded when they ended, the open day folded now foldDay(openSeq, seq, MAX_DAYS); // only the open day changes on a new bar or a live tick, so it is the one day folded again fb_clear(); fb_text("{\"spans\":["); let written = 0; const kept = doneCount < sessions - 1 ? doneCount : sessions - 1; for (let k = kept - 1; k >= 0; k -= 1) if (writeDay((doneHead + MAX_DAYS - k) % MAX_DAYS, written == 0)) written += 1; if (writeDay(MAX_DAYS, written == 0)) written += 1; fb_text("]}"); if (written > 0) writeFrameBuffer(oi_spans); // an unwritten frame leaves the profiles absent; an empty spans list would be refused } // onStart() runs once before the first bar: read the params. function onStart(): void { sessions = i32(p_sessions()); rows = i32(p_rows()); } // onBar() runs once per bar: the bar's open-interest change against the last reading, the bar into the ring, a finished // day folded once where the UTC day changes, the change as a number on every bar, and the day profiles on the live bar only. function onBar(): void { t = bar.time(); const oiNow = in_oi(); const lo = bar.low(); const hi = bar.high(); const change = isNaN(oiNow) || isNaN(prevOi) ? NaN : oiNow - prevOi; // unknown until two readings exist if (!isNaN(oiNow)) prevOi = oiNow; if (bar.isLast() && isNaN(prevOi)) { sb_clear(); sb_text("No open interest on this market"); note.set(16.0, 12.0).text(str_note_sb); } // no reading on any bar (spot, FX): one sentence, not an empty pane if (isNaN(t) || !(hi >= lo)) return; // a bar with no span draws nothing and is not counted const day = dayOf(t); if (day != openDay) { // a new UTC day: the day before is finished, folded once into the finished ring and kept as it ended if (openDay >= 0) { doneHead = (doneHead + 1) % MAX_DAYS; if (doneCount < MAX_DAYS) doneCount += 1; foldDay(openSeq, seq, doneHead); } openDay = day; openSeq = seq + 1; } seq += 1; const slot = seq % MAX_BARS; barT[slot] = t; barLo[slot] = lo; barHi[slot] = hi; barOi[slot] = change; out_oi_change(change); out_oi_tone(isNaN(change) ? NaN : change >= 0.0 ? 1.0 : 0.0); if (bar.isLast()) writeSpans(); } ``` ## How it works **The change, not the level.** `input("oi", oi.close, { missing: "nan" })` reads open interest at each bar's close; the bar's change is the difference from the last reading (NaN until two readings exist, and on a market without open interest). `oi_change` is that number as a histogram under the chart, in the up colour while open interest rose and the down colour while it fell. **Rows per day.** Every bar lands in a ring with its open time, its high and low and its change. Where the UTC day changes, `foldDay` folds the day that just ended once: it finds the day's price span, splits it into `rows` (32) rows, and spreads each bar's change over the rows its range overlapped, in proportion; a row keeps the open interest moved on it (built or unwound, always positive: the bar's length) and the net change (its colour), and the folded day waits in a ring of 30 finished days. On the live bar only the open day is folded again, so a live tick costs one day's bars, never every day's. A day with no span or no change is left out. **One span per day.** `frame("oi_spans")` carries `{ "spans": [{ "start", "end", "prices", "values", "colors" }, ...] }`, one entry per day with its bounds in epoch seconds (the newest `sessions` (10) days: the finished ones as they were folded, then the open day), and feeds `plot.levels({ span: "time" })`: the chart draws every span's rows from the day's first bar, growing right across `width_frac` (0.5) of the day's width, each day scaled to its own biggest row. `hover: true` with `format: "si"` reads a row's open interest as `1.2M` in the hover card. The frame is built with the generated `fb_*` writer, so the live bar allocates nothing. ## Where it runs Perpetual futures with an open-interest feed: Binance Futures, Hyperliquid and the other venues that serve `oi` ([Data sources](../core-concepts/data-sources.md) lists them). A day is folded from the ring of the newest 8192 bars when it ends, and the ring holds a whole day down to 11-second bars, so a 1m chart shows its `sessions` days whole, as far back as the chart has loaded, like a 5m one. ## When data is missing Spot, stocks, FX and prediction markets carry no open interest: every bar's change reads NaN, the histogram stays empty and no profile is drawn (nothing moved), and one line of words shows at the top right of the chart, `No open interest on this market`, plain and muted: the `note` label handle, written on the live bar while no bar has brought a reading, pinned to the pane's top right corner, right-aligned and `safe_area: true`, so it clears the chart's own buttons. A bar without a reading keeps the last one, so the next reading's change covers both bars. The first bar of a run has no change. ## Customize it - **More days, finer rows.** `sessions` up to 30 and `rows` up to 64 (64 rows across 30 days is 1920 rows, inside the frame's 65536 bytes). - **Grow from the right.** `dock: "right"` grows each day's rows from the day's last bar instead. - **Rows with labels.** `labels: true` prints each row's value beside it (`format: "si"` keeps them short); `thickness_px` caps the rows on a coarse grid. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Session OI Levels** under **On price**. 2. Press **Run** on a perpetual chart such as BTCUSDT on Binance Futures at 15m: a profile grows inside each of the last ten days and the open-interest change appears under the chart. 3. Hover a row for the open interest moved there; at the editor's Console prompt, type `oi_change` to read the newest bar's change. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `oi` feed and the `missing: "nan"` policy - [Drawing primitives](../presentation/cards-frames-panels.md) for frames, `plot.levels` and the `span: "time"` frame shape - [Plotting](../presentation/plotting.md) for the histogram output and its colour index # Aggregated CVD One cumulative volume-delta line summed across venues, with volatility bands and sign coloring, on whichever coin the chart shows. Cumulative volume delta tracks the running difference between aggressive buying and aggressive selling. On a single venue it tells a partial story, because flow splits across exchanges. Coin legs read each venue's market for the chart's coin, so the line sums the flow of every venue you pick and follows the chart when you switch coins. ## The wrun indicator ```typescript param("band_len", 60, { min: 10, max: 500, description: "Bars in the volatility band" }); param.multi("venues", ["Binance perp", "Bybit perp", "Binance", "Coinbase"], ["Binance perp", "Bybit perp", "Binance", "Coinbase"], { label: "Venues" }); param.choice("unit", ["USD", "Coin"], "USD", { label: "Unit" }); // The chart's own candles are the grid every other input lines up on. input("close", ohlcv.close); // One buy and one sell input per venue, each on that venue's market for the chart's coin. input("bnf_buy", trades.volume, { exchange: "BINANCE_FUTURES", follow: "coin", side: "BUY", currency: "@unit", missing: "zero", when: "venues", when_bit: 0 }); input("bnf_sell", trades.volume, { exchange: "BINANCE_FUTURES", follow: "coin", side: "SELL", currency: "@unit", missing: "zero", when: "venues", when_bit: 0 }); input("bybit_buy", trades.volume, { exchange: "BYBIT", follow: "coin", side: "BUY", currency: "@unit", missing: "zero", when: "venues", when_bit: 1 }); input("bybit_sell", trades.volume, { exchange: "BYBIT", follow: "coin", side: "SELL", currency: "@unit", missing: "zero", when: "venues", when_bit: 1 }); input("bn_buy", trades.volume, { exchange: "BINANCE", follow: "coin", side: "BUY", currency: "@unit", missing: "zero", when: "venues", when_bit: 2 }); input("bn_sell", trades.volume, { exchange: "BINANCE", follow: "coin", side: "SELL", currency: "@unit", missing: "zero", when: "venues", when_bit: 2 }); input("cb_buy", trades.volume, { exchange: "COINBASE", follow: "coin", side: "BUY", currency: "@unit", missing: "zero", when: "venues", when_bit: 3 }); input("cb_sell", trades.volume, { exchange: "COINBASE", follow: "coin", side: "SELL", currency: "@unit", missing: "zero", when: "venues", when_bit: 3 }); output("cvd", line, lower, { width: 2, color_by: "sign", colors: ["#ff5b7f", "#22d3a5"], description: "Cumulative volume delta over the picked venues", }); output("upper_band", line, lower, { color: "#22d3a5", opacity: 0.35, description: "CVD plus one standard deviation" }); output("lower_band", line, lower, { color: "#ff5b7f", opacity: 0.35, description: "CVD minus one standard deviation" }); output("sign", none, lower); let stdev = new Stdev(60); let cvd: f64 = 0.0; let picked: i32 = 0; function onStart(): void { stdev = new Stdev(i32(p_band_len())); picked = i32(p_venues()); } // A venue's net flow while it is picked; an unpicked venue, or one that lists no market for the coin, adds 0. function net(bit: i32, buy: f64, sell: f64): f64 { return (picked & (1 << bit)) != 0 ? buy - sell : 0.0; } function onBar(): void { // A module-level variable is the accumulator: it survives from bar to bar. cvd += net(0, in_bnf_buy(), in_bnf_sell()) + net(1, in_bybit_buy(), in_bybit_sell()); cvd += net(2, in_bn_buy(), in_bn_sell()) + net(3, in_cb_buy(), in_cb_sell()); const band = stdev.update(cvd); const width = isNaN(band) ? 0.0 : band; out_cvd(cvd); out_upper_band(cvd + width); out_lower_band(cvd - width); out_sign(cvd >= 0.0 ? 1.0 : 0.0); } ``` ## How it works **The timeline spine.** `input("close", ohlcv.close)` is never read by the code. It is the first input, and the first input defines the grid every other input lines up on: one row per candle, always. Without it, the timeline would depend on the trade feeds resolving, and on a market where they are missing the module would have no bars to compute. Load the chart series first, always. **Coin legs.** Each venue is two `trades.volume` inputs, `side: "BUY"` and `side: "SELL"`, with `follow: "coin"` beside its `exchange`: the chart reads that venue's main market for the chart's coin (BTCUSDT on Binance on a BTC chart, ETH-USD on Coinbase on an ETH chart) and picks again when you switch coins. A venue that lists no market for the coin reads `0` under `missing: "zero"`, so it adds nothing. **The venue picker.** `venues` is a multi setting, one bit per venue in its choice order. `when: "venues"` with `when_bit` ties each leg to its option, so the chart fetches only the picked venues, and `net()` reads the same bits, so the line is right on a host that fetches every leg anyway. **The unit.** `currency: "@unit"` binds every leg's unit to the `unit` choice: dollars by default, coins when the reader picks Coin. Dollar volume adds up across venues; coin counts add up too, since every leg here trades the same coin. **Cumulative means module-level.** `cvd` is a module-level variable and each bar adds every picked venue's net flow. That persistence is what turns a per-bar delta into a cumulative line. **Sign coloring and the band.** `sign` is a data-only `1` or `0`, and the `cvd` line indexes its two-entry palette with it: green when the running total is positive, red when negative. `Stdev` over the running total gives the one-sigma envelope; while it is warming the band width is `0`, so the edges sit on the line instead of vanishing. ## Design notes - The legs follow the chart's coin, never its venue: on a BTC chart on any exchange the line sums the four venues' BTC flow. A coin the venues do not list reads `0` from them, so the line stays flat. - The sign tint is `color_by` over a data-only output. To shade between the bands, declare a `range()` between the two band outputs, which the chart draws as a filled band, or a one-bar box between them (the [Anchored VWAP](anchored-vwap.md) recipe shades its band that way). - An alert refuses a coin leg by name, so this Indicator draws on the chart only; for an alert, pin each venue's market with `symbol` and `exchange`. ## Customize it - **Another venue.** Add a pair of legs with that venue's `exchange` id, an option in `venues` for it, and a `when_bit` and a `net()` term for its bit. - **Band width.** `band_len` sets the volatility lookback. Shorten it for a reactive envelope that hugs the line, lengthen it for a smoother, slower band. - **Colors.** The palette on `cvd` and the `color` on each band are hex strings on the declarations; recolor there. - **Alert on the line.** Alerts refuse coin legs, so alert on a copy whose legs pin each venue's market with `symbol` and `exchange` ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press **New indicator** and pick **Blank indicator**: the tab holds the `//@lang=wrun-ts` line alone. 2. Paste the indicator block above under that line and press **Run** on a crypto perp or spot market. 3. At the editor's Console prompt, type `last 20 cvd` to read the running total over the last 20 bars. ## Concepts used - [Multi-source](../core-concepts/multi-source.md#coin-legs-every-venue-follows-the-chart) for coin legs and the setting gate - [Data sources](../core-concepts/data-sources.md) for `trades.volume` with a `side` and the `missing` policies - [Execution model](../core-concepts/execution-model.md) for the module-level accumulator - [Volume and VWAP](../functions/volume-indicators.md) for buy and sell volume as inputs # CVD divergence ![CVD pane under BTC with divergence lines and div tags](/wrun/images/cvd-divergence.png) Cumulative volume delta (aggressive buys minus aggressive sells, summed bar after bar) in coins, in its own pane under the chart, with its own axis. Every confirmed swing high and swing low of price is dotted on the CVD line in the pane. When price makes a higher high while CVD makes a lower high, or a lower low while CVD makes a higher low, the example draws the evidence: a line joining the two price swings on the chart (in the down colour for the bearish case, the up colour for the bullish one), a dashed line joining the two CVD swings in the pane, and a small "div" tag beside the price line. Nothing is drawn on ordinary bars. The parts are side-split `trades.volume` inputs ([Data sources](../core-concepts/data-sources.md)), a `shape` output displaced back to the swing bar, and three handle kinds: line handles on price, a polyline handle in the lower pane and label handles for the tags ([Drawing objects](../presentation/drawing-objects.md)). This is also the `cvd-divergence` template: the **CVD Divergence** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // CVD Divergence: cumulative volume delta, in coins, in its own pane. When price makes a higher high while CVD makes // a lower high (or a lower low while CVD makes a higher low), a line joins the two price swings on the chart, a dashed // line joins the two CVD swings in the pane, every confirmed swing is dotted in the pane, and a small "div" tag names it. param.int("swing", 8, { min: 3, max: 30, label: "Swing strength in bars", description: "Bars on each side a swing high or low must beat; a swing is confirmed this many bars later" }); param.bool("cvd_reset", false, { label: "Reset at midnight", description: "Restart CVD at every UTC midnight; off, it runs from the first loaded bar" }); // a toggle: pb_cvd_reset() reads it in onStart() param.int("lines_kept", 12, { min: 1, max: 60, label: "Divergence lines kept", description: "Divergence lines kept on the chart; the oldest is recycled" }); legend({ title: "({{swing}})" }); // the words after the name in the legend: the swing strength, read by name input("close", ohlcv.close); // the primary input: the chart's own candles define the grid every other input lines up on input("buy", trades.volume, { side: "BUY", missing: "zero" }); // aggressive buy volume; a bar with no prints reads 0 input("sell", trades.volume, { side: "SELL", missing: "zero" }); // aggressive sell volume, the other half of the tape output("cvd", line, lower, { color: "theme.text", width: 2, label: "CVD", format: "si", unit: " coins" }); // cumulative volume delta in the base asset (trades.volume reads coins), in its own pane under the chart output("cvd_swing", shape, lower, { color: "theme.muted", shape_where: "swing_here", displacement_bars: -8, displacement_bars_by: { param: "swing", scale: -1 }, label: "CVD swing", format: "si", unit: " coins" }); // a dot on the CVD at each confirmed swing, drawn back at the swing bar: `swing` bars before the bar that confirms it (-8 is the default strength's shift) output("swing_here", none); // data-only: 1 on the bar that confirms a swing (the dot's gate) output("divergence", none); // data-only: -1 bearish, +1 bullish, 0 none; read it in the Console or fire an alert(...) on it string("text", { max_bytes: 40 }); // one bounded slot every label is written through handles.line({ width: 2 }); // the price link between the two swings (chart time and price) handles.polyline({ panel: "lower", width: 1, lineStyle: "dashed" }); // the CVD link between the two swings, in the pane handles.label({ size: 11, color: "theme.text" }); // the "div" tag on price, and the one line of words when the market has no sided trades const RING = 64; // the swing window: 2 x 30 + 1 bars at the largest strength const MAX_LINES = 60; // handles per kind at the largest setting const highs = new StaticArray(RING); // the last RING bars, rings the swing test reads const lows = new StaticArray(RING); const cvds = new StaticArray(RING); const times = new StaticArray(RING); const points = new StaticArray(4); // x0, y0, x1, y1 for the pane link const lines: LineHandle[] = []; // handle objects allocate once; ids are one space across kinds const links: PolylineHandle[] = []; const tags: LabelHandle[] = []; for (let i = 0; i < MAX_LINES; i += 1) { lines.push(draw.line(i)); links.push(draw.polyline(100 + i)); tags.push(draw.label(200 + i)); } const notice = draw.label(300); const BEARISH = theme.DOWN; // bearish: price up, CVD down const BULLISH = theme.UP; // bullish: price down, CVD up const NOTE_INK = theme.MUTED; let swing = 8; // settings, read in onStart() let resetDaily = false; let linesKept = 12; let barCount = 0; // bars seen let cvd = 0.0; // the running delta let sidedVolume = 0.0; // every sided print seen: 0 means the market has no sided trades let prevDay = -1.0; // the UTC day of the previous bar, for the daily reset let rangeAvg = NaN; // a running mean of high - low: the tag's distance from the line let lastHighPrice = NaN; // the previous confirmed swing high and the CVD at it let lastHighCvd = NaN; let lastHighTime = NaN; let lastLowPrice = NaN; // the previous confirmed swing low and the CVD at it let lastLowCvd = NaN; let lastLowTime = NaN; let divergences = 0; // how many have been drawn: the ring position let swingHere = 0.0; // this bar's results, set by testSwing() let swingCvd = NaN; let pendingKind = 0; // 0 none, -1 bearish, +1 bullish: a divergence to draw this bar let x1 = NaN; // the two price swings and the CVD at each let y1 = NaN; let x2 = NaN; let y2 = NaN; let c1 = NaN; let c2 = NaN; // testSwing() tests the bar `swing` bars back for a swing, then the swing against the previous one of its kind for a divergence. function testSwing(): void { swingHere = 0.0; swingCvd = NaN; pendingKind = 0; if (barCount < 2 * swing + 1) return; // not enough bars on both sides yet const center = barCount - 1 - swing; // the bar under test, `swing` bars back const c = center % RING; let isHigh = true; let isLow = true; for (let k = 1; k <= swing; k += 1) { const leftSlot = (center - k) % RING; const rightSlot = (center + k) % RING; if (!(highs[c] > highs[leftSlot]) || !(highs[c] >= highs[rightSlot])) isHigh = false; // above every bar before it, at or above every bar after it (a flat top counts once, on its first bar) if (!(lows[c] < lows[leftSlot]) || !(lows[c] <= lows[rightSlot])) isLow = false; // the mirror for a swing low } if (!isHigh && !isLow) return; swingHere = 1.0; swingCvd = cvds[c]; if (isHigh) { if (!isNaN(lastHighPrice) && highs[c] > lastHighPrice && cvds[c] < lastHighCvd) { // higher high in price, lower high in CVD pendingKind = -1; x1 = lastHighTime; y1 = lastHighPrice; c1 = lastHighCvd; x2 = times[c]; y2 = highs[c]; c2 = cvds[c]; } lastHighPrice = highs[c]; lastHighCvd = cvds[c]; lastHighTime = times[c]; } if (isLow) { if (!isNaN(lastLowPrice) && lows[c] < lastLowPrice && cvds[c] > lastLowCvd) { // lower low in price, higher low in CVD pendingKind = 1; x1 = lastLowTime; y1 = lastLowPrice; c1 = lastLowCvd; x2 = times[c]; y2 = lows[c]; c2 = cvds[c]; } lastLowPrice = lows[c]; lastLowCvd = cvds[c]; lastLowTime = times[c]; } } function onStart(): void { swing = i32(p_swing()); resetDaily = pb_cvd_reset(); linesKept = i32(p_lines_kept()); } // onBar() runs once per bar: fold the bar into CVD and the rings, test for a swing, write the outputs on every bar, and // draw a divergence on the bar that confirms it. function onBar(): void { const high = bar.high(); const low = bar.low(); const barTime = bar.time(); const buy = in_buy(); const sell = in_sell(); if (resetDaily) { const day = Math.floor(barTime / 86400.0); if (day != prevDay) cvd = 0.0; prevDay = day; } cvd += buy - sell; sidedVolume += buy + sell; const range = high - low; rangeAvg = isNaN(rangeAvg) ? range : rangeAvg + (range - rangeAvg) * 0.1; const slot = barCount % RING; highs[slot] = high; lows[slot] = low; cvds[slot] = cvd; times[slot] = barTime; barCount += 1; testSwing(); out_cvd(cvd); out_swing_here(swingHere); out_cvd_swing(sidedVolume > 0.0 ? swingCvd : NaN); // no dots on a market with no sided trades: the pane holds a flat zero line and the words out_divergence(f64(pendingKind)); if (pendingKind != 0) { const k = divergences % linesKept; // the ring position: the oldest line, link and tag are reused divergences += 1; const tone = pendingKind < 0 ? BEARISH : BULLISH; lines[k].set(x1, y1, x2, y2).color(tone); points[0] = x1; points[1] = c1; points[2] = x2; points[3] = c2; links[k].setPoints(points, 2).color(tone); const offset = (isNaN(rangeAvg) ? 0.0 : rangeAvg) * 0.6; // the tag sits just outside the line, on the swing side const tagY = pendingKind < 0 ? Math.max(y1, y2) + offset : Math.min(y1, y2) - offset; sb_clear(); sb_text("div"); tags[k].set((x1 + x2) * 0.5, tagY).text(str_text_sb); tags[k].color(tone); } if (bar.isLast() && sidedVolume <= 0.0) { // the market served no sided prints at all: say so once, top right sb_clear(); sb_text("No sided trades on this market"); notice.set(16, 14).text(str_text_sb); notice.anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).color(NOTE_INK); } } ``` ## How it works **CVD is a running sum.** `input("buy", trades.volume, { side: "BUY", missing: "zero" })` and its SELL twin deliver the bar's aggressive volume per side (a bar with no prints counts as zero); their difference summed bar after bar is `cvd`, a line in the lower pane labelled CVD. `trades.volume` reads the base asset, so the sum is in coins: `format: "si"` with `unit: " coins"` prints it in the legend as "CVD -17.6K coins". `cvd_reset` (off) runs it from the first loaded bar; on, it restarts at every UTC midnight. **Swings confirm late.** `swing` (8, 3 to 30) is the number of bars on each side a swing must beat, so a swing is confirmed `swing` bars after itself. A swing must beat every bar before it and at least match every bar after it, so a flat top on an odds chart counts once, on its first bar. `swing_here` is 1 on a confirming bar and gates the `cvd_swing` dot, which `displacement_bars_by: { param: "swing", scale: -1 }` draws back on the swing bar itself, `swing` bars before the confirming bar at whatever strength is set (`displacement_bars: -8`, the default's shift, stays for a host that reads only the literal). **A divergence is two swings that disagree.** A higher price high against a lower CVD high is bearish (-1), a lower price low against a higher CVD low is bullish (+1); `divergence` carries the sign on the confirming bar and 0 elsewhere, a data-only signal the editor's Console prompt reads and a declared alert can fire on. On that bar a line handle joins the two price swings (x from `bar.time()`), a dashed polyline handle joins the two CVD swings in the pane, and a label handle writes "div" beside the price line through the one bounded slot. `lines_kept` (12, 1 to 60) lines stay on the chart; the oldest is recycled. ## Where it runs Markets with sided trades: crypto perps and spot, prediction markets. A market where one side does all the trading (CVD climbing the whole window) shows swings and no divergence, which is the honest reading. ## When data is missing On a market with no sided trades (FX, stocks) CVD stays flat at zero, no swing is dotted, and one muted line of words sits at the top right of the chart: "No sided trades on this market". ## Customize it - **Faster swings.** Lower `swing`; more swings confirm and more pairs qualify. - **A session CVD.** Switch `cvd_reset` on to restart the sum at every UTC midnight. - **Dollars instead of coins.** Add `currency: "USD"` to both `trades.volume` inputs and declare `format: "usd"` without the unit on `cvd` and `cvd_swing`: the sum is then each trade's notional, as the native Cumulative Volume Delta reads by default. - **Alert on a divergence.** Bind `divergence` to a `const` and declare `alert("cvd_divergence", { when: ... })`: it fires on the bar a divergence confirms, since the output turns from 0 to -1 or +1 there. Once the indicator is published and on a chart, the signal is in the chart's alert dialog ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **CVD Divergence** under **Order flow**. 2. Press **Run** on a crypto perp or spot market: CVD draws in its own pane, and the evidence lines appear where a divergence confirmed. 3. At the editor's Console prompt, type `last 60 divergence` to read the sign on each of the last 60 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `trades` source, its sides and the `missing` policy - [Drawing objects](../presentation/drawing-objects.md) for line, polyline and label handles and the lower-pane placement - [Plotting](../presentation/plotting.md) for `shape_where` gates and `displacement_bars_by` # Positioning regimes ![Open-interest regime histogram with key card and flip dots](/wrun/images/positioning-regimes.png) Each bar's open-interest change, counted in contracts and as a percent, in its own pane under the chart, colored by who moved: the up colour for price up with open interest up (new longs), the down colour for price down with open interest up (new shorts), a lighter up colour for price up with open interest down (short covering), a lighter down colour for price down with open interest down (long closing). A key card at the top right of the chart names the four regimes, each in its side's colour, and gives each regime's share of the last `key_window` bars, so the colors explain themselves. On price, a small dot marks the bar where the window's leading regime changed hands: in the up colour under the bar when buying pressure took over, in the down colour over the bar when selling pressure did. The parts are an `oi.close` input that reads NaN where the market has none and a `funding.rate_close` input that reads NaN off perpetuals ([Data sources](../core-concepts/data-sources.md)), one histogram output per regime so the legend names every regime ([Plotting](../presentation/plotting.md)), a `draw.card` with one text slot per value cell ([Cards, frames and panels](../presentation/cards-frames-panels.md)), and two `shape` outputs for the leader-flip dots. This is also the `positioning-regimes` template: the **Positioning Regimes** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Positioning Regimes: each bar's open-interest change in its own pane, colored by who moved. On a perpetual, open // interest is counted in coins (the dollar reading over the bar's close), so a price move alone never changes it; a // prediction market's reading is used as served (already a count of YES and NO pairs). Price up with OI up is // new longs (the up colour), price down with OI up is new shorts (the down colour), price up with OI down is short // covering (the up colour, lighter), price down with OI down is long closing (the down colour, lighter). A key card at // the top right gives each regime's share of the last bars, so the colors explain themselves; a dot on price marks the // bar where the window's leading regime changed hands and held for three bars, the up colour for buying pressure, the // down colour for selling pressure. param.int("smoothing", 1, { min: 1, max: 20, label: "Smoothing, bars", description: "Bars the OI change and the price change are averaged over before coloring; 1 = raw" }); param.int("key_window", 24, { min: 4, max: 200, label: "Key window, bars", description: "Bars the key card's shares are counted over" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid every other input lines up on input("oi", oi.close, { missing: "nan" }); // open interest at the bar's close, as served; a bar without a reading, or a market without open interest, reads NaN input("funding", funding.rate_close, { missing: "nan" }); // served on perpetuals only (NaN elsewhere): their open interest is dollars, read in coins output("new_longs", histogram, lower, { unit: "%", color: "theme.up" }); // the bar's OI change in contracts as a percent, drawn by the regime that owns the bar: price up, OI up output("new_shorts", histogram, lower, { unit: "%", color: "theme.down" }); // price down, OI up output("short_covering", histogram, lower, { unit: "%", color: "theme.up", opacity: 0.55 }); // price up, OI down output("long_closing", histogram, lower, { unit: "%", color: "theme.down", opacity: 0.55 }); // price down, OI down output("regime", none); // data-only: 0 new longs, 1 new shorts, 2 short covering, 3 long closing; the Console can read it output("share_new_longs", none); // data-only: each regime's share of the key window, 0..1, read in the Console output("share_new_shorts", none); output("share_short_covering", none); output("share_long_closing", none); output("buyers_lead", shape, overlay, { color: "theme.up" }); // a dot under the bar where the window's leading regime turned to buying pressure (new longs or short covering) output("sellers_lead", shape, overlay, { color: "theme.down" }); // a dot over the bar where it turned to selling pressure (new shorts or long closing) output("leader", none); // data-only: the regime with the most bars in the window, 0..3 string("new_longs", { max_bytes: 8 }); // the card's value cells, one slot each, written on the live bar string("new_shorts", { max_bytes: 8 }); string("short_covering", { max_bytes: 8 }); string("long_closing", { max_bytes: 8 }); string("window", { max_bytes: 16 }); string("text", { max_bytes: 40 }); // the one line of words when the market has no open interest handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 }); // the notice, in pane pixels from the chart's top-right corner draw.card("positioning_key", { title: "Positioning", anchor: "top_right", offset: [56, 0], // inward past the price-axis tags (High, Low, last price reach about 46 px into the pane) rows: [ { label: "New longs", value: { text: "new_longs" }, color: "theme.up" }, { label: "New shorts", value: { text: "new_shorts" }, color: "theme.down" }, { label: "Short covering", value: { text: "short_covering" }, color: "theme.up" }, { label: "Long closing", value: { text: "long_closing" }, color: "theme.down" }, { label: "Window", value: { text: "window" } }, ], }); const MAX_WINDOW = 200; // the ring is sized for the largest window; onStart() reads the one in use const REGIMES = 4; const regimeRing = new StaticArray(MAX_WINDOW); // the last window bars' regimes, -1 where the bar had no reading const counts = new StaticArray(REGIMES); // how many bars of the window sit in each regime const notice = draw.label(0); let smoothing = 1; // settings, read in onStart() let keyWindow = 24; let oiChangeAvg = new Sma(1); // the smoothers, rebuilt in onStart() let priceChangeAvg = new Sma(1); let prevClose = NaN; // the previous bar's close and OI, as served let prevOi = NaN; let perp = false; // funding seen: a perpetual, whose dollar open interest moves with price let oiSeen = false; // any finite OI reading at all: false means the market has no open interest let head = 0; // the ring's write cursor and how many slots hold a bar let filled = 0; let leader = -1; // the regime holding the most bars of the window, once it has held for HOLD_BARS bars let candidate = -1; // the regime leading right now, and how many bars in a row it has led let candidateRun = 0; const HOLD_BARS = 3; // a new leader is marked once it has led three bars in a row let rangeAvg = NaN; // a running mean of high - low: the dot's distance from the bar function share(index: i32): f64 { // a regime's share of the bars in the window that had a reading let counted = 0; for (let i = 0; i < REGIMES; i += 1) counted += counts[i]; return counted == 0 ? NaN : f64(counts[index]) / f64(counted); } function sendShare(value: f64, send: () => i32): void { // "31%" into one card cell sb_clear(); sb_f64(value * 100.0, 0); sb_text("%"); send(); } function onStart(): void { smoothing = i32(p_smoothing()); keyWindow = i32(p_key_window()); oiChangeAvg = new Sma(smoothing); priceChangeAvg = new Sma(smoothing); for (let i = 0; i < REGIMES; i += 1) counts[i] = 0; } // onBar() runs once per bar: the OI change in contracts as a percent, the price change, the regime from their signs, the window counts; // then the histogram and the shares on every bar, the card's cells and the notice on the live bar only. function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const oiNow = in_oi(); const range = high - low; rangeAvg = isNaN(rangeAvg) ? range : rangeAvg + (range - rangeAvg) * 0.1; if (!isNaN(oiNow)) oiSeen = true; if (!isNaN(in_funding())) perp = true; const now = perp ? oiNow / close : oiNow; // both readings in one unit: coins on a perpetual, as served elsewhere const before = perp ? prevOi / prevClose : prevOi; const rawOiChange = isNaN(before) || before <= 0.0 ? NaN : ((now - before) / before) * 100.0; const rawPriceChange = isNaN(prevClose) ? NaN : close - prevClose; prevOi = oiNow; prevClose = close; const oiChange = oiChangeAvg.update(rawOiChange); // NaN until the smoothing window is full or while a reading is missing const priceChange = priceChangeAvg.update(rawPriceChange); let regime = -1; if (!isNaN(oiChange) && !isNaN(priceChange)) { if (oiChange >= 0.0) regime = priceChange >= 0.0 ? 0 : 1; // OI rising: new longs when price rose, new shorts when it fell else regime = priceChange >= 0.0 ? 2 : 3; // OI falling: short covering when price rose, long closing when it fell } const leaving = regimeRing[head]; // the bar that drops out of the window if (filled == keyWindow && leaving >= 0) counts[leaving] -= 1; regimeRing[head] = regime; if (regime >= 0) counts[regime] += 1; head = (head + 1) % keyWindow; if (filled < keyWindow) filled += 1; let shiftDot = NaN; // this bar's dot on price, NaN when the leader held let best = -1; // the window's leader: the regime with the most bars, holding at least two bars in five let bestCount = 0; let counted = 0; for (let i = 0; i < REGIMES; i += 1) { counted += counts[i]; if (counts[i] > bestCount) { bestCount = counts[i]; best = i; } } if (filled < keyWindow || counted == 0 || f64(bestCount) * 5.0 < f64(counted) * 2.0) best = -1; // no leader worth the name yet if (best == candidate) candidateRun += 1; else { candidate = best; candidateRun = 1; } if (candidate >= 0 && candidateRun == HOLD_BARS && candidate != leader) { // the lead changed hands and held: mark it once if (leader >= 0) shiftDot = candidate == 0 || candidate == 2 ? low - rangeAvg * 0.6 : high + rangeAvg * 0.6; // buying pressure below the bar, selling pressure above leader = candidate; } out_new_longs(regime == 0 ? oiChange : NaN); // one bar per regime output; the others read NaN and draw nothing out_new_shorts(regime == 1 ? oiChange : NaN); out_short_covering(regime == 2 ? oiChange : NaN); out_long_closing(regime == 3 ? oiChange : NaN); out_regime(regime < 0 ? NaN : f64(regime)); const newLongs = share(0); const newShorts = share(1); const shortCovering = share(2); const longClosing = share(3); out_share_new_longs(newLongs); out_share_new_shorts(newShorts); out_share_short_covering(shortCovering); out_share_long_closing(longClosing); out_leader(leader < 0 ? NaN : f64(leader)); out_buyers_lead(leader == 0 || leader == 2 ? shiftDot : NaN); out_sellers_lead(leader == 1 || leader == 3 ? shiftDot : NaN); if (bar.isLast()) { if (oiSeen && !isNaN(newLongs)) { // the card appears once every cell has a value; history bars never write them sendShare(newLongs, str_new_longs_sb); sendShare(newShorts, str_new_shorts_sb); sendShare(shortCovering, str_short_covering_sb); sendShare(longClosing, str_long_closing_sb); sb_clear(); sb_int(keyWindow); sb_text(" bars"); str_window_sb(); } else if (!oiSeen) { // the market served no open interest at all: say so once, top right sb_clear(); sb_text("No open interest on this market"); notice.set(16, 14).text(str_text_sb); } } } ``` ## How it works **Who moved is two signs.** On a perpetual, open interest arrives in dollars, so each reading is divided by the bar's close first: a dollar figure rises with price even when no position opened, which would paint short covering as new longs. Only a perpetual serves funding, so a finite funding reading is what marks one. A prediction market's open interest is its collateral, one dollar per YES and NO pair, already a count of contracts, so it is read as served. The bar's price change and its open-interest change in contracts, each averaged over `smoothing` bars (1 is raw), sort the bar into one of four regimes; `regime` carries the index (0 new longs, 1 new shorts, 2 short covering, 3 long closing) as a data-only output. The bar's open-interest change in contracts, as a percent, is written to the one histogram output that owns the regime (`new_longs`, `new_shorts`, `short_covering`, `long_closing`) and NaN to the other three, so each regime is its own series and the legend names it. **The key card counts the window.** A ring of the last `key_window` (24, 4 to 200) regimes gives each regime's share, written to the card's text slots on the live bar (`share_*` carry the same fractions as data-only outputs). The card sits at the top right, offset inward past the price-axis tags. **A leader flip is confirmed.** `leader` is the regime with the most bars in the window. The new leader must hold at least two bars in five of the window and stay in the lead for three bars in a row; on that bar `buyers_lead` (new longs or short covering took over) carries the bar's low and `sellers_lead` the bar's high, the two dots on price. ## Where it runs Perps (Binance Futures, Hyperliquid), whose open interest is counted in coins, and prediction markets, whose open interest is the collateral as served (Polymarket serves it in sparse readings: most bars read NaN and the bars with a reading carry the whole change). The card appears once the window has readings. ## When data is missing Spot, stocks and FX have no open interest: the pane stays empty, the card stays away, and one muted line of words sits at the top right of the chart: "No open interest on this market". ## Customize it - **Smoother regimes.** Raise `smoothing` to average the two changes over more bars before sorting the bar. - **A longer key.** `key_window` up to 200 bars; the ring is sized for the largest window. - **Two series instead of four.** Merge the two buying regimes and the two selling ones into two histogram outputs and a two-row card. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Positioning Regimes** under **Order flow**. 2. Press **Run** on a perp, such as BTCUSDT on Binance Futures: the pane fills with the four regimes and the key card appears once the window has readings. 3. At the editor's Console prompt, type `last 24 regime` to read the regime index of the last 24 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `oi` source and `missing: "nan"` - [Plotting](../presentation/plotting.md) for one histogram output per regime - [Cards, frames and panels](../presentation/cards-frames-panels.md) for `draw.card` and its text slots # Absorption ![Absorption on a 5m BTC chart: a candle where heavy selling went nowhere, boxed across its bar slot with a dot in the up colour under it, and its delta bar lit in the lower pane](/wrun/images/absorption.png) Bars where heavy one-sided volume failed to move price. The bar's delta (aggressive buy volume minus aggressive sell volume) sits in its own pane, muted: the up colour above zero, the down colour below. A bar whose absolute delta spikes past the rolling norm while its range stays inside the ATR is lit bright in the pane, boxed on the chart with a thin border across the bar's whole slot, and dotted: a dot in the down colour above the candle when buying was absorbed (buyers hit the tape and price did not rise), a dot in the up colour below it when selling was absorbed. Flagged bars are rare by design, a few per day on a 15m chart. The parts are side-split `trades.volume` inputs ([Data sources](../core-concepts/data-sources.md)), two histogram outputs sharing one pane (the muted delta on every bar, the bright one on flagged bars only) with a sign palette ([Styling](../presentation/styling.md)), the `Atr` and `Sma` helpers ([TA library](../functions/ta-library.md)), a `plot.spans` section that boxes each flagged candle ([Marks, spans and rays](../presentation/marks-spans-rays.md)) and two `shape` outputs for the dots ([Drawing objects](../presentation/drawing-objects.md)). This is also the `absorption` template: the **Absorption** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Absorption: bars where heavy one-sided volume failed to move price. The bar's delta (buy volume minus sell volume) // sits in its own pane, muted, up colour above zero and down colour below; a bar whose delta spikes past the rolling // norm while its range stays inside the ATR is lit bright in the pane, boxed on the chart across its bar's slot, and // dotted: above the candle when buying was absorbed (down colour), below it when selling was absorbed (up colour). The // boxes are one plot.spans section, which draws in the browser only, so the template cannot be published as Protected. section("Delta"); // the dialog's first section: what makes a bar heavy param.number("delta_spike", 2.0, { min: 1.0, max: 6.0, step: 0.1, label: "Delta spike multiple", description: "A bar is heavy when its absolute delta is this many times the rolling mean of absolute delta" }); param.int("delta_window", 48, { min: 10, max: 400, label: "Delta window in bars", description: "Bars the mean of absolute delta is taken over" }); section("Range"); // the second section: what counts as going nowhere param.number("max_range", 0.8, { min: 0.2, max: 2.0, step: 0.1, label: "Max range in ATRs", description: "A bar failed to move when its range is under this many ATRs" }); param.int("atr_length", 14, { min: 2, max: 100, label: "ATR length in bars", description: "The ATR's Wilder length in bars" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid every other input lines up on input("open", ohlcv.open); // the candle, for the box around a flagged bar input("buy", trades.volume, { side: "BUY", missing: "zero" }); // aggressive buy volume; a bar with no prints reads 0 input("sell", trades.volume, { side: "SELL", missing: "zero" }); // aggressive sell volume, the other half of the tape output("delta", histogram, lower, { colors: ["theme.up", "theme.down"], opacity: 0.45 }); // buy minus sell volume, muted: the up colour above zero, the down colour below output("absorbed", histogram, lower, { colors: ["theme.up", "theme.down"] }); // the same bar, bright, on the bars the test flags; NaN elsewhere output("absorbed_buying", shape, overlay, { color: "theme.down" }); // a dot above a candle where heavy buying went nowhere output("absorbed_selling", shape, overlay, { color: "theme.up" }); // a dot below a candle where heavy selling went nowhere plot.spans({ name: "boxes", slots: 1, colors: ["theme.down", "theme.up"], opacity: 0.08, border: { width: 1, opacity: 1 } }); // a thin box around each flagged candle, across its bar's slot: style 0 the down colour (buying absorbed), 1 the up colour (selling absorbed) string("text", { max_bytes: 40 }); // the one line of words when the market has no sided trades handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 }); // the notice, in pane pixels from the top-right corner const notice = draw.label(0); // the one handle: the notice, allocated once let deltaSpike = 2.0; // settings, read in onStart() let maxRange = 0.8; let meanAbsDelta = new Sma(48); // rebuilt in onStart() let atr = new Atr(14); let sidedVolume = 0.0; // every sided print seen: 0 means the market has no sided trades function onStart(): void { deltaSpike = p_delta_spike(); maxRange = p_max_range(); meanAbsDelta = new Sma(i32(p_delta_window())); atr = new Atr(i32(p_atr_length())); } // onBar() runs once per bar: the delta, the two norms, and the test: heavy delta inside a small range; then the outputs on // every bar, a box around a flagged candle, and the notice on the live bar only. function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); const buy = in_buy(); const sell = in_sell(); const delta = buy - sell; sidedVolume += buy + sell; const norm = meanAbsDelta.update(Math.abs(delta)); // NaN until the window is full const range = atr.update(high, low, close); // NaN until seeded let tone = delta >= 0.0 ? 0 : 1; // 0 buying, 1 selling, 2 absorbed buying, 3 absorbed selling let dotAbove = NaN; let dotBelow = NaN; const heavy = !isNaN(norm) && norm > 0.0 && Math.abs(delta) >= deltaSpike * norm; const stuck = !isNaN(range) && range > 0.0 && high - low <= maxRange * range; if (heavy && stuck) { tone = delta >= 0.0 ? 2 : 3; if (delta >= 0.0) dotAbove = high + range * 0.4; // buyers hit the tape and price did not rise: buying absorbed else dotBelow = low - range * 0.4; // sellers hit the tape and price did not fall: selling absorbed } out_delta(delta); out_absorbed(tone >= 2 ? delta : NaN); out_absorbed_buying(dotAbove); out_absorbed_selling(dotBelow); if (tone >= 2) { // the box around a flagged candle: this bar alone (length 0), its style the absorbed side, no word const pad = range * 0.12; // a little air between the box and the wicks out_boxes_span(0, high + pad, low - pad, 0, tone == 2 ? 0 : 1, -1, 0); } if (bar.isLast() && sidedVolume <= 0.0) { // the market served no sided prints at all: say so once, top right sb_clear(); sb_text("No sided trades on this market"); notice.set(16, 14).text(str_text_sb); } } ``` ## How it works **Heavy is a ratio.** `delta` is buy volume minus sell volume; its absolute value against the rolling mean of absolute delta over `delta_window` (48) bars is the test, and a bar is heavy when the ratio passes `delta_spike` (2.0). Volume is in the market's own units, so the thresholds are ratios and the pane's scale follows the market. **Failed to move is a range test.** The bar's high-to-low range against the ATR over `atr_length` (14) bars must stay under `max_range` (0.8) ATRs. Heavy and narrow together flag the bar: `absorbed` carries the same delta, bright, on flagged bars and NaN elsewhere, so the two histogram outputs share the pane and the muted one never hides a flagged bar. Both use `colors: ["theme.up", "theme.down"]`, a sign palette: entry 0 above zero, entry 1 below; the muted one adds `opacity: 0.45`. **The side names the dot.** Heavy buying that went nowhere puts `absorbed_buying` at the bar's high (a dot in the down colour above the candle); heavy selling that went nowhere puts `absorbed_selling` at the bar's low (a dot in the up colour below it). **The box is a record on its bar.** `plot.spans({ name: "boxes", slots: 1, ... })` declares one batched section of one box a bar, and the build generates `out_boxes_span(slot, top, bottom, lengthBars, style, word, extend)`. On a flagged bar `onBar()` writes slot 0: from the high to the low with 0.12 ATR of air past each wick, a length of 0 (the bar alone, across its whole slot), style 0 (the down colour) for absorbed buying or 1 (the up colour) for absorbed selling, no word (`-1`) and no extension. The fill takes the section's `opacity` (0.08) and the edge its `border` (1 px, opaque). Every flagged bar in the window keeps its box: the record rides the bar's own outputs, so there are no ids to keep and no ring to recycle. A batched section draws in the browser only: an indicator with one cannot be published as Protected for now. ## Where it runs Markets with sided trades: crypto perps and spot, prediction markets. It runs in your browser: the boxes are a batched section, which an indicator published as Protected cannot carry yet. ## When data is missing On a market with no sided trades (FX, stocks) the delta stays at zero and one muted line of words sits at the top right of the chart: "No sided trades on this market". ## Customize it - **More flags.** Lower `delta_spike` or raise `max_range`; both are settings. - **A different norm.** Raise `delta_window` to measure the spike against a longer stretch of bars. - **No boxes.** Delete the `plot.spans` line and the `out_boxes_span` call in `onBar()` to keep the pane and the dots alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Absorption** under **Order flow**. 2. Press **Run** on a crypto perp or spot market, a 15m chart for example: the delta pane fills, and the flagged bars light up with their boxes and dots. 3. At the editor's Console prompt, type `last 60 absorbed` to read the flagged bars' delta over the last 60 bars (NaN where a bar is not flagged). ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `trades` source, its sides and the `missing` policy - [Styling](../presentation/styling.md) for sign palettes on histogram outputs - [Marks, spans and rays](../presentation/marks-spans-rays.md) for the `plot.spans` section and its record writer - [Drawing objects](../presentation/drawing-objects.md) for the dots' `shape` outputs and the notice's label handle # Liquidation bursts ![Liquidation Bursts on a 1h BTC chart: bubbles sized and captioned by each burst in USD, in the down colour under the low for a long flush and the up colour over the high for a short squeeze, above the stacked liquidation columns](/wrun/images/liquidation-bursts.png) Long and short liquidations in USD in their own pane under the chart, one column per bar: long liquidations (forced sells) in the down colour at its foot and short liquidations (forced buys) in the up colour stacked on them, so the column is the bar's total and the legend reads each side in dollars ("Long liquidations $14.1M"). A bar whose liquidations on one side jump past the rolling norm (a z-score over the window) gets a bubble on price with its size printed on it, "12.4M" or "850K": a bubble in the down colour under the bar's low for a long flush, one in the up colour over its high for a short squeeze, its area growing with the size. One bubble per bar, the bigger side, and every burst in the window keeps its bubble. The parts are two `liquidations` inputs split by side ([Data sources](../core-concepts/data-sources.md)), two histogram outputs stacked into one column, the `Sma` and `Stdev` helpers behind the z-score ([TA library](../functions/ta-library.md)), and one `plot.marks` section for the bubbles ([Marks, spans and rays](../presentation/marks-spans-rays.md)). This is also the `liquidation-bursts` template: the **Liquidation Bursts** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Liquidation Bursts: long and short liquidations in USD in their own pane, one column per bar, longs (forced sells) // in the down colour at its foot and shorts (forced buys) in the up colour stacked on them. A bar whose liquidations // jump past the rolling norm (a z-score over the window) gets a bubble on price with the size printed on it: a long // flush in the down colour under the bar's low, a short squeeze in the up colour over its high, the bubble's area // growing with the size in USD from the bubble unit. The bubbles are one plot.marks section, which draws in the // browser only, so the template cannot be published as Protected. param.number("burst_z", 3.0, { min: 1.0, max: 8.0, step: 0.1, label: "Burst threshold in deviations", description: "A bar is a burst when its liquidations sit this many deviations above the window's mean" }); param.int("window", 96, { min: 10, max: 500, label: "Window in bars", description: "Bars the mean and deviation are taken over" }); param.number("bubble_unit", 1000000, { min: 1, max: 1000000000, label: "Bubble unit in USD", description: "A burst of this many USD or less draws the smallest bubble; the area grows with the size, up to the largest bubble at about 20 times this. $1M suits BTC perps, whose smallest bursts on a 1h chart run near $1M" }); legend({ title: "({{window}})" }); // the words after the name in the legend: the window, read by name input("close", ohlcv.close); // the primary input: the chart's own candles define the grid every other input lines up on input("long_liq", liquidations.liquidations, { side: "SELL", missing: "zero" }); // longs are liquidated by forced sells; a bar with none reads 0 input("short_liq", liquidations.liquidations, { side: "BUY", missing: "zero" }); // shorts are liquidated by forced buys output("long_liqs", histogram, lower, { color: "theme.down", stack: "liqs", label: "Long liquidations", format: "usd" }); // at the foot of the column, in dollars output("short_liqs", histogram, lower, { color: "theme.up", stack: "liqs", label: "Short liquidations", format: "usd" }); // stacked on the longs: the column is the bar's total output("burst", none); // data-only: -1 a long flush, +1 a short squeeze, 0 none; read it in the Console or fire an alert(...) on it plot.marks({ name: "bursts", slots: 1, size: { law: "sqrt", unit: "@bubble_unit" }, text: { mode: 2, format: "compact", min_px: 0 }, colors: ["theme.down", "theme.up"] }); // one bubble on a burst bar, its size printed on it ("12.4M"): side 0 a long flush in the down colour, 1 a short squeeze in the up colour string("text", { max_bytes: 40 }); // the one line of words when the market has no liquidations handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 }); // the notice, in pane pixels from the top-right corner const notice = draw.label(0); // the one handle: the notice, allocated once let burstZ = 3.0; // settings, read in onStart() let longMean = new Sma(96); // rebuilt in onStart() let longDev = new Stdev(96); let shortMean = new Sma(96); let shortDev = new Stdev(96); let liquidationsSeen = 0.0; // every liquidation seen: 0 means the market has none let rangeAvg = NaN; // a running mean of high - low: the bubble's distance from the bar function isBurst(value: f64, mean: f64, dev: f64): bool { // past the norm, with a norm to speak of return value > 0.0 && !isNaN(mean) && !isNaN(dev) && dev > 0.0 && value >= mean + burstZ * dev; } function onStart(): void { burstZ = p_burst_z(); const window = i32(p_window()); longMean = new Sma(window); longDev = new Stdev(window); shortMean = new Sma(window); shortDev = new Stdev(window); } // onBar() runs once per bar: both sides into their norms, the burst test per side, the bubble's place; then the two stacked // histograms on every bar, a bubble on a burst bar, and the notice on the live bar only. function onBar(): void { const high = bar.high(); const low = bar.low(); const longLiq = in_long_liq(); const shortLiq = in_short_liq(); liquidationsSeen += longLiq + shortLiq; const range = high - low; rangeAvg = isNaN(rangeAvg) ? range : rangeAvg + (range - rangeAvg) * 0.1; const longBurst = isBurst(longLiq, longMean.update(longLiq), longDev.update(longLiq)); const shortBurst = isBurst(shortLiq, shortMean.update(shortLiq), shortDev.update(shortLiq)); let burst = 0; let bubbleY = NaN; let bubbleUsd = NaN; if (longBurst && (!shortBurst || longLiq >= shortLiq)) { // one bubble per bar: the bigger side burst = -1; bubbleY = low - rangeAvg * 0.6; bubbleUsd = longLiq; } else if (shortBurst) { burst = 1; bubbleY = high + rangeAvg * 0.6; bubbleUsd = shortLiq; } out_long_liqs(longLiq); out_short_liqs(shortLiq); out_burst(f64(burst)); if (burst != 0) out_bursts_mark(0, bubbleY, bubbleUsd, burst < 0 ? 0 : 1, 0, 0); // the bubble at its price with the size in USD; side 0 a flush, 1 a squeeze; no fill count; centred on the bar if (bar.isLast() && liquidationsSeen <= 0.0) { // the market served no liquidations at all: say so once, top right sb_clear(); sb_text("No liquidations on this market"); notice.set(16, 14).text(str_text_sb); } } ``` ## How it works **A liquidation's side is the forced order's side.** `input("long_liq", liquidations.liquidations, { side: "SELL", missing: "zero" })` reads longs liquidated by forced sells and its BUY twin reads shorts liquidated by forced buys, the same reading the native Liquidations indicator uses for its Longs and Shorts. A bar with none reads 0. `long_liqs` and `short_liqs` share `stack: "liqs"`: the longs fill the foot of each column in the down colour and the shorts stack on them in the up colour, both written positive and printed in dollars (`format: "usd"`), so the column's height is the bar's total and neither side reads negative. **A burst is a z-score.** Each side's liquidations against their mean and standard deviation over `window` (96) bars give a z-score; a bar is a burst when the bigger side sits `burst_z` (3.0) deviations above the mean. `burst` carries -1 for a long flush, +1 for a short squeeze, 0 otherwise: a data-only signal a declared alert can fire on. **The bubble is the size.** `plot.marks({ name: "bursts", slots: 1, ... })` declares one batched section of one mark a bar, and the build generates `out_bursts_mark(slot, price, qty, side, fills, offsetMs)`. On a burst bar `onBar()` writes slot 0: the price 0.6 of the running mean range under the bar's low for a flush or over its high for a squeeze, the size in USD as the quantity, side 0 for a flush (the first colour, the down colour) or 1 for a squeeze (the up colour), no fill count and no offset (the bubble sits on the bar's centre). The chart grows the bubble's area with the quantity over `size.unit`, which `"@bubble_unit"` binds to the **Bubble unit** setting: a burst of that many USD or less draws the smallest bubble and one about 20 times it the largest. The default, $1M, fits BTC perps, whose bursts on a 1h chart run from about $1M to $20M; lower it on a thinner market so its bursts do not all draw the smallest bubble. `text: { mode: 2, format: "compact", min_px: 0 }` prints the size on every bubble, however small ("12.4M", "850K", "920"): a caption is the number alone, with no "$". One bubble per bar, the bigger side, and every burst in the window keeps its bubble: the record rides the bar's own outputs, so there are no ids to recycle and nothing to cap. A batched section draws in the browser only: an indicator with one cannot be published as Protected for now. ## Where it runs Perps (Binance Futures, Hyperliquid). The pane's axis is in USD. The threshold is a ratio to the market's own norm, so a thin market whose bars mostly carry no liquidations marks small sizes ("413" on a quiet alt) while BTC marks millions; raise `burst_z` to keep only the biggest, and lower **Bubble unit** to grow a thin market's bubbles. It runs in your browser: the bubbles are a batched section, which an indicator published as Protected cannot carry yet. ## When data is missing Spot, prediction markets, stocks and FX have no liquidations: both histograms stay at zero and one muted line of words sits at the top right of the chart, "No liquidations on this market". ## Customize it - **Fewer bubbles.** Raise `burst_z`; the histograms keep every bar. - **A longer norm.** `window` up to 500 bars smooths the mean and the deviation. - **Both sides marked.** Declare `slots: 2` and write slot 1 for the smaller side when both burst; each slot adds three outputs. - **Alert on a burst.** Bind `burst` to a `const` and declare `alert("liquidation_burst", { when: ... })`: it fires on the bar a burst starts. Once the indicator is published and on a chart, the signal is in the chart's alert dialog ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Liquidation Bursts** under **Order flow**. 2. Press **Run** on a perp, such as BTCUSDT on Binance Futures: the stacked columns fill and the bursts get their bubbles on price. 3. At the editor's Console prompt, type `last 60 burst` to read the burst sign of the last 60 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `liquidations` source and its sides - [TA library](../functions/ta-library.md) for `Sma` and `Stdev` - [Marks, spans and rays](../presentation/marks-spans-rays.md) for the `plot.marks` section, its size law and its caption - [Drawing objects](../presentation/drawing-objects.md) for the notice's label handle and the text slot # Book Heat ![Resting order book painted behind the candles as a heatmap, with a bid-ask imbalance pane](/wrun/images/book-heat.png) The chart market's resting order book painted behind the candles, bar by bar: every price level the book held when the bar closed is a cell, and the brighter its shade the more size rested there, bids below the price and asks above it on one square-root scale, so a wall reads as a bright band the price has to trade through and a thin book as a faint wash. The heatmap sits under the candles, so the bars stay readable on top of it. Below the chart, the bid-ask imbalance inside a depth window around the mid price, in the up colour while the bids outweigh the asks and the down colour while they do not. The parts are a celled `book.cells` input ([Order book functions](../functions/order-flow-kit.md)), a `plot.heatmap` declaration that paints that input's block without any output carrying it ([Price canvases](../presentation/price-canvases.md)), and one histogram output read off the same block ([Plotting](../presentation/plotting.md)). This is also the `book-heat` template: the **Book Heat** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Book Heat: the chart market's resting order book painted behind the candles as a heatmap of resting size by price, // bar by bar: the brighter the shade, the more size rested at that price when the bar closed, bids below the price and // asks above it on one scale, so a wall reads as a bright band the price has to trade through. Below the chart, the // bid-ask imbalance inside a depth window around the mid: the up colour while bids outweigh asks, else the down colour. param.number("depth_pct", 1.0, { min: 0.1, max: 10, step: 0.1, label: "Depth window in percent", description: "Depth window for the imbalance: percent around the mid price, each side" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("book", book.cells, { max_cells: 1000, block_size: 10, description: "The resting book at the bar's close, one [price, size, side] level per tuple" }); // side +1 bid, -1 ask; the chart serves its own market's book, up to 500 levels a side output("imbalance", histogram, lower, { colors: ["theme.up", "theme.down"], format: "%", label: "Book imbalance", description: "Bid size minus ask size inside the depth window, as a percent of both" }); // the up colour above zero, the down colour below plot.heatmap({ name: "book_heat", cells: "book", value: "size", behind_candles: true, scale: "sqrt", auto_quantile: 0.98, opacity: 0.85, label: "Resting size", tooltip: "{{value:si}} resting at {{price}}" }); // the host paints the block the input already delivers; no output carries it const TUPLE = 3; // f64s per level: price, size, side let depth = 0.01; // the setting, read in onStart() function onStart(): void { depth = p_depth_pct() / 100.0; } // onBar() runs once per bar: the host paints the block itself; the module reads the same block for the imbalance. function onBar(): void { const n = in_book_cells(); if (n < TUPLE * 2) { // an empty block (no book served for this bar) or one level alone: no reading out_imbalance(NaN); return; } const cells = in_book_view(); // this bar's levels in place: the first n values of the build's own buffer let bestBid = -Infinity; let bestAsk = Infinity; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (cells[i + 2] > 0.0) { if (cells[i] > bestBid) bestBid = cells[i]; } else if (cells[i] < bestAsk) bestAsk = cells[i]; } if (!isFinite(bestBid) || !isFinite(bestAsk)) { // one side only: no mid to measure around out_imbalance(NaN); return; } const mid = (bestBid + bestAsk) * 0.5; let bids = 0.0; let asks = 0.0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (Math.abs(cells[i] - mid) > mid * depth) continue; // outside the window if (cells[i + 2] > 0.0) bids += cells[i + 1]; else asks += cells[i + 1]; } const total = bids + asks; out_imbalance(total > 0.0 ? (100.0 * (bids - asks)) / total : NaN); } ``` ## How it works **The block is the canvas.** `input("book", book.cells, { max_cells: 1000, block_size: 10 })` delivers the resting book at each bar's close as `[price, size, side]` tuples, side `+1` for a bid level and `-1` for an ask level, up to 500 levels a side. `plot.heatmap({ name: "book_heat", cells: "book", value: "size" })` tells the host to paint that block: one cell per level, one column per bar, the cell's height the book's own price grouping (`row_height` overrides it), its colour the level's size on the heatmap's ramp. The module never copies or forwards the block; the host reads the same rows the input already delivered. **The scale.** With no `palette`, the heatmap ramps from the chart's background to its text colour, low to high, one ink on a dark and a light chart alike; `scale: "sqrt"` keeps the many small levels visible beside the walls; `auto_quantile: 0.98` sets the top of the scale at the 98th percentile of every cell in the run, so a single outsized order does not flatten the rest. `value` picks what a cell reads: `"size"` (both sides), `"bid"`, `"ask"`, or `"signed"` (bids positive, asks negative, which centres the palette on zero). `behind_candles: true` is the default; `false` paints over the candles instead. `opacity: 0.85` leaves the grid visible through the cells. **The reading beside it.** The histogram sums bid and ask size inside `depth_pct` (1%) of the mid, the mid being the best bid and the best ask averaged, and prints their difference as a percent of both: the up colour above zero, the down colour below (the two `colors` of a histogram are its sign colours). A bar whose block is empty reads NaN and draws nothing, in the pane and on the canvas alike. **The hover.** `tooltip: "{{value:si}} resting at {{price}}"` puts a readout under the cursor over any cell, `label` its title; drop `tooltip` for a heatmap with no hover. ## Where it runs Any market the chart serves an order book for: crypto spot and perpetual venues, Polymarket markets. The chart serves the book snapshots its own order book lane fetches for the chart's market; `block_size` is required by the declaration but the chart reads neither it nor `max_depth`. The heatmap paints as far back as the book history the chart holds; older bars carry an empty block. ## When data is missing A market with no book lane is refused by name before any fetch, naming the input and the way out. A market whose bars all arrive without a book (FX and stocks, where the lane answers empty) runs: the map stays empty and the histogram reads NaN on every bar. No message says why: the recipe keeps nothing from one bar to the next, so no bar knows the others came without a book too ([Per-bar scripts](../core-concepts/per-bar-scripts.md)). A bar with no snapshot carries an empty block: the column is blank and the histogram reads NaN. A book that lists one side only (a halted market, a one-sided prediction market) has no mid, so the histogram reads NaN while the heatmap still paints the side it has. ## Customize it - **Read one side.** Change `value: "size"` to `"bid"` or `"ask"` to paint one side of the book, or to `"signed"` for a diverging map (bids in the up colour, asks in the down colour) with the palette `["theme.down", "theme.bg", "theme.up"]`. - **Fix the scale.** Set `min` and `max` in size units to compare days on one scale; `auto_quantile` then goes away. - **Coarser rows.** `row_height: 50` groups the book into 50-unit price rows on a market whose levels are finer than the chart can show. - **Over the candles.** `behind_candles: false` paints the cells over the bars, with `opacity: 0.5` to keep them visible. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Book Heat** under **Order flow**. 2. Press **Run** on a liquid crypto chart (Binance Futures BTCUSDT, for example): the book paints behind the candles as the snapshots arrive and the imbalance pane fills below. 3. Hover a cell for its resting size; at the editor's Console prompt, type `imbalance` to read the live bar's reading. 4. Open the indicator's settings: on the **Style** page, the heatmap's **Sensitivity** slider recolours it live, toward Vivid to light up thinner levels, toward Subtle to keep the brightest colours for the walls ([The Style page](../settings/style-page.md#the-sensitivity-row)). ## Concepts used - [Order book functions](../functions/order-flow-kit.md) for the `book` celled class, its tuple and the depth-window scans - [Price canvases](../presentation/price-canvases.md) for `plot.heatmap`, the `value` words, the colour scale and the hover readout - [Plotting](../presentation/plotting.md) for histogram outputs and their sign colours # Liquidation Heat ![Liquidation levels painted behind the candles as a heatmap that follows price](/wrun/images/liquidation-heat.png) Where the leverage opened on recent bars would be liquidated, painted behind the candles as a heatmap. Every bar seeds liquidation prices below its close for longs and above it for shorts at four leverage tiers (10x, 25x, 50x and 100x), each weighted by a share of the bar's volume; a level the price trades through is consumed and leaves the map, the rest fade with age until `lookback` bars have passed. The map is 64 rows centred on the close, so it follows price up and down: the brighter a row, the more leverage sits there waiting to be flushed, and a dense band just above or below the price is where a sweep would run. The parts are an `out.grid` of 64 rows written cell by cell from `onBar()`, two data-only outputs that place the grid on the price axis, and a `plot.heatmap` declaration over the grid ([Price canvases](../presentation/price-canvases.md)). Every number is computed in the indicator from the chart's own candles ([Data sources](../core-concepts/data-sources.md)). This is also the `liquidation-heat` template: the **Liquidation Heat** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Liquidation Heat: where the leverage opened on recent bars would be liquidated, painted behind the candles as a // heatmap. Every bar seeds liquidation prices below its close for longs and above it for shorts at four leverage // tiers (10x, 25x, 50x, 100x), weighted by the bar's volume; a level the price trades through is consumed, the rest // fade with age. The map is 64 rows centred on the close, so it follows price: the brighter a row, the more leverage // sits there waiting to be flushed. param.int("lookback", 240, { min: 20, max: 2000, label: "Lookback in bars", description: "Bars a seeded level stays on the map before it has faded out" }); param.number("row_pct", 0.1, { min: 0.01, max: 2, step: 0.01, label: "Row height in percent", description: "Row height as a percent of the close" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid and seed the levels output("grid_low", none, overlay, { description: "The bottom edge of the map's lowest row on this bar" }); // data-only: the heatmap reads it output("row_step", none, overlay, { description: "The map's row height in price on this bar" }); out.grid("heat", { rows: 64 }); // 64 data-only outputs heat_0..heat_63, one per row of the map, written with out_heat(row, value) plot.heatmap({ name: "liq_heat", grid: "heat", price_low: "grid_low", price_step: "row_step", scale: "linear", min: 0, auto_quantile: 0.98, opacity: 0.8, behind_candles: true, label: "Liquidation heat", tooltip: "{{value:si}} seeded at {{price}}" }); // the chart's one-ink ramp, faint for most cells: the candles stay readable on top const ROWS = 64; // rows in the map, the grid's declared count const TIERS = 4; // leverage tiers seeded per bar const MAX_LEVELS = 4096; // seeded levels ride a ring: the oldest is recycled const leverage = new StaticArray(TIERS); const levelPrice = new StaticArray(MAX_LEVELS); // each seeded level's price, weight and the bar it was seeded on const levelSize = new StaticArray(MAX_LEVELS); const levelBar = new StaticArray(MAX_LEVELS); const rowHeat = new StaticArray(ROWS); // this bar's map, folded from the live levels let head = 0; // the ring position let used = 0; // levels in use let barIndex = 0; // bars seen let lookback = 240; // settings, read in onStart() let rowPct = 0.001; function onStart(): void { lookback = i32(p_lookback()); rowPct = p_row_pct() / 100.0; leverage[0] = 10.0; leverage[1] = 25.0; leverage[2] = 50.0; leverage[3] = 100.0; } function seed(price: f64, size: f64): void { // one liquidation level into the ring levelPrice[head] = price; levelSize[head] = size; levelBar[head] = barIndex; head = (head + 1) % MAX_LEVELS; if (used < MAX_LEVELS) used += 1; } function clearRows(): void { // no map on this bar: every cell empty for (let r = 0; r < ROWS; r += 1) out_heat(r, NaN); } // onBar() runs once per bar: consume the levels the bar traded through, seed this bar's, then fold the live levels // onto the 64-row grid around the close and write the grid, its bottom edge and its step. function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); barIndex += 1; if (isNaN(close) || close <= 0.0) { out_grid_low(NaN); out_row_step(NaN); clearRows(); return; } for (let k = 0; k < used; k += 1) { // a level inside the bar's range was flushed: it leaves the map if (levelSize[k] > 0.0 && levelPrice[k] >= low && levelPrice[k] <= high) levelSize[k] = 0.0; } const volume = bar.volume(); const weight = isNaN(volume) || volume <= 0.0 ? 1.0 : volume; // a market with no volume still seeds, one unit a bar const share = weight / f64(TIERS); // each tier takes an equal share of the bar's volume for (let i = 0; i < TIERS; i += 1) { // longs opened here are liquidated below the close, shorts above it seed(close * (1.0 - 1.0 / leverage[i]), share); seed(close * (1.0 + 1.0 / leverage[i]), share); } const step = close * rowPct; const gridLow = close - step * f64(ROWS / 2); // the middle row holds the close for (let r = 0; r < ROWS; r += 1) rowHeat[r] = 0.0; for (let k = 0; k < used; k += 1) { if (levelSize[k] <= 0.0) continue; const age = barIndex - levelBar[k]; if (age > lookback) { // faded out levelSize[k] = 0.0; continue; } const r = i32(Math.floor((levelPrice[k] - gridLow) / step)); if (r < 0 || r >= ROWS) continue; // outside the map this bar; it comes back when price moves toward it rowHeat[r] += levelSize[k] * (1.0 - f64(age) / f64(lookback)); } out_grid_low(gridLow); out_row_step(step); for (let r = 0; r < ROWS; r += 1) out_heat(r, rowHeat[r] > 0.0 ? rowHeat[r] : NaN); // NaN = an empty cell } ``` ## How it works **A grid the module writes.** `out.grid("heat", { rows: 64 })` declares 64 data-only outputs `heat_0` to `heat_63`, one per row of the map, and the generated writer `out_heat(row, value)` fills them in `onBar()`; a row outside 0 to 63 aborts the run by name, and NaN leaves a cell empty. The two outputs beside it place the grid: `grid_low` is the bottom edge of row 0 on each bar and `row_step` every row's height in price, so the map moves with the close and keeps its shape when the chart's scale changes. `plot.heatmap({ grid: "heat", price_low: "grid_low", price_step: "row_step" })` ties the three together; a heatmap takes `cells` or `grid`, never both. **The levels.** Each bar seeds eight levels into a ring of 4,096: for every tier, a long opened at the close is liquidated at `close x (1 - 1 / leverage)` and a short at `close x (1 + 1 / leverage)`, each level weighted by a quarter of the bar's volume (one unit on a market without volume). Before seeding, the bar's range is swept: a level between the low and the high was flushed and is zeroed. Then every live level is folded onto the 64 rows around the close with a linear fade, `1 - age / lookback`; a level older than `lookback` is dropped, and one outside the map this bar is kept, since it comes back when price moves toward it. **The scale.** With no `palette`, the heatmap ramps from the chart's background to its text colour, one ink on a dark and a light chart alike, so the candles stay readable where they cross the map. `scale: "linear"` with `min: 0` keeps most cells faint and lets only the dense rows stand out, and `auto_quantile: 0.98` sets the top of the scale at the 98th percentile of every cell in the run. `behind_candles: true` keeps the bars on top. `row_pct` (0.1% of the close) sets the row height: finer rows separate the tiers, coarser rows merge them into bands. ## Where it runs Any chart: the map is built from the chart's own candles, so it draws on every market and interval. It reads best on perpetual and futures charts, where the leverage it models is traded; on spot or a prediction market the rows still draw, but there is no leverage to be flushed at them. ## When data is missing A bar whose close is NaN writes an empty map and places nothing. A market without volume seeds one unit a bar, so the map still draws, with every bar weighing the same. The map holds only what the chart has seen: the first `lookback` bars of a run build it up from nothing. ## Customize it - **A longer memory.** Raise `lookback` to keep levels longer before they fade; lower it for a map of the last session only. - **Finer or coarser rows.** `row_pct` sets the row height as a percent of the close; `rows: 64` in `out.grid` sets how many rows the map spans (2 to 128). - **Other tiers.** Change the four leverages in `onStart()`; the ring holds eight levels per bar regardless. - **A fixed scale.** Set `min` and `max` on the heatmap to compare days on one scale, or `floor` to hide the faintest cells. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Liquidation Heat** under **Order flow**. 2. Press **Run** on a perpetual chart: the map paints behind the candles, bright where recent leverage would be liquidated, and clears where price has already swept. 3. Hover a cell for the weight seeded at that price; at the editor's Console prompt, type `row_step` to read the row height in price. ## Concepts used - [Price canvases](../presentation/price-canvases.md) for `out.grid`, `plot.heatmap` over a grid, `price_low` and `price_step` - [Data sources](../core-concepts/data-sources.md) for the chart's own candles as the primary input - [Plotting](../presentation/plotting.md) for data-only outputs # OI Liquidation Heat ![Estimated liquidations painted behind the candles as a heatmap built from open interest, bright bands that end where price ran into them](/wrun/images/liquidation-heat-oi.png) Where the positions opened over the lookback would be liquidated, estimated from the market's open interest and painted behind the candles as a heatmap. It is the model of the [Liquidation Map](liquidation-map.md) drawn through time: every bar keeps the same ledger of opened positions and folds it onto a map of 128 rows around the close, its rows on round prices so the bands run straight, and each column shows the estimate as it stood on that bar. The brighter a row, the more money a sweep there would force out. A level that price trades through is gone from that bar on, so the bands end where price ran into them, and a band that runs on to the right edge is money still waiting. Resting the pointer on a cell reads its dollars and its price. The parts are an `oi.close` input and side-split `trades.volume` inputs read as positions ([Data sources](../core-concepts/data-sources.md)), an `out.grid` of 128 rows written cell by cell from `onBar()`, two data-only outputs that place the grid on the price axis, a `plot.heatmap` declaration over the grid ([Price canvases](../presentation/price-canvases.md)), and a label handle for the one sentence shown without open interest ([Drawing objects](../presentation/drawing-objects.md)). This is also the `liquidation-heat-oi` template: the **OI Liquidation Heat** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // OI Liquidation Heat: where the positions opened over the lookback would be liquidated, ESTIMATED from the market's // open interest and sided volume, painted behind the candles as a heatmap. It is the Liquidation Map's model drawn // through time: every bar keeps the same ledger and folds it onto a 128-row map around the close, its rows on round // prices so the bands run straight, and each column shows the estimate as it stood on that bar. The brighter a row, // the more money a sweep there would force out; a level price trades through is gone from that bar on, so the bands // end where price ran into them. // // The model, per bar: a rise in open interest opens positions at the bar's typical price, split into longs and // shorts by the bar's buy share of sided volume, and across four leverage tiers (10x, 25x, 50x, 100x) with fixed // weights; each position's liquidation price follows from its leverage and the maintenance margin. A fall in open // interest scales every live level down in proportion. A long level is swept when a later bar's low reaches it, a // short level when a later bar's high does. Levels older than the lookback drop. Nothing here is a venue's own // liquidation feed: it is a model of where the open positions sit, built from the open-interest change bar by bar. section("Positions"); param.int("lookback", 672, { min: 96, max: 2000, label: "Lookback in bars", description: "Bars of opened positions kept in the map, in the chart's own bars; the map covers no more than the chart has loaded" }); param.number("maint_margin_pct", 0.5, { min: 0, max: 2, step: 0.1, label: "Maintenance margin in percent", description: "Maintenance margin as a percent of the position: the distance a liquidation sits short of the leverage's full move" }); section("Map"); param.number("range_pct", 5, { min: 2, max: 25, step: 0.5, label: "Map range in percent", description: "Map range: percent around the close, each side; the 128 rows split it on round prices, so the reach varies a little and a narrower range draws finer rows" }); legend({ title: "estimated, up to {{lookback}} bars" }); // the words after the name in the legend: up to, since a chart holding fewer bars builds from those input("close", ohlcv.close); // the chart's own candles: the map's centre, the entry price and the sweeps input("oi", oi.close, { missing: "nan", description: "Open interest in USD; NaN on a market without it (spot, FX, prediction markets), which blanks the map" }); input("buy", trades.volume, { side: "BUY", missing: "zero", description: "Buy volume of the bar: its share of sided volume is the share of new positions read as longs" }); input("sell", trades.volume, { side: "SELL", missing: "zero", description: "Sell volume of the bar" }); output("grid_low", none, overlay, { description: "The bottom edge of the map's lowest row on this bar" }); // data-only: the heatmap reads it output("row_step", none, overlay, { description: "The map's row height in price on this bar" }); output("longs_near", none, overlay, { format: "usd", description: "Estimated long liquidations within 5% below the close, USD, every bar" }); // data-only: the Console and alerts read them output("shorts_near", none, overlay, { format: "usd", description: "Estimated short liquidations within 5% above the close, USD, every bar" }); out.grid("heat", { rows: 128 }); // 128 data-only outputs heat_0..heat_127, one per row of the map in USD, written with out_heat(row, value) string("note", { max_bytes: 80 }); // the one sentence shown when the market has no open interest handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 12, style: "plain", safe_area: true }); plot.heatmap({ name: "liq_heat", grid: "heat", price_low: "grid_low", price_step: "row_step", scale: "linear", min: 0, auto_quantile: 0.98, opacity: 0.8, behind_candles: true, label: "Estimated liquidations", tooltip: "{{value:usd}} at {{price}}" }); // Leverage tiers the opened positions are spread over, and the share of new open interest each tier takes: the // Liquidation Map's guess at a perpetual's crowd (most size at low leverage, a thin tail at 100x), so the two // templates estimate the same levels. const TIERS = 4; const SLOTS = TIERS * 2; // per bar: four long levels, then four short levels function tierLeverage(tier: i32): f64 { return tier == 0 ? 10.0 : tier == 1 ? 25.0 : tier == 2 ? 50.0 : 100.0; } function tierWeight(tier: i32): f64 { return tier == 0 ? 0.4 : tier == 1 ? 0.3 : tier == 2 ? 0.2 : 0.1; } const ROWS = 128; // rows in the map, the grid's declared count const MAX_LOOKBACK = 2000; // the ring is sized for the largest lookback setting const levelPrice = new StaticArray(MAX_LOOKBACK * SLOTS); // the ledger: one price and one USD size per level, SLOTS per bar const levelUsd = new StaticArray(MAX_LOOKBACK * SLOTS); // 0 once swept or dropped const rowUsd = new StaticArray(ROWS); // this bar's map: USD per row const note = draw.label(0); // the one muted sentence; a handle allocates once at module load let lookback = 672; // settings, read in onStart() let mm = 0.005; let rangeFrac = 0.05; let head = -1; // the ring: head is the newest bar, count the bars in use let count = 0; let prevOi: f64 = NaN; // the last finite open interest reading let oiSeen = false; // the market served open interest at least once let noteShown = false; let gridLow: f64 = NaN; // this bar's map: the bottom edge of row 0 and the row height let step: f64 = NaN; let longsNear = 0.0; // live long levels within 5% below the close, USD let shortsNear = 0.0; // live short levels within 5% above the close, USD function onStart(): void { lookback = i32(p_lookback()); mm = p_maint_margin_pct() / 100.0; rangeFrac = p_range_pct() / 100.0; } function niceStep(raw: f64): f64 { // the nearest of 1, 2, 2.5 and 5 times a power of ten (in ratio terms): rows on round prices that line up bar to bar const mag = Math.pow(10.0, Math.floor(Math.log(raw) / Math.LN10)); const m = raw / mag; return (m < 1.414 ? 1.0 : m < 2.236 ? 2.0 : m < 3.536 ? 2.5 : m < 7.071 ? 5.0 : 10.0) * mag; // the cut points are the geometric midpoints } function addToMap(price: f64, usd: f64): void { // a live level adds its USD to the row it falls in; off the map it waits for price to come near const pos = (price - gridLow) / step; if (pos >= 0.0 && pos < f64(ROWS)) rowUsd[i32(pos)] += usd; } // One pass over the ledger: the levels this bar traded through are gone, the rest fold onto this bar's map and, // within 5% of the close, into the near sums. function sweepAndFold(close: f64, high: f64, low: f64): void { const nearLo = close * 0.95; const nearHi = close * 1.05; longsNear = 0.0; shortsNear = 0.0; for (let r = 0; r < ROWS; r += 1) rowUsd[r] = 0.0; const used = count * SLOTS; for (let i = 0; i < used; i += 1) { const usd = levelUsd[i]; if (usd <= 0.0) continue; const price = levelPrice[i]; if (i % SLOTS < TIERS) { // a long level: swept once a bar's low reaches it if (low <= price) { levelUsd[i] = 0.0; continue; } if (price >= nearLo) longsNear += usd; } else { // a short level: swept once a bar's high reaches it if (high >= price) { levelUsd[i] = 0.0; continue; } if (price <= nearHi) shortsNear += usd; } addToMap(price, usd); } } function openPositions(base: i32, close: f64, high: f64, low: f64, dOi: f64): void { // new open interest, placed at its liquidation prices const buy = in_buy(); const sell = in_sell(); const total = buy + sell; const longShare = total > 0.0 ? buy / total : 0.5; const entry = isNaN(high) || isNaN(low) ? close : (high + low + close) / 3.0; // the bar's typical price const nearLo = close * 0.95; const nearHi = close * 1.05; for (let tier = 0; tier < TIERS; tier += 1) { const move = 1.0 / tierLeverage(tier) - mm; // the adverse move that liquidates this tier if (move <= 0.0) continue; // a margin wider than the tier's whole move: nobody holds that position const longPrice = entry * (1.0 - move); const shortPrice = entry * (1.0 + move); const longUsd = dOi * longShare * tierWeight(tier); const shortUsd = dOi * (1.0 - longShare) * tierWeight(tier); levelPrice[base + tier] = longPrice; levelUsd[base + tier] = longUsd; levelPrice[base + TIERS + tier] = shortPrice; levelUsd[base + TIERS + tier] = shortUsd; if (longUsd > 0.0) { if (longPrice >= nearLo) longsNear += longUsd; addToMap(longPrice, longUsd); } if (shortUsd > 0.0) { if (shortPrice <= nearHi) shortsNear += shortUsd; addToMap(shortPrice, shortUsd); } } } function scaleAll(factor: f64): void { // open interest fell: every live level shrinks in proportion, and the map with it const used = count * SLOTS; for (let i = 0; i < used; i += 1) if (levelUsd[i] > 0.0) levelUsd[i] *= factor; for (let r = 0; r < ROWS; r += 1) rowUsd[r] *= factor; longsNear *= factor; shortsNear *= factor; } function writeEmpty(): void { // no map on this bar: every cell empty, the grid unplaced out_grid_low(NaN); out_row_step(NaN); out_longs_near(NaN); out_shorts_near(NaN); for (let r = 0; r < ROWS; r += 1) out_heat(r, NaN); } function writeNote(): void { // on the live bar: the one sentence while the market has served no open interest, gone once it does if (!bar.isLast()) return; if (!oiSeen) { sb_clear(); sb_text("No open interest on this market, so no liquidation estimate"); note.set(16.0, 12.0).text(str_note_sb); noteShown = true; } else if (noteShown) { note.delete(); noteShown = false; } } // onBar() runs once per bar: recycle the oldest bar's slots, sweep the ledger with the bar's range while folding the // survivors onto this bar's map, fold the bar's open-interest change in (new positions at their liquidation prices, // or every level scaled down), then write the map, its bottom edge, its row height and the near sums. function onBar(): void { const close = bar.close(); const high = bar.high(); const low = bar.low(); if (isNaN(close) || close <= 0.0) { // no price on this bar: no map, and the ledger waits for the next one writeEmpty(); return; } head = (head + 1) % lookback; // this bar's slots: the oldest bar's levels are recycled once the ring is full if (count < lookback) count += 1; const base = head * SLOTS; for (let s = 0; s < SLOTS; s += 1) { levelUsd[base + s] = 0.0; levelPrice[base + s] = NaN; } step = niceStep((close * rangeFrac * 2.0) / f64(ROWS)); gridLow = (Math.floor(close / step) - f64(ROWS / 2)) * step; // a fixed lattice of round prices, the close in the middle row sweepAndFold(close, high, low); const oiNow = in_oi(); if (!isNaN(oiNow)) { // a bar without a reading changes nothing: the last reading carries forward oiSeen = true; if (!isNaN(prevOi)) { const dOi = oiNow - prevOi; if (dOi > 0.0) openPositions(base, close, high, low, dOi); else if (dOi < 0.0 && prevOi > 0.0) scaleAll(oiNow / prevOi); } prevOi = oiNow; } writeNote(); if (!oiSeen) { writeEmpty(); return; } out_grid_low(gridLow); out_row_step(step); out_longs_near(longsNear); out_shorts_near(shortsNear); for (let r = 0; r < ROWS; r += 1) out_heat(r, rowUsd[r] > 0.0 ? rowUsd[r] : NaN); // NaN = an empty cell } ``` ## How it works **Open interest is read as positions.** On every bar `in_oi()` (the `oi.close` input, in USD) is compared with the last finite reading; a bar without a reading changes nothing. A rise is new open interest opened at the bar's typical price (high, low and close averaged), split into longs and shorts by the bar's buy share of `in_buy()` and `in_sell()`, and spread over four leverage tiers, 10x, 25x, 50x and 100x, weighted 40, 30, 20 and 10 percent in `tierLeverage` and `tierWeight`. Each tier is liquidated by an adverse move of one over its leverage less `maint_margin_pct`: a 10x long opened at 84,000 with the default 0.5% margin is liquidated about 9.5% lower, near 76,000, and a 10x short about 9.5% higher, near 92,000. A fall in open interest scales every live level down in proportion (`scaleAll`), the map and the near sums with it. **The ledger is a ring.** `levelPrice` and `levelUsd` are two fixed arrays sized for the largest lookback, eight slots per bar (four long tiers, then four short tiers); once `lookback` bars are held, the oldest bar's slots are recycled, so a level older than the lookback drops. `sweepAndFold` walks the ledger once per bar: a long level is gone once the bar's low reaches it, a short level once the bar's high does, and every level left adds its dollars to the row it falls in. A level outside the map on this bar stays in the ledger and comes back when price moves toward it. Nothing fades with age: a level keeps its full size until a sweep, a fall in open interest or the lookback takes it. **The map follows the close.** The 128 rows reach about `range_pct` each side of the close (5% by default). `niceStep()` snaps the row height to a round price (1, 2, 2.5 or 5 times a power of ten), so the rows sit on the same prices bar after bar and the bands run straight: 50 on BTC near 85,000, a reach of 3,200 each side, varying a little as the snap moves. `grid_low` is the bottom edge of row 0 on each bar, a whole number of rows below the close's row, and `row_step` every row's height in price; `plot.heatmap({ grid: "heat", price_low: "grid_low", price_step: "row_step" })` reads the two to place the grid, so the map moves with the close. `out_heat(row, value)` writes a row's dollars, and NaN leaves a cell empty. A narrower range draws finer rows and leaves the far tiers off the map until price comes near them. **The scale.** With no `palette`, the heatmap ramps from the chart's background to its text colour, one ink on a dark and a light chart alike. `scale: "linear"` with `min: 0` keeps most cells faint and lets only the stacked rows stand out, and `auto_quantile: 0.98` sets the top of the scale at the 98th percentile of every cell in the run, so one huge row does not wash out the rest. `behind_candles: true` keeps the bars on top, and the tooltip `{{value:usd}} at {{price}}` reads a cell as its dollars and its price. **The near sums.** `longs_near` and `shorts_near` are data-only outputs written on every bar: the estimated long liquidations within 5% below the close and the short liquidations within 5% above it, in USD. They draw nothing; read them at the editor's Console prompt or set an alert on them. **An estimate, beside two siblings.** Nothing here is a venue's own liquidation feed: read a band as "about this much, about here". [Liquidation Heat](liquidation-heat.md) builds its map from the candles alone: every bar seeds levels at its close weighted by its volume, and the levels fade with age, so it draws on any chart but knows nothing of positions opened or closed. The [Liquidation Map](liquidation-map.md) is this model, with the same tiers, margin, sweeps and lookback, docked on the price axis as a two-sided profile measured on the live bar only. This recipe keeps that ledger and draws it on every bar, behind the candles. ## Where it runs Perpetual futures with open interest: Binance Futures and Hyperliquid perpetuals, at any interval. The lookback is counted in the chart's own bars, so 672 is a week at 15m and four weeks at 1h, and the map covers no more than the chart has loaded: a 1h chart holding 297 bars builds from those 297, which is why the legend reads "up to 672 bars". Every bar draws its own column, so the history shows how the estimate moved; the forming bar replays from the chart's snapshot, so the ring advances once per bar on live ticks too ([Repainting](../core-concepts/repainting.md)). No market refuses the run: the `oi` input declares `missing: "nan"`, so a market without open interest reads NaN and gets the sentence below instead of a toast. ## When data is missing On a market without open interest (spot pairs, FX, prediction markets) the map stays empty and one line of words shows at the top right, `No open interest on this market, so no liquidation estimate`, in plain muted text: the `note` label handle pinned to the pane's top right corner and right-aligned, clear of the price axis. `longs_near` and `shorts_near` read NaN there. Once the market serves open interest, the sentence goes and the map builds up from the first rise. On a market with open interest but without sided trades, every new position is split half longs and half shorts. A bar whose close is NaN writes an empty column and leaves the ledger as it was. ## Customize it - **A longer or shorter memory.** `lookback` (672, 96 to 2000) is the bars of opened positions the map keeps, in the chart's own bars: 672 is a week at 15m and four weeks at 1h. `maint_margin_pct` (0.5, 0 to 2) is the maintenance margin as a percent of the position: a larger margin moves every liquidation price closer to its entry, and a margin as wide as a tier's whole move leaves that tier out. - **A finer or wider map.** `range_pct` (5, 2 to 25) is about how far around the close the map reaches each side; the 128 rows split it on round prices, so a narrower range draws finer rows and a wider one brings the 10x tier into view. `rows: 128` in `out.grid` is the most a grid holds; a smaller grid needs `ROWS` changed to match. - **Another crowd.** The tier mix, 10x, 25x, 50x and 100x at 40, 30, 20 and 10 percent, is a guess at a perpetual's crowd, named in `tierLeverage` and `tierWeight` at the top of the file. It is the Liquidation Map's mix, so the two estimate the same levels; change both to keep them agreeing. - **A fixed scale.** Set `min` and `max` on the heatmap to compare days on one scale, or `floor` to hide the faintest cells. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **OI Liquidation Heat** under **Order flow**. 2. Press **Run** on a perpetual with open interest, such as BTCUSDT on Binance Futures at 15m: the map paints behind the candles, bright where opened positions would be liquidated, and each band ends where price swept it. The legend reads "OI Liquidation Heat estimated, up to 672 bars". 3. Rest the pointer on a cell for the dollars at that price; at the editor's Console prompt, type `last 20 longs_near` to read the estimated long liquidations within 5% below the price on the last 20 bars. ## Concepts used - [Price canvases](../presentation/price-canvases.md) for `out.grid`, `plot.heatmap` over a grid, `price_low` and `price_step` - [Data sources](../core-concepts/data-sources.md) for the `oi` and `trades` sources, `side` and the `missing` policies - [Drawing objects](../presentation/drawing-objects.md) for `handles.label`, the `draw.label(id)` handle and pane anchors - [Plotting](../presentation/plotting.md) for data-only outputs # Volume Footprint ![Footprint cells on each candle with imbalances lit and a delta pane below](/wrun/images/volume-footprint.png) Each bar's traded volume by price, split into its buy and sell halves and printed as footprint cells on the candle: the sells on the left, the buys on the right, the point of control lit and the value area shaded. An imbalance, a cell where one side out-traded the diagonal other three to one, is lit in the chart's up or down colour, and three stacked imbalances are boxed, so the trader sees where the aggression was and where it was absorbed. Below the chart, the bar's delta as a histogram, in the up colour when buying led and the down colour when selling did, and under it the day's cumulative delta as a line in a pane of its own, so a large running sum never flattens the bars. The parts are a celled `volume_profile.cells` input ([Volume profile](../functions/order-flow-kit.md)), a `plot.footprint` declaration that prints that input's block cell by cell without any output carrying it ([Price canvases](../presentation/price-canvases.md)), and two outputs read off the same block, each in a pane of its own below the chart ([Plotting](../presentation/plotting.md#panes)). This is also the `volume-footprint` template: the **Volume Footprint** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volume Footprint: each bar's traded volume by price, split into its buy and sell halves and printed as footprint // cells on the candle, the point of control and the value area lit, the imbalances lit where one side out-traded the // diagonal other three to one and three stacked imbalances boxed. Below the chart, the bar's delta as a histogram, in // the up colour when buying led and the down colour when selling did, and under it the day's cumulative delta as a line // in a pane of its own, so a large running sum never flattens the bars. param.bool("reset_daily", true, { label: "Reset each UTC day", description: "Start the cumulative delta again at each UTC day" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("profile", volume_profile.cells, { max_cells: 8192, description: "This bar's volume by price level" }); // [low, high, buy, sell] per level; measured on Binance Futures BTCUSDT: about 280 levels per 15m bar, 860 per 1h bar output("delta", histogram, lower, { colors: ["theme.up", "theme.down"], format: "si", label: "Delta", description: "Buy volume minus sell volume this bar" }); // up above zero, down below pane("cum", { height_frac: 0.15 }); // the running sum's own pane under the delta's, on a scale of its own output("cum_delta", line, lower, { pane: "cum", color: "theme.text", width: 2, format: "si", label: "Cumulative delta", description: "The delta summed since the day began, or since the first bar" }); plot.footprint({ name: "footprint", cells: "profile", mode: "split_bar", labels: true, imbalance: true, imbalance_ratio: 3, stacked_imbalances: 3, imbalance_buy_color: "theme.up", imbalance_sell_color: "theme.down", poc: true, value_area: 0.7, cell_metric: "delta" }); // the host prints the block the input already delivers const TUPLE = 4; // f64s per level: low, high, buy, sell let resetDaily = true; // the setting, read in onStart() let cumDelta = 0.0; // the running sum let day: f64 = NaN; // the UTC day the sum belongs to function onStart(): void { resetDaily = pb_reset_daily(); } // onBar() runs once per bar: sum the block's buy and sell halves; the delta on every bar, the running sum started // again at each UTC day when asked. function onBar(): void { const today = Math.floor(bar.time() / 86400.0); if (resetDaily && today != day) { cumDelta = 0.0; day = today; } const n = in_profile_cells(); if (n < TUPLE) { // an empty block: the bar's delta is unknown out_delta(NaN); out_cum_delta(cumDelta); return; } const cells = in_profile_view(); // this bar's levels in place: the first n values of the build's own buffer let buy = 0.0; let sell = 0.0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { buy += cells[i + 2]; sell += cells[i + 3]; } const delta = buy - sell; cumDelta += delta; out_delta(delta); out_cum_delta(cumDelta); } ``` ## How it works **The block is the footprint.** `input("profile", volume_profile.cells, { max_cells: 8192 })` delivers each bar's volume by price level as `[low, high, buy, sell]` tuples. `plot.footprint({ name: "footprint", cells: "profile" })` tells the host to print that block on the candle: one column per bar, one cell per level, its height the input's bucket width times the native footprint's row table for the chart interval (`row_height` overrides it in price units). The module never copies the block; the host reads the rows the input already delivered. **The look.** `mode: "split_bar"` prints the sells left and the buys right of the candle; `"cluster"`, `"stacked_bar"`, `"ladder"` and `"imbalance_only"` are the other modes. `labels: true` prints each cell's number (`hide_zero` drops the zeros). `imbalance: true` with `imbalance_ratio: 3` lights a cell whose side out-traded the diagonal other three to one, in `imbalance_buy_color` (`theme.up`) and `imbalance_sell_color` (`theme.down`); `stacked_imbalances: 3` boxes three in a row. `poc: true` and `value_area: 0.7` light the point of control and shade the value area; `cell_metric: "delta"` grades the cells by their delta (`"volume"` and `"trades"` are the alternatives). **The reading beside it.** The histogram sums the block's buy and sell halves and prints their difference: the up colour above zero, the down colour below (the two `colors` of a histogram are its sign colours). The line sums the delta from the first bar, or from each UTC day when `reset_daily` is on, and `pane("cum", { height_frac: 0.15 })` with `pane: "cum"` on the output puts it in a second pane under the histogram's, on a scale of its own: after a trending day the running sum is many times any one bar's delta, and on one shared scale the bars would lie flat. A bar whose block is empty reads NaN in the histogram and holds the running sum. ## Where it runs Markets with a volume profile lane: crypto spot and perpetual venues and Polymarket markets, where the venue reports buy and sell volume per level. The footprint reads best from 1 minute to 1 hour, where a bar holds a few dozen to a few hundred levels (about 280 per 15m bar on Binance Futures BTCUSDT, 860 per 1h bar); `max_cells: 8192` leaves room for a 4h bar. ## When data is missing A market with no volume profile lane is refused by name before any fetch. A bar with no levels carries an empty block: the column prints nothing and the histogram reads NaN. A block larger than `max_cells` refuses the run rather than truncating; raise the cap for a coarser interval. ## Customize it - **Cluster mode.** `mode: "cluster"` prints one cell per level with the delta inside, the classic cluster chart; `"imbalance_only"` prints the lit cells alone. - **A stricter imbalance.** Raise `imbalance_ratio` to 4 or 5 to light fewer cells, or set `imbalance: false` for a plain footprint. - **Volume instead of delta.** `cell_metric: "volume"` grades the cells by total volume, with `volume_color` as the ink. - **Row height in price.** `row_height: 10` on a BTC chart prints one cell per 10 USD instead of the native table. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volume Footprint** under **Order flow**. 2. Press **Run** on a 5m or 15m chart of a liquid crypto market: the cells print on the candles once the levels arrive, the imbalances lit, and the delta and cumulative delta panes fill below. 3. Hover a cell for its buy and sell volume; at the editor's Console prompt, type `delta` and `cum_delta` to read the live bar. ## Concepts used - [Volume profile](../functions/order-flow-kit.md) for the `volume_profile` celled class and its tuple - [Price canvases](../presentation/price-canvases.md) for `plot.footprint`, its modes, the imbalance words and the value area - [Plotting](../presentation/plotting.md) for histogram and line outputs and named panes below the chart # TPO Letters ![Market Profile letters on each day with the initial balance lines](/wrun/images/tpo-letters.png) The chart's own candles folded into a Market Profile: one letter per 30 minutes of the day, printed on every price the market traded during that half hour, the day's letters stacked into a profile with the point of control and the value area lit and the initial balance (the first hour) marked. The module adds the initial balance's high and low as dashed lines on price once the balance is set, so the trader sees the day's opening range beside the letters that built it and where the later letters broke out of it. The parts are a `plot.tpo` declaration with no `cells`, which builds the letters from the chart's own candles ([Price canvases](../presentation/price-canvases.md)), and two line outputs computed in `onBar()` from the day's first letters ([Plotting](../presentation/plotting.md)). This is also the `tpo-letters` template: the **TPO Letters** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // TPO Letters: the chart's own candles folded into a Market Profile, one letter per 30 minutes of the day printed on // every price the market traded during that half hour, the point of control and the value area lit, the initial // balance marked. The module adds the initial balance's high and low as lines on price once the balance is set, so // the trader sees the day's opening range beside the letters that built it. param.int("ib_letters", 2, { min: 1, max: 8, label: "Initial balance letters", description: "Letters in the initial balance: 2 is the first hour of 30-minute letters" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid and feed the letters output("ib_high", line, overlay, { color: "theme.muted", width: 1, line_style: "dashed", format: "price", label: "IB high", description: "The initial balance high: the day's first letters' high; NaN until the balance is set" }); output("ib_low", line, overlay, { color: "theme.muted", width: 1, line_style: "dashed", format: "price", label: "IB low", description: "The initial balance low" }); plot.tpo({ name: "tpo", period: "day", letter_minutes: 30, display: "both", initial_balance: true, ib_color: "theme.text", poc: true, vah: true, val: true, value_area: 0.7, poc_color: "theme.text", vah_color: "theme.muted", val_color: "theme.muted", outside_va_opacity: 0.3 }); // no cells: the host builds the letters from the chart's own candles (30 minutes or finer) const LETTER_SECONDS = 1800.0; // 30-minute letters, the declaration's letter_minutes let ibLetters = 2; // the setting, read in onStart() let day: f64 = NaN; // the UTC day being built let ibHigh: f64 = NaN; // the balance so far let ibLow: f64 = NaN; function onStart(): void { ibLetters = i32(p_ib_letters()); } // onBar() runs once per bar: a new UTC day starts a new balance; the bars inside the first letters grow it; the two // lines print once the balance's last letter has closed and hold until the next day. function onBar(): void { const t = bar.time(); const today = Math.floor(t / 86400.0); if (today != day) { day = today; ibHigh = NaN; ibLow = NaN; } const letter = i32(Math.floor((t - today * 86400.0) / LETTER_SECONDS)); // this bar's letter in its day if (letter < ibLetters) { // inside the balance: grow it, print nothing yet const high = bar.high(); const low = bar.low(); if (!isNaN(high) && (isNaN(ibHigh) || high > ibHigh)) ibHigh = high; if (!isNaN(low) && (isNaN(ibLow) || low < ibLow)) ibLow = low; out_ib_high(NaN); out_ib_low(NaN); return; } out_ib_high(ibHigh); out_ib_low(ibLow); } ``` ## How it works **Letters from the candles.** `plot.tpo({ name: "tpo", period: "day", letter_minutes: 30 })` tells the host to build one letter per 30 minutes of each UTC day from the chart's own bars: a price row prints a letter for every letter interval in which it lay inside a bar's high-low range. The letter must be a whole multiple of the chart's bars, so the profile needs a chart of 30 minutes or finer; to run it on a coarser chart, declare an `intrabar` input (5-minute bars inside each chart bar) and name it in `cells`, or a `volume_profile` input, whose buckets also give each letter its volume. `display: "both"` prints blocks and letters (`"letters"` or `"blocks"` alone are the others). **The profile's marks.** `poc`, `vah` and `val` light the point of control and the value area edges (`value_area: 0.7`), the rows outside the value area faded to `outside_va_opacity`; `initial_balance: true` marks the first hour in `ib_color`. `single_prints`, `poor_extremes` and `counts` are off by default and switch on by name; `color_mode` colours the blocks by period (the default), by TPO count, or by volume or delta on `volume_profile` cells. **The lines beside it.** `ib_letters` (2) is the number of letters in the initial balance. Each UTC day starts a new balance; the bars inside its first letters grow its high and low; once the last of those letters has closed, `ib_high` and `ib_low` print as dashed muted lines and hold until the next day. Before the balance is set they read NaN and draw nothing. ## Where it runs Any chart of 30 minutes or finer: crypto, stocks, forex and CME futures alike, since the letters are built from the chart's own candles. On a coarser chart the legend chip and the Console say so by name and point to an `intrabar` input. ## When data is missing A bar with a NaN high or low grows no balance and prints no letter. A day with fewer bars than the initial balance never sets its lines. The profile holds only the days the chart has loaded. ## Customize it - **Weekly profiles.** `period: "week"` stacks a whole week's letters into one profile (`"month"` a month's); with 30-minute letters the alphabet wraps. - **A wider balance.** Raise `ib_letters` to 4 for a two-hour initial balance. - **Letters only.** `display: "letters"` drops the blocks for a classic text profile; `font_family: "mono"` lines the letters up. - **Row height.** Left out, the row is the chart's own (75 dollars on BTC at 15m, about 25 to 90 rows a day), and a `row_height` so fine that a day holds more than 512 rows is coarsened, with `tpo 'tpo': row_height 1 coarsened to 8 (512 rows per day is the chart's limit)` in the Console and on the legend chip ([Row height](../presentation/price-canvases.md#row-height)). - **With volume.** Declare `input("profile", volume_profile.cells, { max_cells: 8192 })`, add `cells: "profile"`, and switch `color_mode` to `"volume"` or set `volume_profile: true` for a volume profile beside the letters. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **TPO Letters** under **Order flow**. 2. Press **Run** on a 5m or 15m chart: the letters print day by day, the point of control and the value area lit, and the initial balance lines appear an hour into each day. 3. Hover a row for its letters and count; at the editor's Console prompt, type `ib_high` to read the live day's balance high. ## Concepts used - [Price canvases](../presentation/price-canvases.md) for `plot.tpo`, the letter rule, `period`, `display` and the profile marks - [Plotting](../presentation/plotting.md) for line outputs with a dashed style - [Data sources](../core-concepts/data-sources.md) for the `intrabar` and `volume_profile` celled classes a TPO can read instead of the candles # Session Volume Profile ![Session volume profiles inside each day's span with the session delta below](/wrun/images/session-volume-profile.png) Each day's volume by price, drawn inside the day's own time span: the profile grows from the day's first bar, buy volume in the up colour and sell volume in the down colour stacked on every row, the point of control and the value area lit, the three level prices tagged. Under the chart, the session delta: buy minus sell volume since the day opened, in the up colour while buyers carry the day and the down colour while sellers do. The trader sees where each day's volume was accepted and who paid for it. The parts are a celled `volume_profile.cells` input read as a block in `onBar()` ([Volume profile](../functions/order-flow-kit.md)), a `plot.profile` declaration the chart draws from those same cells ([Price canvases](../presentation/price-canvases.md)) and one histogram output under the chart ([Plotting](../presentation/plotting.md)). This is also the `session-volume-profile` template: the **Session Volume Profile** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Session Volume Profile: each day's volume by price, drawn by the chart inside the day's own time span from the // bar-by-bar profile cells, with the point of control and the value area lit and the level prices tagged. The module // adds the session's running delta, buy minus sell volume since the day opened, as a histogram under the chart. The // trader sees where each day's volume was accepted and whether buyers or sellers carried it there. input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("profile", volume_profile.cells, { max_cells: 8192, description: "This bar's volume by price level" }); // [low, high, buy, sell] per level; measured on Binance Futures BTCUSDT: about 280 levels per 15m bar, 860 per 1h bar output("session_delta", histogram, lower, { color_by: "delta_tone", colors: ["theme.down", "theme.up"], label: "Session delta", format: "si", description: "Buy minus sell volume since the session opened" }); // the down colour while sellers lead the day, the up colour while buyers do; the legend names it output("delta_tone", none, overlay, { description: "1 while the session delta is positive, 0 while it is negative" }); // data-only: the histogram's colour index plot.profile({ name: "session_vp", cells: "profile", span: "session", session: "1d", mode: "stacked_bar", buy_color: "theme.up", sell_color: "theme.down", width_frac: 0.7, value_area: 0.7, value_area_shade: true, poc: true, vah: true, val: true, level_labels: true }); // one profile per day, drawn by the chart from the cells above: the module never touches it let sessionDay: i64 = -1; // the UTC day number of the session being summed let buyVolume = 0.0; // the session's buy and sell volume so far let sellVolume = 0.0; // onBar() runs once per bar: reset the sums where the UTC day changes, add the bar's cells, write the delta. function onBar(): void { const t = bar.time(); if (isNaN(t)) return; const day = i64(Math.floor(t / 86400.0)); if (day != sessionDay) { sessionDay = day; buyVolume = 0.0; sellVolume = 0.0; } // a new day: the sums start over const n = in_profile_cells(); // f64s in this bar's block: four per level if (n >= 4) { const cells = in_profile_view(); // this bar's cells in place: the first n values of the build's own buffer for (let i = 0; i + 3 < n; i += 4) { buyVolume += cells[i + 2]; sellVolume += cells[i + 3]; } } const delta = buyVolume - sellVolume; out_session_delta(delta); out_delta_tone(delta >= 0.0 ? 1.0 : 0.0); } ``` ## How it works **The chart draws the profile.** `plot.profile({ cells: "profile", span: "session", session: "1d" })` names the celled input and anchors one profile to each day: the chart folds that day's `[low, high, buy, sell]` cells into rows, scales the rows to the day's biggest, grows them from the day's first bar across `width_frac` (0.7) of the day's width, and lights the point of control and the `value_area` (0.7) rows; `level_labels` tags the POC, VAH and VAL prices. The module never writes a frame for it: the cells it reads for the delta are the cells the chart draws. **The session delta.** On every bar the module sums the block's buy and sell volume into the day's totals, resets them where the UTC day changes, and writes `session_delta` (buy minus sell) as a histogram under the chart, coloured by `delta_tone` (1 while buyers lead, 0 while sellers do). `label: "Session delta"` names it in the legend and on the Style page, and `format: "si"` prints it with K, M and B from 1,000 ("Session delta 1.2K"). **Words to try.** `mode: "split_bar"` draws buy and sell on opposite sides of each row and `"delta"` the net; `span: "developing"` keeps only the current day's profile, growing bar by bar; `span: "visible"` folds the bars on screen into one profile at the pane edge; `behind_candles: true` (span `"session"` only) puts the fills under the candles; `background: true` washes each day's box. Every word is listed on [Price canvases](../presentation/price-canvases.md). ## Where it runs Markets with a volume profile lane: crypto (Binance Futures, Binance spot, Hyperliquid) and Polymarket markets. Daily profiles read best on charts from 5m to 1h; on a 1d chart each day is one bar. ## When data is missing Stocks and FX have no profile lane: the run stops with the toast `Volume profile data is unavailable for '' (the volume_profile source lane answered empty or was declined), so the indicator cannot compute.`, where `<title>` is the tab's title. A bar without a profile block adds nothing to its day; a day with no cells draws no profile; the delta on a day's first bar is that bar's own. ## Customize it - **Weekly profiles.** `session: "1w"`; `"4h"` cuts four-hour profiles on an intraday chart. - **A trading region.** `session: "us"`, `"eu"` or `"asia"` cuts the profiles on that region's hours. - **A range of your own.** `span: "range"` with `start` naming an output that holds the range's first second (epoch seconds, read on the last bar) and `end` another, or absent for the newest bar. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Session Volume Profile** under **Order flow**. 2. Press **Run** on a crypto chart such as BTCUSDT on Binance Futures at 15m: a profile grows inside each day, the level prices tag at its edge, and the session delta appears under the chart. 3. At the editor's Console prompt, type `session_delta` to read the delta on the newest bar. ## Concepts used - [Volume profile](../functions/order-flow-kit.md) for the celled profile input and the block layout - [Price canvases](../presentation/price-canvases.md) for `plot.profile`, its spans and session words - [Plotting](../presentation/plotting.md) for the histogram output and its colour index <!-- source: https://openmarket.xyz/wrun/cookbook/option-prints --> # Option prints Option Prints lists the large option trades on this symbol, newest first, and marks each one on the price chart. A print is one option trade, and its premium is the money paid for it. A big print at the ask (the seller's price) means someone paid up for that bet. That is bullish on a call (a bet on a rise), bearish on a put (a bet on a fall). Use it on a US stock, coin or CME (Chicago futures exchange) future to see where large money bets now. Under the hood: a celled `option_prints.cells` input holds the window's 2,000 newest prints and each bar's 16 largest together ([Data sources](../core-concepts/data-sources.md#option_prints)). It is read through its `present` mask ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). Five scalar `options_flow` inputs of scope `prints` carry the data plane's per-bar sums of every print at the smallest premium ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). A ring keeps the newest kept prints for a frame that feeds a `panel.table` ([Table](../presentation/cards-frames-panels.md#table)). Its rows name their contracts in `markets` with `fb_contract` ([Rows that open a market](../presentation/cards-frames-panels.md#rows-that-open-a-market)). A contract reads `SPY 450C 21 Nov`, or `SPY 450C 15 Jan '27` in another year. Three `plot.marks` sections draw the contracts, a crypto chain's coins and the soft dots ([Marks](../presentation/marks-spans-rays.md#marks)). A `render.bgcolor` wash covers the bars the chart served in part ([Plotting](../presentation/plotting.md#text-labels-tables-strips-tints)). The options kit's `optionsTradeDay` gives the days to expiry ([Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). Its `flowSideCode` and `flowScore` give each mark's score ([Flow score](../functions/options-kit.md#flow-score)). `fbExpiryLabel` names each contract's expiry ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)). `market.option_contract()` marks an option contract's own chart ([Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file)). This is also the `option-prints` template: the **Option Prints** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Option Prints: the large option trades on this symbol, newest first, in a table under the chart. A print is one // option trade, and each one also shows as a mark on the price where it traded. A line reads the time, the contract, // the side of the quote, the size and the premium (the money paid). A big print at the ask (the seller's price) means // someone paid up for that bet. That is bullish on a call (a bet on a rise), bearish on a put (a bet on a fall). // Use it to see where large money bets right now. // // Under the hood: the option prints of the chart's underlying, filtered, newest first, in a table under // the chart, each one also a mark on price at the underlying's price when it printed. The filters are settings: the // smallest premium, calls or puts, the side of the quote, the days to expiry and out of the money only. A row reads the // time (on the market's clock), the contract, its days to expiry, the side (AA above the ask, A at the ask, M the mid, B // at the bid, BB below the bid, a dash with no quote; a crypto or CME print carries the taker's side, A bought and B // sold), the size (contracts, coins on crypto), the price, the premium, the underlying's price, the IV, the delta and the // lean: bullish for a call bought or a put sold, bearish for a call sold or a put bought, neutral at the mid. A crypto // chain's marks ride a section of their own, its sizes being coins. A US listed row (OPRA) names its contract, so the // chart can open it. The chart serves three days of prints at the smallest premium (10,000 and up), the days to expiry // and the types you set: the window's 2,000 newest prints for the table and each bar's 16 largest for the marks, and the // data plane sums every such print per bar for the readings of a bar cut to its largest. A bar past the history the data // plane keeps is served in part: a faint wash covers it and partial reads 1. // It reads the chart's own underlying: on an option contract's own chart (market.option_contract()) the table fills, // its caption says so and the marks stay off, since the price axis is the contract's own. A contract names its expiry // as 21 Nov, or 15 Jan '27 in another year. Each mark carries the print's score, the options kit's flowScore from -100 // bearish to 100 bullish (the side of the quote through flowSideCode, call or put, the moneyness against the price the // mark sits at, the days to expiry; these marks read no open interest and count no repeat hits): its hover prints the // score's size, its colour takes the full tone from 60 either way, a soft dot from 20 to 60 and the muted ink below 20, // and Marks by score draws only the bullish prints (40 and up) or only the bearish ones (-40 and below). section("Filters"); param.number("min_premium", 25000, { min: 10000, max: 1000000000, step: 5000, label: "Smallest premium, USD", description: "Hides trades with less premium (the money paid) than this. The chart loads trades from $10,000 up." }); param.choice("types", ["both", "calls", "puts"], "both", { label: "Calls or puts" }); param.choice("sides", ["every side", "at or above the ask", "at or below the bid", "outside the quote"], "every side", { label: "Side of the quote", description: "At the ask (the seller's price) keeps buyers paying up, at the bid (the buyer's price) sellers giving in. Outside the quote keeps trades past both prices, and none on crypto or CME, which carry no quote." }); param.int("max_dte", 0, { min: 0, max: 1000, label: "Days to expiry, at most", description: "Keeps options that expire within this many days. 0 keeps every expiry." }); param.bool("otm_only", false, { label: "Out of the money only", description: "Keeps calls (bets on a rise) whose strike (the option's price level) sits above the price. Keeps puts (bets on a fall) whose strike sits below it. A strike within 0.5% counts too. A trade that did not record that price stays out." }); section("Display"); param.int("rows", 30, { min: 5, max: 100, label: "Trades listed", description: "How many of the newest trades the table shows." }); param.number("mark_unit", 50000, { min: 1000, max: 1000000000, step: 1000, label: "Mark unit, USD", description: "A trade with this premium (the money paid) or less draws the smallest mark. Bigger trades draw bigger marks." }); param.choice("score_filter", ["all", "bullish", "bearish"], "all", { label: "Marks by score", description: "Each trade scores how strongly it leans, from -100 (bearish) to 100 (bullish). bullish marks scores of 40 and up, bearish -40 and below. The table and the readings keep every trade." }); input("close", ohlcv.close); // the chart's own close: where a print without its underlying is marked, and the check that the chart is the underlying's input("prints", option_prints.cells, { max_cells: 16, newest: 2000, min_premium: "@min_premium", max_dte: "@max_dte", types: "@types", history: "3d", overflow: "largest", description: "This symbol's option trades at your premium, expiry and type filters. It loads the 2,000 newest and each bar's 16 largest over three days, live on a real-time chart." }); // [offset_ms, print_key, root_code, expiry_ms, side_cp, strike, price, size, premium, aggressor, outside, underlying, iv, delta, venue, present] per print input("call_ask", options_flow.call_prem_ask, { scope: "prints", min_premium: "@min_premium", max_dte: "@max_dte", missing: "nan" }); // the data plane's per-bar sums of every print at the smallest premium and days to expiry, calls and puts by side: the readings of a bar cut to its largest input("call_bid", options_flow.call_prem_bid, { scope: "prints", min_premium: "@min_premium", max_dte: "@max_dte", missing: "nan" }); input("put_ask", options_flow.put_prem_ask, { scope: "prints", min_premium: "@min_premium", max_dte: "@max_dte", missing: "nan" }); input("put_bid", options_flow.put_prem_bid, { scope: "prints", min_premium: "@min_premium", max_dte: "@max_dte", missing: "nan" }); input("printed", options_flow.prints, { scope: "prints", min_premium: "@min_premium", max_dte: "@max_dte", missing: "nan" }); // the count of those prints, calls and puts together market.zone(); // the market's clock: a print's time, its days to expiry, and whether a row names a US listed contract market.option_contract(); // 1 on an option contract's own chart: its price axis is the contract's premium, so no marks // The readings, data-only: NaN on a bar the chart served no block for. output("kept", none, overlay, { description: "Trades in this bar that pass your filters. Blank on a bar cut to its largest trades under a type, side or out of the money filter." }); output("bull_premium", none, overlay, { format: "usd", description: "Premium (the money paid) of the bullish trades kept, in USD. Bullish means calls (bets on a rise) bought and puts (bets on a fall) sold. Blank on a bar cut to its largest trades under outside the quote or out of the money only." }); output("bear_premium", none, overlay, { format: "usd", description: "Premium (the money paid) of the bearish trades kept, in USD. Bearish means calls (bets on a rise) sold and puts (bets on a fall) bought. Blank wherever bull_premium is blank." }); output("partial", none, overlay, { description: "1 on a bar older than the trade history OpenMarket keeps. Its trades can be incomplete." }); plot.marks({ name: "print_marks", slots: 16, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 35, x: 1, text: { mode: 0 }, colors: ["theme.down", "theme.up", "theme.muted"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); // up to 16 of the bar's kept prints, largest first, scoring 60 or more either way or under 20: side 0 bearish down, 1 bullish up, 2 muted; fills the score's size plot.marks({ name: "coin_marks", slots: 16, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 35, x: 1, text: { mode: 0 }, colors: ["theme.down", "theme.up", "theme.muted"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); // the same marks on a crypto chain (zone 0), whose sizes are coins plot.marks({ name: "soft_marks", slots: 16, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 10, look: 1, x: 1, text: { mode: 0 }, colors: ["theme.down", "theme.up"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); // the prints scoring 20 to 60 either way, on every chain: a soft dot, no edge, side 0 bearish, 1 bullish render.bgcolor("served_in_part", { where: "partial", color: "#64748b14" }); // a faint wash over a bar served in part const print_rows = frame("print_rows", { max_bytes: 49152 }); // the table, rewritten on the live bar panel.table({ name: "print_table", title: "Option prints", x: "category", place: "below", frame: print_rows, height_frac: 0.3, font_size: 10, cell_padding: 3, valign: "middle", header_text_color: "theme.muted", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", border_width: 0, series: [ { name: "Time" }, { name: "Contract" }, { name: "Days left", align: "right", format: "int" }, { name: "Side", align: "center" }, { name: "Size", align: "right", format: "auto" }, { name: "Price", align: "right", format: "0.00" }, { name: "Premium", align: "right", format: "usd" }, { name: "Spot", align: "right", format: "0.00" }, { name: "IV", align: "right", format: "0.0", unit: "%" }, { name: "Delta", align: "right", format: "0.00" }, { name: "Lean" }, ], }); const PRINT = 16; // f64s per print: OPTION_PRINTS_TUPLE const ROW = 16; // f64s a kept row holds: the time, the contract, price, size, premium, aggressor, outside, underlying, iv, delta, present, the bar's open, its place const NEWEST = 2000.0; // the input's newest: the window's newest prints, every one of which the chart serves const MAX_ROWS = 100; // the rows setting's largest value const MAX_MARKS = 16; // the marks section's slots const NEAR_SPOT = 0.2; // a print's underlying within 20% of the close: the chart is the underlying's const MONTHS: StaticArray<string> = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; // A symbol code's characters (0-9 are 1 to 10, A-Z 11 to 36, the dot 37), written one by one so no row allocates. const CODE_CHARS: StaticArray<string> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "."]; const rootDigits = new StaticArray<i32>(10); const kept = new StaticArray<f64>(MAX_ROWS * ROW); // the newest kept prints, a ring const largest = new StaticArray<i32>(MAX_MARKS); // the bar's largest kept prints, as offsets into the block, biggest first let clock = new Clock("UTC"); // a print's time of day on the market's own clock, set in onStart() let minPremium = 25000.0; // settings, read in onStart() let types = 0; let sides = 0; let maxDte = 0.0; let otmOnly = false; let rows = 30; let scoreFilter = 0; // 0 every mark, 1 the bullish ones, 2 the bearish ones let zone = 0; // the market's clock, read in onStart() let optionContract = false; // the chart is one option contract's own: the table fills, the marks stay off let head = 0; // the ring's next slot, and how many slots hold a row let filled = 0; let held = 0.0; // the prints the blocks held so far, oldest first: a print's place among them let lastMarkerMs: f64 = NaN; // the open of the newest bar served in part, past the history the data plane keeps let lastCutMs: f64 = NaN; // the open of the newest bar cut to its largest prints let lastCutFirst = 0.0; // the place of that bar's first print function onStart(): void { minPremium = p_min_premium(); types = i32(p_types()); sides = i32(p_sides()); maxDte = p_max_dte(); otmOnly = pb_otm_only(); rows = i32(p_rows()); scoreFilter = i32(p_score_filter()); zone = i32(p_market_zone()); optionContract = i32(p_market_option_contract()) == 1; clock = new Clock(SESSION_TZ_IDS[zone]); } // +1 bullish, -1 bearish, 0 neutral, from the contract's side (+1 call, -1 put) and the print's side of the quote // (aggressor +1 the ask, -1 the bid, 0 the mid, 2 no quote). function leanOf(sideCp: f64, aggressor: f64): i32 { if (aggressor == 1.0) return sideCp > 0.0 ? 1 : -1; if (aggressor == -1.0) return sideCp > 0.0 ? -1 : 1; return 0; } // Whether the print at offset `at` passes the filters. A tuple whose size or premium is 0 is the chart's marker for a // bar served in part, never a print. function passes(cells: StaticArray<f64>, at: i32, barMs: f64): bool { const premium = cells[at + 8]; if (!(cells[at + 7] > 0.0) || !(premium >= minPremium)) return false; const sideCp = cells[at + 4]; if ((types == 1 && sideCp < 0.0) || (types == 2 && sideCp > 0.0)) return false; const aggressor = cells[at + 9]; const outside = hasBit(cells[at + 15], 3) ? cells[at + 10] : 0.0; // bit 3: the quote was valid if (sides == 1 && aggressor != 1.0) return false; if (sides == 2 && aggressor != -1.0) return false; if (sides == 3 && outside == 0.0) return false; if (maxDte > 0.0 && optionsTradeDay(cells[at + 3], zone) - optionsTradeDay(barMs + cells[at], zone) > maxDte) return false; if (otmOnly) { if (!hasBit(cells[at + 15], 2)) return false; // bit 2: the print carries its underlying const strike = cells[at + 5]; const spot = cells[at + 11]; const outOfMoney = sideCp > 0.0 ? strike >= spot * 0.995 : strike <= spot * 1.005; if (!outOfMoney) return false; } return true; } // 0 out of the money, 1 at the money (the strike within 0.5% of the underlying), 2 in the money; out without a price. function moneynessOf(sideCp: f64, strike: f64, spot: f64): i32 { if (!(spot > 0.0)) return 0; if (Math.abs(strike - spot) <= spot * 0.005) return 1; return (sideCp > 0.0 ? strike > spot : strike < spot) ? 0 : 2; } // The print's score, -100 to 100 (flowScore): the side of the quote (flowSideCode, `outside` read under a valid quote // only), call or put, the moneyness against `spot` (where its mark sits: its underlying, else the close) and its days to // expiry. No open interest and no repeat count: the size reads as past the open interest and no hit adds. function scoreOf(cells: StaticArray<f64>, at: i32, barMs: f64, spot: f64): f64 { const outside = hasBit(cells[at + 15], 3) ? cells[at + 10] : 0.0; const sideCp = cells[at + 4]; const dte = optionsTradeDay(cells[at + 3], zone) - optionsTradeDay(barMs + cells[at], zone); return flowScore(flowSideCode(cells[at + 9], outside), sideCp, moneynessOf(sideCp, cells[at + 5], spot), dte, NaN, 0); } // Where the print's mark sits: its underlying when it carries one above 0, else the close. function markPrice(cells: StaticArray<f64>, at: i32, close: f64): f64 { return hasBit(cells[at + 15], 2) && cells[at + 11] > 0.0 ? cells[at + 11] : close; } // Whether Marks by score draws the print at offset `at`: every print, the bullish ones (40 and up) or the bearish ones // (-40 and below). function scoreDraws(cells: StaticArray<f64>, at: i32, barMs: f64, close: f64): bool { if (scoreFilter == 0) return true; const score = scoreOf(cells, at, barMs, markPrice(cells, at, close)); return scoreFilter == 1 ? score >= 40.0 : score <= -40.0; } // The print at offset `at` into the ring, its time made absolute. function keep(cells: StaticArray<f64>, at: i32, barMs: f64): void { const base = head * ROW; kept[base] = barMs + cells[at]; for (let f = 0; f < 4; f += 1) kept[base + 1 + f] = cells[at + 2 + f]; // root_code, expiry_ms, side_cp, strike for (let f = 0; f < 8; f += 1) kept[base + 5 + f] = cells[at + 6 + f]; // price, size, premium, aggressor, outside, underlying, iv, delta kept[base + 13] = cells[at + 15]; kept[base + 14] = barMs; kept[base + 15] = held; head = (head + 1) % rows; if (filled < rows) filled += 1; } // Slides the print at offset `at` into the list of the bar's largest, biggest first; returns the list's new length. function offer(cells: StaticArray<f64>, at: i32, count: i32): i32 { const premium = cells[at + 8]; if (count == MAX_MARKS && premium <= cells[largest[count - 1] + 8]) return count; let i = count < MAX_MARKS ? count : count - 1; for (; i > 0 && cells[largest[i - 1] + 8] < premium; i -= 1) largest[i] = largest[i - 1]; largest[i] = at; return count < MAX_MARKS ? count + 1 : count; } // ── The table ── // The characters of a symbol code into rootDigits, last first, and their count; 0 for anything no symbol encodes to. function rootLength(code: f64): i32 { if (!(code >= 1.0) || code > 6278211847988223.0 || code != Math.floor(code)) return 0; let rest = u64(code); let count = 0; while (rest > 0) { const value = i32(rest % 38); if (value == 0 || count == 10) return 0; rootDigits[count] = value; count += 1; rest = rest / 38; } return count; } function fbRoot(code: f64): void { // the option root as listed, or ? when the code names none const count = rootLength(code); if (count == 0) fb_text("?"); for (let i = count - 1; i >= 0; i -= 1) fb_text(CODE_CHARS[rootDigits[i] - 1]); } function fbPad(value: i32): void { // two digits, zero first if (value < 10) fb_text("0"); fb_int(value); } function fbStrike(strike: f64): void { // 450, 452.5, 1.25: the strike as listed fb_f64(strike, strike == Math.floor(strike) ? 0 : strike * 10.0 == Math.floor(strike * 10.0) ? 1 : 2); } function fbContract(base: i32, nowMs: f64): void { // "SPY 450C 21 Nov": the root, the strike, call or put, the expiry's date (15 Jan '27 in another year) fb_text("\""); fbRoot(kept[base + 1]); fb_text(" "); fbStrike(kept[base + 4]); fb_text(kept[base + 3] > 0.0 ? "C " : "P "); fbExpiryLabel(kept[base + 2], nowMs, zone); fb_text("\""); } function fbTime(ms: f64, todayKey: i32): void { // 15:59:58 today, 16OCT 15:59 on an earlier day, on the market's clock clock.update(Math.floor(ms / 1000.0)); const today = clock.dayKey() == todayKey; fb_text("\""); if (!today) { fbPad(clock.dayOfMonth()); fb_text(MONTHS[clock.month() - 1]); fb_text(" "); } fbPad(clock.hour()); fb_text(":"); fbPad(clock.minute()); if (today) { fb_text(":"); fbPad(clock.second()); } fb_text("\""); } function fbSide(aggressor: f64, outside: f64, lean: i32): void { // AA, A, M, B, BB or a dash, inked by the lean fb_text("{\"text\":\""); if (aggressor == 1.0) fb_text(outside > 0.0 ? "AA" : "A"); else if (aggressor == -1.0) fb_text(outside < 0.0 ? "BB" : "B"); else if (aggressor == 0.0) fb_text("M"); else fb_text("-"); fb_text(lean > 0 ? "\",\"text_color\":\"theme.up\"}" : lean < 0 ? "\",\"text_color\":\"theme.down\"}" : "\",\"text_color\":\"theme.muted\"}"); } // The contract a row names so the chart can open it: a US listed contract (OPRA, on the New York zone's charts) with a // root of 1 to 6 characters, an expiry, a call or a put and a strike below 100,000; any other row names no market. function fbMarket(base: i32): void { const count = rootLength(kept[base + 1]); const strike = kept[base + 4]; if (zone != 1 || count < 1 || count > 6 || !(kept[base + 2] > 0.0) || !(strike > 0.0) || strike >= 100000.0) fb_text("null"); else fb_contract(kept[base + 1], kept[base + 2], kept[base + 3] > 0.0 ? 1.0 : -1.0, strike); } function slotOf(k: i32): i32 { // the ring slot of the k-th newest row return ((head - 1 - k + rows * 2) % rows) * ROW; } // Whether a print the table would list can be missing: a bar at or after the oldest row was served past the history the // data plane keeps, or was cut to its largest prints while the oldest row is older than the window's 2,000 newest (each // of those arrives, so rows among them are whole). A cut bar newer than the 2,000th newest print means a host that cut // every bar to its largest: then any cut bar at or after the oldest row counts. function servedInPart(): bool { if (filled == 0) return false; const oldest = slotOf(filled - 1); const oldestBarMs = kept[oldest + 14]; if (lastMarkerMs >= oldestBarMs) return true; if (!(lastCutMs >= oldestBarMs)) return false; const newestWhole = held - lastCutFirst + 1.0 >= NEWEST; // the newest cut bar held the 2,000th newest print, or is older const amongNewest = held - kept[oldest + 15] < NEWEST; // the oldest row is among the 2,000 newest return !(newestWhole && amongNewest); } function writeTable(nowMs: f64): void { clock.update(Math.floor(nowMs / 1000.0)); const todayKey = clock.dayKey(); fb_clear(); fb_text("{\"title\":\"Option prints, "); fb_int(filled); fb_text(filled == 1 ? " trade" : " trades"); fb_text("\",\"caption\":\""); if (filled == 0) fb_text("No print passes the filters yet"); else if (optionContract) fb_text("On a contract's own chart, no marks"); // the price axis is the contract's premium else if (servedInPart()) fb_text("Some bars here show only their largest trades"); else { fb_text("Newest first, "); fb_text(SESSION_TZ_LABELS[zone]); // New York, Chicago or UTC fb_text(zone == 0 ? "" : " time"); } fb_text("\",\"rows\":["); for (let k = 0; k < filled; k += 1) { const base = slotOf(k); const sideCp = kept[base + 3]; const aggressor = kept[base + 8]; const present = kept[base + 13]; const lean = leanOf(sideCp, aggressor); if (k > 0) fb_text(","); fb_text("["); fbTime(kept[base], todayKey); fb_text(","); fbContract(base, nowMs); fb_text(","); fb_f64(optionsTradeDay(kept[base + 2], zone) - optionsTradeDay(kept[base], zone), 0); fb_text(","); fbSide(aggressor, hasBit(present, 3) ? kept[base + 9] : 0.0, lean); fb_text(","); fb_f64(kept[base + 6], kept[base + 6] == Math.floor(kept[base + 6]) ? 0 : 4); // whole contracts bare, a coin size to four decimals fb_text(","); fb_num(kept[base + 5]); fb_text(","); fb_f64(kept[base + 7], 0); fb_text(","); if (hasBit(present, 2)) fb_num(kept[base + 10]); // bit 2: the underlying else fb_text("\"\""); fb_text(","); if (hasBit(present, 0)) fb_num(kept[base + 11]); // bit 0: the IV, percent else fb_text("\"\""); fb_text(","); if (hasBit(present, 1)) fb_num(kept[base + 12]); // bit 1: the delta else fb_text("\"\""); fb_text(lean > 0 ? ",{\"text\":\"Bullish\",\"text_color\":\"theme.up\"}]" : lean < 0 ? ",{\"text\":\"Bearish\",\"text_color\":\"theme.down\"}]" : ",{\"text\":\"Neutral\",\"text_color\":\"theme.muted\"}]"); } fb_text("],\"markets\":["); for (let k = 0; k < filled; k += 1) { if (k > 0) fb_text(","); fbMarket(slotOf(k)); } fb_text("]}"); writeFrameBuffer(print_rows); } // A sum the data plane left unset (no print of that kind in the bar) reads 0. function orZero(value: f64): f64 { return isNaN(value) ? 0.0 : value; } function readings(count: f64, bull: f64, bear: f64, partial: f64): void { out_kept(count); out_bull_premium(bull); out_bear_premium(bear); out_partial(partial); } // The readings of a bar cut to its largest prints, from the data plane's sums of every print of the bar at the smallest // premium and days to expiry: by lean on the sides kept (bullish a call at the ask or a put at the bid, bearish the other // way round), the count with both types and every side kept alone (the sums count both types), and NaN where the sums // cannot tell (outside the quote, out of the money only) or were not served (the chart's chip says why). function cutReadings(): void { const callAsk = in_call_ask(); const callBid = in_call_bid(); const putAsk = in_put_ask(); const putBid = in_put_bid(); const printed = in_printed(); if (sides == 3 || otmOnly || (isNaN(callAsk) && isNaN(callBid) && isNaN(putAsk) && isNaN(putBid) && isNaN(printed))) { readings(NaN, NaN, NaN, 0.0); return; } const ask = sides != 2; // every side, or at or above the ask const bid = sides != 1; // every side, or at or below the bid const bull = (types != 2 && ask ? orZero(callAsk) : 0.0) + (types != 1 && bid ? orZero(putBid) : 0.0); const bear = (types != 2 && bid ? orZero(callBid) : 0.0) + (types != 1 && ask ? orZero(putAsk) : 0.0); readings(types == 0 && sides == 0 ? orZero(printed) : NaN, bull, bear, 0.0); } // onBar() runs once per bar: the bar's prints through the filters, each kept one into the ring, the bar's largest into // the marks; the readings on every bar (a bar cut to its largest reads the data plane's sums), the table on the live bar. function onBar(): void { const close = bar.close(); const barMs = bar.time() * 1000.0; const n = in_prints_cells(); const cells = in_prints_view(); if (n < 0) readings(NaN, NaN, NaN, NaN); // no block on this bar: before the history the chart serves else if (n == PRINT && !(cells[7] > 0.0) && isPartial(cells[15])) { // the marker alone: past the history the data plane keeps lastMarkerMs = barMs; readings(0.0, 0.0, 0.0, 1.0); } else { const first = held + 1.0; // the place of the bar's first print let count = 0; let marks = 0; let bull = 0.0; let bear = 0.0; let cut = false; // bit 14: the bar arrived cut to its 16 largest and its prints among the window's newest for (let i = 0; i + PRINT - 1 < n; i += PRINT) { if (isPartial(cells[i + 15])) cut = true; if (cells[i + 7] > 0.0) held += 1.0; if (!passes(cells, i, barMs)) continue; count += 1; const lean = leanOf(cells[i + 4], cells[i + 9]); if (lean > 0) bull += cells[i + 8]; else if (lean < 0) bear += cells[i + 8]; keep(cells, i, barMs); if (scoreDraws(cells, i, barMs, close)) marks = offer(cells, i, marks); // Marks by score keeps it among the marks } if (cut) { lastCutMs = barMs; lastCutFirst = first; cutReadings(); } else readings(f64(count), bull, bear, 0.0); for (let k = 0; k < marks && !optionContract; k += 1) { // no marks on an option contract's own chart const at = largest[k]; const price = markPrice(cells, at, close); if (!(close > 0.0) || !(price > 0.0) || Math.abs(price / close - 1.0) > NEAR_SPOT) continue; // not the underlying's chart const score = scoreOf(cells, at, barMs, price); const strength = Math.abs(score); const offset = cells[at]; const fills = i32(Math.floor(strength + 0.5)); // the hover's score, 0 to 100 const tone = strength < 20.0 ? 2 : score > 0.0 ? 1 : 0; // muted under 20, else the up or down colour const offsetMs = !(offset > 0.0) ? 0 : offset >= 1073741824.0 ? 1073741824 : i32(offset); if (strength >= 20.0 && strength < 60.0) out_soft_marks_mark(k, price, cells[at + 8], tone, fills, offsetMs); // 20 to 60: the soft tone else if (zone == 0) out_coin_marks_mark(k, price, cells[at + 8], tone, fills, offsetMs); // a coin size: the coin section else out_print_marks_mark(k, price, cells[at + 8], tone, fills, offsetMs); } } if (bar.isLast()) writeTable(barMs); } ``` ## How it works **The chart serves the prints.** The input asks for the prints at **Smallest premium** and up (`min_premium: "@min_premium"`, the chart serving from 10,000), within **Days to expiry, at most** (`max_dte: "@max_dte"`, 0 every expiry) and of the types **Calls or puts** keeps (`types: "@types"`), three days of history (`history: "3d"`) and, on a real-time chart, the live prints as they print. Of those it reads two cuts in one read: the window's 2,000 newest prints (`newest: 2000`), which the table lists, and each bar's 16 largest by premium (`overflow: "largest"`, `max_cells: 16`), which the marks draw. Each bar holds its 16 largest and every print of the 2,000 newest that falls in it, each once, in time order, so the input's buffer holds 2,016 prints. A bar cut that way carries bit 14 on its first print: a bar older than the 2,000 newest that held more than its 16 largest, and the bar holding the 2,000th newest print when it held more than 16, since its older prints past its largest are left out. A bar newer than that holds every print and never carries it. Each print is sixteen numbers: its time inside the bar, its key, the contract (`root_code`, `expiry_ms`, `side_cp`, `strike`), the price, the size, the premium, the side of the quote (`aggressor`, `outside`), the underlying, the IV, the delta, the venue and the `present` mask. **The sums.** Five `options_flow` inputs of scope `prints` read the data plane's own sums of every print of the bar at the same smallest premium and days to expiry (`min_premium: "@min_premium"`, `max_dte: "@max_dte"`), whichever prints the cuts kept: the premium of the calls at the ask and at the bid, of the puts at the ask and at the bid, and the count of those prints, calls and puts together (`printed`). They read `NaN` on a bar with no such print (`missing: "nan"`), which the package reads as 0. A bar cut to its largest prints takes its readings from them. **The filters are settings.** **Smallest premium** (25,000 by default, 10,000 at least) drops the smaller prints. **Calls or puts** (both by default) keeps one type, and the chart serves that type alone. **Side of the quote** keeps the prints at or above the ask, at or below the bid, or outside the quote (above the ask or below the bid, read only where the quote was valid, bit 3). On a crypto or CME chart the first two keep the taker's buys and sells, and outside the quote keeps none, since those prints carry no quote. **Days to expiry, at most** keeps the expiries within that many days of the print's trade date on the market's clock (0 keeps every expiry). **Out of the money only** keeps calls struck at or above 99.5% of the print's underlying and puts struck at or below 100.5% of it (a strike within 0.5% counts as out), and leaves out a print that carries no underlying (bit 2 clear). **The side and the lean.** The data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask (`A`), below it at the bid (`B`), exactly on it at the mid (`M`), and with no valid quote it has no side (a dash). `AA` is an ask-side print that printed above the ask, `BB` a bid-side print below the bid. The lean reads the side against the contract: a call at the ask or a put at the bid leans bullish, a call at the bid or a put at the ask bearish, the mid and no side neutral. On a crypto or CME chain the venue names the taker instead: a print the taker bought reads `A`, one it sold `B`, and bit 3 says only that the side is known, so no row there reads `AA`, `BB`, `M` or a dash. The side cell and the lean cell take the chart's up colour, its down colour or the muted ink. **The table.** The newest kept prints sit in a ring as large as **Trades listed** (30, up to 100), filled bar by bar through the history and the live bar, and the table is rewritten on the live bar, newest first. The time is on the market's clock (`market.zone()`: New York on a US stock, Chicago on a CME future, UTC on crypto): hours, minutes and seconds on the newest bar's trade date, then the day, the month, hours and minutes before it (`16OCT 15:59`), and the days to expiry count on the same clock. Size prints whole contracts bare and a fractional size, a coin's, to four decimals. Price, Spot, IV and Delta print through their columns' formats; Spot, IV and Delta stay empty for a print that does not carry them (bits 2, 0 and 1). The title counts the trades (`Option prints, 30 trades`) and the caption names the clock ("Newest first, New York time", "Newest first, Chicago time" or "Newest first, UTC"). Every print among the window's 2,000 newest arrives, so the table is whole while its rows lie among them; the caption says "Some bars here show only their largest trades" when a listed row can be missing a print: a bar at or after the oldest row lies past the history the data plane keeps, or the filters reach a row older than the 2,000 newest on a bar cut to its largest. **Rows that name their contract.** The frame's `markets` list holds one entry per row, in the rows' order: the row's contract written with `fb_contract(root_code, expiry_ms, side_cp, strike)` straight from the print. A row whose root does not decode to 1 to 6 characters, or whose strike is not above 0 and below 100,000, names no market (`null`), and its contract cell reads `?` where the root would be. A row names a market on a US stock chart only (`market.zone()` 1, New York): a row's market is a US listed (OSI) contract and one bad entry fails the whole frame, so on any other market every row names no market. **The marks.** Up to 16 of each bar's kept prints, largest premium first, are marks on price at the print's own time inside the bar (`x: 1`), at the underlying's price when the print carries it and at the bar's close when it does not, the area growing with the premium from the **Mark unit** (50,000), which draws the smallest mark. On a crypto chain (`market.zone()` 0) the size is coins: the marks ride a second section, `coin_marks`, the same look. **The score on the marks.** Each mark's colour follows the print's flow score, the options kit's `flowScore` ([Flow score](../functions/options-kit.md#flow-score)) from -100 to 100: `flowSideCode` of its side of the quote (`outside` read only under a valid quote, bit 3), call or put, the moneyness against the price the mark sits at (at the money within 0.5%) and its days to expiry on the market's clock. These marks read no open interest and count no repeat hits, so the size factor reads as past the open interest and no hit adds; the flow tape's Score column reads both. A bought call or a sold put scores above 0, a sold call or a bought put below. From 60 either way the mark takes the full tone, the up colour or the down colour, in its chain's section; from 20 to 60 it is a soft dot of the same colour with no edge, in a third section, `soft_marks`, on every chain; under 20 (the mid, no quote) it takes the muted ink. The hover reads the premium, the price and the score's size (`score 80`; the colour says which way), carried in `fills`. **Marks by score** (all by default) keeps the bullish prints, scoring 40 and up, or the bearish ones, -40 and below, among the marks before they rank, so the 16 slots fill with that side's largest; the table and the readings keep every print. On an option contract's own chart, which `market.option_contract()` marks (`i32(p_market_option_contract())` reads 1 there), no print draws a mark; on any chart a print whose underlying sits more than 20% from the bar's close draws none, since the chart is not the underlying's, the rule that keeps the marks off a contract's chart where the host writes 0. **The readings.** Four data-only outputs on every bar: `kept` (the prints the filters kept), `bull_premium` and `bear_premium` (their premium by lean, USD) and `partial` (1 on a bar the chart served in part, past the history the data plane keeps). A whole bar reads them from its prints. A bar cut to its largest reads them from the sums: `bull_premium` the calls at the ask and the puts at the bid, `bear_premium` the calls at the bid and the puts at the ask, of the types and the sides kept, and `kept` the count of those prints with both types and every side kept. The sums do not split by outside the quote or out of the money, and count both types together, so on a cut bar `bull_premium` and `bear_premium` read `NaN` with **Side of the quote** at outside the quote or **Out of the money only** on, and `kept` reads `NaN` with one type, one side or out of the money only kept. Each reads `NaN` on a bar the chart served no block for. ## What the settings do - **Smallest premium, USD**: Hides trades with less premium (the money paid) than this, from $10,000 up. - **Calls or puts**: Keeps calls (bets on a rise), puts (bets on a fall) or both. - **Side of the quote**: Keeps trades at the ask (buyers paying up), the bid (sellers giving in), or outside both. - **Days to expiry, at most**: Keeps options that expire within this many days, and 0 keeps every expiry. - **Out of the money only**: Keeps calls with a strike (the option's price level) above the price, puts below it. - **Trades listed**: How many of the newest trades the table shows, from 5 to 100. - **Mark unit, USD**: The premium that draws the smallest mark, so bigger trades draw bigger marks. - **Marks by score**: Marks all trades, or only strong leans: scores of 40 to 100 (bullish) or -40 to -100 (bearish). ## Where it runs On crypto, it reads each coin's own listed options, with prices in USD per coin and sizes in coins. A copy you run from the editor (where you write and run indicators) reads them too ([Data sources](../core-concepts/data-sources.md#option_prints)). An exchange can list a coin's options in two sets, such as Deribit's BTC and BTC_USDC. The table and the marks read one set, the one named like the coin. A busy bar cut to its largest trades reads its totals from every set. On a US stock or ETF with listed options, every indicator in your browser can read them. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). A CME trade's price is in points. Its premium (the money paid) counts each point at the contract's value, $50 on ES (the S&P 500 future). Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read these trades. On an option contract's own chart, it reads the symbol behind that contract. There the table still lists trades, and its caption reads "On a contract's own chart, no marks". The marks stay off, since that chart's price axis is the option's own price. CME prints are 10 minutes behind unless you have real-time CME data, and crypto has no delay. The legend shows which delay applies. ## When data is missing - **No data yet.** A bar older than the three days the chart loads has no data, and it draws nothing. In the Console (the editor's prompt that shows a reading by its name), its four readings stay blank. They are the kept count (`kept`), the bullish and bearish premium (`bull_premium`, `bear_premium`) and the incomplete-bar flag (`partial`). - **A quiet bar.** A bar where no trade meets your premium (the money paid) and expiry filters keeps 0 trades. It shows no premium and draws no mark. - **A bar cut to its largest trades.** A busy bar sends its 16 largest trades and every trade among the 2,000 newest. Its marks are its largest trades anyway. Its readings come from totals of every trade in the bar. They stay blank where those totals cannot answer your filters. Two settings can leave such a bar with fewer marks than passing trades. They are **Side of the quote** and **Out of the money only**. OpenMarket picks the 16 largest before those two settings apply, so some of them drop out. If fewer than **Trades listed** of the 2,000 newest trades pass, the table goes on with older bars' largest trades. Its caption then says so. - **A bar older than the stored history.** OpenMarket keeps a limited trade history. An older bar arrives as one empty marker, which never counts as a trade. A faint shade covers the bar. In the Console, `partial` reads 1, and the premiums and `kept` read 0. The caption reads "Some bars here show only their largest trades" while such a bar sits among the listed trades. - **Trades without their totals.** In the Console, a cut bar that arrives without its totals reads blank `kept`, `bull_premium` and `bear_premium`. Its trades and marks still draw. A chip on the legend names the data the chart could not load. - **Nothing passes the filters.** The table lists no trade, and its caption reads "No print passes the filters yet". ## Customize it - **Only the big ones.** Raise Smallest premium to 250,000 and Mark unit with it: the table and the marks keep the trades that move the most money. - **Short-dated flow.** Set Days to expiry, at most to 7 and turn Out of the money only on: the table reads the near-term bets. - **Urgency.** Set Side of the quote to outside the quote on a US stock chart: the prints that paid above the ask or sold below the bid, the ones that chose speed over price. - **One side of the flow.** Set Marks by score to bullish: the chart marks only the bought calls and the sold puts that score 40 and up, while the table still lists every print. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Option Prints** under **Order flow**. 2. Press **Run** on a chart whose underlying lists options, a US stock such as SPY, ES1! or a BTC chart: the copy stands the table under the chart and sits the marks on the candles at the prints' times. On ES1! the copy reads the prints once you accept the CME market data terms, at your own tier, and the legend names the tier. 3. At the editor's Console prompt, type `kept` and `bull_premium` to read the newest bar's counts. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_prints) for the `option_prints` celled class, its tuple and its knobs, and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit`, `isPartial` and bit 14 - [Table](../presentation/cards-frames-panels.md#table) and [Rows that open a market](../presentation/cards-frames-panels.md#rows-that-open-a-market) for `panel.table` over a frame, styled cells and `markets` - [Marks](../presentation/marks-spans-rays.md#marks) for `plot.marks`, its size law and `x: 1` - [Plotting](../presentation/plotting.md#text-labels-tables-strips-tints) for `render.bgcolor` gated by a data-only output - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel`, and the [Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file) for `market.option_contract()` <!-- source: https://openmarket.xyz/wrun/cookbook/flow-tape --> # Flow tape Flow Tape groups this symbol's option trades into the orders they likely came from, newest first. A sweep is one order split across exchanges to get done fast, and a block is one large trade. Tags flag orders that open new positions, beat open interest (contracts still held open), repeat, or look unusual. Scores run from -100 to 100, above 0 for a bet on a rise, further out when urgent or large. Use it on a US stock, coin or CME (Chicago futures exchange) future to spot urgent bets as they happen. Under the hood: a celled `option_prints.cells` input ([Data sources](../core-concepts/data-sources.md#option_prints)) feeds a list of open orders that the prints merge into. A celled `option_contract_state.cells` input carries the open interest and the volume today ([Data sources](../core-concepts/data-sources.md#option_contract_state)). Both are read through their `present` masks ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). An order is a SWEEP on two venues or more, a SPLIT on one, and a BLOCK at the block size. Tags read OPEN, OPEN+, VOL>OI, REPEAT and UNUSUAL. A ring keeps the closed rows, and its frame feeds a `panel.table` under the chart ([Table](../presentation/cards-frames-panels.md#table)). Its rows name their contracts in `markets` with `fb_contract` ([Rows that open a market](../presentation/cards-frames-panels.md#rows-that-open-a-market)). The options kit's `optionsTradeDay` gives the trade dates ([Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). Its `flowSideCode` and `flowScore` give each row's score ([Flow score](../functions/options-kit.md#flow-score)). `fbExpiryLabel` names each contract's expiry ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)). This is also the `flow-tape` template: the **Flow Tape** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Flow Tape: this symbol's option trades, grouped into the orders they likely came from, newest first. A print is one // option trade, and each line of the table under the chart is one order. A sweep is one order split across exchanges to // get done fast, and a block is one large trade. Tags flag orders that open new positions, beat open interest // (contracts still held open), repeat or look unusual. Scores run from -100 to 100. A call (a bet on a rise) bought or // a put (a bet on a fall) sold scores above 0. Urgent or large orders score further from 0. Use it to spot urgent, // unusual bets as they happen. // // Under the hood: the option prints of the chart's underlying, merged into the orders they most likely // came from and tagged, newest first, in a table under the chart. Prints of one contract on one side of the quote within // a short window of the first are one row: a SWEEP when they printed on two venues or more (an order that took the best // price on each venue in turn, inferred from the prints since the trade conditions are not served), a SPLIT when they // printed on one venue, and a BLOCK when one print alone holds at least the block size (contracts, or coins on a crypto // chart). A crypto or CME chain trades on one venue, so there no order sweeps and the sweep readings read NaN. A row // also reads OPEN when its size exceeds the contract's open interest before the day (a print that size cannot all be // closing), OPEN+ when an OPEN row holds at least the large premium (a large opening order), VOL>OI when the // contract's volume today has passed that open interest, REPEAT when the contract printed on the row's side of the // quote in 3 bursts or more within the last 5 sessions the tape has seen (a burst ends once 60 s pass without a print of // it, and counts while it holds at least half the premium of the contract's largest; a contract whose bursts the tape // cannot all keep reads no REPEAT until the lost ones leave the window), and UNUSUAL (this tape's own rule) when a row // of today was bought at the ask, out of the money, within 60 days of expiry, with VOL>OI and at least the unusual // premium. Open interest and volume come from the chain summary, so those tags read for today's prints, and // OPEN for the prior day's too; a crypto chain's open interest is live, so there the prior UTC day's stands for it // before today and the day before reads none. A row reads the time (on the market's clock), the contract, the days to // expiry, the kind, the side (AA above the ask, A at the ask, M the mid, B at the bid, BB below the bid; the taker's // side on crypto and CME, A bought and B sold), the size, the average price, the premium, the underlying's price, the // prints and venues, the tags and the score: the options kit's flowScore, -100 bearish to 100 bullish, from the side as // the row reads it (flowSideCode), call or put, the moneyness against the row's underlying (at the money within 0.5%; the // chart's close where no print carried one), the days to expiry, the size over that open interest (past it where the // summary holds none) and the repeat hits. The score's sign is the row's lean (a call bought or a put sold bullish, a // call sold or a put bought bearish, the mid neutral), in the up colour, the down colour or the muted ink. Smallest // score keeps the rows by their score. A US listed row (OPRA) names its contract so the chart can open it. The chart // serves the window's 2,000 newest prints of 5,000 and up (three days), and every print up to 1 s before the oldest of // them so an order keeps its legs: a leg under 5,000 is not seen, and an older bar's sweep readings read 0. section("Orders"); param.int("window_ms", 1000, { min: 50, max: 10000, label: "Merge window, ms", description: "Trades in one contract on one side, within this many milliseconds of the first, count as one order." }); param.int("block_size", 500, { min: 10, max: 100000, label: "Block size", description: "A single trade of at least this many contracts reads BLOCK (one big trade). This applies on US stocks and CME.", visible_by: { size_unit: [0, 2, 3] } }); param.number("block_coins", 25, { min: 0.01, max: 100000, step: 1, label: "Block size, coins", description: "A single trade of at least this many coins reads BLOCK (one big trade) on a crypto chart.", visible_by: { size_unit: [1] } }); param.number("unusual_premium", 100000, { min: 5000, max: 1000000000, step: 5000, label: "Unusual premium, USD", description: "The smallest premium (the money paid) an order needs to read UNUSUAL." }); param.number("large_premium", 100000, { min: 5000, max: 1000000000, step: 5000, label: "Large opening premium, USD", description: "An OPEN order with at least this premium (the money paid) also reads OPEN+, a large new position." }); section("Table"); param.number("min_premium", 50000, { min: 5000, max: 1000000000, step: 5000, label: "Smallest premium, USD", description: "Hides orders with less premium (the money paid) than this. The chart loads trades from $5,000 up." }); param.choice("show", ["every order", "sweeps, splits and blocks", "sweeps only"], "every order", { label: "Show", description: "A sweep (one order split across exchanges to get done fast) needs two exchanges or more. A split is several trades on one exchange. Crypto and CME trade on one, so sweeps only lists none there." }); param.int("rows", 30, { min: 5, max: 100, label: "Orders listed", description: "How many of the newest orders the table shows." }); param.number("min_score", -100, { min: -100, max: 100, step: 5, label: "Smallest score", description: "Scores run from -100 (bearish) to 100 (bullish). -100 or 0 lists every order. Above 0 lists orders at least that far from 0, either way. Below 0 lists orders at or below it." }); input("close", ohlcv.close); // the chart's own candles: the grid the prints line up on, and the price a row's moneyness falls back to input("prints", option_prints.cells, { max_cells: 5000, min_premium: 5000, history: "3d", newest: 2000, newest_tail_ms: 1000, description: "This symbol's option trades of $5,000 and up: the 2,000 newest of three days. It adds every trade up to 1 second before the oldest, so an order keeps all its trades. It updates live on a real-time chart." }); // [offset_ms, print_key, root_code, expiry_ms, side_cp, strike, price, size, premium, aggressor, outside, underlying, iv, delta, venue, present] per print input("state", option_contract_state.cells, { max_cells: 16000, expiries: "nearest:12", strike_window_pct: 25, description: "This symbol's options summary on the newest bar: each contract's open interest (contracts still held open), the prior day's, and its volume today. It covers the twelve nearest expiries and strikes within 25% of the price." }); // [root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present] per contract market.size_unit(); // the market's facts: its clock (a row's time, its trade date and days to go, whether it names a US listed contract) and its size unit (the block size read) // The readings, data-only: rows that closed on the bar (an order closes once its window has passed). output("sweeps", none, overlay, { description: "Sweeps (orders split across exchanges) that closed in this bar, at or above the smallest premium (the money paid). Blank on crypto and CME, which trade on one exchange." }); output("sweep_lean", none, overlay, { format: "usd", description: "Premium (the money paid) of this bar's bullish sweeps (orders split across exchanges) minus its bearish sweeps, in USD. Blank on crypto and CME." }); output("partial", none, overlay, { description: "1 on a bar older than the trade history OpenMarket keeps. Orders there may lack some trades." }); const tape_rows = frame("tape_rows", { max_bytes: 65536 }); // the table, rewritten on the live bar panel.table({ name: "tape", title: "Flow tape", x: "category", place: "below", frame: tape_rows, height_frac: 0.35, font_size: 10, cell_padding: 3, valign: "middle", header_text_color: "theme.muted", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", border_width: 0, series: [ { name: "Time" }, { name: "Contract" }, { name: "Days left", align: "right", format: "int" }, { name: "Kind" }, { name: "Side", align: "center" }, { name: "Size", align: "right", format: "auto" }, { name: "Price", align: "right", format: "0.00" }, { name: "Premium", align: "right", format: "usd" }, { name: "Spot", align: "right", format: "0.00" }, { name: "Prints" }, { name: "Tags" }, { name: "Score", align: "right", format: "0.0", signed: true }, ], }); const PRINT = 16; // f64s per print: OPTION_PRINTS_TUPLE const STATE = 13; // OPTION_CONTRACT_STATE_TUPLE const OPEN = 64; // orders still open to more prints const VENUES = 8; // distinct venues an order counts const ROW = 19; // f64s a closed row holds (the R_ offsets below) const MAX_ROWS = 100; // the rows setting's largest value: the ring of closed rows, which Smallest score lists from // A row: its first print's time, the contract, the side of the quote, size, premium, price times size, prints, venues, // whether a leg printed above the ask (1) or below the bid (2), the last underlying and IV seen, which of those two it // holds (bit 2 the underlying, bit 0 the IV), its bar's open, whether a leg came from a bar served in part, the // contract's repeat hits on its side after its last leg, and the close of the bar it opened on. const R_TIME = 0; const R_ROOT = 1; const R_EXPIRY = 2; const R_SIDE = 3; const R_STRIKE = 4; const R_AGGRESSOR = 5; const R_SIZE = 6; const R_PREMIUM = 7; const R_PX_SIZE = 8; const R_LEGS = 9; const R_VENUES = 10; const R_OUTSIDE = 11; const R_UNDERLYING = 12; const R_IV = 13; const R_HELD = 14; const R_BAR = 15; const R_PARTIAL = 16; const R_REPEAT = 17; const R_CLOSE = 18; // Repeat hits: each contract's bursts on each side of the quote (the ask family, a taker's buy on crypto and CME, or the // bid family) for up to 512 contracts and sides (what the 4 MB of module memory holds beside the inputs' buffers), kept // as each trade date's three largest: the window's largest burst and whether three bursts reach half of it read exactly // from them, however many bursts a date holds. A contract and side keeps its place while it holds a burst inside the // window. One that finds no place, or a date that finds none, reads no repeat hits until the lost bursts leave the // window: never a count the kept bursts alone would make up. const KEYS = 512; const DATES = 6; // the trade dates a contract's bursts are kept by: the window's 5 sessions and one past the newest const BURST_GAP_MS = 60000.0; // a print 60 s or more after the one before starts a new burst const SESSIONS = 5; // the sessions a burst counts within const REPEAT_SHARE = 0.5; // a burst counts at this share of the contract's largest burst's premium or more const REPEAT_HITS = 3; // the bursts a REPEAT row needs const MONTHS: StaticArray<string> = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; // A symbol code's characters (0-9 are 1 to 10, A-Z 11 to 36, the dot 37), written one by one so no row allocates. const CODE_CHARS: StaticArray<string> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "."]; const rootDigits = new StaticArray<i32>(10); const orders = new StaticArray<f64>(OPEN * ROW); // the open orders, built like rows const orderVenues = new StaticArray<f64>(OPEN * VENUES); // each open order's distinct venues const orderUsed = new StaticArray<bool>(OPEN); const tape = new StaticArray<f64>(MAX_ROWS * ROW); // the newest rows, a ring const listedAt = new StaticArray<i32>(MAX_ROWS); // the rows the table lists on the live bar: each one's ring offset, const listedScore = new StaticArray<f64>(MAX_ROWS); // its score, const listedOi = new StaticArray<f64>(MAX_ROWS); // the open interest before its day const listedVolume = new StaticArray<f64>(MAX_ROWS); // and the contract's volume today (NaN where none reads) const keyRoot = new StaticArray<f64>(KEYS); // the repeat hits' contracts and sides const keyExpiry = new StaticArray<f64>(KEYS); const keySide = new StaticArray<f64>(KEYS); const keyStrike = new StaticArray<f64>(KEYS); const keyFamily = new StaticArray<f64>(KEYS); // +1 the ask family, -1 the bid family const keyUsed = new StaticArray<bool>(KEYS); const burstMs = new StaticArray<f64>(KEYS); // the burst each contract and side prints now: its newest print, const burstPremium = new StaticArray<f64>(KEYS); // its premium so far const burstDay = new StaticArray<f64>(KEYS); // and its first print's trade date, NaN before any burst const keyBlind = new StaticArray<f64>(KEYS); // the newest trade date whose bursts the contract and side lost const dateDay = new StaticArray<f64>(KEYS * DATES); // each kept trade date, NaN for a free place, const dateTop = new StaticArray<f64>(KEYS * DATES * 3); // and its three largest finished bursts, largest first, 0 for none const sessionDays = new StaticArray<f64>(SESSIONS); // the newest trade dates the bars opened on, a ring burstDay.fill(NaN); keyBlind.fill(-Infinity); dateDay.fill(NaN); let clock = new Clock("UTC"); // a row's time of day on the market's own clock, set in onStart() let windowMs = 1000.0; // settings, read in onStart() let blockSize = 500.0; let unusualPremium = 100000.0; let largePremium = 100000.0; let minPremium = 50000.0; let show = 0; let rows = 30; let minScore = -100.0; let zone = 0; // the market's clock, read in onStart() let head = 0; // the ring's next slot, and how many slots hold a row let stored = 0; let sessionHead = 0; // the session ring's next slot, and how many it holds let sessionsHeld = 0; let barSweeps = 0; // this bar's sweeps and their lean, for the outputs let barSweepLean = 0.0; let lastPartialMs: f64 = NaN; // the open of the newest bar served in part let lastDay: f64 = NaN; // the newest bar's trade date on the market's clock, and the one before it let priorDay: f64 = NaN; let tableBlind: f64 = -Infinity; // the newest trade date a print found no place for its contract and side let rowPriorOi: f64 = NaN; // what readOi() read for a row: the open interest before its day, let rowVolumeToday: f64 = NaN; // and the contract's volume today function onStart(): void { windowMs = f64(p_window_ms()); zone = i32(p_market_zone()); blockSize = sizeUnit(i32(p_market_kind()), p_market_point_value(), zone) == 1 ? p_block_coins() : f64(p_block_size()); // coins on a crypto chart unusualPremium = p_unusual_premium(); largePremium = p_large_premium(); minPremium = p_min_premium(); show = i32(p_show()); rows = i32(p_rows()); minScore = p_min_score(); clock = new Clock(SESSION_TZ_IDS[zone]); } // +1 bullish, -1 bearish, 0 neutral, from the contract's side (+1 call, -1 put) and the side of the quote. function leanOf(sideCp: f64, aggressor: f64): i32 { if (aggressor == 1.0) return sideCp > 0.0 ? 1 : -1; if (aggressor == -1.0) return sideCp > 0.0 ? -1 : 1; return 0; } // 2 a sweep (two venues or more), 1 a split (one venue), 3 a block (one print of the block size), 0 one print. function kindOf(row: StaticArray<f64>, at: i32): i32 { if (row[at + R_LEGS] >= 2.0) return row[at + R_VENUES] >= 2.0 ? 2 : 1; return row[at + R_SIZE] >= blockSize ? 3 : 0; } // ── Repeat hits ── // A trade date into the session ring, and the oldest one it holds: a burst counts from that date on. function pushSession(day: f64): void { sessionDays[sessionHead] = day; sessionHead = (sessionHead + 1) % SESSIONS; if (sessionsHeld < SESSIONS) sessionsHeld += 1; } function oldestSession(): f64 { if (sessionsHeld == 0) return -Infinity; return sessionsHeld < SESSIONS ? sessionDays[0] : sessionDays[sessionHead]; } // Whether a contract and side's place holds nothing inside the window (a trade date from `from` on): free to take. function keyFree(k: i32, from: f64): bool { if (!keyUsed[k]) return true; if (burstDay[k] >= from || keyBlind[k] >= from) return false; for (let j = 0; j < DATES; j += 1) if (dateDay[k * DATES + j] >= from) return false; return true; } // A finished burst of `premium` from trade date `day` into its date's three largest. A date with no place left (every // place holds a date inside the window) takes the oldest date's place, and the contract and side reads no repeat hits // until that date leaves the window. function keepBurst(k: i32, day: f64, premium: f64, from: f64): void { const base = k * DATES; let at = -1; let open = -1; let oldest = -1; for (let j = 0; j < DATES && at < 0; j += 1) { const held = dateDay[base + j]; if (held == day) at = j; else if (!(held >= from)) { if (open < 0) open = j; } else if (oldest < 0 || held < dateDay[base + oldest]) oldest = j; } if (at < 0) { at = open >= 0 ? open : oldest; if (open < 0 && dateDay[base + at] > keyBlind[k]) keyBlind[k] = dateDay[base + at]; // a date inside the window lost dateDay[base + at] = day; for (let t = 0; t < 3; t += 1) dateTop[(base + at) * 3 + t] = 0.0; } const top = (base + at) * 3; if (premium > dateTop[top]) { dateTop[top + 2] = dateTop[top + 1]; dateTop[top + 1] = dateTop[top]; dateTop[top] = premium; } else if (premium > dateTop[top + 1]) { dateTop[top + 2] = dateTop[top + 1]; dateTop[top + 1] = premium; } else if (premium > dateTop[top + 2]) dateTop[top + 2] = premium; } // A print of `premium` at `ms` into its contract's bursts on its side (`family`), and the contract's repeat hits after // it, counted to three: its bursts within the last 5 sessions that hold at least half the premium of the largest of // them. The burst it prints now and each kept date's three largest hold the largest and, while fewer than three reach // half of it, every one that does; 0 while the contract and side has lost a burst inside the window. function repeatHits(root: f64, expiry: f64, sideCp: f64, strike: f64, family: f64, ms: f64, premium: f64): i32 { const from = oldestSession(); const day = optionsTradeDay(ms, zone); let k = -1; for (let i = 0; i < KEYS && k < 0; i += 1) { if (keyUsed[i] && keyStrike[i] == strike && keyExpiry[i] == expiry && keySide[i] == sideCp && keyRoot[i] == root && keyFamily[i] == family) k = i; } if (k < 0) { // a contract and side not held: the first place that holds nothing inside the window for (let i = 0; i < KEYS && k < 0; i += 1) if (keyFree(i, from)) k = i; if (k < 0) { // none: this one is not kept, and a contract and side taken on later may have printed before if (day > tableBlind) tableBlind = day; return 0; } keyUsed[k] = true; keyRoot[k] = root; keyExpiry[k] = expiry; keySide[k] = sideCp; keyStrike[k] = strike; keyFamily[k] = family; burstDay[k] = NaN; keyBlind[k] = tableBlind >= from ? tableBlind : -Infinity; for (let j = 0; j < DATES; j += 1) dateDay[k * DATES + j] = NaN; } if (!isNaN(burstDay[k]) && ms - burstMs[k] < BURST_GAP_MS) { // within 60 s of its last print: the same burst burstMs[k] = ms; burstPremium[k] += premium; } else { if (burstDay[k] >= from) keepBurst(k, burstDay[k], burstPremium[k], from); burstMs[k] = ms; burstPremium[k] = premium; burstDay[k] = day; } if (keyBlind[k] >= from) return 0; const now = burstDay[k] >= from ? burstPremium[k] : 0.0; let largest = now; for (let j = 0; j < DATES; j += 1) { if (!(dateDay[k * DATES + j] >= from)) continue; const top = dateTop[(k * DATES + j) * 3]; if (top > largest) largest = top; } let hits = now > 0.0 && now >= largest * REPEAT_SHARE ? 1 : 0; for (let j = 0; j < DATES; j += 1) { if (!(dateDay[k * DATES + j] >= from)) continue; for (let t = 0; t < 3; t += 1) { const held = dateTop[(k * DATES + j) * 3 + t]; if (held > 0.0 && held >= largest * REPEAT_SHARE) hits += 1; } } return hits < REPEAT_HITS ? hits : REPEAT_HITS; } // ── Merging prints into orders ── // An order leaves the open list: into the tape when it passes the table's filters. function closeOrder(o: i32): void { orderUsed[o] = false; const at = o * ROW; if (!(orders[at + R_PREMIUM] >= minPremium)) return; const kind = kindOf(orders, at); if ((show == 1 && kind == 0) || (show == 2 && kind != 2)) return; if (kind == 2) { barSweeps += 1; const lean = leanOf(orders[at + R_SIDE], orders[at + R_AGGRESSOR]); if (lean > 0) barSweepLean += orders[at + R_PREMIUM]; else if (lean < 0) barSweepLean -= orders[at + R_PREMIUM]; } const base = head * ROW; for (let f = 0; f < ROW; f += 1) tape[base + f] = orders[at + f]; head = (head + 1) % MAX_ROWS; if (stored < MAX_ROWS) stored += 1; } // Every order whose window has passed by `nowMs` closes, oldest first; with `all`, every order closes. function closeDue(nowMs: f64, all: bool): void { for (;;) { let oldest = -1; for (let o = 0; o < OPEN; o += 1) { if (orderUsed[o] && (oldest < 0 || orders[o * ROW + R_TIME] < orders[oldest * ROW + R_TIME])) oldest = o; } if (oldest < 0 || (!all && orders[oldest * ROW + R_TIME] + windowMs >= nowMs)) return; closeOrder(oldest); } } // The print at offset `at` of the block joins its open order, or opens one; it also runs into its contract's bursts. function take(cells: StaticArray<f64>, at: i32, barMs: f64, partial: bool, close: f64): void { const ms = barMs + cells[at]; closeDue(ms, false); const root = cells[at + 2]; const expiry = cells[at + 3]; const sideCp = cells[at + 4]; const strike = cells[at + 5]; const aggressor = cells[at + 9]; let o = -1; for (let k = 0; k < OPEN; k += 1) { const kb = k * ROW; if (orderUsed[k] && orders[kb + R_STRIKE] == strike && orders[kb + R_EXPIRY] == expiry && orders[kb + R_SIDE] == sideCp && orders[kb + R_ROOT] == root && orders[kb + R_AGGRESSOR] == aggressor) { o = k; break; } } if (o < 0) { for (let k = 0; k < OPEN && o < 0; k += 1) if (!orderUsed[k]) o = k; if (o < 0) { // every slot is open: the oldest order closes first let oldest = 0; for (let k = 1; k < OPEN; k += 1) if (orders[k * ROW + R_TIME] < orders[oldest * ROW + R_TIME]) oldest = k; closeOrder(oldest); o = oldest; } const fresh = o * ROW; for (let f = 0; f < ROW; f += 1) orders[fresh + f] = 0.0; orders[fresh + R_TIME] = ms; orders[fresh + R_ROOT] = root; orders[fresh + R_EXPIRY] = expiry; orders[fresh + R_SIDE] = sideCp; orders[fresh + R_STRIKE] = strike; orders[fresh + R_AGGRESSOR] = aggressor; orders[fresh + R_BAR] = barMs; orders[fresh + R_CLOSE] = close; orderUsed[o] = true; } const b = o * ROW; const size = cells[at + 7]; const present = cells[at + 15]; orders[b + R_SIZE] += size; orders[b + R_PREMIUM] += cells[at + 8]; orders[b + R_PX_SIZE] += cells[at + 6] * size; orders[b + R_LEGS] += 1.0; if (partial) orders[b + R_PARTIAL] = 1.0; if (hasBit(present, 3)) { // bit 3: the quote was valid, so outside says where the leg printed const outside = cells[at + 10]; const flags = i32(orders[b + R_OUTSIDE]); if (outside > 0.0) orders[b + R_OUTSIDE] = f64(flags | 1); else if (outside < 0.0) orders[b + R_OUTSIDE] = f64(flags | 2); } const held = i32(orders[b + R_HELD]); if (hasBit(present, 2)) { // bit 2: the underlying orders[b + R_UNDERLYING] = cells[at + 11]; orders[b + R_HELD] = f64(held | 4); } if (hasBit(present, 0)) { // bit 0: the IV, percent orders[b + R_IV] = cells[at + 12]; orders[b + R_HELD] = f64(i32(orders[b + R_HELD]) | 1); } const venue = cells[at + 14]; const seen = i32(orders[b + R_VENUES]); let known = false; for (let v = 0; v < seen; v += 1) if (orderVenues[o * VENUES + v] == venue) known = true; if (!known && seen < VENUES) { orderVenues[o * VENUES + seen] = venue; orders[b + R_VENUES] = f64(seen + 1); } // The ask family (a taker's buy) or the bid family (a taker's sale); the mid and an unquoted print count no hit. const family = aggressor == 1.0 ? 1.0 : aggressor == -1.0 ? -1.0 : 0.0; if (family != 0.0) orders[b + R_REPEAT] = f64(repeatHits(root, expiry, sideCp, strike, family, ms, cells[at + 8])); } // ── The table ── // The characters of a symbol code into rootDigits, last first, and their count; 0 for anything no symbol encodes to. function rootLength(code: f64): i32 { if (!(code >= 1.0) || code > 6278211847988223.0 || code != Math.floor(code)) return 0; let rest = u64(code); let count = 0; while (rest > 0) { const value = i32(rest % 38); if (value == 0 || count == 10) return 0; rootDigits[count] = value; count += 1; rest = rest / 38; } return count; } function fbRoot(code: f64): void { // the option root as listed, or ? when the code names none const count = rootLength(code); if (count == 0) fb_text("?"); for (let i = count - 1; i >= 0; i -= 1) fb_text(CODE_CHARS[rootDigits[i] - 1]); } function fbPad(value: i32): void { // two digits, zero first if (value < 10) fb_text("0"); fb_int(value); } function fbStrike(strike: f64): void { // 450, 452.5, 1.25: the strike as listed fb_f64(strike, strike == Math.floor(strike) ? 0 : strike * 10.0 == Math.floor(strike * 10.0) ? 1 : 2); } function fbContract(base: i32, nowMs: f64): void { // "SPY 450C 21 Nov": the root, the strike, call or put, the expiry's date (15 Jan '27 in another year) fb_text("\""); fbRoot(tape[base + R_ROOT]); fb_text(" "); fbStrike(tape[base + R_STRIKE]); fb_text(tape[base + R_SIDE] > 0.0 ? "C " : "P "); fbExpiryLabel(tape[base + R_EXPIRY], nowMs, zone); fb_text("\""); } function fbTime(ms: f64, todayKey: i32): void { // 15:59:58 today, 16OCT 15:59 on an earlier day, on the market's clock clock.update(Math.floor(ms / 1000.0)); const today = clock.dayKey() == todayKey; fb_text("\""); if (!today) { fbPad(clock.dayOfMonth()); fb_text(MONTHS[clock.month() - 1]); fb_text(" "); } fbPad(clock.hour()); fb_text(":"); fbPad(clock.minute()); if (today) { fb_text(":"); fbPad(clock.second()); } fb_text("\""); } // The chain summary's row for a contract: its offset into the block, or -1 when the summary does not hold it. function stateOf(cells: StaticArray<f64>, n: i32, base: i32): i32 { const strike = tape[base + R_STRIKE]; const expiry = tape[base + R_EXPIRY]; const sideCp = tape[base + R_SIDE]; const root = tape[base + R_ROOT]; for (let i = 0; i + STATE - 1 < n; i += STATE) { if (cells[i + 3] == strike && cells[i + 1] == expiry && cells[i + 2] == sideCp && cells[i] == root) return i; } return -1; } // A row's open interest before its day and the contract's volume today, into rowPriorOi and rowVolumeToday (NaN where // none reads): the summary's open interest for today's rows, the prior day's for the trade date before; volume today // for today's rows only. A crypto chain's open interest is live: there the prior UTC day's stands for today's rows and // the day before has none. function readOi(base: i32, state: StaticArray<f64>, n: i32, today: f64): void { const day = optionsTradeDay(tape[base + R_TIME], zone); const at = n > 0 && (day == today || day == priorDay) ? stateOf(state, n, base) : -1; rowPriorOi = NaN; rowVolumeToday = NaN; if (at < 0) return; const present = state[at + 12]; const before = zone == 0 ? 11 : 10; // bit 10 the open interest, bit 11 the prior day's: each its column's index if (day == today) { if (hasBit(present, before)) rowPriorOi = state[at + before]; if (hasBit(present, 9)) rowVolumeToday = state[at + 9]; // bit 9: contracts today } else if (zone != 0 && hasBit(present, 11)) rowPriorOi = state[at + 11]; // bit 11: the prior day's, for the trade date before } // 0 out of the money, 1 at the money (the strike within 0.5% of the underlying), 2 in the money; out without a price. function moneynessOf(sideCp: f64, strike: f64, spot: f64): i32 { if (!(spot > 0.0)) return 0; if (Math.abs(strike - spot) <= spot * 0.005) return 1; return (sideCp > 0.0 ? strike > spot : strike < spot) ? 0 : 2; } // A row's score: the side as the Side cell reads it (AA +2, A +1, M and a dash 0, B -1, BB -2), call or put, the // moneyness against its underlying (the close of the bar it opened on where no leg carried one), its days to expiry, // its size over the open interest before its day (NaN, read as past it, where none reads) and its repeat hits. function scoreOf(base: i32, priorOi: f64): f64 { const aggressor = tape[base + R_AGGRESSOR]; const flags = i32(tape[base + R_OUTSIDE]); const outside = aggressor == 1.0 && (flags & 1) != 0 ? 1.0 : aggressor == -1.0 && (flags & 2) != 0 ? -1.0 : 0.0; const sideCp = tape[base + R_SIDE]; const spot = (i32(tape[base + R_HELD]) & 4) != 0 ? tape[base + R_UNDERLYING] : tape[base + R_CLOSE]; const dte = optionsTradeDay(tape[base + R_EXPIRY], zone) - optionsTradeDay(tape[base + R_TIME], zone); const sizeVsOi = isNaN(priorOi) ? NaN : tape[base + R_SIZE] / priorOi; return flowScore(flowSideCode(aggressor, outside), sideCp, moneynessOf(sideCp, tape[base + R_STRIKE], spot), dte, sizeVsOi, i32(tape[base + R_REPEAT])); } // Whether Smallest score lists a row: -100 or 0 every row; above 0 a score at least that far from 0 either way; below 0 // a score at or below it. function scoreKept(score: f64): bool { if (minScore <= -100.0 || minScore == 0.0) return true; return minScore > 0.0 ? Math.abs(score) >= minScore : score <= minScore; } // The row's tags into the frame, and whether it reads UNUSUAL, from the open interest before its day and the // contract's volume today (readOi). function fbTags(base: i32, priorOi: f64, volumeToday: f64, today: f64): bool { const day = optionsTradeDay(tape[base + R_TIME], zone); const opening = !isNaN(priorOi) && tape[base + R_SIZE] > priorOi; const large = opening && tape[base + R_PREMIUM] >= largePremium; const volOverOi = !isNaN(priorOi) && !isNaN(volumeToday) && volumeToday > priorOi; const repeat = tape[base + R_REPEAT] >= f64(REPEAT_HITS); const spot = tape[base + R_UNDERLYING]; const strike = tape[base + R_STRIKE]; const sideCp = tape[base + R_SIDE]; const otm = (i32(tape[base + R_HELD]) & 4) != 0 && spot > 0.0 && (sideCp > 0.0 ? strike >= spot * 0.995 : strike <= spot * 1.005); const dte = optionsTradeDay(tape[base + R_EXPIRY], zone) - day; const unusual = day == today && volOverOi && otm && dte <= 60.0 && tape[base + R_AGGRESSOR] == 1.0 && tape[base + R_PREMIUM] >= unusualPremium; fb_text(unusual ? "{\"text\":\"" : "\""); let words = 0; if (opening) { fb_text("OPEN"); words += 1; } if (large) { fb_text(" OPEN+"); // an OPEN row: never the first word words += 1; } if (volOverOi) { fb_text(words > 0 ? " VOL>OI" : "VOL>OI"); words += 1; } if (repeat) { fb_text(words > 0 ? " REPEAT" : "REPEAT"); words += 1; } if (unusual) { fb_text(words > 0 ? " UNUSUAL" : "UNUSUAL"); fb_text("\",\"font_weight\":\"bold\"}"); } else fb_text("\""); return unusual; } // The score cell, the row's lean by its sign: the number in the up colour above 0 (bullish), the down colour below // (bearish), muted at 0 (neutral), bold from 60 either way. function fbScore(score: f64): void { fb_text("{\"value\":"); fb_num(score); fb_text(score > 0.0 ? ",\"text_color\":\"theme.up\"" : score < 0.0 ? ",\"text_color\":\"theme.down\"" : ",\"text_color\":\"theme.muted\""); fb_text(Math.abs(score) >= 60.0 ? ",\"font_weight\":\"bold\"}" : "}"); } // The contract a row names so the chart can open it: a US listed contract (OPRA, on the New York zone's charts) with a // root of 1 to 6 characters, an expiry, a call or a put and a strike below 100,000; any other row names no market. function fbMarket(base: i32): void { const count = rootLength(tape[base + R_ROOT]); const strike = tape[base + R_STRIKE]; if (zone != 1 || count < 1 || count > 6 || !(tape[base + R_EXPIRY] > 0.0) || !(strike > 0.0) || strike >= 100000.0) fb_text("null"); else fb_contract(tape[base + R_ROOT], tape[base + R_EXPIRY], tape[base + R_SIDE] > 0.0 ? 1.0 : -1.0, strike); } function slotOf(k: i32): i32 { // the ring slot of the k-th newest row return ((head - 1 - k + MAX_ROWS * 2) % MAX_ROWS) * ROW; } function writeTable(nowMs: f64): void { clock.update(Math.floor(nowMs / 1000.0)); const todayKey = clock.dayKey(); const today = optionsTradeDay(nowMs, zone); const n = in_state_cells(); const state = in_state_view(); // The rows listed: the newest that Smallest score keeps, up to Table rows. let filled = 0; for (let k = 0; k < stored && filled < rows; k += 1) { const base = slotOf(k); readOi(base, state, n, today); const score = scoreOf(base, rowPriorOi); if (!scoreKept(score)) continue; listedAt[filled] = base; listedScore[filled] = score; listedOi[filled] = rowPriorOi; listedVolume[filled] = rowVolumeToday; filled += 1; } const oldestBarMs = filled > 0 ? tape[listedAt[filled - 1] + R_BAR] : NaN; let unusualRows = 0; fb_clear(); fb_text("{\"rows\":["); for (let k = 0; k < filled; k += 1) { const base = listedAt[k]; const sideCp = tape[base + R_SIDE]; const aggressor = tape[base + R_AGGRESSOR]; const lean = leanOf(sideCp, aggressor); const kind = kindOf(tape, base); const outside = i32(tape[base + R_OUTSIDE]); if (k > 0) fb_text(","); fb_text("["); fbTime(tape[base + R_TIME], todayKey); fb_text(","); fbContract(base, nowMs); fb_text(","); fb_f64(optionsTradeDay(tape[base + R_EXPIRY], zone) - optionsTradeDay(tape[base + R_TIME], zone), 0); fb_text(kind == 2 ? ",{\"text\":\"SWEEP\",\"font_weight\":\"bold\"}," : kind == 1 ? ",\"SPLIT\"," : kind == 3 ? ",{\"text\":\"BLOCK\",\"font_weight\":\"bold\"}," : ",\"-\","); fb_text("{\"text\":\""); if (aggressor == 1.0) fb_text((outside & 1) != 0 ? "AA" : "A"); else if (aggressor == -1.0) fb_text((outside & 2) != 0 ? "BB" : "B"); else if (aggressor == 0.0) fb_text("M"); else fb_text("-"); fb_text(lean > 0 ? "\",\"text_color\":\"theme.up\"}," : lean < 0 ? "\",\"text_color\":\"theme.down\"}," : "\",\"text_color\":\"theme.muted\"},"); fb_f64(tape[base + R_SIZE], tape[base + R_SIZE] == Math.floor(tape[base + R_SIZE]) ? 0 : 4); // whole contracts bare, a coin size to four decimals fb_text(","); fb_num(tape[base + R_SIZE] > 0.0 ? tape[base + R_PX_SIZE] / tape[base + R_SIZE] : NaN); fb_text(tape[base + R_PREMIUM] >= unusualPremium ? ",{\"value\":" : ","); // bold from the unusual premium up, so a big order stands out fb_f64(tape[base + R_PREMIUM], 0); fb_text(tape[base + R_PREMIUM] >= unusualPremium ? ",\"font_weight\":\"bold\"}," : ","); if ((i32(tape[base + R_HELD]) & 4) != 0) fb_num(tape[base + R_UNDERLYING]); else fb_text("\"\""); fb_text(",\""); fb_int(i64(tape[base + R_LEGS])); if (tape[base + R_LEGS] >= 2.0) { fb_text(" on "); fb_int(i64(tape[base + R_VENUES])); fb_text(tape[base + R_VENUES] >= 2.0 ? " exchanges" : " exchange"); } if (tape[base + R_PARTIAL] > 0.0) fb_text(", in part"); fb_text("\","); if (fbTags(base, listedOi[k], listedVolume[k], today)) unusualRows += 1; fb_text(","); fbScore(listedScore[k]); fb_text("]"); } fb_text("],\"markets\":["); for (let k = 0; k < filled; k += 1) { if (k > 0) fb_text(","); fbMarket(listedAt[k]); } fb_text("],\"title\":\"Flow tape, "); fb_int(filled); fb_text(filled == 1 ? " order" : " orders"); if (unusualRows > 0) { fb_text(", "); fb_int(unusualRows); fb_text(" unusual"); } fb_text("\",\"caption\":\""); if (filled == 0) fb_text("No order passes the filters yet"); else if (lastPartialMs >= oldestBarMs) fb_text("Some bars here are incomplete: orders may lack trades"); else { fb_text("Newest first, "); fb_text(SESSION_TZ_LABELS[zone]); // New York, Chicago or UTC fb_text(zone == 0 ? "" : " time"); fb_text(zone == 1 ? ", sweeps estimated" : ", one exchange, no sweeps"); // a crypto or CME chain trades on one venue } fb_text("\"}"); writeFrameBuffer(tape_rows); } // onBar() runs once per bar: the orders whose window passed before the bar opened close; the bar's prints merge into // orders in time order; the outputs on every bar; on the live bar every open order closes into the table (the chart // restores the state before the next tick, so an order still open keeps merging). function onBar(): void { const barMs = bar.time() * 1000.0; const day = optionsTradeDay(barMs, zone); if (day != lastDay) { if (!isNaN(lastDay)) priorDay = lastDay; lastDay = day; pushSession(day); } barSweeps = 0; barSweepLean = 0.0; closeDue(barMs, false); const n = in_prints_cells(); let partial = false; if (n > 0) { const cells = in_prints_view(); const close = bar.close(); for (let i = 0; i + PRINT - 1 < n; i += PRINT) if (isPartial(cells[i + 15])) partial = true; for (let i = 0; i + PRINT - 1 < n; i += PRINT) { if (!(cells[i + 7] > 0.0) || !(cells[i + 8] > 0.0)) continue; // the chart's marker for a bar served in part, never a print take(cells, i, barMs, partial, close); } } if (partial) lastPartialMs = barMs; if (bar.isLast()) { closeDue(barMs, true); writeTable(barMs); } out_sweeps(n < 0 || zone != 1 ? NaN : f64(barSweeps)); // one venue (crypto, CME): no sweep to count out_sweep_lean(n < 0 || zone != 1 ? NaN : barSweepLean); out_partial(n < 0 ? NaN : partial ? 1.0 : 0.0); } ``` ## How it works **The kinds are inferred.** The data does not carry the exchanges' trade conditions (the code an exchange stamps on an intermarket sweep, a floor trade or a cross), so the tape infers each order's kind from the prints themselves: the same contract, the same side of the quote, and how many prints and venues an order took. A sweep here is an order that took the best price on two venues or more within the window; a split took several prints on one venue; a block is one print of at least **Block size** (500 contracts, on a US stock and on CME) or, on a crypto chart, **Block size, coins** (25); each setting shows only on the charts whose size unit it counts (`visible_by`), and the package picks one through `sizeUnit` over `market.size_unit()`. The caption says so, naming the market's clock: "Newest first, New York time, sweeps estimated" on a US stock. A crypto or CME chain trades on one venue (its prints carry venue 0), so no order there can sweep: an order of several prints is a split, `sweeps` and `sweep_lean` read `NaN` rather than 0, and the caption reads "Newest first, Chicago time, one exchange, no sweeps" on CME and "Newest first, UTC, one exchange, no sweeps" on crypto. **Prints merge into orders.** A print joins the open order with the same contract (root, expiry, call or put, strike) and the same side of the quote (`aggressor`) whose first print is within **Merge window, ms** (1,000) of it; otherwise it opens a new order. An order closes once a print, or a bar's open, comes later than its window: the oldest order first, and the oldest when a 65th order would open. An order sums its contracts and its premium, counts its prints and up to eight distinct venues, keeps the volume-weighted average price of its legs, and keeps the last underlying and IV a leg carried. On the live bar every open order closes into the table; the chart restores the state before the next tick, so an order still inside its window keeps merging. **The side of an order.** The data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask, below it at the bid, exactly on it at the mid, and with no valid quote it has no side. An order's side cell reads `A`, `B`, `M` or a dash, and `AA` when one of its legs printed above the ask or `BB` when one printed below the bid (judged only where the quote was valid, bit 3). On a crypto or CME chain the venue names the taker instead: `A` the taker bought, `B` it sold. The lean reads the side against the contract: a call at the ask or a put at the bid leans bullish, a call at the bid or a put at the ask bearish, the mid and no side neutral; the side cell and the score take the chart's up colour, its down colour or the muted ink by it. **The open interest tags.** The chain summary on the newest bar carries each contract's open interest (`oi`, bit 10), the prior observation (`oi_prev`, bit 11) and its contracts today (`volume_day`, bit 9). The open interest before an order's day is the summary's `oi` for an order of the newest bar's trade date, and its `oi_prev` for an order of the trade date before it; older orders read no open interest tag. A crypto chain's `oi` is live, so there the prior UTC day's (`oi_prev`) stands for today's orders, and an order of the trade date before reads no open interest tag. **OPEN**: the order's size exceeds that open interest, so not all of it can be closing. **VOL>OI**, for today's orders: the contract's volume today has passed its open interest. A contract the summary does not hold (an expiry past the twelve nearest, or a strike more than 25% from the underlying: `expiries: "nearest:12"`, `strike_window_pct: 25`) reads neither tag. **OPEN+, a large opening order.** A row reads OPEN+ beside OPEN when it is an OPEN row (its size past the open interest before its day) whose premium is at least **Large opening premium, USD** (100,000). A row that is not OPEN never reads OPEN+, however large. **REPEAT, the same contract hit again and again.** Every print of 5,000 and up runs into its contract's bursts on its side of the quote: the ask family (`A` and `AA`, or a taker's buy on crypto and CME) or the bid family (`B` and `BB`, or a taker's sale); a print at the mid or with no quote counts in neither. A print 60 seconds or more after the contract's last one on that side starts a new burst, and one sooner joins it. A row reads REPEAT when, after its last leg, the contract holds three bursts or more on the row's side within the last five sessions (the five newest trade dates the chart's bars opened on), each counted burst holding at least half the premium of the largest of them. The tape keeps each trade date's three largest bursts of a contract on each side, which is all the rule needs: the window's largest burst is among them, and so is every burst that reaches half of it while fewer than three do, however many bursts the contract printed. It keeps up to 512 contracts and sides, each holding its place while it holds a burst inside the window. A contract that finds every place taken, or a seventh trade date inside the window for one contract, reads no REPEAT until the bursts it could not keep leave the window, rather than counting from part of them. The tape sees only the prints the chart serves (three days of them). **The score.** The last column is the row's flow score, the options kit's `flowScore` ([Flow score](../functions/options-kit.md#flow-score)), from -100 to 100: `flowSideCode` of the side as the Side cell reads it (`AA` +2, `A` +1, `M` and a dash 0, `B` -1, `BB` -2), call or put, the moneyness against the row's last underlying (at the money within 0.5%; the close of the bar the order opened on when no leg carried one), its days to expiry, its size over the open interest before its day (read as past it when the summary holds none) and its repeat hits (three or more add 10). Its sign is the lean: a bought call or a sold put scores above 0 in the up colour, a sold call or a bought put below 0 in the down colour, the mid 0 in the muted ink, and the cell turns bold from 60 either way. The Score column prints one decimal with its sign (`+80.0`, `-68.8` for -68.85). **Smallest score** (-100 to 100) picks the rows: -100, the default, or 0 lists every row; a value above 0 lists the rows scoring at least that far from 0 either way (60 lists the rows of 60 and up and of -60 and below); a value below 0 lists only the rows scoring at or below it (-40 lists the bearish rows of -40 and below). **UNUSUAL, this tape's own rule.** An order reads UNUSUAL when all of these hold: it is from today, its contract reads VOL>OI, it printed on the ask side (`A` or `AA`), it is out of the money against its last underlying (a call struck at or above 99.5% of it, a put at or below 100.5%), its expiry is within 60 days of the order's trade date, and its premium is at least **Unusual premium, USD** (100,000). The tags cell then turns bold, and the title counts the unusual rows (`Flow tape, 30 orders, 2 unusual`). **The table.** Closed orders at or above **Smallest premium, USD** (50,000) enter a ring of the 100 newest; **Show** keeps every order, only sweeps, splits and blocks, or only sweeps (none on a crypto or CME chain). The table is rewritten on the live bar, newest first, with the newest **Orders listed** (30, up to 100) that Smallest score keeps: the first print's time on the market's clock (`market.zone()`: New York on a US stock, Chicago on a CME future, UTC on crypto; hours, minutes and seconds on the newest bar's trade date, the day, the month, hours and minutes before it), the contract (`SPY 450C 21 Nov`; an expiry in another year reads its year, `SPY 450C 15 Jan '27`), its days to expiry on the same clock, the kind (`SWEEP` and `BLOCK` in bold, `SPLIT`, or a dash for one print), the side, the size (whole contracts bare, a fractional size, a coin's, to four decimals), the average price, the premium, the underlying's price (empty without one), the prints and venues (`4 on 3 exchanges`, with `, in part` when a leg came from a bar served in part), the tags and the score. A table holds at most twelve columns, so the score stands where a lean word would: its sign and its ink are the lean. **Rows that name their contract.** The frame's `markets` list holds one entry per row, in the rows' order, the order's contract written with `fb_contract(root_code, expiry_ms, side_cp, strike)`. A row whose root does not decode to 1 to 6 characters, or whose strike is not above 0 and below 100,000, names no market (`null`) and reads `?` where the root would be. A row names a market on a US stock chart only (`market.zone()` 1, New York): a row's market is a US listed (OSI) contract and one bad entry fails the whole frame, so on any other market every row names no market. **The readings.** Three data-only outputs on every bar: `sweeps` (the sweep rows at or above the smallest premium that closed on the bar), `sweep_lean` (their bullish premium minus their bearish premium, USD) and `partial` (1 on a bar the chart served in part). Each reads `NaN` on a bar the chart served no block for, and the two sweep readings read `NaN` on a crypto or CME chart, where no order sweeps. ## What the settings do - **Merge window, ms**: Trades in one contract and side within this many milliseconds count as one order. - **Block size**: One trade of at least this many contracts reads BLOCK on US stocks and CME. - **Block size, coins**: One trade of at least this many coins reads BLOCK on a crypto chart. - **Unusual premium, USD**: The smallest premium (the money paid) an order needs to read UNUSUAL. - **Large opening premium, USD**: An OPEN order with at least this premium also reads OPEN+, a large new position. - **Smallest premium, USD**: Hides orders with less premium (the money paid) than this, from $5,000 up. - **Show**: Lists every order, only sweeps, splits (several trades on one exchange) and blocks, or only sweeps. - **Orders listed**: How many of the newest orders the table shows, from 5 to 100. - **Smallest score**: At -100 or 0 it keeps every order. At 40 it keeps scores of 40 and above or -40 and below, at -40 only -40 and below. ## Where it runs On crypto, it reads each coin's own listed options, with sizes in coins. A copy you run from the editor (where you write and run indicators) reads them too ([Data sources](../core-concepts/data-sources.md#option_prints)). On a US stock or ETF with listed options, every indicator in your browser can read them. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). It also reads the options summary, each contract's open interest (contracts still held open) and volume today. Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read these trades or that summary. On an option contract's own chart, it reads the symbol behind that contract, so the tape matches the stock's chart. The indicator stops if the options summary holds over 16,000 contracts, rather than read only part of them. CME prints are 10 minutes behind unless you have real-time CME data, and crypto has no delay. The legend shows which delay applies. ## When data is missing - **No data yet.** A bar older than the three days the chart loads has no data. In the Console (the editor's prompt that shows a reading by its name), its three readings stay blank. They are the sweep count (`sweeps`), the sweeps' lean (`sweep_lean`) and the incomplete-bar flag (`partial`). - **A quiet bar.** A bar with no trade of $5,000 or more adds nothing. Orders whose window has passed still close on it. The chart loads the 2,000 newest trades of $5,000 and up. It adds every trade up to 1 second before the oldest of them, which keeps each order's trades together. An older bar arrives empty, so there the Console reads 0 for `sweeps` and `sweep_lean`. - **A bar older than the stored history.** OpenMarket keeps a limited trade history, and it flags older bars. An empty one arrives as a single empty marker, which never joins an order. In the Console, `partial` reads 1 there. An order with a trade from that bar ends its Prints column with "in part". The caption reads "Some bars here are incomplete: orders may lack trades". It shows while such a bar sits among the listed orders. A trade under $5,000 of premium (the money paid) never arrives. So a sweep of smaller trades shows only its larger ones. - **No options summary.** Without the summary on the newest bar, no order reads OPEN, OPEN+, VOL>OI or UNUSUAL. Each score then counts the order's size as larger than the open interest (contracts still held open). The kinds, REPEAT and the rest of each order stay the same. - **Nothing passes the filters.** The table lists no order, and its caption reads "No order passes the filters yet". ## Customize it - **A tighter merge.** Lower Merge window to 250 ms: only legs that printed together merge, which is how a sweep across venues usually prints. - **The sweep tape.** On a US stock chart, set Show to sweeps only and Smallest premium to 100,000: the urgent orders that went venue to venue. - **Bigger blocks.** Raise Block size to 2,000 on an index or a large ETF, where 500 contracts is an ordinary print; on a crypto chart, raise Block size, coins on ETH, where 25 coins is a small print. - **The strong flow only.** Set Smallest score to 60: the rows that bought or sold with conviction either way, the bold scores. Set it to -60 for the bearish ones alone. - **Larger opening orders.** Raise Large opening premium to 500,000 on SPY, where an opening order of 100,000 is common. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Flow Tape** under **Order flow**. 2. Press **Run** on a chart whose underlying lists options, a US stock such as SPY, ES1! or a BTC chart: the copy stands the tape under the chart, newest order first. On ES1! the copy reads the prints once you accept the CME market data terms, at your own tier, and the legend names the tier. 3. At the editor's Console prompt, type `sweeps` and `sweep_lean` to read the sweeps that closed on the newest bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_prints) for `option_prints` and [`option_contract_state`](../core-concepts/data-sources.md#option_contract_state), their tuples and their knobs, and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit`, `isPartial` and bit 14 - [Table](../presentation/cards-frames-panels.md#table) and [Rows that open a market](../presentation/cards-frames-panels.md#rows-that-open-a-market) for `panel.table` over a frame, styled cells and `markets` - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel` <!-- source: https://openmarket.xyz/wrun/cookbook/flow-marks --> # Flow marks Flow Marks draws big option trades as marks on price, bigger for more premium (the money paid for an option). Up-colour marks lean bullish, calls (bets on a rise) bought or puts (bets on a fall) sold. Down-colour marks lean bearish, soft dots lean less, and muted ones barely lean. A column under the chart shows each bar's bullish minus bearish premium. Use it on a US stock, coin or CME (Chicago futures exchange) future to see where big bets landed. Under the hood: a celled `option_prints.cells` input is cut by the data plane to each bar's largest prints at the smallest premium ([Data sources](../core-concepts/data-sources.md#option_prints)). It holds the types kept and is read through its `present` mask ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). Beside it, five scalar `options_flow` inputs of scope `prints` carry the data plane's per-bar sums of every print at that premium ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). Three `plot.marks` sections with a size law bound to a setting draw the contracts, a crypto chain's coins and the soft dots ([Marks](../presentation/marks-spans-rays.md#marks)). Each mark is toned by its flow score from the options kit's `flowSideCode`, `flowScore` and `optionsTradeDay` ([Flow score](../functions/options-kit.md#flow-score)). It takes the full tone from 60 either way, a soft dot from 20 to 60, and the muted ink under 20. A histogram is coloured per bar by a data-only ladder output ([Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks)). A `render.bgcolor` wash covers the bars the chart served in part ([tints](../presentation/plotting.md#text-labels-tables-strips-tints)). This is also the `flow-marks` template: the **Flow Marks** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Flow Marks: the large option trades on this symbol, drawn as marks on the price where they traded. A print is one // option trade, and a bigger mark means more premium (the money paid for an option). A big print at the ask (the // seller's price) means someone paid up for that bet. The up colour means bullish: calls (bets on a rise) bought, puts // (bets on a fall) sold. The down colour means bearish: calls sold, puts bought. A soft dot leans less, and a muted // mark barely leans. A column under the chart shows each bar's bullish minus bearish premium. Use it to see which // prices drew large bets. // // Under the hood: the large option prints of the chart's underlying, drawn on price. Each print of at least the // smallest premium you set is a mark at the underlying's price when it printed, at its own time inside the bar, toned // by its score, the options kit's flowScore from -100 bearish to 100 bullish: the side of the quote (flowSideCode: // above the ask, at it, the mid, at the bid, below it; on crypto and CME the taker's side), call or put, the moneyness // against the price the mark sits at, the days to expiry (no open interest and no repeat count: the size reads as past // the open interest). The up colour when it scores 60 or more (a call bought, a put sold), the down colour at -60 or // below (a call sold, a put bought), a soft dot of the same colour from 20 to 60 either way, muted under 20 (the mid, // no quote). A mark's area grows with the premium, the largest of each bar prints it, and its hover reads the score's // size. Marks by score draws only the bullish prints (40 and up) or only the bearish ones (-40 and below). Under the // chart, each bar's bullish minus bearish premium as a column. The chart serves each bar's 24 largest prints at the // smallest premium, of the types kept, up to 90 days of them, and the data plane sums every such print per bar for the // column and the readings. A bar past the history the data plane keeps is served in part: a faint wash covers it and // partial reads 1. It reads the chart's own underlying, so it belongs on the underlying's chart; on an option // contract's chart the price axis is the contract's own, so the marks stay off and the columns still draw. section("Prints"); param.number("min_premium", 100000, { min: 25000, max: 1000000000, step: 5000, label: "Smallest premium, USD", description: "Trades with less premium (the money paid) than this draw no mark and count in no column. The chart loads trades from $25,000 up." }); param.choice("types", ["both", "calls", "puts"], "both", { label: "Calls or puts" }); param.int("max_marks", 12, { min: 1, max: 24, label: "Marks per bar", description: "How many of each bar's largest trades draw a mark, biggest first." }); param.number("mark_unit", 100000, { min: 1000, max: 1000000000, step: 1000, label: "Mark unit, USD", description: "A trade with this premium (the money paid) or less draws the smallest mark. Bigger trades draw bigger marks." }); param.choice("score_filter", ["all", "bullish", "bearish"], "all", { label: "Marks by score", description: "Each trade scores how strongly it leans, from -100 (bearish) to 100 (bullish). bullish marks scores of 40 and up, bearish -40 and below. The columns and the readings keep every trade." }); input("close", ohlcv.close); // the chart's own close: where a print without its underlying is marked, and the check that the chart is the underlying's input("prints", option_prints.cells, { max_cells: 24, min_premium: "@min_premium", types: "@types", history: "90d", overflow: "largest", description: "This symbol's option trades at your smallest premium, of the types kept. It loads each bar's 24 largest, up to 90 days back, live on a real-time chart." }); // [offset_ms, print_key, root_code, expiry_ms, side_cp, strike, price, size, premium, aggressor, outside, underlying, iv, delta, venue, present] per print input("call_ask", options_flow.call_prem_ask, { scope: "prints", min_premium: "@min_premium", missing: "nan" }); // the data plane's per-bar sums of every print at the smallest premium, calls and puts by side: the column and the readings input("call_bid", options_flow.call_prem_bid, { scope: "prints", min_premium: "@min_premium", missing: "nan" }); input("put_ask", options_flow.put_prem_ask, { scope: "prints", min_premium: "@min_premium", missing: "nan" }); input("put_bid", options_flow.put_prem_bid, { scope: "prints", min_premium: "@min_premium", missing: "nan" }); input("printed", options_flow.prints, { scope: "prints", min_premium: "@min_premium", missing: "nan" }); // the count of those prints, calls and puts together market.zone(); // the market's clock zone: 0 on crypto, whose sizes are coins, so its marks ride their own section; a print's days to expiry read on its calendar // The readings, data-only: the Console reads them. NaN on a bar the chart served no block for. output("bull_premium", none, overlay, { format: "usd", description: "Premium (the money paid) of this bar's bullish trades at or above the smallest premium, in USD. Bullish means calls (bets on a rise) bought and puts (bets on a fall) sold." }); output("bear_premium", none, overlay, { format: "usd", description: "Premium (the money paid) of this bar's bearish trades, in USD. Bearish means calls (bets on a rise) sold and puts (bets on a fall) bought." }); output("marked", none, overlay, { description: "Trades in this bar at or above the smallest premium (the money paid), of the types kept. Blank with one type kept on a bar of more than 24 such trades." }); output("partial", none, overlay, { description: "1 on a bar older than the trade history OpenMarket keeps. Its trades can be incomplete." }); output("net_premium", histogram, lower, { color_by: "net_tone", colors: ["theme.down", "theme.up", "theme.muted"], label: "Bullish minus bearish premium", format: "usd", hint: "Includes cross and late trades", description: "This bar's bullish premium (the money paid) minus its bearish premium, in USD. Above 0 means more money bet on a rise. Includes cross and late trades." }); output("net_tone", none, lower, { description: "The column's colour: 0 bearish, 1 bullish, 2 a bar older than the trade history OpenMarket keeps." }); // The marks: side 0 bearish (down colour), 1 bullish (up colour), 2 muted; the hover reads premium, price and the // score's size (fills, 0 to 100). A print scoring 60 or more either way, or under 20, rides its chain's section. plot.marks({ name: "large_prints", slots: 24, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 35, x: 1, text: { mode: 1, field: "qty", format: "compact", min_px: 24 }, colors: ["theme.down", "theme.up", "theme.muted"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); plot.marks({ name: "coin_prints", slots: 24, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 35, x: 1, text: { mode: 1, field: "qty", format: "compact", min_px: 24 }, colors: ["theme.down", "theme.up", "theme.muted"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); // the same marks on a crypto chain (zone 0) plot.marks({ name: "soft_prints", slots: 24, size: { law: "sqrt", unit: "@mark_unit" }, opacity_pct: 10, look: 1, x: 1, text: { mode: 1, field: "qty", format: "compact", min_px: 24 }, colors: ["theme.down", "theme.up"], tooltip: "{{qty}} premium at {{price}}, score {{fills}}" }); // the prints scoring 20 to 60 either way, on every chain: a soft dot, no edge render.bgcolor("served_in_part", { where: "partial", color: "#64748b14" }); // a faint wash over a bar served in part const PRINT = 16; // f64s per print: OPTION_PRINTS_TUPLE const MAX_MARKS = 24; // the marks section's slots const NEAR_SPOT = 0.2; // a print's underlying within 20% of the close: the chart is the underlying's const largest = new StaticArray<i32>(MAX_MARKS); // the bar's largest kept prints, as offsets into the block, biggest first let minPremium = 100000.0; // settings, read in onStart() let types = 0; let maxMarks = 12; let scoreFilter = 0; // 0 every mark, 1 the bullish ones, 2 the bearish ones let zone = 0; // the market's clock zone, read in onStart(): 0 is a crypto chain function onStart(): void { minPremium = p_min_premium(); types = i32(p_types()); maxMarks = i32(p_max_marks()); scoreFilter = i32(p_score_filter()); zone = i32(p_market_zone()); } // 0 out of the money, 1 at the money (the strike within 0.5% of the underlying), 2 in the money; out without a price. function moneynessOf(sideCp: f64, strike: f64, spot: f64): i32 { if (!(spot > 0.0)) return 0; if (Math.abs(strike - spot) <= spot * 0.005) return 1; return (sideCp > 0.0 ? strike > spot : strike < spot) ? 0 : 2; } // Where the print's mark sits: its underlying when it carries one above 0 (bit 2), else the close. function markPrice(cells: StaticArray<f64>, at: i32, close: f64): f64 { return hasBit(cells[at + 15], 2) && cells[at + 11] > 0.0 ? cells[at + 11] : close; } // The print's score, -100 to 100 (flowScore): the side of the quote (flowSideCode, `outside` read under a valid quote // only), call or put, the moneyness against `spot` (where its mark sits) and its days to expiry on the market's // calendar. No open interest and no repeat count: the size reads as past the open interest and no hit adds. function scoreOf(cells: StaticArray<f64>, at: i32, barMs: f64, spot: f64): f64 { const outside = hasBit(cells[at + 15], 3) ? cells[at + 10] : 0.0; const sideCp = cells[at + 4]; const dte = optionsTradeDay(cells[at + 3], zone) - optionsTradeDay(barMs + cells[at], zone); return flowScore(flowSideCode(cells[at + 9], outside), sideCp, moneynessOf(sideCp, cells[at + 5], spot), dte, NaN, 0); } // Whether Marks by score draws the print at offset `at`: every print, the bullish ones (40 and up) or the bearish ones // (-40 and below). function scoreDraws(cells: StaticArray<f64>, at: i32, barMs: f64, close: f64): bool { if (scoreFilter == 0) return true; const score = scoreOf(cells, at, barMs, markPrice(cells, at, close)); return scoreFilter == 1 ? score >= 40.0 : score <= -40.0; } // Slides the print at offset `at` into the list of the bar's largest, biggest first; returns the list's new length. function offer(cells: StaticArray<f64>, at: i32, kept: i32): i32 { const premium = cells[at + 8]; if (kept == maxMarks && premium <= cells[largest[kept - 1] + 8]) return kept; // smaller than every print kept let i = kept < maxMarks ? kept : kept - 1; // the slot that opens: the end, or the smallest kept for (; i > 0 && cells[largest[i - 1] + 8] < premium; i -= 1) largest[i] = largest[i - 1]; largest[i] = at; return kept < maxMarks ? kept + 1 : kept; } // A sum the data plane left unset (no print of that kind in the bar) reads 0. function orZero(value: f64): f64 { return isNaN(value) ? 0.0 : value; } // The bar's readings and its column. function readings(bull: f64, bear: f64, marked: f64, partial: f64, net: f64, tone: f64): void { out_bull_premium(bull); out_bear_premium(bear); out_marked(marked); out_partial(partial); out_net_premium(net); out_net_tone(tone); } // onBar() runs once per bar: the block's prints at or above the smallest premium of the kept types, the largest kept // for the marks; the data plane's sums for the readings and the column; then the marks. A tuple whose size is 0 is the // chart's marker for a bar served in part, never a print. function onBar(): void { const close = bar.close(); const barMs = bar.time() * 1000.0; // a print's own time: its bar's open plus its offset const n = in_prints_cells(); if (n < 0) { // no block on this bar: before the history the chart serves readings(NaN, NaN, NaN, NaN, NaN, NaN); return; } const cells = in_prints_view(); if (n == PRINT && !(cells[7] > 0.0) && isPartial(cells[15])) { // the marker alone: past the history the data plane keeps readings(0.0, 0.0, 0.0, 1.0, NaN, 2.0); return; } let count = 0; let kept = 0; let cut = false; // bit 14: the bar held more prints than its 24 largest for (let i = 0; i + PRINT - 1 < n; i += PRINT) { if (isPartial(cells[i + 15])) cut = true; const premium = cells[i + 8]; if (!(cells[i + 7] > 0.0) || !(premium >= minPremium)) continue; // the marker tuple, or under the smallest premium const sideCp = cells[i + 4]; if ((types == 1 && sideCp < 0.0) || (types == 2 && sideCp > 0.0)) continue; count += 1; if (scoreDraws(cells, i, barMs, close)) kept = offer(cells, i, kept); // Marks by score keeps it among the marks } const callAsk = in_call_ask(); const callBid = in_call_bid(); const putAsk = in_put_ask(); const putBid = in_put_bid(); const printed = in_printed(); if (count > 0 && isNaN(callAsk) && isNaN(callBid) && isNaN(putAsk) && isNaN(putBid) && isNaN(printed)) { readings(NaN, NaN, NaN, 0.0, NaN, NaN); // prints but no sums: the chart did not serve them (its chip says why) } else { const bull = (types != 2 ? orZero(callAsk) : 0.0) + (types != 1 ? orZero(putBid) : 0.0); // calls at the ask, puts at the bid const bear = (types != 2 ? orZero(callBid) : 0.0) + (types != 1 ? orZero(putAsk) : 0.0); // calls at the bid, puts at the ask const marked = types == 0 ? orZero(printed) : cut ? NaN : f64(count); // the sums count both types: one type counts its block, whole unless cut readings(bull, bear, marked, 0.0, count > 0 ? bull - bear : NaN, bull >= bear ? 1.0 : 0.0); // no kept print: no column } for (let k = 0; k < kept; k += 1) { const at = largest[k]; const price = markPrice(cells, at, close); if (!(close > 0.0) || !(price > 0.0) || Math.abs(price / close - 1.0) > NEAR_SPOT) continue; // not the underlying's chart: no mark const score = scoreOf(cells, at, barMs, price); const strength = Math.abs(score); const offset = cells[at]; const fills = i32(Math.floor(strength + 0.5)); // the hover's score, 0 to 100 const tone = strength < 20.0 ? 2 : score > 0.0 ? 1 : 0; // muted under 20, else the up or down colour const offsetMs = !(offset > 0.0) ? 0 : offset >= 1073741824.0 ? 1073741824 : i32(offset); if (strength >= 20.0 && strength < 60.0) out_soft_prints_mark(k, price, cells[at + 8], tone, fills, offsetMs); // 20 to 60: the soft tone else if (zone == 0) out_coin_prints_mark(k, price, cells[at + 8], tone, fills, offsetMs); // a coin size: the coin section else out_large_prints_mark(k, price, cells[at + 8], tone, fills, offsetMs); } } ``` ## How it works **The large prints.** The prints input asks the data plane for each bar's 24 largest prints by premium (`overflow: "largest"`, `max_cells: 24`, the most marks a bar draws) at the **Smallest premium** setting (`min_premium: "@min_premium"`) and of the types **Calls or puts** keeps (`types: "@types"`), with up to 90 days of history (`history: "90d"`), and on a real-time chart the live prints as they print. Every print of 25,000 and up is a large print the data plane keeps 90 days, so the history this indicator reads is whole wherever the chart reaches. A bar with more prints than its 24 largest carries bit 14 on its first print, which the marks do not need: they are the bar's largest anyway. A change of either setting fetches again, with no rebuild. **The sums.** Five `options_flow` inputs of scope `prints` read the data plane's own sums of every print of the bar at the same smallest premium (`min_premium: "@min_premium"`), whichever prints the cut kept: the premium of the calls at the ask and at the bid, of the puts at the ask and at the bid, and the count of those prints (`printed`). They read `NaN` on a bar with no such print (`missing: "nan"`), which the package reads as 0. **What a bar keeps.** **Smallest premium** (100,000 by default, 25,000 at least) drops the smaller prints, and **Calls or puts** (both by default) keeps one type. `bull_premium` is the premium of the calls at the ask plus the puts at the bid, `bear_premium` the calls at the bid plus the puts at the ask, each of the types kept; a print at the mid or with no quote counts but leans neither way. `marked` counts the prints at the smallest premium: from the sums with both types kept, and from the bar's own prints with one type kept, which reads `NaN` on a bar of more than 24 such prints (the sums count calls and puts together). **The side and the lean.** The data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask, below it at the bid, exactly on it at the mid, and with no valid quote it has no side. A call at the ask or a put at the bid leans bullish; a call at the bid or a put at the ask leans bearish. On a crypto or CME chain the venue names the taker instead: a call the taker bought or a put it sold leans bullish, the other two bearish, and no print there sits at the mid. **The marks.** The bar's largest prints by premium, up to **Marks per bar** (12, at most 24), are marks at the print's own time inside the bar (`x: 1`): at the underlying's price when the print carries it (bit 2), at the bar's close when it does not. The area grows with the premium from **Mark unit** (100,000), which draws the smallest mark, and the largest mark of each bar prints its premium where it is wide enough. On a crypto chain (`market.zone()` 0) the size is coins: the marks ride a second section, `coin_prints`, the same look and caption. A print whose underlying sits more than 20% from the bar's close draws no mark, since the chart is not the underlying's. **The score on the marks.** Each mark's colour follows the print's flow score, the options kit's `flowScore` ([Flow score](../functions/options-kit.md#flow-score)): `flowSideCode` of its side of the quote (`outside` read only under a valid quote, bit 3), call or put, the moneyness against the price the mark sits at (at the money within 0.5%) and its days to expiry from its own time (the bar's open plus its offset, which is why the package reads `bar.time()`) on the market's clock. These marks read no open interest and count no repeat hits, so the size factor reads as past the open interest. From 60 either way a mark takes the full tone in its chain's section; from 20 to 60 it is a soft dot of the same colour with no edge, in a third section, `soft_prints`, on every chain; under 20 it takes the muted ink. The hover reads the premium, the price and the score's size (`score 80`; the colour says which way), carried in `fills`. **Marks by score** (all by default) keeps the bullish prints, scoring 40 and up, or the bearish ones, -40 and below, among the marks before they rank; the column and the readings keep every print. **The column.** `net_premium` is the bar's bullish premium minus its bearish premium from the sums, a histogram in its own pane under the chart, in the up colour at or above zero and the down colour below (`net_tone` picks the colour); a bar with no kept print draws no column. **The readings.** Data-only outputs on every bar: `bull_premium`, `bear_premium` (USD), `marked` (the prints kept) and `partial` (1 on a bar the chart served in part, past the history the data plane keeps). Each reads `NaN` on a bar the chart served no block for. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the column's hover and the description of `net_premium`. ## What the settings do - **Smallest premium, USD**: Hides trades with less premium (the money paid) than this, from $25,000 up. - **Calls or puts**: Keeps calls (bets on a rise), puts (bets on a fall) or both. - **Marks per bar**: How many of each bar's largest trades draw a mark, from 1 to 24. - **Mark unit, USD**: The premium that draws the smallest mark, so bigger trades draw bigger marks. - **Marks by score**: Marks all trades, or only strong leans: scores of 40 to 100 (bullish) or -40 to -100 (bearish). ## Where it runs On crypto, it reads each coin's own listed options, with sizes in coins and premium (the money paid) in USD. A copy you run from the editor (where you write and run indicators) reads them too ([Data sources](../core-concepts/data-sources.md#option_prints)). Take a 1-minute Deribit BTC chart with **Smallest premium, USD** at 25,000. On 17 October 2026 at 11:28 UTC, an 84000 put sold in RFQ 58101 (a trade priced privately on request). A put is a bet on a fall, and it sold at the bid (the buyer's price). That draws one soft dot in the up colour at the index price (Deribit's bitcoin reference price), 81,457.69. Its column reads +32,990.36. The put's strike (the option's price level) sits above the price, so it is in the money. With 13 days to expiry (the day the option ends), it scores 40.8 out of 100. A score from 20 to 60 either way draws a soft dot. An exchange can list a coin's options in two sets, such as Deribit's BTC and BTC_USDC. On crypto, the column and the readings count every set. The marks read one set, the one named like the coin. On a US stock or ETF with listed options, every indicator in your browser can read them. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read these trades. On an option contract's own chart, it reads the symbol behind that contract. That chart's price axis is the option's own price, so the marks stay off and the columns still draw. CME prints are 10 minutes behind unless you have real-time CME data, and crypto has no delay. The legend shows which delay applies. ## When data is missing - **No data yet.** A bar older than the 90 days the chart loads has no data. Every reading stays blank, and it draws nothing. - **A quiet bar.** A bar with no trade at your smallest premium, of the types kept, draws no mark and no column. In the Console (the editor's prompt that shows a reading by its name), `marked` and the premiums read 0. - **A bar cut to its largest trades.** The chart sends each bar's 24 largest trades and flags a bar that held more. Its marks are its largest trades anyway. The column and the readings come from totals of every trade, so the bar still reads whole. In the Console, the count of marked trades (`marked`) stays blank when only calls or only puts are kept. - **A bar older than the stored history.** OpenMarket keeps a limited trade history. An older bar arrives as one empty marker, which never counts as a trade. A faint shade covers it, and it draws no column. In the Console, `partial` reads 1, the colour code `net_tone` reads 2, and the premiums and `marked` read 0. - **Trades without their totals.** A bar with a kept trade but no totals draws no column, but its marks still draw. In the Console, every reading is blank except `partial`, which reads 0. A chip on the legend names the data the chart could not load. ## Customize it - **Only the whales.** Raise Smallest premium to 1,000,000 and Mark unit to 1,000,000: a few marks a day, each one a large bet. - **One side of the book.** Set Calls or puts to puts to watch the hedges and the downside bets alone. - **A quieter chart.** Lower Marks per bar to 3 on a short timeframe: only the largest prints of each bar draw. - **The bearish flow alone.** Set Marks by score to bearish: only the sold calls and the bought puts scoring -40 and below draw, while the column still nets every print. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Flow Marks** under **Order flow**. 2. Press **Run** on a chart whose underlying lists options, a US stock such as SPY, ES1! or a BTC chart: once the chart serves its option prints the marks sit on the candles and the columns stand under the chart; until then the legend's chip names the source the chart does not serve yet. 3. At the editor's Console prompt, type `bull_premium` and `bear_premium` to read the newest bar's large-print premium by lean. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_prints) for the `option_prints` celled class, its tuple and its knobs, and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit`, `isPartial` and bit 14 - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `options_flow` and its scope `prints`, and [Knobs from a setting](../core-concepts/data-sources.md#knobs-from-a-setting) for `"@min_premium"` and `"@types"` - [Marks](../presentation/marks-spans-rays.md#marks) for `plot.marks`, a size unit bound to a setting, captions and `x: 1` - [Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks) for a histogram coloured by a ladder output, and [tints](../presentation/plotting.md#text-labels-tables-strips-tints) for `render.bgcolor` <!-- source: https://openmarket.xyz/wrun/cookbook/contract-sides --> # Contract sides Contract Sides shows where option trades hit the quote, calls (bets on a rise) beside puts (bets on a fall). A is at the ask (the seller's price, so the buyer paid up), and AA above it, paid for speed. B is at the bid (the buyer's price, so the seller gave in), BB below it, and M the middle. A column shows each bar's bullish contracts, calls bought and puts sold, minus its bearish ones. Use it to see who drove today's options on a US stock, coin or CME (Chicago futures exchange) future. Under the hood: twenty scalar `options_flow` inputs read the data plane's per-bar sums by side with `missing: "zero"` ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). A ring keeps each bar's sums. A frame feeds a `panel.bars` under the chart with a per-run title ([Bars](../presentation/cards-frames-panels.md#bars)). It holds contracts in six groups (**AA**, **A**, **M**, **B**, **BB** and **No side**), or premium in three. The three are at the ask and above, at the bid and below, and the rest. On crypto and CME it holds **Bought** and **Sold** alone. Beside it, a histogram is coloured per bar by a data-only ladder output ([Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks)). The options kit's `optionsTradeDay` finds today's session ([Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). This is also the `contract-sides` template: the **Contract Sides** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Contract Sides: where this symbol's option trades hit the quote, as bars under the chart. Calls (bets on a rise) sit // beside puts (bets on a fall). A print is one option trade. A means at the ask (the seller's price, so the buyer paid // up), and AA above it, paid for speed. B means at the bid (the buyer's price, so the seller gave in), and BB below it. // M is the middle, and No side had no quote. On crypto and CME (Chicago futures exchange) futures the bars read Bought // and Sold instead. A column shows each bar's bullish contracts (calls bought, puts sold) minus its bearish ones. Use // it to see whether buyers or sellers drove today's options. // // Under the hood: where the options of the chart's underlying traded against the quote, calls beside puts. The data // plane sums each bar's prints by side, calls apart from puts, and the bars under the chart sum those over today's // session or the last bars you pick. On a US stock, by the midpoint rule: AA above the ask, A the rest of the ask side, // M the mid, B the rest of the bid side, BB below the bid, and no side (no quote to judge); premium splits at or above // the ask, at or below the bid, and the rest (the mid and no side). Crypto and CME prints carry the taker's side // instead of a quote, so there the bars read bought and sold alone, in coins on crypto. A print at the ask or above was // most likely bought, one at the bid or below sold, and one outside the quote paid up for speed. Under the chart, each // bar's bullish minus bearish contracts (calls bought and puts sold, minus calls sold and puts bought). It reads the // chart's own underlying (an option contract's chart reads the contract's underlying). section("Window"); param.choice("measure", ["contracts", "premium"], "contracts", { label: "Measure" }); param.choice("window", ["today", "last bars"], "today", { label: "Window", description: "today sums the newest bar's trading day, on the market's own clock. last bars sums the number of bars set below." }); param.int("bars", 60, { min: 1, max: 500, label: "Bars", when: "window", description: "How many recent bars last bars sums." }); input("close", ohlcv.close); // the chart's own candles: the grid the flow lines up on // The bar's prints summed by side of the quote, calls and puts apart: contracts at the ask, at the bid, at the mid and // with no side, the contracts above the ask and below the bid, and premium by the same four sides. A quiet side reads 0. input("call_ask", options_flow.call_contracts_ask, { missing: "zero" }); input("call_bid", options_flow.call_contracts_bid, { missing: "zero" }); input("call_mid", options_flow.call_contracts_mid, { missing: "zero" }); input("call_none", options_flow.call_contracts_none, { missing: "zero" }); input("call_above", options_flow.call_contracts_above_ask, { missing: "zero" }); input("call_below", options_flow.call_contracts_below_bid, { missing: "zero" }); input("put_ask", options_flow.put_contracts_ask, { missing: "zero" }); input("put_bid", options_flow.put_contracts_bid, { missing: "zero" }); input("put_mid", options_flow.put_contracts_mid, { missing: "zero" }); input("put_none", options_flow.put_contracts_none, { missing: "zero" }); input("put_above", options_flow.put_contracts_above_ask, { missing: "zero" }); input("put_below", options_flow.put_contracts_below_bid, { missing: "zero" }); input("call_prem_ask", options_flow.call_prem_ask, { missing: "zero" }); input("call_prem_bid", options_flow.call_prem_bid, { missing: "zero" }); input("call_prem_mid", options_flow.call_prem_mid, { missing: "zero" }); input("call_prem_none", options_flow.call_prem_none, { missing: "zero" }); input("put_prem_ask", options_flow.put_prem_ask, { missing: "zero" }); input("put_prem_bid", options_flow.put_prem_bid, { missing: "zero" }); input("put_prem_mid", options_flow.put_prem_mid, { missing: "zero" }); input("put_prem_none", options_flow.put_prem_none, { missing: "zero" }); market.zone(); // the market's clock: the trade date today's window reads, and a US quote (zone 1) or the taker's side output("lean", histogram, lower, { color_by: "lean_tone", colors: ["theme.down", "theme.up"], label: "Bullish minus bearish contracts", format: "si", description: "Bullish contracts minus bearish contracts in this bar, in coins on crypto. Bullish counts calls (bets on a rise) at or above the ask (the seller's price). It adds puts (bets on a fall) at or below the bid (the buyer's price)." }); output("lean_tone", none, lower, { description: "The column's colour: 0 bearish, 1 bullish." }); output("above_ask", none, lower, { format: "si", description: "Option contracts that traded above the ask (the seller's price) in this bar. Blank on crypto and CME, whose trades carry no quote." }); output("below_bid", none, lower, { format: "si", description: "Option contracts that traded below the bid (the buyer's price) in this bar. Blank on crypto and CME." }); output("call_ask_share", none, lower, { format: "%", decimals: 1, description: "Percent of the window's calls (bets on a rise) bought at the ask (the seller's price) or above. On crypto and CME, the percent bought. Live bar only." }); output("put_ask_share", none, lower, { format: "%", decimals: 1, description: "Percent of the window's puts (bets on a fall) bought at the ask (the seller's price) or above. Live bar only." }); const side_rows = frame("side_rows", { max_bytes: 2048 }); panel.bars({ name: "by_side", title: "Contracts by side", x: "category", place: "below", frame: side_rows, orientation: "vertical", labels: true, series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }], format: "si", hover_card: true, legend_style: "title", height_frac: 0.22 }); const SLOTS = 18; // per bar: calls AA, A, M, B, BB, none; puts the same; then calls' premium at the ask, at the bid, the rest; puts the same const MAX_BARS = 500; // the bars setting's largest value const ring = new StaticArray<f64>(MAX_BARS * SLOTS); // the last bars' sums, one slot per bar const ringDay = new StaticArray<f64>(MAX_BARS); // each slot's trade date on the market's clock const barSums = new StaticArray<f64>(SLOTS); // this bar's sums const sums = new StaticArray<f64>(SLOTS); // the window's sums const BUCKETS: StaticArray<string> = ["AA", "A", "M", "B", "BB", "No side"]; const PREMIUM_BUCKETS: StaticArray<string> = ["Ask and above", "Bid and below", "Mid and no side"]; let measure = 0; // settings, read in onStart() let today = true; let bars = 60; let zone = 0; // the market's clock, read in onStart() let head = 0; // the ring's next slot, and how many slots hold a bar let filled = 0; function onStart(): void { measure = i32(p_measure()); today = p_window() == 0.0; bars = i32(p_bars()); zone = i32(p_market_zone()); } // One option type's sums into barSums (base 0 the calls, 6 the puts): its contracts by bucket (AA and BB are the part // of the ask and bid sides that printed outside the quote) and its premium at the ask, at the bid and the rest (the // mid and no side). function add(base: i32, ask: f64, bid: f64, mid: f64, none: f64, above: f64, below: f64, premAsk: f64, premBid: f64, premMid: f64, premNone: f64): void { const aboveAsk = Math.min(above, ask); const belowBid = Math.min(below, bid); barSums[base] = aboveAsk; barSums[base + 1] = ask - aboveAsk; barSums[base + 2] = mid; barSums[base + 3] = bid - belowBid; barSums[base + 4] = belowBid; barSums[base + 5] = none; const premiumBase = 12 + (base == 0 ? 0 : 3); barSums[premiumBase] = premAsk; barSums[premiumBase + 1] = premBid; barSums[premiumBase + 2] = premMid + premNone; } function share(part: f64, whole: f64): f64 { return whole > 0.0 ? (part / whole) * 100.0 : NaN; } // One row of the bars: its name, the calls' value and the puts' (a coin's size to four decimals, whole numbers bare). function fbRow(name: string, calls: f64, puts: f64): void { fb_text("["); fb_str(name); fb_text(","); fb_f64(calls, measure == 0 && calls != Math.floor(calls) ? 4 : 0); fb_text(","); fb_f64(puts, measure == 0 && puts != Math.floor(puts) ? 4 : 0); fb_text("]"); } // The bars under the chart: one category per side, calls beside puts, over the window. function writeBars(windowBars: i32): void { fb_clear(); fb_text("{\"title\":\""); fb_text(measure == 1 ? "Premium by side, " : zone == 0 ? "Coins by side, " : "Contracts by side, "); if (today) fb_text("today"); else { fb_text("last "); fb_int(windowBars); fb_text(windowBars == 1 ? " bar" : " bars"); } fb_text("\",\"rows\":["); if (zone != 1) { // crypto and CME prints carry the taker's side, never a quote: bought (the ask side), then sold fbRow("Bought", measure == 0 ? sums[0] + sums[1] : sums[12], measure == 0 ? sums[6] + sums[7] : sums[15]); fb_text(","); fbRow("Sold", measure == 0 ? sums[3] + sums[4] : sums[13], measure == 0 ? sums[9] + sums[10] : sums[16]); } else { for (let b = 0; b < (measure == 0 ? 6 : 3); b += 1) { if (b > 0) fb_text(","); if (measure == 0) fbRow(BUCKETS[b], sums[b], sums[6 + b]); else fbRow(PREMIUM_BUCKETS[b], sums[12 + b], sums[15 + b]); } } fb_text("]}"); writeFrameBuffer(side_rows); } // onBar() runs once per bar: the bar's sums by side into its ring slot; the column and the bar's readings on every // bar; the window's sums, the two shares and the bars on the live bar. function onBar(): void { const barMs = bar.time() * 1000.0; add(0, in_call_ask(), in_call_bid(), in_call_mid(), in_call_none(), in_call_above(), in_call_below(), in_call_prem_ask(), in_call_prem_bid(), in_call_prem_mid(), in_call_prem_none()); add(6, in_put_ask(), in_put_bid(), in_put_mid(), in_put_none(), in_put_above(), in_put_below(), in_put_prem_ask(), in_put_prem_bid(), in_put_prem_mid(), in_put_prem_none()); const slot = head * SLOTS; for (let s = 0; s < SLOTS; s += 1) ring[slot + s] = barSums[s]; ringDay[head] = optionsTradeDay(barMs, zone); head = (head + 1) % MAX_BARS; if (filled < MAX_BARS) filled += 1; const bullish = barSums[0] + barSums[1] + barSums[9] + barSums[10]; // calls at the ask or above, puts at the bid or below const bearish = barSums[3] + barSums[4] + barSums[6] + barSums[7]; // calls at the bid or below, puts at the ask or above out_lean(bullish + bearish > 0.0 ? bullish - bearish : NaN); // a bar with no sided contract draws no column out_lean_tone(bullish >= bearish ? 1.0 : 0.0); out_above_ask(zone == 1 ? barSums[0] + barSums[6] : NaN); // outside the quote: a US quote's alone out_below_bid(zone == 1 ? barSums[4] + barSums[10] : NaN); if (!bar.isLast()) { out_call_ask_share(NaN); out_put_ask_share(NaN); return; } // The window: today's bars, or the last `bars`, newest first from the ring. for (let s = 0; s < SLOTS; s += 1) sums[s] = 0.0; const day = optionsTradeDay(barMs, zone); let windowBars = 0; for (let k = 0; k < filled; k += 1) { const at = (head - 1 - k + MAX_BARS) % MAX_BARS; if (today ? ringDay[at] != day : k >= bars) break; for (let s = 0; s < SLOTS; s += 1) sums[s] += ring[at * SLOTS + s]; windowBars += 1; } const calls = sums[0] + sums[1] + sums[2] + sums[3] + sums[4] + sums[5]; const puts = sums[6] + sums[7] + sums[8] + sums[9] + sums[10] + sums[11]; out_call_ask_share(share(sums[0] + sums[1], calls)); out_put_ask_share(share(sums[6] + sums[7], puts)); writeBars(windowBars); } ``` ## How it works **Each bar's flow, by side.** The inputs read the data plane's own sums of the bar's prints (`options_flow`, the chart's underlying), calls apart from puts: the contracts at the ask, at the bid, at the mid and with no side, the contracts above the ask and below the bid, and the premium at the same four sides. Each reads `missing: "zero"`: a side where nothing traded in the bar reads 0, as does a bar with no print at all. On a US stock the data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask, below it at the bid, exactly on it at the mid, and with no valid quote it has no side. A crypto venue and CME name the taker's side instead: a print the taker bought counts at the ask, one the taker sold at the bid, and none counts at the mid, with no side or outside the quote. Sizes are contracts on a US stock and on CME and coins on crypto (0.6 BTC is 0.6, never 1). **Six buckets of contracts.** A print above the ask is an ask-side print, and one below the bid a bid-side print, so the buckets split those two sides: **AA** is the contracts above the ask, **A** the rest of the ask side, **B** the rest of the bid side, **BB** the contracts below the bid; **M** and **No side** are the mid and the unquoted prints. Each bucket is summed for the calls and for the puts. Off the US quote (crypto and CME) the bars read two rows instead: **Bought**, the ask side, and **Sold**, the bid side. **Three buckets of premium.** The data plane sums the premium of the bar's prints at each side of the quote, so premium splits three ways: **Ask and above**, **Bid and below**, and **Mid and no side**, the premium at the mid plus the premium with no side. On crypto and CME premium reads **Bought** and **Sold** alone, the premium at the ask and at the bid, since no print trades at the mid there. **The window.** **Window** sums today's bars (the trade date the newest bar is on, on the market's clock: the New York date on a US stock; up to the last 500 bars) or the last **Bars** bars (60, up to 500). **Measure** picks contracts (six buckets on a US stock, two off it) or premium (three, or two). The bars stand under the chart on the live bar, calls in the up colour beside puts in the down colour in each bucket, titled by the measure and the window (`Contracts by side, today`, `Coins by side, today` on crypto, `Premium by side, last 60 bars`). A whole number prints bare and a coin's size to four decimals. **The column.** `lean` is each bar's bullish contracts (calls at the ask or above plus puts at the bid or below) minus its bearish contracts (calls at the bid or below plus puts at the ask or above), a histogram in its own pane, the up colour at or above zero and the down colour below (`lean_tone` picks the colour); a bar with no contract on a side of the quote draws no column. **The readings.** Data-only outputs: `above_ask` and `below_bid` (the bar's contracts outside the quote, calls and puts; `NaN` on crypto and CME, which carry no quote), and on the live bar `call_ask_share` and `put_ask_share`, the share of the window's call contracts and of its put contracts at the ask or above (bought, on crypto and CME), in percent. ## What the settings do - **Measure**: Counts contracts (coins on crypto), or premium (the money paid) in USD. - **Window**: Sums today's trading day, or the number of recent bars you set below. - **Bars**: How many recent bars the last bars window sums, from 1 to 500. ## Where it runs On crypto, it reads the coin's options on one exchange, usually Deribit. An exchange can list a coin's options in two sets, such as Deribit's BTC and BTC_USDC. It reads one set, the one named like the coin. On crypto and CME, trades carry no quote, only whether the buyer or the seller started them. There the bars read Bought and Sold. A copy you run from the editor (where you write and run indicators) reads them too. On a US stock or ETF with listed options, every indicator in your browser can read them. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read this options flow. On an option contract's own chart, it reads the symbol behind that contract, so the bars match the stock's chart. CME data is 10 minutes behind unless you have real-time CME data, and the legend shows which delay applies. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. An older bar reads 0 everywhere and draws no column. ## When data is missing - **A quiet side.** A side where nothing traded in the bar reads 0, so it adds nothing to its group. - **A bar with no trades.** A bar where nothing traded, or one older than the history the chart loads, reads 0 everywhere. It adds zeros to the window and draws no column. In the Console (the editor's prompt that shows a reading by its name), `lean_tone`, the column's colour code, reads 1. The Console also reads 0 for `above_ask` and `below_bid` on a US stock, and blank on crypto and CME. ## Customize it - **The session's verdict.** Keep Window at today and Measure at premium: the dollars bought against the dollars sold since the open. - **A rolling view.** Set Window to last bars and Bars to 12 on a 5-minute chart: the last hour's sides. - **Urgency alone.** Read `above_ask` and `below_bid` in the Console: the contracts that crossed the spread to trade. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Contract Sides** under **Order flow**. 2. Press **Run** on a Deribit BTC chart or on a US stock chart such as SPY: the bars stand under the chart with the column in its own pane; on a US stock the legend names the tier the read was served at. 3. At the editor's Console prompt, type `call_ask_share` and `put_ask_share` to read the window's shares bought at the ask. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `options_flow`, its flow fields by side and its `missing` fill - [Bars](../presentation/cards-frames-panels.md#bars) for `panel.bars` over a frame with two series and a per-run title - [Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks) for a histogram coloured by a ladder output - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` <!-- source: https://openmarket.xyz/wrun/cookbook/strike-footprint --> # Strike footprint Coloured boxes behind the candles show where options traded, at each strike (option price level) and in each bar. The up colour means the premium (money paid for options) there leaned bullish, the down colour bearish. Read a strike from left to right to see when traders kept coming back to it. The Lens setting switches to calls alone, puts alone, or contracts traded. Use it to spot levels traders defend or target, on coins, CME (Chicago futures exchange) futures or US stocks. Under the hood: it reads `option_strike_flow.cells` grouped by expiry and strike ([Data sources](../core-concepts/data-sources.md#option_strike_flow)) through its `present` mask ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). It paints an `out.grid` of 41 levels through a diverging `plot.heatmap` whose hover format follows the Lens setting's `style_values` ([Options on a setting](../settings/options.md)). It places each bar's boxes through two data-only values ([Heatmaps](../presentation/price-canvases.md#heatmaps), [A grid the module computes](../presentation/price-canvases.md#a-grid-the-module-computes)). It washes incomplete bars with `render.bgcolor` ([Plotting](../presentation/plotting.md#text-labels-tables-strips-tints)) and finds the same-day expiry with `optionsTradeDay` ([the options functions](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). This is also the `strike-footprint` template: the **Strike Footprint** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Strike Footprint: where options traded, strike by strike and bar by bar, painted behind the candles. A strike is an // option's price level, and each box sits at that price on the chart. Each column is one bar. A box in the up colour // means bullish money outweighed bearish money at that strike. Calls (bets on a rise) bought at the ask (buyers paying // the seller's price) are bullish. Puts (bets on a fall) sold at the bid (sellers taking the buyer's price) are bullish // too. A box in the down colour means the reverse: more puts bought and calls sold. Brighter boxes mean more premium // (money paid for options). The Lens setting can show calls alone, puts alone, or the number of contracts traded. Hover // a box to read its value. Read a strike from left to right to see when traders kept coming back to it. A strike that // keeps lighting up is a level traders defend or target. Use it to see which nearby strikes are busy right now. // // Under the hood: each column is one bar and each cell one strike, at its own price on the chart: the up colour where // the flow leaned bullish (calls bought at the ask and puts sold at the bid outweighed calls sold and puts bought), the // down colour where it leaned bearish, brighter with the premium. The default lens is that bullish net premium; the // others are the calls' net premium alone, the puts' alone, and the contracts traded; the cell hover prints the lens in // its own unit, dollars or a count of contracts. The strikes shown sit around each bar's close, one row per listed // strike step (the most common gap between neighbouring strikes, or the step you set), every expiry summed, the // same-day expiry alone (on crypto, the one within 24 hours), or the later ones. The data plane sums each bar's flow // per expiry, strike and side, only the strikes within 15% of the underlying (a row further out draws empty), so each // row keeps its expiry for the same-day rule and a session of five-minute bars fits the chart's read. A bar the chart // served in part draws what it holds and a faint wash marks it, since its cells are a floor. It reads the chart's own // underlying and draws at strike prices: on an option contract's chart no strike lands near the price axis and nothing // draws. Every print takes a side, cross trades and late prints too: the cell hover and the Lens setting say so. param.choice("lens", ["bullish net premium", "call net premium", "put net premium", "contracts"], "bullish net premium", { label: "Lens", description: "What each box measures: bullish net premium (money paid for options), calls or puts alone, or contracts traded. The premium choices include cross and late trades.", style_values: ["usd", "usd", "usd", "auto"] }); // style_values: the cell hover's number format per lens (the heatmap's format: "@lens"), dollars or a plain count param.int("strikes", 17, { min: 5, max: 41, label: "Strikes shown", description: "How many strikes (option price levels) to show around the price, centred on the nearest one" }); param.number("strike_step", 0, { min: 0, max: 100000, step: 0.5, label: "Strike step", description: "The price gap between two neighbouring strikes (option price levels) on the chart. 0 uses the most common gap between listed strikes." }); param.choice("expiries", ["every expiry", "0DTE only", "after today"], "every expiry", { label: "Expiries", description: "Which expiry dates count. 0DTE only keeps options that expire on the bar's trading day, or within 24 hours on crypto. After today leaves those out." }); input("close", ohlcv.close); // the chart's own close: the strike each bar's rows centre on input("flow", option_strike_flow.cells, { max_cells: 10000, group: "expiry_strike", strike_window_pct: 15, description: "Each bar's flow per expiry, strike and side of the underlying, strikes within 15% of the underlying" }); // [expiry_ms, strike, side_cp, dte_class, vol_ask, vol_bid, vol_mid, vol_none, vol_above_ask, vol_below_bid, prem_ask, prem_bid, prem_mid, prem_none, present] per expiry, strike and side market.zone(); // the market's clock: the trade date the same-day expiry is judged on (on crypto, the next 24 hours) output("grid_low", none, overlay, { description: "The price at the bottom edge of the boxes on this bar, half a step under the lowest strike" }); // data-only: the heatmap reads it output("row_step", none, overlay, { description: "The strike step: how much price each box covers on this bar" }); output("flow_total", none, overlay, { format: "si", description: "The Lens value added up over the strikes shown on this bar, in dollars or contracts. Includes cross and late trades" }); output("partial", none, overlay, { description: "1 on a bar whose options data arrived only in part. Its boxes then show a minimum." }); out.grid("flow", { rows: 41 }); // one data-only output per row, flow_0 the lowest strike; out_flow(row, value) plot.heatmap({ name: "strike_flow", grid: "flow", price_low: "grid_low", price_step: "row_step", center: 0, palette: ["theme.down", "theme.bg", "theme.up"], auto_quantile: 0.97, opacity: 0.8, behind_candles: true, format: "@lens", label: "Strike flow", tooltip: "{{value}} at the {{price}} strike. Includes cross and late trades" }); // {{value}} prints in the lens's format: $7.0K on a premium lens, 30 on contracts render.bgcolor("served_in_part", { where: "partial", color: "#64748b14" }); // a faint wash over a bar served in part const FLOW = 15; // f64s per row: OPTION_STRIKE_FLOW_TUPLE const ROWS = 41; // the grid's declared rows const NEAR = 0.1; // strikes within 10% of the close teach the step const MAX_NEAR = 256; // distinct strikes a bar keeps for the step const MAX_GAPS = 16; // distinct gaps the step's tally keeps const cellSum = new StaticArray<f64>(ROWS); // this bar's cells const cellSeen = new StaticArray<bool>(ROWS); const nearStrikes = new StaticArray<f64>(MAX_NEAR); // this bar's distinct strikes near the close, ascending const gapValue = new StaticArray<f64>(MAX_GAPS); // the gaps seen between neighbouring strikes, and how often const gapCount = new StaticArray<f64>(MAX_GAPS); let lens = 0; // settings, read in onStart() let shown = 17; let fixedStep = 0.0; let expiries = 0; let zone = 0; // the market's clock, read in onStart() let gaps = 0; // distinct gaps in the tally function onStart(): void { lens = i32(p_lens()); shown = i32(p_strikes()); if (shown % 2 == 0) shown -= 1; // an odd count keeps the close's strike in the middle row fixedStep = p_strike_step(); expiries = i32(p_expiries()); zone = i32(p_market_zone()); } // Whether the contract expiring at expiryMs counts under the expiries setting, for the bar opening at barMs on the // trade date `today`: the same day's expiry, on crypto (zone 0, dailies at 08:00 UTC) the one within 24 hours. function counts(expiryMs: f64, today: f64, barMs: f64): bool { if (expiries == 0) return true; const sameDay = zone == 0 ? expiryMs > barMs && expiryMs - barMs <= 86400000.0 : optionsTradeDay(expiryMs, zone) == today; return expiries == 1 ? sameDay : !sameDay; } // One row's value under the lens: its net premium (at the ask minus at the bid) signed by the side it leans (a call // +1, a put -1), one side's net premium alone, or its contracts; NaN when the lens leaves it out. function valueOf(cells: StaticArray<f64>, at: i32): f64 { const sideCp = cells[at + 2]; const net = cells[at + 10] - cells[at + 11]; if (lens == 0) return sideCp > 0.0 ? net : -net; if (lens == 1) return sideCp > 0.0 ? net : NaN; if (lens == 2) return sideCp < 0.0 ? net : NaN; return cells[at + 4] + cells[at + 5] + cells[at + 6] + cells[at + 7]; } // The bar's distinct strikes within 10% of the close teach the tally of gaps between neighbours (to the cent). function learnStep(cells: StaticArray<f64>, n: i32, close: f64): void { let count = 0; for (let i = 0; i + FLOW - 1 < n; i += FLOW) { const strike = cells[i + 1]; if (!(strike > 0.0) || Math.abs(strike / close - 1.0) > NEAR) continue; let j = 0; while (j < count && nearStrikes[j] < strike) j += 1; if (j < count && nearStrikes[j] == strike) continue; // listed already if (count == MAX_NEAR) continue; for (let k = count; k > j; k -= 1) nearStrikes[k] = nearStrikes[k - 1]; nearStrikes[j] = strike; count += 1; } for (let k = 1; k < count; k += 1) { const gap = Math.round((nearStrikes[k] - nearStrikes[k - 1]) * 100.0) / 100.0; if (!(gap > 0.0)) continue; let g = 0; while (g < gaps && gapValue[g] != gap) g += 1; if (g == gaps) { if (gaps == MAX_GAPS) continue; gapValue[g] = gap; gapCount[g] = 0.0; gaps += 1; } gapCount[g] += 1.0; } } // The strike step: the setting, else the gap seen most often (the smaller on a tie); NaN before any gap. function stepOf(): f64 { if (fixedStep > 0.0) return fixedStep; let best = -1; for (let g = 0; g < gaps; g += 1) { if (best < 0 || gapCount[g] > gapCount[best] || (gapCount[g] == gapCount[best] && gapValue[g] < gapValue[best])) best = g; } return best < 0 ? NaN : gapValue[best]; } function clearRows(): void { // no column on this bar: every cell empty for (let r = 0; r < ROWS; r += 1) out_flow(r, NaN); } // onBar() runs once per bar: the bar's strikes teach the step; the strike nearest the close takes the middle row and // each row joins its strike's row; then the grid, its bottom edge and its step. function onBar(): void { const close = bar.close(); const n = in_flow_cells(); let partial = false; if (n > 0) { const block = in_flow_view(); for (let i = 0; i + FLOW - 1 < n; i += FLOW) if (isPartial(block[i + 14])) partial = true; if (close > 0.0) learnStep(block, n, close); } out_partial(n < 0 ? NaN : partial ? 1.0 : 0.0); const step = stepOf(); if (n <= 0 || !(close > 0.0) || isNaN(step)) { out_grid_low(NaN); out_row_step(NaN); out_flow_total(n < 0 ? NaN : 0.0); clearRows(); return; } const cells = in_flow_view(); const barMs = bar.time() * 1000.0; const today = optionsTradeDay(barMs, zone); const half = (shown - 1) / 2; const middle = Math.round(close / step) * step; // the strike nearest the close for (let r = 0; r < ROWS; r += 1) { cellSum[r] = 0.0; cellSeen[r] = false; } for (let i = 0; i + FLOW - 1 < n; i += FLOW) { const strike = cells[i + 1]; if (!(strike > 0.0) || !counts(cells[i], today, barMs)) continue; // no strike: the all-zero row of a bar served in part const value = valueOf(cells, i); if (isNaN(value)) continue; const r = i32(Math.round((strike - middle) / step)) + half; if (r < 0 || r >= shown) continue; // outside the strikes shown cellSum[r] += value; cellSeen[r] = true; } let total = 0.0; for (let r = 0; r < ROWS; r += 1) { const value = r < shown && cellSeen[r] ? cellSum[r] : NaN; if (!isNaN(value)) total += value; out_flow(r, value); } out_grid_low(middle - (f64(half) + 0.5) * step); out_row_step(step); out_flow_total(total); } ``` ## How it works **Each strike's flow.** The data plane sums each bar's prints per expiry, strike and option type (`group: "expiry_strike"`), the strikes within 15% of the underlying (`strike_window_pct: 15`, `max_cells: 10000`), and the input hands the bar one tuple per row: its contracts by side of the quote and its premium at the ask and at the bid. On a US stock the data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask, below it at the bid. A crypto venue and CME name the taker's side instead: bought at the ask, sold at the bid. **The read is what the grid draws.** The grid draws at most 41 rows around the close, so the input asks for the strikes within 15% of the underlying, where it asked for 25%: the widest grid at a chain's listed step near the money sits inside that (41 rows at SPY's one-dollar step reach about 3% each side of the price, 17 rows at a coin's 1,000 step about 13%). The narrower ask holds fewer rows a bar, so the chart reads a whole regular session of five-minute bars at once instead of only its newest bars. A grid that reaches further, such as 41 rows at a step of 5 on SPY, draws its outermost rows empty; raise `strike_window_pct` in the source for it, and the chart reads fewer bars at a time. **The lens.** **Lens** picks each row's value. **Bullish net premium** (the default) is a call's premium at the ask minus at the bid, and a put's the other way round, so calls bought and puts sold count up and calls sold and puts bought count down. **Call net premium** and **Put net premium** keep one side's premium at the ask minus at the bid. **Contracts** counts every contract traded, whatever its side, so it paints the up half of the scale alone. **Expiries** sums every expiry, keeps only the contracts expiring on the bar's own trade date on the market's clock (`market.zone()`: the New York date on a US stock, the CME trade date on a future; `0DTE only`), or leaves those out (`after today`). On crypto, whose dailies expire at 08:00 UTC, `0DTE only` keeps the contracts expiring within 24 hours after the bar's open: the daily that expired this morning never counts, and tomorrow's does. **The strike step.** One row holds one strike. **Strike step** fixes the price between two rows; left at 0, the step is the gap seen most often between neighbouring strikes that traded within 10% of the close, counted to the cent over every bar so far (the smaller gap on a tie), so a chain listed every dollar near the money reads 1, and a BTC chain listed every 1,000 reads 1,000. Before any bar has taught a gap, nothing draws. **The rows around the close.** The row in the middle holds the strike step's multiple nearest the bar's close, and **Strikes shown** (17, from 5 to 41) rows sit around it; an even count drops by one so the close's strike stays in the middle. Each tuple adds its value to its strike's row, and a strike outside the rows shown adds nothing. `grid_low` (half a step under the lowest row's strike) and `row_step` place the rows on the price axis bar by bar, so each column follows its own close. **The heatmap.** `plot.heatmap` paints the grid behind the candles: the down colour below zero, the chart's background at zero, the up colour above, the scale's ends at the 97th percentile of the run, at 80% opacity. The hover reads the cell's value and its strike, in the lens's unit: `format: "@lens"` paints the heatmap's number format from the Lens setting, whose `style_values` give each choice its word (`usd` on the three premium lenses, `auto` on contracts), so the hover's `{{value}}` reads `$7.0K` on a premium lens and `30` on contracts. A row with no contract stays empty. **The readings.** Data-only outputs on every bar: `flow_total` (the lens summed over the strikes shown, in dollars, or contracts on the contracts lens), `grid_low`, `row_step` and `partial` (1 on a bar the chart served in part), with the grid's own outputs `flow_0` (the lowest strike) to `flow_40`. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the cell hover, the hint of **Lens** and the description of `flow_total`. ## What the settings do - **Lens**: Picks what each box measures: bullish net premium, calls or puts alone, or contracts traded. - **Strikes shown**: How many strikes (option price levels) appear around the price. - **Strike step**: The price gap between two strikes, where 0 uses the most common listed gap. - **Expiries**: Every expiry, only 0DTE (options that expire today), or only those after today. ## Where it runs It runs on coins with listed options and reads the coin's own options. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read this data. On a futures chart from CME, the Chicago exchange, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read this data. They stop with an error that names it. It draws at strike prices, so use it on the stock's or coin's own chart. On an option contract's chart, the price axis shows the contract's own price, so nothing draws. A bar with more than 10,000 entries stops the run rather than cutting data. An entry is one expiry, strike and option type. US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless your account has real-time CME access. The chart's legend says which you see. ## When data is missing - **No data.** A bar older than the chart's options history has no data. Then the Console (the editor's panel that prints values) shows `flow_total` and `partial` empty, and no column draws. - **No trades.** A bar where no option traded draws no column, and the Console's `flow_total` reading shows 0. - **Part of a bar.** Sometimes only part of a bar's options data arrives. On a busy symbol, an older bar may come as one empty marker instead of its trades. This indicator never counts that marker as a trade. Such a bar draws the boxes it has, a faint wash covers it, and the Console's `partial` reading shows 1. Its boxes then show a minimum. ## Customize it - **The same-day expiry.** Set Expiries to 0DTE only on an index ETF: the strikes the day's expiring flow is fighting over. - **One side.** Set Lens to call net premium to see where calls were bought and where they were sold, strike by strike. - **A wider ladder.** Raise Strikes shown to 41 on a quiet chart, or set Strike step to 5 on a chain listed every five dollars; a grid that reaches past 15% of the underlying draws its outer rows empty until you raise `strike_window_pct` in the source. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Strike Footprint** under **Order flow**. 2. Press **Run** on a Deribit BTC chart at 5 minutes or on a US stock chart such as SPY: the cells paint behind the candles; on a US stock the legend names the tier the read was served at. 3. At the editor's Console prompt, type `flow_total` and `row_step` to read the newest bar's total and the strike step it drew with. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_strike_flow) for the `option_strike_flow` celled class, its tuple and [its knobs](../core-concepts/data-sources.md#the-knobs), and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `isPartial` and bit 14 - [Options on a setting](../settings/options.md) for `style_values`, the hover's number format per lens - [Heatmaps](../presentation/price-canvases.md#heatmaps) and [A grid the module computes](../presentation/price-canvases.md#a-grid-the-module-computes) for `out.grid` and `plot.heatmap` with `price_low` and `price_step` - [Plotting](../presentation/plotting.md#text-labels-tables-strips-tints) for `render.bgcolor` gated by a data-only output - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` <!-- source: https://openmarket.xyz/wrun/cookbook/premium-tide --> # Premium tide Two lines under the chart sum the whole options market's premium (money paid for options) each session. The up-colour line is calls (bets on a rise) and the down-colour line is puts (bets on a fall). Each line is net: bought at the ask (the seller's price) minus sold at the bid (the buyer's price). Rising calls or falling puts lean bullish, the reverse bearish, and a pane below shows the same in contracts. Use it to read the whole options market's mood from a crypto, CME (Chicago futures exchange) or US stock chart. Under the hood: the recipe reads `options_flow` net premium and contract fields under `scope: "market"`. Each tide's set sits behind its own option of a multi setting through `when` and `when_bit` ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It takes the trade date and session from the `time` source ([Data sources](../core-concepts/data-sources.md#the-time-source)) and the market's clock from `market.zone()` ([The market's facts](../settings/sessions-and-units.md#the-markets-facts)). It draws a histogram in a named pane and a `render.hud` card in the chart's default look from data-only readings and `string` texts ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)). It is also the `premium-tide` template, the **Premium Tide** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Premium Tide: two lines under the chart sum the whole options market's premium (money paid for options) each session. // The up-colour line is calls (bets on a rise) and the down-colour line is puts (bets on a fall). Each line is net: // bought at the ask (the seller's price) minus sold at the bid (the buyer's price). Rising calls or falling puts lean // bullish, the reverse bearish, and a pane below shows the same in contracts. Use it to read the whole options market's // mood from a crypto, CME (Chicago futures exchange) or US stock chart. // // Technical notes: the tide reads the whole options market (every US listed underlying, the coin on every crypto venue, // or CME's market), summed through the session: the regular session on a US stock, the whole trading day on CME. The // net call premium is the call premium bought at the ask minus the call premium sold at the bid (the taker's side on // crypto and CME), the net put premium the same on puts, each print's premium counted up to 2,000,000 so one block // cannot swamp the market. Both run from the session's start (09:30 New York on a US stock; the 17:00 Chicago open on // CME, whose evening, night and hours after the regular window count too; 00:00 UTC on crypto, where every bar is in // session; each trade date starts again) as two lines under the chart, calls in the up colour and puts in the down // colour, and a pane below sums the net volume (coins on crypto): call contracts bought at the ask minus sold at the // bid, minus the same on puts. Prints at the mid or with no quote count in neither. Tides picks what is summed: the // whole market or the contracts expiring that day (0DTE), each over every strike or only the out-of-the-money ones, // each pick one more read fetched only while it is picked. With one tide picked the two lines are its calls and its // puts; with several, each picked tide draws one line, its net call minus net put premium, in its own tier of white // (the whole market's brightest), and the net volume and the card follow the first one picked. The rows come from // options_flow's market scope, one per bar: 1-minute rows reach back 7 days, 5-minute rows 30 and daily rows are kept, // so older intraday bars carry none. A bar the tide sums (in the regular session, on CME in any part of its trading // day) without a row adds nothing and is counted, the sums a floor while that count is above 0; bars outside the // session draw nothing. Every print takes a side, cross and late trades too: the card says so above the count of bars // with no row, and the lines' and sums' hover too. param.multi("tides", ["Whole market", "Whole market, out of the money", "0DTE", "0DTE, out of the money"], ["Whole market"], { label: "Tides", description: "Which options the tide sums. 0DTE means options that expire today. Out of the money means calls whose strike (price level) is above the price, and puts whose strike is below. Each pick loads extra data, and with several picked each draws its own net line." }); input("close", ohlcv.close); // the chart's own candles: the bar grid (the tide reads the chart's whole options market) input("trade_date", time.trade_date); // the bar's trade date (the New York date on a US stock, on CME the one that opens at 17:00 Chicago): the sums start again on each input("session", time.session); // 1 in the regular session, 2 before it, 3 after it, 0 closed: the tide sums 1, and 1 to 3 on CME market.zone(); // the market's clock, written by the chart: 2 Chicago (CME), whose whole trading day the tide sums // Six fields a tide, each set read only while its tide is picked (when_bit is the tide's place in Tides): the net call // and net put premium with each print capped, then the call and put contracts at the ask and at the bid. input("mkt_ncp", options_flow.net_call_prem_capped, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: net call premium in dollars, each trade capped at $2,000,000." }); input("mkt_npp", options_flow.net_put_prem_capped, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: net put premium in dollars, each trade capped at $2,000,000." }); input("mkt_ca", options_flow.call_contracts_ask, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: call contracts bought at the ask" }); input("mkt_cb", options_flow.call_contracts_bid, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: call contracts sold at the bid" }); input("mkt_pa", options_flow.put_contracts_ask, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: put contracts bought at the ask" }); input("mkt_pb", options_flow.put_contracts_bid, { scope: "market", when: "tides", when_bit: 0, missing: "nan", description: "Whole market: put contracts sold at the bid" }); input("otm_ncp", options_flow.net_call_prem_capped, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: net call premium in dollars, each trade capped at $2,000,000." }); input("otm_npp", options_flow.net_put_prem_capped, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: net put premium in dollars, each trade capped at $2,000,000." }); input("otm_ca", options_flow.call_contracts_ask, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: call contracts bought at the ask" }); input("otm_cb", options_flow.call_contracts_bid, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: call contracts sold at the bid" }); input("otm_pa", options_flow.put_contracts_ask, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: put contracts bought at the ask" }); input("otm_pb", options_flow.put_contracts_bid, { scope: "market", moneyness: "otm", when: "tides", when_bit: 1, missing: "nan", description: "Whole market, out of the money: put contracts sold at the bid" }); input("zd_ncp", options_flow.net_call_prem_capped, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): net call premium in dollars, each trade capped at $2,000,000." }); input("zd_npp", options_flow.net_put_prem_capped, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): net put premium in dollars, each trade capped at $2,000,000." }); input("zd_ca", options_flow.call_contracts_ask, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): call contracts bought at the ask" }); input("zd_cb", options_flow.call_contracts_bid, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): call contracts sold at the bid" }); input("zd_pa", options_flow.put_contracts_ask, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): put contracts bought at the ask" }); input("zd_pb", options_flow.put_contracts_bid, { scope: "market", dte: "0dte", when: "tides", when_bit: 2, missing: "nan", description: "0DTE (expiring today): put contracts sold at the bid" }); input("zd_otm_ncp", options_flow.net_call_prem_capped, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: net call premium in dollars, each trade capped at $2,000,000." }); input("zd_otm_npp", options_flow.net_put_prem_capped, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: net put premium in dollars, each trade capped at $2,000,000." }); input("zd_otm_ca", options_flow.call_contracts_ask, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: call contracts bought at the ask" }); input("zd_otm_cb", options_flow.call_contracts_bid, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: call contracts sold at the bid" }); input("zd_otm_pa", options_flow.put_contracts_ask, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: put contracts bought at the ask" }); input("zd_otm_pb", options_flow.put_contracts_bid, { scope: "market", dte: "0dte", moneyness: "otm", when: "tides", when_bit: 3, missing: "nan", description: "0DTE (expiring today), out of the money: put contracts sold at the bid" }); pane("volume", { title: "Net volume", height_frac: 0.16, format: "si" }); // One tide picked: its calls and its puts. Several: one net premium line per picked tide, in the tide's tier. output("ncp", line, lower, { color: "theme.up", width: 2, label: "Net call premium", format: "usd", hint: "Includes cross and late trades", description: "With one tide picked: its net call premium (money paid for calls) since the session opened, in dollars. The session opens at 09:30 New York on US stocks and 17:00 Chicago on CME. Empty with several tides picked or outside the session." }); output("npp", line, lower, { color: "theme.down", width: 2, label: "Net put premium", format: "usd", hint: "Includes cross and late trades", description: "With one tide picked: its net put premium (money paid for puts) since the session opened, in dollars." }); output("net_mkt", line, lower, { color: "theme.text", width: 2, label: "Whole market", format: "usd", hint: "Includes cross and late trades", description: "With several tides picked: the whole market's net call premium minus net put premium since the session opened, in dollars. Above zero calls lead, below zero puts lead." }); output("net_otm", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Whole market, out of the money", format: "usd", hint: "Includes cross and late trades", description: "With several tides picked: the same for out-of-the-money options, calls with a strike above the price and puts below it." }); output("net_zd", line, lower, { color: "theme.text", opacity: 0.32, width: 1, label: "0DTE", format: "usd", hint: "Includes cross and late trades", description: "With several tides picked: the same for 0DTE options, the ones that expire today." }); output("net_zd_otm", line, lower, { color: "theme.text", opacity: 0.32, width: 1, label: "0DTE, out of the money", format: "usd", hint: "Includes cross and late trades", description: "With several tides picked: the same for options that expire today and are out of the money." }); output("zero", line, lower, { color: "theme.muted", width: 1, line_style: "dashed", legend: false, description: "The zero line of the premium pane." }); // keeps zero inside the pane's scale output("net_volume", histogram, lower, { pane: "volume", color_by: "volume_tone", colors: ["theme.down", "theme.up"], width: 0.8, label: "Net volume", format: "si", description: "The first picked tide's net contracts since the session opened, in coins on crypto. That is calls bought at the ask minus sold at the bid, minus the same for puts. Above zero calls lead, below zero puts lead." }); // The readings, data-only: the card reads them and the Console can too. output("volume_tone", none, lower, { description: "The net volume's colour: 0 below zero, 1 at or above zero." }); output("lead_ncp", none, lower, { format: "usd", description: "The first picked tide's net call premium this session, in dollars. Empty before its first options data." }); output("lead_npp", none, lower, { format: "usd", description: "The first picked tide's net put premium this session, in dollars." }); output("net_premium", none, lower, { format: "usd", description: "The first picked tide's net call premium minus net put premium this session, in dollars. Above zero the tide leans bullish, below zero bearish. Includes cross and late trades." }); output("lead_volume", none, lower, { format: "si", description: "The first picked tide's net volume this session, in contracts or coins on crypto." }); output("bar_ncp", none, lower, { format: "usd", description: "This bar's net call premium for the first picked tide in dollars, empty on a bar with no options data." }); output("bar_npp", none, lower, { format: "usd", description: "This bar's net put premium for the first picked tide in dollars, empty on a bar with no options data." }); output("missing_bars", none, lower, { description: "Bars this session that the first picked tide sums but that had no options data. The tide sums regular-session bars, and every bar of the trading day on CME. Above 0, read the sums as at least what they show." }); output("tone", none, lower, { description: "The side that leads: 0 puts, 1 even or no reading, 2 calls." }); string("read", { max_bytes: 48 }); // the headline: which side leads the tide, or why there is no reading string("title", { max_bytes: 64 }); // the card's title: the first picked tide, and how many more // The card: the first picked tide's lean leads as the headline, then its two sums, their difference, its net volume // and the bars with no row, under the line that the sums include cross and late trades. render.hud("tide_card", { position: "top_right", safe_area: true, title: "{{title}}", columns: 2, tiles: [ tile.pill("Tide", "read", { headline: true }), tile.value("Net call premium", "lead_ncp", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Net put premium", "lead_npp", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Calls minus puts", "net_premium", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Net volume", "lead_volume", { format: "si" }), tile.rows("Includes cross and late trades", [["Bars with no options data", "missing_bars", "int"]]), ], }); const TIDES = 4; // the options of Tides, in its order const FIELDS = 6; // the fields read per tide const NAMES: StaticArray<string> = ["Whole market", "Whole market, out of the money", "0DTE", "0DTE, out of the money"]; const ncp = new StaticArray<f64>(TIDES); // this session's sums, per tide const npp = new StaticArray<f64>(TIDES); const vol = new StaticArray<f64>(TIDES); const rows = new StaticArray<i32>(TIDES); // summed bars of this session that carried a row const missing = new StaticArray<i32>(TIDES); // summed bars of this session without one const runRows = new StaticArray<i32>(TIDES); // summed rows over the whole run const cur = new StaticArray<f64>(FIELDS); // this bar's fields of one tide let picks = 0.0; // the Tides bitmask, read in onStart() let lead = -1; // the first picked tide, -1 with none let picked = 0; // how many tides are picked let day: f64 = NaN; // the trade date the sums run over let zone = 0; // the market's clock, read in onStart() function onStart(): void { picks = p_tides(); zone = i32(p_market_zone()); lead = -1; picked = 0; for (let t = 0; t < TIDES; t += 1) { if (!multiHas(picks, t)) continue; if (lead < 0) lead = t; picked += 1; } } // This bar's six fields of tide t into cur: the capped net call and net put premium, then the call and put contracts // at the ask and at the bid. function readTide(t: i32): void { if (t == 0) { cur[0] = in_mkt_ncp(); cur[1] = in_mkt_npp(); cur[2] = in_mkt_ca(); cur[3] = in_mkt_cb(); cur[4] = in_mkt_pa(); cur[5] = in_mkt_pb(); } else if (t == 1) { cur[0] = in_otm_ncp(); cur[1] = in_otm_npp(); cur[2] = in_otm_ca(); cur[3] = in_otm_cb(); cur[4] = in_otm_pa(); cur[5] = in_otm_pb(); } else if (t == 2) { cur[0] = in_zd_ncp(); cur[1] = in_zd_npp(); cur[2] = in_zd_ca(); cur[3] = in_zd_cb(); cur[4] = in_zd_pa(); cur[5] = in_zd_pb(); } else { cur[0] = in_zd_otm_ncp(); cur[1] = in_zd_otm_npp(); cur[2] = in_zd_otm_ca(); cur[3] = in_zd_otm_cb(); cur[4] = in_zd_otm_pa(); cur[5] = in_zd_otm_pb(); } } // Tide t's net premium line, drawn with several tides picked. function writeNet(t: i32, value: f64): void { if (t == 0) out_net_mkt(value); else if (t == 1) out_net_otm(value); else if (t == 2) out_net_zd(value); else out_net_zd_otm(value); } // The card's words, on the live bar. function writeWords(): void { sb_clear(); if (lead < 0) sb_text("Pick a tide"); else if (runRows[lead] == 0) sb_text("No options flow on this chart yet"); else if (rows[lead] == 0) sb_text("No options flow yet this session"); else if (ncp[lead] - npp[lead] > 0.0) sb_text("Calls lead the tide"); else if (ncp[lead] - npp[lead] < 0.0) sb_text("Puts lead the tide"); else sb_text("Calls and puts even"); str_read_sb(); sb_clear(); sb_text("Premium tide"); if (lead >= 0) { sb_text(", "); sb_text(NAMES[lead]); } if (picked > 1) { sb_text(" +"); sb_int(picked - 1); } str_title_sb(); } // onBar() runs once per bar: a new trade date starts every tide's sums again; on a bar the tide sums each picked // tide's row adds to its sums, or counts as missing; then the lines, the net volume, the readings and, on the live // bar, the words. A tide that is not picked is skipped even on a host that fetches its lane anyway. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; for (let t = 0; t < TIDES; t += 1) { ncp[t] = 0.0; npp[t] = 0.0; vol[t] = 0.0; rows[t] = 0; missing[t] = 0; } } // The bars the tide sums: the regular session (time.session 1), and on CME (zone 2) its whole trading day, from the // 17:00 Chicago open through the evening, the night and the hours after the regular window (1 to 3). const regular = zone == 2 ? in_session() >= 1.0 : in_session() == 1.0; let barNcp: f64 = NaN; let barNpp: f64 = NaN; for (let t = 0; t < TIDES; t += 1) { if (!multiHas(picks, t)) { writeNet(t, NaN); continue; } readTide(t); let served = true; for (let f = 0; f < FIELDS; f += 1) if (isNaN(cur[f])) served = false; if (regular) { if (served) { ncp[t] += cur[0]; npp[t] += cur[1]; vol[t] += cur[2] - cur[3] - (cur[4] - cur[5]); rows[t] += 1; runRows[t] += 1; } else missing[t] += 1; } if (t == lead && served) { barNcp = cur[0]; barNpp = cur[1]; } writeNet(t, picked > 1 && regular && rows[t] > 0 ? ncp[t] - npp[t] : NaN); } const reading = lead >= 0 && rows[lead] > 0; const drawn = reading && regular; const net = reading ? ncp[lead] - npp[lead] : NaN; out_ncp(drawn && picked == 1 ? ncp[lead] : NaN); out_npp(drawn && picked == 1 ? npp[lead] : NaN); out_zero(0.0); out_net_volume(drawn ? vol[lead] : NaN); out_volume_tone(drawn ? (vol[lead] >= 0.0 ? 1.0 : 0.0) : NaN); out_lead_ncp(reading ? ncp[lead] : NaN); out_lead_npp(reading ? npp[lead] : NaN); out_net_premium(net); out_lead_volume(reading ? vol[lead] : NaN); out_bar_ncp(barNcp); out_bar_npp(barNpp); out_missing_bars(lead >= 0 ? f64(missing[lead]) : NaN); out_tone(reading ? (net > 0.0 ? 2.0 : net < 0.0 ? 0.0 : 1.0) : 1.0); if (bar.isLast()) writeWords(); } ``` ## How it works **The tide.** Each bar's row carries the market's premium at the ask and at the bid, calls and puts apart, each print's premium capped at 2,000,000 (`net_call_prem_capped`, `net_put_prem_capped`). The net call premium rises when calls are bought at the ask and falls when they are sold at the bid; the net put premium does the same on puts. Prints at the mid or with no quote to side them count in neither; on crypto and CME every print carries the taker's side. The net volume is the same reading in contracts: calls bought at the ask minus sold at the bid, minus the puts' (`call_contracts_ask` and the rest). **The session.** The sums start again on each trade date (`time.trade_date`) and add only the session's bars: on a US stock the regular session (`time.session` reads `1`), so the tide runs from 09:30 to 16:00 New York. Index options trade before the open too, so the market serves rows on pre-market bars; the tide leaves them out and draws nothing there. On crypto every bar is in session and the trade date is the UTC day. On CME (`market.zone()` 2) the tide counts the whole trading day, from the 17:00 Chicago open through the evening, the night and the hours after the regular window (`time.session` reads `1` to `3`), because the exchange's options trade through all of it; the daily halt adds nothing. On a daily chart every bar is a whole session, so each bar is that day's tide. **Tides.** `tides` is a multi setting, one option per tide: the whole market (`scope: "market"`), its out-of-the-money contracts (`moneyness: "otm"`, a strike within 0.5% of the underlying counting as out), the contracts expiring on the print's own trade date (`dte: "0dte"`) and those out of the money. Every tide's six inputs carry `when: "tides"` and that option's `when_bit`, so the chart fetches a tide's rows only while it is picked; the code reads the same bits (`multiHas`), so a tide that is not picked draws nothing even on a host that fetched its lane anyway. One tide picked draws its calls and puts (`ncp`, `npp`); several draw one net line each (`net_mkt`, `net_otm`, `net_zd`, `net_zd_otm`) in the tide's tier of the text colour (the whole market at full strength and widest, its out-of-the-money tide fainter, the two same-day tides faintest and thinnest), and the net volume, the card and its readings follow the first one picked. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the line over the card's count of bars with no flow row, the hover of each tide's line and of the card's three premium values, and the description of `net_premium`. ## What the settings do - **Tides**: Picks what to sum, from the whole market to 0DTE (expiring today) options, and several picks draw one line each. - **Tide**: Names the side that leads the first picked tide this session, calls or puts. - **Net call premium**: Calls bought at the ask minus calls sold at the bid this session, in dollars. - **Net put premium**: Puts bought at the ask minus puts sold at the bid this session, in dollars. - **Calls minus puts**: Net call premium minus net put premium, where above zero leans bullish and below zero bearish. - **Net volume**: Net call contracts minus net put contracts this session, in coins on crypto. - **Bars with no options data**: Bars the tide sums this session without data, so above 0 read the sums as at least what they show. ## Where it runs It works on three kinds of charts. On a coin with listed options, the tide reads that coin's options on every crypto exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart, every indicator in your browser can read it. The same goes for the charts of that stock's option contracts. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). The tide reads the whole market, whatever symbol the chart shows. On a US stock that means every US listed option, so it fits well on SPY. On CME it means the whole exchange's options. US options data runs 15 minutes behind unless you have real-time US options data. CME data runs 10 minutes behind unless you have real-time CME data. The legend shows which delay you get. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. Daily charts keep every day. On an intraday chart, older sessions stay blank. Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read it. They say which data they lack. ## When data is missing The card says why instead of going blank. It reads "Pick a tide" while Tides has nothing picked. It reads "No options flow on this chart yet" while the first picked tide has no options data yet. It reads "No options flow yet this session" while the newest session has none. **Bars with no options data** counts the bars the first tide sums this session that had no data. On CME those are the whole trading day's bars. Above 0, read the sums as at least what they show. A tide with no options data draws no line. If the chart cannot load a data source, the legend shows a chip with the reason. ## Customize it - **The whole picture at once.** Pick all four tides: the market's net line, its out-of-the-money one and the same-day contracts' two, side by side. - **Another tide.** Change one tide's knobs: `scope: "index"` with `dte: "0dte"` reads the indices' same-day contracts, `dte: "week"` the contracts expiring in one to seven days. The equity and ETF scopes read empty until the data plane stamps each underlying's kind, and a crypto or CME chart serves no issue-type scope. A sheet reads at most 32 inputs, so a fifth tide of six inputs takes the place of one of the four. - **Uncapped premium.** Swap `net_call_prem_capped` and `net_put_prem_capped` for `net_call_prem` and `net_put_prem` to count every print's premium in full. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Premium Tide** under **Order flow**. 2. Press **Run** on a BTC chart or a US stock chart: the tide draws under the chart, the net volume below it and the card at the top right. On a US stock or a CME future the copy reads the market flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `lead_ncp`, `lead_npp` and `net_premium` to read the first tide's sums on the live bar, or `missing_bars` to see how many bars carried no row. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class, its fields and the `scope`, `dte` and `moneyness` knobs - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` and `time.session` - [The market's facts](../settings/sessions-and-units.md#the-markets-facts) for `market.zone()`, which counts CME's whole trading day - [Setting kinds](../settings/kinds.md) for `param.multi` and its bitmask - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the card, its pill and values - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/options-market-stats --> # Options market stats This shows if traders are buying more calls (bets on a rise) or puts (bets on a fall) today. On a stock chart it reads all US listed options, on a CME (Chicago futures exchange) future all CME options. On crypto it reads this coin's options on every exchange. Two lines show the put/call ratio (puts traded per call): above 1.0 puts lead, often fear or hedging. Use it to read the market's mood before trusting one chart's move. Under the hood: it sums the market's options trades bar by bar from `options_flow` read with `scope: "market"`. That is every US listed option on a US stock chart, and the exchange's whole market on CME. On crypto it is the coin on every venue, in coins. The Breakdown groups switch on by `when` and `when_bit` from a multi setting ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It restarts each trade date and counts regular-session bars with no data through `time.trade_date` and `time.session` ([Data sources](../core-concepts/data-sources.md#the-time-source)). It writes a `panel.table` on the live bar ([Frames and panels](../presentation/cards-frames-panels.md)). It also draws a `render.hud` card in the default look over data-only numbers and text ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)). It is the `options-market-stats` template: **Options Market Stats** under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Options Market Stats: are traders buying more calls or more puts today? Calls are bets on a rise, and puts are bets // on a fall or protection against one. On a US stock chart it reads every US listed option. On a CME (Chicago futures // exchange) future it reads all of CME's options. On crypto it reads this coin's options on every exchange. Two lines // under the chart show the put/call ratio (puts traded for each call). One counts contracts, the other premium (the // money paid for an option). Above the dashed line at 1.0, puts lead, often a sign of fear or hedging. Below it, calls // lead. A table adds the day's totals, and a card says which side leads. Use it to read the market's mood before you // trust a move on one chart. // // Under the hood: the whole market is every US listed underlying on a US stock chart, the chart's coin on every // crypto venue (sizes in coins), the CME exchange's market on a futures chart. Two lines under the chart read the // day's put/call ratios so far, by contracts and by premium (the put contracts over the call contracts, the put // premium over the call premium, every bar of the trade date summed), with a dashed line at 1.0 where puts match // calls; on a daily chart each bar is that day's ratio. A table under the chart reads the day for the whole market // and, picked in Breakdown, for equities, ETFs and indices alone (a US stock chart's issue types: never asked // elsewhere) and for the contracts expiring that day (0DTE): call and put contracts, their ratio, call and put // premium, its ratio and the prints. A card at the top right says which side leads by the contract ratio, then the // day's sums and the 0DTE share of the contracts. The equity and ETF rows need each underlying's kind, which the data // plane stamps from a daily reference list: until it does they read empty, and the table and a line at the top of the // chart say so. The rows come from options_flow's market scopes, one per bar: 1-minute rows reach back 7 days, // 5-minute rows 30 and daily rows are kept, so older intraday bars carry none; a regular-session bar without a row // adds nothing and is counted, the sums being a floor while that count is above 0. param.multi("breakdown", ["Equities", "ETFs", "Indices", "0DTE"], ["Equities", "ETFs", "Indices", "0DTE"], { label: "Breakdown", description: "Extra groups the table adds below the whole market. 0DTE means options that expire today. Each group is one more download, made only while it is picked." }); input("close", ohlcv.close); // the chart's own candles: the bar grid (the stats read the whole market of the chart's plane) input("trade_date", time.trade_date); // the bar's trade date (New York on a US stock, UTC on crypto): the sums start again on each input("session", time.session); // 1 in the regular session: the bars a missing row is counted on // Five fields per row of the table: every underlying always, the breakdown rows only while picked (when_bit is the // row's place in Breakdown). input("mkt_calls", options_flow.call_contracts_total, { scope: "market", missing: "nan", description: "Whole market: call contracts traded in this bar." }); input("mkt_puts", options_flow.put_contracts_total, { scope: "market", missing: "nan", description: "Whole market: put contracts traded in this bar." }); input("mkt_cprem", options_flow.call_prem_total, { scope: "market", missing: "nan", description: "Whole market: call premium (money paid for calls) in this bar, in dollars." }); input("mkt_pprem", options_flow.put_prem_total, { scope: "market", missing: "nan", description: "Whole market: put premium (money paid for puts) in this bar, in dollars." }); input("mkt_prints", options_flow.prints, { scope: "market", missing: "nan", description: "Whole market: option trades in this bar." }); input("eq_calls", options_flow.call_contracts_total, { scope: "equity", when: "breakdown", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Equities: call contracts traded in this bar." }); input("eq_puts", options_flow.put_contracts_total, { scope: "equity", when: "breakdown", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Equities: put contracts traded in this bar." }); input("eq_cprem", options_flow.call_prem_total, { scope: "equity", when: "breakdown", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Equities: call premium in this bar, in dollars." }); input("eq_pprem", options_flow.put_prem_total, { scope: "equity", when: "breakdown", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Equities: put premium in this bar, in dollars." }); input("eq_prints", options_flow.prints, { scope: "equity", when: "breakdown", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Equities: option trades in this bar." }); input("etf_calls", options_flow.call_contracts_total, { scope: "etf", when: "breakdown", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "ETFs: call contracts traded in this bar." }); input("etf_puts", options_flow.put_contracts_total, { scope: "etf", when: "breakdown", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "ETFs: put contracts traded in this bar." }); input("etf_cprem", options_flow.call_prem_total, { scope: "etf", when: "breakdown", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "ETFs: call premium in this bar, in dollars." }); input("etf_pprem", options_flow.put_prem_total, { scope: "etf", when: "breakdown", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "ETFs: put premium in this bar, in dollars." }); input("etf_prints", options_flow.prints, { scope: "etf", when: "breakdown", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "ETFs: option trades in this bar." }); input("idx_calls", options_flow.call_contracts_total, { scope: "index", when: "breakdown", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Indices: call contracts traded in this bar." }); input("idx_puts", options_flow.put_contracts_total, { scope: "index", when: "breakdown", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Indices: put contracts traded in this bar." }); input("idx_cprem", options_flow.call_prem_total, { scope: "index", when: "breakdown", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Indices: call premium in this bar, in dollars." }); input("idx_pprem", options_flow.put_prem_total, { scope: "index", when: "breakdown", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Indices: put premium in this bar, in dollars." }); input("idx_prints", options_flow.prints, { scope: "index", when: "breakdown", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Indices: option trades in this bar." }); input("zd_calls", options_flow.call_contracts_total, { scope: "market", dte: "0dte", when: "breakdown", when_bit: 3, missing: "nan", description: "0DTE (options that expire today): call contracts traded in this bar." }); input("zd_puts", options_flow.put_contracts_total, { scope: "market", dte: "0dte", when: "breakdown", when_bit: 3, missing: "nan", description: "0DTE: put contracts traded in this bar." }); input("zd_cprem", options_flow.call_prem_total, { scope: "market", dte: "0dte", when: "breakdown", when_bit: 3, missing: "nan", description: "0DTE: call premium in this bar, in dollars." }); input("zd_pprem", options_flow.put_prem_total, { scope: "market", dte: "0dte", when: "breakdown", when_bit: 3, missing: "nan", description: "0DTE: put premium in this bar, in dollars." }); input("zd_prints", options_flow.prints, { scope: "market", dte: "0dte", when: "breakdown", when_bit: 3, missing: "nan", description: "0DTE: option trades in this bar." }); market.zone(); // the market's clock: the issue-type rows are a US stock chart's (zone 1), the market row a crypto chart's coin on every venue (zone 0) output("pc_volume", line, lower, { color: "theme.text", width: 2, label: "Put/call, contracts", format: "0.00", description: "Today's put contracts divided by call contracts so far, whole market. Blank before today's first data." }); output("pc_premium", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Put/call, premium", format: "0.00", description: "Today's put premium divided by call premium so far, whole market." }); output("parity", line, lower, { color: "theme.muted", width: 1, line_style: "dashed", legend: false, description: "1.0: as many puts as calls" }); // The readings, data-only: the card reads them and the Console can too. output("calls_today", none, lower, { format: "si", description: "Call contracts traded today through this bar, whole market." }); output("puts_today", none, lower, { format: "si", description: "Put contracts traded today through this bar, whole market." }); output("call_premium_today", none, lower, { format: "usd", description: "Call premium traded today, whole market, in dollars." }); output("put_premium_today", none, lower, { format: "usd", description: "Put premium traded today, whole market, in dollars." }); output("prints_today", none, lower, { format: "si", description: "Option trades today, whole market." }); output("zero_dte_share", none, lower, { format: "%", decimals: 1, description: "Contracts that expire today as a percent of all contracts traded today. Blank while 0DTE is not picked." }); output("missing_bars", none, lower, { description: "Regular-session bars today with no whole-market data. While above 0, the sums are a lower bound." }); output("tone", none, lower, { description: "The side that leads: 0 puts lead, 1 even or no reading, 2 calls lead" }); string("read", { max_bytes: 48 }); // the headline: which side leads, or why there is no reading string("title", { max_bytes: 48 }); // the card's title: the day string("note", { max_bytes: 96 }); // the line at the top while a picked equity or ETF row has read nothing // The table, rewritten on the live bar: one row per underlying group, the day's sums. const stat_rows = frame("stat_rows", { max_bytes: 4096 }); panel.table({ name: "market_stats", title: "Options market today", x: "category", place: "below", frame: stat_rows, height_frac: 0.18, font_size: 10, cell_padding: 3, valign: "middle", header_text_color: "theme.muted", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", border_width: 0, series: [ { name: "Group" }, { name: "Calls", align: "right", format: "si" }, { name: "Puts", align: "right", format: "si" }, { name: "Put/call", align: "right", format: "0.00" }, { name: "Call premium", align: "right", format: "usd" }, { name: "Put premium", align: "right", format: "usd" }, { name: "Put/call, premium", align: "right", format: "0.00" }, { name: "Trades", align: "right", format: "si" }, ], }); // The card: which side leads by the contract ratio, then the day's sums. render.hud("market_card", { position: "top_right", safe_area: true, title: "{{title}}", columns: 2, tiles: [ tile.pill("Who leads", "read", { headline: true }), tile.value("Call contracts", "calls_today", { format: "si" }), tile.value("Put contracts", "puts_today", { format: "si" }), tile.rows([ ["Put/call, contracts", "pc_volume", "0.00"], ["Call premium", "call_premium_today", "usd"], ["Put premium", "put_premium_today", "usd"], ["Put/call, premium", "pc_premium", "0.00"], ["Trades", "prints_today", "si"], ["0DTE share", "zero_dte_share", "%"], ["Bars with no data", "missing_bars", "int"], ]), ], }); render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const GROUPS = 5; // every underlying, then the four Breakdown rows in its order const FIELDS = 5; // call and put contracts, call and put premium, prints const EVEN_BAND = 0.1; // a put/call ratio within 10% of 1 reads even const NAMES: StaticArray<string> = ["Whole market", "Equities", "ETFs", "Indices", "0DTE"]; // The rows that read each underlying's kind as the data plane stamps it: equities and ETFs. const KINDED: StaticArray<bool> = [false, true, true, false, false]; const MONTHS: StaticArray<string> = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const sums = new StaticArray<f64>(GROUPS * FIELDS); // today's sums, group by group const rows = new StaticArray<i32>(GROUPS); // today's bars that carried a row, per group const runRows = new StaticArray<i32>(GROUPS); // rows over the whole run, per group const cur = new StaticArray<f64>(FIELDS); // this bar's fields of one group const dateClock = new Clock("UTC"); // the trade date's day and month let breakdown = 0.0; // the Breakdown bitmask, read in onStart() let zone = 0; // the market's clock, read in onStart() let day: f64 = NaN; // today's trade date, epoch seconds let missing = 0; // regular-session bars of today without a row for every underlying function onStart(): void { breakdown = p_breakdown(); zone = i32(p_market_zone()); } // Whether group g is read: every underlying always, a breakdown row while picked, the issue-type rows (1 to 3) on a US // stock chart only (a host that fetches a lane anyway is not read). function readOn(g: i32): bool { return g == 0 || (multiHas(breakdown, g - 1) && (zone == 1 || g == 4)); } // This bar's five fields of group g into cur. function readGroup(g: i32): void { if (g == 0) { cur[0] = in_mkt_calls(); cur[1] = in_mkt_puts(); cur[2] = in_mkt_cprem(); cur[3] = in_mkt_pprem(); cur[4] = in_mkt_prints(); } else if (g == 1) { cur[0] = in_eq_calls(); cur[1] = in_eq_puts(); cur[2] = in_eq_cprem(); cur[3] = in_eq_pprem(); cur[4] = in_eq_prints(); } else if (g == 2) { cur[0] = in_etf_calls(); cur[1] = in_etf_puts(); cur[2] = in_etf_cprem(); cur[3] = in_etf_pprem(); cur[4] = in_etf_prints(); } else if (g == 3) { cur[0] = in_idx_calls(); cur[1] = in_idx_puts(); cur[2] = in_idx_cprem(); cur[3] = in_idx_pprem(); cur[4] = in_idx_prints(); } else if (g == 4) { cur[0] = in_zd_calls(); cur[1] = in_zd_puts(); cur[2] = in_zd_cprem(); cur[3] = in_zd_pprem(); cur[4] = in_zd_prints(); } } function ratio(top: f64, bottom: f64): f64 { return bottom > 0.0 ? top / bottom : NaN; } // A ratio cell: two decimals, or an empty cell when there is no ratio (no call or no call premium). function fbRatio(value: f64): void { if (isNaN(value)) fb_text('""'); else fb_f64(value, 2); } // The table on the live bar: every underlying, then each picked breakdown row. A row without a row today says why in // its first value cell: the equity and ETF rows wait for the data plane's issue types while they never read one. function writeTable(): void { fb_clear(); fb_text('{"rows":['); let written = 0; for (let g = 0; g < GROUPS; g += 1) { if (!readOn(g)) continue; if (written > 0) fb_text(","); written += 1; fb_text("["); fb_str(g == 0 && zone == 0 ? "Every venue" : NAMES[g]); // on crypto the market is the chart's coin on every venue if (rows[g] == 0) { fb_text(',{"text":'); fb_str(KINDED[g] && runRows[g] == 0 ? "waits for symbol types" : "no data today"); fb_text(',"text_color":"theme.muted"},"","","","","",""]'); continue; } const at = g * FIELDS; fb_text(","); fb_f64(sums[at], 0); fb_text(","); fb_f64(sums[at + 1], 0); fb_text(","); fbRatio(ratio(sums[at + 1], sums[at])); fb_text(","); fb_f64(sums[at + 2], 0); fb_text(","); fb_f64(sums[at + 3], 0); fb_text(","); fbRatio(ratio(sums[at + 3], sums[at + 2])); fb_text(","); fb_f64(sums[at + 4], 0); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_STAT_ROWS); } // The card's words and the line at the top, on the live bar. function writeWords(pcVolume: f64): void { sb_clear(); if (runRows[0] == 0) sb_text("No options flow on this chart yet"); else if (rows[0] == 0) sb_text("No options flow yet today"); else if (isNaN(pcVolume)) sb_text("Puts only: no call traded yet"); else { sb_text(Math.abs(pcVolume - 1.0) <= EVEN_BAND ? "Even: put/call " : pcVolume < 1.0 ? "Calls lead: put/call " : "Puts lead: put/call "); sb_f64(pcVolume, 2); } str_read_sb(); sb_clear(); sb_text("Options market"); if (!isNaN(day)) { dateClock.update(day); // the trade date is its date at 00:00 UTC sb_text(", "); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } str_title_sb(); let waiting = false; // a picked equity or ETF row that read nothing in the whole run for (let g = 0; g < GROUPS; g += 1) if (KINDED[g] && readOn(g) && runRows[g] == 0) waiting = true; str_note(waiting ? "Equity and ETF totals stay empty until each symbol's type (stock or ETF) is known" : ""); // an empty text draws no label } // onBar() runs once per bar: a new trade date starts today's sums again; every read group's row joins its sums (a // regular-session bar without a row for every underlying counts as missing); then the ratio lines, the readings and, // on the live bar, the table and the words. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; for (let i = 0; i < GROUPS * FIELDS; i += 1) sums[i] = 0.0; for (let g = 0; g < GROUPS; g += 1) rows[g] = 0; missing = 0; } for (let g = 0; g < GROUPS; g += 1) { if (!readOn(g)) continue; readGroup(g); let served = true; for (let f = 0; f < FIELDS; f += 1) if (isNaN(cur[f])) served = false; if (!served) { if (g == 0 && in_session() == 1.0) missing += 1; continue; } for (let f = 0; f < FIELDS; f += 1) sums[g * FIELDS + f] += cur[f]; rows[g] += 1; runRows[g] += 1; } const reading = rows[0] > 0; const calls = sums[0]; const puts = sums[1]; const pcVolume = reading ? ratio(puts, calls) : NaN; out_pc_volume(pcVolume); out_pc_premium(reading ? ratio(sums[3], sums[2]) : NaN); out_parity(1.0); out_calls_today(reading ? calls : NaN); out_puts_today(reading ? puts : NaN); out_call_premium_today(reading ? sums[2] : NaN); out_put_premium_today(reading ? sums[3] : NaN); out_prints_today(reading ? sums[4] : NaN); const zeroDte = readOn(4) && reading && rows[4] > 0 ? ratio(sums[4 * FIELDS] + sums[4 * FIELDS + 1], calls + puts) : NaN; out_zero_dte_share(isNaN(zeroDte) ? NaN : zeroDte * 100.0); out_missing_bars(f64(missing)); out_tone(!reading ? 1.0 : isNaN(pcVolume) ? 0.0 : Math.abs(pcVolume - 1.0) <= EVEN_BAND ? 1.0 : pcVolume < 1.0 ? 2.0 : 0.0); // no call traded: the puts lead if (!bar.isLast()) return; writeTable(); writeWords(pcVolume); } ``` ## How it works **The day's sums.** Each bar's row carries the market's call and put contracts, call and put premium and prints (`call_contracts_total`, `put_contracts_total`, `call_prem_total`, `put_prem_total`, `prints`). The sums start again on each trade date (`time.trade_date`) and add every bar of the date, the pre-market included, since the market trades there too. The ratios on each bar are the sums' so far: put contracts over call contracts (`pc_volume`) and put premium over call premium (`pc_premium`). A day without a call has no ratio: the line breaks and the card says puts only. **Who leads.** The headline reads the contract ratio: within 10% of 1 is even, under it the calls lead and over it the puts lead. The 0DTE share is the same-day contracts (`dte: "0dte"`) over every contract of the day. **Breakdown.** `breakdown` is a multi setting, one option per extra row of the table. Every row's five inputs carry `when: "breakdown"` and that option's `when_bit`, so the chart fetches a row's rows only while it is picked; the code reads the same bits (`multiHas`), so a row that is not picked is neither read nor listed, even on a host that fetched its lane anyway. **The kind of each underlying.** The equity, ETF and index rows read `scope: "equity"`, `"etf"` and `"index"`, which sum the rows of the underlyings of that kind. The data plane stamps each underlying's kind from a daily reference list; until it does, the equity and ETF rows read nothing, so the table says "waits for symbol types" in their place and a line at the top of the chart says so. An index root is also stamped by its own chain, so the index row reads rows without the list. The kinds are a US stock chart's: the fifteen issue-type inputs carry `needed_by: { size_unit: [2, 3] }` (the shares and contracts markets, so a US stock and its option contracts' charts), and the code reads them on the New York zone only (`market.zone()` 1), so a crypto chart never asks for them and a CME chart lists neither them nor the line about issue types. On a crypto chart the market row is named "Every venue": the chart's coin on every crypto venue. ## What the settings do - **Breakdown**: extra groups the table adds below the whole market: Equities, ETFs, Indices and 0DTE (options that expire today). Each picked group costs one more download. - **Who leads**: which side leads by the contract put/call ratio, with the ratio itself. - **Call contracts**: call contracts traded today across the market it reads. - **Put contracts**: put contracts traded today across the market it reads. - **Put/call, contracts**: today's put contracts divided by call contracts, above 1 when puts lead. - **Call premium**: the money paid for calls today. - **Put premium**: the money paid for puts today. - **Put/call, premium**: today's put premium divided by call premium. - **Trades**: how many option trades went through today. - **0DTE share**: the share of today's contracts that expire today. - **Bars with no data**: regular-session bars today without market data, so the sums are at least what they show. ## Where it runs On a coin with listed options it reads that coin's options on every crypto exchange, sized in coins. So does a copy you run from the editor (where you write and run your own indicators). On a US stock or ETF chart, or one of its option charts, every browser indicator can read it. It runs 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), every browser indicator can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). It runs 10 minutes behind unless you have real-time CME data. On US stock and CME charts it reads the whole market, whatever the chart's own symbol is. The equity, ETF and index groups appear on US stock charts only. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. Daily data is kept, so a daily chart reads the ratios back to the first stored day. Alerts and Protected indicators (published so they run on OpenMarket's servers with their code hidden) cannot read this data. They say so by name. ## When data is missing The card says why instead of going blank. It reads "No options flow on this chart yet" while no bar has market data. It reads "No options flow yet today" while today has none. The card's **Bars with no data** line counts today's regular-session bars without market data. Above 0, read the sums as at least what they show. In the table a group with nothing today says "no data today". The equity and ETF groups say "waits for symbol types" until each symbol is tagged a stock or an ETF. On a crypto or CME chart the table lists the **Whole market** group and 0DTE alone. A data source the chart cannot read shows its own chip on the legend, with the reason. ## Customize it - **Out of the money only.** Add `moneyness: "otm"` to every input to read the contracts whose strike is past the underlying; each new set of knobs is one more read. - **The next seven days.** Change the 0DTE row's `dte: "0dte"` to `dte: "week"` for the contracts expiring in one to seven days. - **A leaner chart.** Untick every option of Breakdown: the table keeps its whole-market group and the chart downloads one data source. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options Market Stats** under **Order flow**. 2. Press **Run** on a BTC chart: the copy reads BTC's options on every crypto venue and draws the two ratios under the chart, the table below it and the card at the top right. On a US stock chart the copy draws them too, at your own tier (real time on a real-time US options account, else delayed 15 minutes), as the official package does. 3. At the editor's Console prompt, type `pc_volume`, `pc_premium` and `zero_dte_share` to read the day on the live bar, or `missing_bars` to see how many bars carried no row. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class, its fields and the `scope` and `dte` knobs - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` and `time.session` - [Setting kinds](../settings/kinds.md) for `param.multi` and its bitmask - [Frames and panels](../presentation/cards-frames-panels.md) for the table and its frame - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card, its pill and rows - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/net-flow --> # Net flow Two lines under the chart sum the premium (money paid for options) in this symbol's options each session. The up-colour line is calls (bets on a rise) and the down-colour line is puts (bets on a fall). Each line is net: bought at the ask (the seller's price) minus sold at the bid (the buyer's price). Rising calls or falling puts lean bullish, the reverse bearish, and the card at the top right names the leader. Use it to see which way options traders bet today, on crypto, CME (Chicago futures exchange) or US stock charts. Under the hood: the recipe reads the `options_flow` net premium and contract fields with `missing: "nan"`. It reads this symbol by default, and `scope: "market"` behind the Whole market setting ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It takes the trade date and session from the `time` source ([Data sources](../core-concepts/data-sources.md#the-time-source)). It draws a `render.hud` card in the chart's default look from data-only readings and two `string` texts ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `net-flow` template, the **Net Flow** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Net Flow: two lines under the chart sum the premium (money paid for options) in this symbol's options each session. // The up-colour line is calls (bets on a rise) and the down-colour line is puts (bets on a fall). Each line is net: // bought at the ask (the seller's price) minus sold at the bid (the buyer's price). Rising calls or falling puts lean // bullish, the reverse bearish, and the card at the top right names the leader. Use it to see which way options traders // bet today, on crypto, CME (Chicago futures exchange) or US stock charts. // // Technical notes: the net call premium is the call premium bought at the ask minus the call premium sold at the bid; // the net put premium is the same on puts. Both run from the session's first bar (each trade date starts again). Prints // at the mid or with no quote count in neither line (on crypto and CME each print has the taker's side). The Whole // market setting draws the same two lines over the whole market instead (every US listed underlying, the coin on every // crypto venue or CME's market: a second read, fetched only while it is on), and Cap each trade counts each print's // premium up to 2,000,000, so one block cannot swamp a session. The card reads the session: which side the flow leans // to (bullish: calls bought and puts sold; bearish: puts bought and calls sold), the two sums, their difference and the // net contracts (coins on crypto), bought at the ask minus sold at the bid, calls minus puts. The rows come from // options_flow, one per bar: 1-minute rows reach back 7 days and 5-minute rows 30 days, so older bars carry none. A bar // without a row adds nothing, and the card counts the regular-session bars that had none: while that count is above 0 // the sums are a floor. Every print takes a side, cross trades and late prints too: the card says so above that count, // and the lines' and sums' hover too. section("What it counts"); param.bool("market", false, { label: "Whole market", description: "Draws the whole options market instead: all US options, the coin on every crypto exchange, or all CME options. It loads that extra data only while this is on." }); param.bool("capped", false, { label: "Cap each trade", description: "Counts at most $2,000,000 of premium (money paid for options) per trade, so one huge trade cannot swamp the session." }); input("close", ohlcv.close); // the chart's own candles: the bar grid input("trade_date", time.trade_date); // the bar's trade date, the New York date on a US stock: the sums start again on each input("session", time.session); // 1 in the regular session: the bars a missing row is counted on input("call_net", options_flow.net_call_prem, { missing: "nan", description: "This bar's net call premium (money paid for calls) in dollars: bought at the ask minus sold at the bid." }); // NaN on a bar the class serves no row for input("put_net", options_flow.net_put_prem, { missing: "nan", description: "This bar's net put premium (money paid for puts) in dollars: bought at the ask minus sold at the bid." }); input("call_net_capped", options_flow.net_call_prem_capped, { missing: "nan", description: "This bar's net call premium with each trade capped at $2,000,000." }); input("put_net_capped", options_flow.net_put_prem_capped, { missing: "nan", description: "This bar's net put premium with each trade capped at $2,000,000." }); input("call_ask", options_flow.call_contracts_ask, { missing: "nan", description: "Call contracts bought at the ask (the seller's price) in this bar." }); input("call_bid", options_flow.call_contracts_bid, { missing: "nan", description: "Call contracts sold at the bid (the buyer's price) in this bar." }); input("put_ask", options_flow.put_contracts_ask, { missing: "nan", description: "Put contracts bought at the ask in this bar." }); input("put_bid", options_flow.put_contracts_bid, { missing: "nan", description: "Put contracts sold at the bid in this bar." }); // The whole market's rows, the same fields under scope "market": fetched only while Whole market is on. input("mkt_call_net", options_flow.net_call_prem, { scope: "market", when: "market", missing: "nan", description: "The whole market's net call premium in dollars, on crypto the coin on every exchange." }); input("mkt_put_net", options_flow.net_put_prem, { scope: "market", when: "market", missing: "nan", description: "The whole market's net put premium in dollars, on crypto the coin on every exchange." }); input("mkt_call_net_capped", options_flow.net_call_prem_capped, { scope: "market", when: "market", missing: "nan", description: "The whole market's net call premium, each trade capped at $2,000,000." }); input("mkt_put_net_capped", options_flow.net_put_prem_capped, { scope: "market", when: "market", missing: "nan", description: "The whole market's net put premium, each trade capped at $2,000,000." }); input("mkt_call_ask", options_flow.call_contracts_ask, { scope: "market", when: "market", missing: "nan", description: "The whole market's call contracts bought at the ask." }); input("mkt_call_bid", options_flow.call_contracts_bid, { scope: "market", when: "market", missing: "nan", description: "The whole market's call contracts sold at the bid." }); input("mkt_put_ask", options_flow.put_contracts_ask, { scope: "market", when: "market", missing: "nan", description: "The whole market's put contracts bought at the ask." }); input("mkt_put_bid", options_flow.put_contracts_bid, { scope: "market", when: "market", missing: "nan", description: "The whole market's put contracts sold at the bid." }); market.zone(); // the market's clock: on crypto (zone 0) the whole market is the coin on every venue output("ncp", line, lower, { color: "theme.up", width: 2, label: "Net call premium", format: "usd", hint: "Includes cross and late trades", description: "Net call premium since the session opened, in dollars: money paid for calls (bets on a rise). Calls bought at the ask lift it, and calls sold at the bid lower it. Empty until the session's first options data." }); output("npp", line, lower, { color: "theme.down", width: 2, label: "Net put premium", format: "usd", hint: "Includes cross and late trades", description: "Net put premium since the session opened, in dollars: money paid for puts (bets on a fall). Puts bought at the ask lift it, and puts sold at the bid lower it." }); output("zero", line, lower, { color: "theme.muted", width: 1, line_style: "dashed", legend: false, description: "The zero line: above it more premium was bought than sold, below it more was sold." }); // keeps zero inside the pane's scale // The readings, data-only: the card reads them and the Console can too. output("net_premium", none, lower, { description: "Net call premium minus net put premium this session, in dollars. Above zero the flow leans bullish, below zero bearish. Includes cross and late trades." }); output("net_contracts", none, lower, { description: "Contracts bought at the ask minus sold at the bid this session, calls minus puts, in coins on crypto." }); output("bar_call_net", none, lower, { description: "This bar's net call premium in dollars, empty on a bar with no options data." }); output("bar_put_net", none, lower, { description: "This bar's net put premium in dollars, empty on a bar with no options data." }); output("missing_bars", none, lower, { description: "Regular-session bars this session with no options data. Above 0, read the sums as at least what they show." }); output("tone", none, lower, { description: "The session's lean: 0 bearish, 1 even or no reading, 2 bullish." }); string("read", { max_bytes: 48 }); // the headline: the session's lean, or why there is no reading string("title", { max_bytes: 48 }); // the card's title: the scope and the cap // The card: the session's lean leads as the headline, then the two sums, their difference, the net contracts and the // bars with no flow row, under the line that the sums include cross and late trades. render.hud("flow_card", { position: "top_right", safe_area: true, title: "{{title}}", columns: 2, tiles: [ tile.pill("Session", "read", { headline: true }), tile.value("Net call premium", "ncp", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Net put premium", "npp", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Calls minus puts", "net_premium", { format: "usd", hint: "Includes cross and late trades" }), tile.value("Net contracts", "net_contracts", { format: "si" }), tile.rows("Includes cross and late trades", [["Bars with no options data", "missing_bars", "int"]]), ], }); let wholeMarket = false; // settings, read in onStart() let capped = false; let zone = 0; // the market's clock, read in onStart() let day: f64 = NaN; // the trade date the sums run over let ncp = 0.0; // the session's sums let npp = 0.0; let netContracts = 0.0; let rows = 0; // bars of this session that carried a flow row let missing = 0; // regular-session bars of this session without one let runRows = 0; // flow rows over the whole run function onStart(): void { wholeMarket = pb_market(); capped = pb_capped(); zone = i32(p_market_zone()); } // The card's words, on the live bar. function writeCard(net: f64): void { sb_clear(); if (runRows == 0) sb_text("No options flow on this chart yet"); else if (rows == 0) sb_text("No options flow yet this session"); else if (net > 0.0) sb_text("Bullish flow leads"); else if (net < 0.0) sb_text("Bearish flow leads"); else sb_text("Calls and puts even"); str_read_sb(); sb_clear(); sb_text(!wholeMarket ? "Net flow, this symbol" : zone == 0 ? "Net flow, every exchange" : "Net flow, whole market"); if (capped) sb_text(", capped"); str_title_sb(); } // onBar() runs once per bar: a new trade date starts the sums again; this bar's row, from the scope the settings // pick, adds to them, or counts as missing on a regular-session bar; then the lines, the readings and, on the live // bar, the card's words. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; ncp = 0.0; npp = 0.0; netContracts = 0.0; rows = 0; missing = 0; } // The market inputs read NaN while Whole market is off: their lane is never fetched. const callNet = wholeMarket ? (capped ? in_mkt_call_net_capped() : in_mkt_call_net()) : capped ? in_call_net_capped() : in_call_net(); const putNet = wholeMarket ? (capped ? in_mkt_put_net_capped() : in_mkt_put_net()) : capped ? in_put_net_capped() : in_put_net(); const served = !isNaN(callNet) && !isNaN(putNet); if (served) { ncp += callNet; npp += putNet; rows += 1; runRows += 1; const contracts = wholeMarket ? in_mkt_call_ask() - in_mkt_call_bid() - (in_mkt_put_ask() - in_mkt_put_bid()) : in_call_ask() - in_call_bid() - (in_put_ask() - in_put_bid()); if (!isNaN(contracts)) netContracts += contracts; } else if (in_session() == 1.0) missing += 1; const reading = rows > 0; const net = ncp - npp; out_ncp(reading ? ncp : NaN); out_npp(reading ? npp : NaN); out_zero(0.0); out_net_premium(reading ? net : NaN); out_net_contracts(reading ? netContracts : NaN); out_bar_call_net(served ? callNet : NaN); out_bar_put_net(served ? putNet : NaN); out_missing_bars(f64(missing)); out_tone(reading ? (net > 0.0 ? 2.0 : net < 0.0 ? 0.0 : 1.0) : 1.0); if (bar.isLast()) writeCard(net); } ``` ## How it works **One row a bar.** `options_flow` serves one row of sums per bar: the premium and the contracts of every print, split by where the print traded against the quote (at the ask, at the bid, at the mid, or with no quote to side it) and by calls and puts. `net_call_prem` is the call premium at the ask minus the call premium at the bid, and `net_put_prem` the same on puts, so a print at the mid or with no quote counts in neither. On crypto and CME every print carries the taker's side: bought at the ask or sold at the bid. A bar the class serves no row for reads `NaN`, because every input declares `missing: "nan"`: the package can tell a bar with no row from a bar whose flow summed to zero. **Sums by session.** `time.trade_date` changes on the first bar of each trade date on the market's clock (the New York date on a US stock, the UTC day on crypto, the CME trade date that opens at 17:00 Chicago), and the sums start again there: the call line is the net call premium since the session's first bar, the put line the net put premium. A bar without a row adds nothing. On a regular-session bar (`time.session` reads `1`) it also counts in `missing_bars`, and the card prints that count: while it is above 0 the sums are a floor, the flow of those bars being unknown. A pre-market bar without a row counts as nothing. **The lean and the contracts.** `net_premium` is the net call premium minus the net put premium: bullish flow (calls bought, puts sold) above zero and bearish flow (puts bought, calls sold) below. The card leads with it in words, Bullish flow leads or Bearish flow leads. `net_contracts` is the same idea in contracts (coins on a crypto chain): calls bought at the ask minus sold at the bid, minus the puts'. **The market's lines.** Whole market reads the same fields under `scope: "market"`: every US listed underlying at once on a US stock, the chart's coin on every crypto venue on crypto (the card's title then reads "Net flow, every venue"), the exchange's market on CME. Those inputs carry `when: "market"`, so the chart fetches their rows only while the setting is on; off, they read their fill (`NaN`) and the package draws the chart's own underlying. **Cap each trade** reads the `_capped` twins, where each print's premium counts up to 2,000,000. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the line over the card's count of bars with no flow row, the hover of the two lines and of the card's three premium values, and the description of `net_premium`. ## What the settings do - **Whole market**: Draws the whole options market instead: all US options, the coin on every crypto exchange, or all CME options. - **Cap each trade**: Counts at most $2,000,000 of premium per trade, so one huge trade cannot swamp the session. - **Session**: Names the side that leads this session, bullish when calls are bought or puts sold, bearish the reverse. - **Net call premium**: Calls bought at the ask minus calls sold at the bid this session, in dollars. - **Net put premium**: Puts bought at the ask minus puts sold at the bid this session, in dollars. - **Calls minus puts**: Net call premium minus net put premium, where above zero leans bullish and below zero bearish. - **Net contracts**: Net call contracts minus net put contracts this session, in coins on crypto. - **Bars with no options data**: Regular-session bars this session without data, so above 0 read the sums as at least what they show. ## Where it runs It works on three kinds of charts. On a coin with listed options, it reads that coin's own options on its exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read it. The same goes for the charts of that stock's option contracts. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data runs 15 minutes behind unless you have real-time US options data. CME data runs 10 minutes behind unless you have real-time CME data. The legend shows which delay you get. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. On a 1-minute chart, older sessions stay blank. Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read it. They say which data they lack. ## When data is missing The card says why instead of going blank. It reads "No options flow on this chart yet" while no bar on the chart has options data. It reads "No options flow yet this session" while the newest session has none. The lines stay empty until that session's first options data. **Bars with no options data** counts this session's regular-session bars without data. Above 0, read the sums as at least what they show. If the chart cannot load a data source, the legend shows a chip with the reason. ## Customize it - **The market's tide.** Turn on Whole market to read the whole market (every US listed underlying, or the coin on every crypto venue), the call and put lines then summing its sided premium. - **Blocks capped.** Turn on Cap each trade when a single block trade would otherwise decide the session. - **0DTE only.** Add `dte: "0dte"` to the inputs to read the contracts expiring on the print's own trade date, or `moneyness: "otm"` for the out-of-the-money contracts; each new set of knobs is one more read. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Net Flow** under **Order flow**. 2. Press **Run** on a BTC chart or a US stock chart: the two lines draw under the chart and the card at the top right. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `ncp`, `npp` and `net_premium` to read the session's sums on the live bar, or `missing_bars` to see how many bars carried no row. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class, its fields and the `scope`, `dte` and `moneyness` knobs - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` and `time.session` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the card, its pill and values - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/flow-vwap --> # Flow VWAP The line on the candles is a VWAP (the average price weighted by what traded there). Here the weight is premium (the money paid for an option), not volume, by default from buyers who paid up. Price above the line trades above where that money went in, and price below trades under it. The 1σ and 2σ bands (one and two standard deviations) show how far price has stretched from the line. Use it to see where options buyers committed money, on crypto, CME (Chicago futures exchange) futures or US stock charts. Under the hood: the recipe reads `options_flow` premium fields with `missing: "nan"` on the symbol a setting names (`underlying: "@chain"`, [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). A second set with `dte: "0dte"` is fetched only while a setting is on (`when`). The trade date and session come from the `time` source ([Data sources](../core-concepts/data-sources.md#the-time-source)). It draws five lines and two shaded bands on price ([Plotting](../presentation/plotting.md#ranges-and-panels)) and a `render.hud` card from data-only readings and two `string` texts ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)). It is also the `flow-vwap` template, the **Flow VWAP** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Flow VWAP: the line on the candles is a VWAP (the average price weighted by what traded there). Here the weight is // premium (the money paid for an option), not volume, by default from buyers who paid up. Price above the line trades // above where that money went in, and price below trades under it. The 1σ and 2σ bands (one and two standard // deviations) show how far price has stretched from the line. Use it to see where options buyers committed money, on // crypto, CME (Chicago futures exchange) futures or US stock charts. // // Technical notes: the chart's price is weighted by aggressive options premium, summed from the anchor, with bands one // and two premium-weighted standard deviations either side. Each bar's price (HLC3 by default: the high, the low and // the close over 3) counts as much as the bar's options premium, by default the premium bought at the ask on calls and // puts: the buyers who paid up. The premium is the options_flow row of the chain the Options chain setting picks, and // the price is always the chart's own: on an NQ chart with the chain set to QQQ, QQQ's premium weighs NQ's bars, with // no ratio between the two. From the anchor's first bar (each trade date under Session, the first trade date of each // week under Week) the line is the sum of price x premium over the sum of premium. The bands sit one and two // premium-weighted standard deviations of those prices from the line, lightly shaded. The sums run as a weighted // Welford update (the mean, and the premium-weighted sum of squared gaps from it, whose ratio to the premium is the // variance), so a price near 25,000 keeps its precision. A bar without a flow row, or with no premium, adds nothing: // the lines keep their last value, and they read NaN until the anchor's first bar with premium. The rows come from // options_flow, one per bar: 1-minute rows reach back 7 days and 5-minute rows 30 days, so older bars carry none. A // card at the top right reads where the close sits against the line, in standard deviations, then the premium since the // anchor, one standard deviation in price and the regular-session bars since the anchor that carried no flow row. Every // print takes a side, cross trades and late prints too: the premium's hover says so. section("Which premium"); param.choice("chain", ["Chart's own", "Index or ETF this future tracks", "QQQ", "NDX", "SPY", "SPX"], "Chart's own", { label: "Options chain", style_values: ["auto", "derived", "QQQ", "NDX", "SPY", "SPX"], description: "Whose options premium (money paid for options) weighs each bar's price. Chart's own uses this symbol's options. Index or ETF this future tracks uses NDX on NQ and SPX on ES. Or pick QQQ, NDX, SPY or SPX by name. The price always stays the chart's own." }); param.choice("weight", ["Bought at the ask", "Ask and bid", "All premium"], "Bought at the ask", { label: "Premium", description: "Which premium weighs each bar. Bought at the ask counts buyers who paid the seller's price. Ask and bid adds sellers who took the buyer's price. All premium counts every trade, at the mid and with no quote too." }); param.choice("types", ["Calls and puts", "Calls", "Puts"], "Calls and puts", { label: "Contracts", description: "Whose premium counts: calls (bets on a rise) and puts (bets on a fall), calls alone or puts alone." }); param.bool("zero_dte", false, { label: "0DTE only", description: "Weighs each bar by the premium of options that expire today (0DTE) only. It loads that extra data only while this is on." }); section("Anchor"); param.choice("anchor", ["Session", "Week"], "Session", { label: "Anchor", description: "Where the line starts again: each session, or the first session of each week, which is Monday's." }); section("Price"); param.choice("price", ["HLC3", "Close", "HL2"], "HLC3", { label: "Price", description: "Each bar's price, the one the premium weighs. HLC3 averages the high, low and close. Close takes the close, and HL2 averages the high and low." }); section("Bands"); param.bool("band1", true, { label: "1σ band", description: "Lines one premium-weighted standard deviation (1σ) above and below the Flow VWAP, lightly shaded." }); param.bool("band2", true, { label: "2σ band", description: "Lines two premium-weighted standard deviations (2σ) above and below the Flow VWAP, shaded fainter." }); input("close", ohlcv.close); // the chart's own candles: the bar grid and the price the premium weighs input("high", ohlcv.high); input("low", ohlcv.low); input("trade_date", time.trade_date); // the bar's trade date: Session starts the sums again on each, Week on each week's first input("session", time.session); // 1 in the regular session: the bars a missing row is counted on // Each bar's premium in the chain the Options chain setting picks ("@chain": the chart reads the picked choice's word). input("call_ask", options_flow.call_prem_ask, { underlying: "@chain", missing: "nan", description: "Call premium bought at the ask in this bar, in dollars." }); // NaN on a bar the class serves no row for input("put_ask", options_flow.put_prem_ask, { underlying: "@chain", missing: "nan", description: "Put premium bought at the ask in this bar, in dollars." }); input("call_bid", options_flow.call_prem_bid, { underlying: "@chain", missing: "nan", description: "Call premium sold at the bid in this bar, in dollars." }); input("put_bid", options_flow.put_prem_bid, { underlying: "@chain", missing: "nan", description: "Put premium sold at the bid in this bar, in dollars." }); input("call_total", options_flow.call_prem_total, { underlying: "@chain", missing: "nan", description: "Call premium of every trade in this bar in dollars, whatever its side." }); input("put_total", options_flow.put_prem_total, { underlying: "@chain", missing: "nan", description: "Put premium of every trade in this bar in dollars, whatever its side." }); // The same six over the contracts expiring that day: fetched only while 0DTE only is on. input("zd_call_ask", options_flow.call_prem_ask, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): call premium bought at the ask in this bar, in dollars." }); input("zd_put_ask", options_flow.put_prem_ask, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): put premium bought at the ask in this bar, in dollars." }); input("zd_call_bid", options_flow.call_prem_bid, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): call premium sold at the bid in this bar, in dollars." }); input("zd_put_bid", options_flow.put_prem_bid, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): put premium sold at the bid in this bar, in dollars." }); input("zd_call_total", options_flow.call_prem_total, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): call premium of every trade in this bar, in dollars." }); input("zd_put_total", options_flow.put_prem_total, { underlying: "@chain", dte: "0dte", when: "zero_dte", missing: "nan", description: "0DTE (expiring today): put premium of every trade in this bar, in dollars." }); output("fvwap", line, overlay, { color: "theme.text", width: 2, format: "price", label: "Flow VWAP", axis_label: true, description: "The price weighted by options premium (money paid for options) since the anchor. It is the sum of price times premium over the sum of premium. Empty until the anchor's first bar with premium." }); // first output on price: the package homes on the chart output("up1", line, overlay, { color: "theme.muted", width: 1, line_style: "dotted", format: "price", label: "Flow VWAP +1σ", description: "The Flow VWAP plus one premium-weighted standard deviation (1σ) of the prices since the anchor. Empty while 1σ band is off." }); output("lo1", line, overlay, { color: "theme.muted", width: 1, line_style: "dotted", format: "price", label: "Flow VWAP -1σ", description: "The Flow VWAP minus one premium-weighted standard deviation (1σ). Empty while 1σ band is off." }); output("up2", line, overlay, { color: "theme.muted", opacity: 0.6, width: 1, line_style: "dotted", format: "price", label: "Flow VWAP +2σ", description: "The Flow VWAP plus two premium-weighted standard deviations (2σ). Empty while 2σ band is off." }); output("lo2", line, overlay, { color: "theme.muted", opacity: 0.6, width: 1, line_style: "dotted", format: "price", label: "Flow VWAP -2σ", description: "The Flow VWAP minus two premium-weighted standard deviations (2σ). Empty while 2σ band is off." }); fill("up1", "lo1", { color: "theme.muted", opacity: 0.08 }); // the 1σ band, lightly shaded fill("up2", "lo2", { color: "theme.muted", opacity: 0.04 }); // the 2σ band, fainter: inside 1σ the two shades add up // The readings, data-only: the card reads them and the Console can too. output("sigma", none, overlay, { format: "price", description: "One premium-weighted standard deviation (1σ) of the prices since the anchor, in price. Empty until the anchor's first bar with premium." }); output("weight_sum", none, overlay, { format: "usd", description: "The premium since the anchor that weighs the line, in dollars. Empty until the anchor's first options data. Includes cross and late trades." }); output("bar_weight", none, overlay, { format: "usd", description: "This bar's premium in dollars, empty on a bar with no options data." }); output("distance", none, overlay, { description: "How far the close sits from the Flow VWAP, in premium-weighted standard deviations (σ). Above zero the close is above the line, below zero under it. Empty while σ is 0 or unknown." }); output("missing_bars", none, overlay, { description: "Regular-session bars since the anchor with no options data. The line leaves them out." }); string("read", { max_bytes: 48 }); // the headline: where the close sits against the line, or that no flow came yet string("title", { max_bytes: 48 }); // the card's title: the chain, the anchor and 0DTE // The card: where the close sits leads as the headline, then the premium since the anchor, one standard deviation in // price and the bars with no flow row. render.hud("flow_card", { position: "top_right", safe_area: true, title: "{{title}}", columns: 2, tiles: [ tile.pill("Price", "read", { headline: true }), tile.value("Premium since anchor", "weight_sum", { format: "usd", hint: "Includes cross and late trades" }), tile.value("1σ in price", "sigma", { format: "price" }), tile.rows("Since the anchor", [["Bars with no options data", "missing_bars", "int"]]), ], }); const DAY_SEC = 86400.0; // seconds in a day: trade_date over it is the day number since 1970-01-01 const AT_SIGMA = 0.05; // the card reads At Flow VWAP inside this many deviations, where one decimal would read 0.0 let chain = 0; // settings, read in onStart() let weightMode = 0; // 0 bought at the ask, 1 at the ask and at the bid, 2 every print let types = 0; // 0 calls and puts, 1 calls, 2 puts let zeroDte = false; let weekly = false; let priceMode = 0; // 0 HLC3, 1 the close, 2 HL2 let band1 = true; let band2 = true; let anchor: f64 = NaN; // the anchor the sums run over: the trade date, or its week let weight = 0.0; // the premium since the anchor let mean = 0.0; // the premium-weighted mean price since the anchor: the Flow VWAP once weight is above 0 let m2 = 0.0; // the premium-weighted sum of squared gaps from the mean: the variance is m2 over weight let rows = 0; // bars since the anchor that carried a flow row let missing = 0; // regular-session bars since the anchor without one function onStart(): void { chain = i32(p_chain()); weightMode = i32(p_weight()); types = i32(p_types()); zeroDte = pb_zero_dte(); weekly = p_anchor() == 1.0; priceMode = i32(p_price()); band1 = pb_band1(); band2 = pb_band2(); } // The anchor a trade date falls in: the date itself under Session; under Week its week's number. Day 0, 1970-01-01, // was a Thursday, so adding 3 days before dividing by 7 starts each week on a Monday. function anchorOf(date: f64): f64 { return weekly ? Math.floor((date / DAY_SEC + 3.0) / 7.0) : date; } // This bar's premium: the sides and the types the settings pick, from the 0DTE set while 0DTE only is on (its inputs // read NaN while it is off: their lane is never fetched). NaN on a bar without a flow row; never below 0. function barWeight(): f64 { let calls = zeroDte ? in_zd_call_ask() : in_call_ask(); let puts = zeroDte ? in_zd_put_ask() : in_put_ask(); if (weightMode == 1) { calls += zeroDte ? in_zd_call_bid() : in_call_bid(); puts += zeroDte ? in_zd_put_bid() : in_put_bid(); } else if (weightMode == 2) { calls = zeroDte ? in_zd_call_total() : in_call_total(); puts = zeroDte ? in_zd_put_total() : in_put_total(); } const w = types == 1 ? calls : types == 2 ? puts : calls + puts; return w < 0.0 ? 0.0 : w; } // This bar's price, the chart's own: HLC3, the close or HL2. function barPrice(): f64 { const close = in_close(); if (priceMode == 1) return close; if (priceMode == 2) return (in_high() + in_low()) / 2.0; return (in_high() + in_low() + close) / 3.0; } // The card's words, on the live bar. function writeCard(centre: f64, distance: f64, close: f64): void { sb_clear(); if (isNaN(centre)) sb_text("No options premium yet"); else if (distance >= AT_SIGMA || (isNaN(distance) && close > centre)) sb_text("Above Flow VWAP"); else if (distance <= -AT_SIGMA || (isNaN(distance) && close < centre)) sb_text("Below Flow VWAP"); else sb_text("At Flow VWAP"); if (!isNaN(centre) && Math.abs(distance) >= AT_SIGMA) { sb_text(" "); sb_signed(distance, 1); sb_text("σ"); } str_read_sb(); sb_clear(); sb_text("Flow VWAP, "); sb_text(chain == 0 ? "this symbol" : chain == 1 ? "tracked index or ETF" : chain == 2 ? "QQQ" : chain == 3 ? "NDX" : chain == 4 ? "SPY" : "SPX"); sb_text(weekly ? ", week" : ", session"); if (zeroDte) sb_text(", 0DTE"); str_title_sb(); } // onBar() runs once per bar: a new anchor starts the sums again; this bar's premium weighs its price into the running // mean and squared gaps (a weighted Welford step), or counts as missing on a regular-session bar without a row; then // the line, the bands, the readings and, on the live bar, the card's words. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && anchorOf(date) != anchor) { anchor = anchorOf(date); weight = 0.0; mean = 0.0; m2 = 0.0; rows = 0; missing = 0; } const w = barWeight(); const served = !isNaN(w); const price = barPrice(); if (served) { rows += 1; if (w > 0.0 && !isNaN(price)) { const total = weight + w; const gap = price - mean; // from the mean before this bar mean += (w / total) * gap; // the anchor's first bar weighs 1 of 1: the mean starts at its price exactly m2 += w * gap * (price - mean); // the gap before times the gap after: 0 on a bar at the mean weight = total; } } else if (in_session() == 1.0) missing += 1; const centre = weight > 0.0 ? mean : NaN; const sigma = weight > 0.0 ? Math.sqrt(m2 > 0.0 ? m2 / weight : 0.0) : NaN; // a rounding step below 0 reads 0 out_fvwap(centre); out_up1(band1 ? centre + sigma : NaN); out_lo1(band1 ? centre - sigma : NaN); out_up2(band2 ? centre + 2.0 * sigma : NaN); out_lo2(band2 ? centre - 2.0 * sigma : NaN); out_sigma(sigma); out_weight_sum(rows > 0 ? weight : NaN); out_bar_weight(served ? w : NaN); const close = in_close(); const distance = sigma > 0.0 ? (close - centre) / sigma : NaN; out_distance(distance); out_missing_bars(f64(missing)); if (bar.isLast()) writeCard(centre, distance, close); } ``` ## How it works **The weight.** `options_flow` serves one row of sums per bar: the premium of every print, split by where the print traded against the quote and by calls and puts ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). Premium picks the sides that weigh the bar: **Bought at the ask** (the default) reads `call_prem_ask` and `put_prem_ask`, **Ask and bid** adds `call_prem_bid` and `put_prem_bid`, and **All premium** reads `call_prem_total` and `put_prem_total`, the prints at the mid and with no quote included. Contracts keeps the calls or the puts alone. A weight below 0 counts as 0, so the sums of premium and of squared gaps never fall below 0. **The line.** From the anchor's first bar, the Flow VWAP is the sum of price x premium over the sum of premium: FVWAP = Σ(P W) / Σ W. Three bars at 600, 602 and 601 weighted 100,000, 300,000 and 600,000 give (600 x 100,000 + 602 x 300,000 + 601 x 600,000) / 1,000,000 = 601.20: most of the money printed while the price sat at 601. P is the chart's own bar price: HLC3, the high, the low and the close over 3 (the default); the close; or HL2, the high and the low over 2. **The bands.** σ is the premium-weighted standard deviation of the prices since the anchor: the square root of Σ W (P - FVWAP)² / Σ W. In the example the squared gaps from 601.20 are 1.44, 0.64 and 0.04, weighted 1, 3 and 6 tenths of the premium, so the variance is 0.36 and σ is 0.6: the 1σ band runs from 600.60 to 601.80 and the 2σ band from 600.00 to 602.40. `fill` shades each band, the 1σ band at 8 percent opacity and the 2σ band at 4 percent, so inside 1σ the two shades add up. **1σ band** and **2σ band** turn each pair of lines off, and a band that is off writes NaN while the line stays. **Precision.** The package keeps the mean and the premium-weighted sum of squared gaps from it as it goes (a weighted Welford update): each bar moves the mean by its share of the premium times its gap, and adds its premium times its gap before the move times its gap after it. It never takes Σ W P² over the premium minus the squared mean: at NQ's 25,000 each square is 625,000,000, and a variance of a few points squared would sit in the last digits of that difference. **The anchor.** Session starts the sums again when `time.trade_date` changes: the New York date on a US stock, the CME trade date that opens at 17:00 Chicago, the UTC date on crypto. Week starts them again on the first trade date of each week: a trade date over 86,400 is its day number since 1970-01-01, a Thursday, so that number plus 3, over 7 and rounded down, is the same from Monday to Sunday. On CME the Sunday evening bars carry Monday's trade date, so the week starts at Sunday's 17:00 Chicago open. **A bar without flow.** A bar the class serves no row for reads `NaN`, because every flow input declares `missing: "nan"`: it adds nothing, and the lines keep their last value. On a regular-session bar (`time.session` reads `1`) it also counts in `missing_bars`, which the card prints. A row whose premium is 0 adds nothing either, and counts as no missing bar. Before the anchor's first bar with premium the lines read NaN, so each session's line starts at its first row: on a US stock the pre-market bars carry none. **Another chain's premium.** Every flow input declares `underlying: "@chain"`: the chart reads the Options chain setting's picked word, its `style_values` entry (`"auto"`, `"derived"`, `"QQQ"`, `"NDX"`, `"SPY"` or `"SPX"`), and fetches that root's rows, so a change in the settings dialog fetches again without a rebuild. `"auto"` reads the chart's own chain; `"derived"` reads the first root the chart's future tracks in the derived table ([Derived roots](../functions/options-kit.md#derived-roots)): NDX on NQ, SPX on ES. To weigh an NQ chart by QQQ's premium, pick QQQ by name. Only the weights move: the price is the chart's own bar, so no ETF-to-futures ratio enters the line, and the bands are in the chart's own points. **0DTE only.** The second set of six inputs reads the same fields with `dte: "0dte"`: the contracts expiring on the print's own trade date. They carry `when: "zero_dte"`, so the chart fetches their rows only while 0DTE only is on; off, they read NaN and the package reads the first set. **The card.** The headline reads where the close sits: **Above Flow VWAP** or **Below Flow VWAP** with the distance in σ at one decimal (`distance`, the close minus the line over σ), **At Flow VWAP** within 0.05σ (where one decimal would read 0.0), and **No options premium yet** before the anchor's first bar with premium. With σ at 0 (one price weighted so far) it reads Above, Below or At without a number. The title names the chain, the anchor and 0DTE; under the headline sit the premium since the anchor (`weight_sum`), one σ in price (`sigma`) and the regular-session bars since the anchor with no flow row. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions. Bought at the ask and Ask and bid weigh those prints too: the premium tile's hover and the description of `weight_sum` say so. ## What the settings do - **Options chain**: Picks whose options weigh the price: this symbol's, the index or ETF this future tracks, or one by name. - **Premium**: Picks which premium counts: bought at the ask, at the ask and the bid, or every trade. - **Contracts**: Counts calls and puts together, calls alone or puts alone. - **0DTE only**: Counts only options that expire today. - **Anchor**: Starts the line again each session, or on the first session of each week. - **Price**: Picks each bar's price: HLC3 averages high, low and close, Close is the close, HL2 averages high and low. - **1σ band**: Shows lines one standard deviation above and below the Flow VWAP, lightly shaded. - **2σ band**: Shows lines two standard deviations above and below the Flow VWAP, shaded fainter. The card at the top right shows four readings. - **Price**: The card's headline, not the Price setting: where the close sits against the Flow VWAP, in standard deviations (σ). - **Premium since anchor**: The options premium that weighs the line since it last started, in dollars. - **1σ in price**: The price distance from the line to the 1σ band. - **Bars with no options data**: Regular-session bars since the anchor without data, which the line leaves out. ## Where it runs It works on three kinds of charts. On a coin with listed options, it reads that coin's own options. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read it. The same goes for the charts of that stock's option contracts. US options data runs 15 minutes behind unless you have real-time US options data. On a CME futures chart, every indicator in your browser can read the future's own options too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data runs 10 minutes behind unless you have real-time CME data. A symbol you pick in Options chain follows its own market's rules. QQQ's options on a CME NQ (Nasdaq 100 future) chart are US listed options, at your US options delay. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. On a 1-minute chart, older sessions stay blank. Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read it. They say which data they lack. ## When data is missing The card says "No options premium yet" until the anchor's first bar with premium. The lines stay empty until then. **Bars with no options data** counts the regular-session bars since the anchor without data. The line leaves them out, so it follows the money that traded, not the time that passed. Index or ETF this future tracks works only on charts that track one, such as NQ, ES or SPY. On BTC or a single stock there is none, so pick Chart's own there. If the chart cannot load a data source, the legend shows a chip with the reason. ## Customize it - **The week's value.** Set Anchor to Week to carry the line and its bands across the week's sessions. - **Calls against puts.** Run two copies, one with Contracts on Calls and one on Puts: where the call buyers and the put buyers each paid up. - **Every print.** Set Premium to All premium to weigh the price by all the option money, sided or not. - **A third band.** Declare `up3` and `lo3` lines after `lo2`, then write `out_up3(centre + 3.0 * sigma)` and `out_lo3(centre - 3.0 * sigma)` beside the 2σ lines in `onBar()`, for the extreme moves. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Flow VWAP** under **Order flow**. 2. Press **Run** on a US stock or ETF chart (QQQ, SPY) or on a coin with listed options: the line and its bands draw on the candles and the card at the top right. On an NQ chart, set Options chain to QQQ to weigh NQ's prices by QQQ's premium. 3. At the editor's Console prompt, type `fvwap`, `sigma` and `distance` to read the live bar, or `missing_bars` to see how many bars carried no row. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class, its fields and the `dte` knob - [Knobs from a setting](../core-concepts/data-sources.md#knobs-from-a-setting) for `"@chain"` and a choice's `style_values` - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` and `time.session` - [Plotting](../presentation/plotting.md#ranges-and-panels) for the bands' `fill` - [Theme colours](../presentation/styling.md#theme-colours) for `theme.text` and `theme.muted` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card and its pill - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/options-volume --> # Options volume On crypto, CME (Chicago futures exchange) or US stock charts, columns under the chart show options contracts traded each bar. Calls (bets on a rise) stack above zero and puts (bets on a fall) below. Columns split into bought at the ask (the seller's price), sold at the bid (the buyer's price), or neither. Big call buying leans bullish and big put buying leans bearish. Use the card's put/call ratio (puts traded per call) to judge the session. Under the hood: the recipe reads eight `options_flow` fields, the contracts by side for calls and puts ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It draws ten `bar` columns that share one `stack`, so positives pile up above zero and negatives below in the order they are declared ([Plotting](../presentation/plotting.md)). A `render.hud` card with no `look` word sits over them ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `options-volume` template, the **Options Volume** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Options Volume: on crypto, CME (Chicago futures exchange) or US stock charts, columns under the chart show options // contracts traded each bar. Calls (bets on a rise) stack above zero and puts (bets on a fall) below. Columns split // into bought at the ask (the seller's price), sold at the bid (the buyer's price), or neither. Big call buying leans // bullish and big put buying leans bearish. Use the card's put/call ratio (puts traded per call) to judge the session. // // Technical notes: the option contracts traded on the chart's underlying in every bar, calls stacked above zero and // puts below, each column split by where its prints traded against the quote. By side (the default): calls bought at // the ask in the up colour, sold at the bid in a paler up and at the mid or with no quote muted; puts the same in the // down colour under zero. Bullish and bearish: calls bought at the ask and puts sold at the bid stack above zero as // bullish, puts bought at the ask and calls sold at the bid below zero as bearish, and the prints at the mid or with no // quote split evenly into a muted band on each side, since they carry no side. A card at the top right reads the // session (each trade date starts again): the call and put contracts, the put/call ratio and the bullish share of the // sided contracts. The rows come from options_flow, one per bar: 1-minute rows reach back 7 days and 5-minute rows 30 // days, so older bars carry none; a bar without a row draws no column, and the card counts the regular-session bars // that had none, the sums being a floor while that count is above 0. param.choice("split", ["By side", "Bullish and bearish"], "By side", { label: "Split", description: "By side splits each column into trades at the ask, at the bid, and with no clear side. Bullish and bearish puts calls bought and puts sold above zero, and puts bought and calls sold below. Trades with no clear side split evenly between the two." }); input("close", ohlcv.close); // the chart's own candles: the bar grid input("trade_date", time.trade_date); // the bar's trade date: the card's sums start again on each input("session", time.session); // 1 in the regular session: the bars a missing row is counted on input("call_ask", options_flow.call_contracts_ask, { missing: "nan", description: "Call contracts bought at the ask (the seller's price) in this bar." }); // NaN on a bar the class serves no row for input("call_bid", options_flow.call_contracts_bid, { missing: "nan", description: "Call contracts sold at the bid (the buyer's price) in this bar." }); input("call_mid", options_flow.call_contracts_mid, { missing: "nan", description: "Call contracts traded at the mid, halfway between the bid and the ask, in this bar." }); input("call_none", options_flow.call_contracts_none, { missing: "nan", description: "Call contracts traded with no quote to tell their side, in this bar." }); input("put_ask", options_flow.put_contracts_ask, { missing: "nan", description: "Put contracts bought at the ask in this bar." }); input("put_bid", options_flow.put_contracts_bid, { missing: "nan", description: "Put contracts sold at the bid in this bar." }); input("put_mid", options_flow.put_contracts_mid, { missing: "nan", description: "Put contracts traded at the mid in this bar." }); input("put_none", options_flow.put_contracts_none, { missing: "nan", description: "Put contracts traded with no quote to tell their side, in this bar." }); // The columns: one stack, the calls (or the bullish side) above zero and the puts (or the bearish side) below, in // declaration order. Each split writes its own columns; the other split's read NaN and draw nothing. output("calls_ask", bar, lower, { color: "theme.up", width: 0.8, stack: "contracts", label: "Calls bought at the ask", format: "si", description: "Calls (bets on a rise) bought at the ask, the seller's price. Shown in the By side split." }); output("calls_bid", bar, lower, { color: "theme.up", opacity: 0.55, width: 0.8, stack: "contracts", label: "Calls sold at the bid", format: "si", description: "Calls sold at the bid, the buyer's price. Shown in the By side split." }); output("calls_other", bar, lower, { color: "theme.muted", width: 0.8, stack: "contracts", label: "Calls, no clear side", format: "si", description: "Calls traded at the mid or with no quote, so with no clear side. Shown in the By side split." }); output("puts_ask", bar, lower, { color: "theme.down", width: 0.8, stack: "contracts", label: "Puts bought at the ask", format: "si", description: "Puts (bets on a fall) bought at the ask, drawn below zero. Shown in the By side split." }); output("puts_bid", bar, lower, { color: "theme.down", opacity: 0.55, width: 0.8, stack: "contracts", label: "Puts sold at the bid", format: "si", description: "Puts sold at the bid, drawn below zero. Shown in the By side split." }); output("puts_other", bar, lower, { color: "theme.muted", width: 0.8, stack: "contracts", label: "Puts, no clear side", format: "si", description: "Puts traded at the mid or with no quote, drawn below zero. Shown in the By side split." }); output("bullish", bar, lower, { color: "theme.up", width: 0.8, stack: "contracts", label: "Bullish", format: "si", description: "Calls bought at the ask plus puts sold at the bid: bets on a rise. Shown in the Bullish and bearish split." }); output("neutral_up", bar, lower, { color: "theme.muted", width: 0.8, stack: "contracts", label: "Neutral", format: "si", description: "Half the contracts with no clear side, drawn above zero. Shown in the Bullish and bearish split." }); output("neutral_down", bar, lower, { color: "theme.muted", width: 0.8, stack: "contracts", label: "Neutral, below", legend: false, format: "si", description: "The other half, drawn below zero. Shown in the Bullish and bearish split." }); output("bearish", bar, lower, { color: "theme.down", width: 0.8, stack: "contracts", label: "Bearish", format: "si", description: "Puts bought at the ask plus calls sold at the bid: bets on a fall, drawn below zero. Shown in the Bullish and bearish split." }); // The readings, data-only: the card reads them and the Console can too. output("session_calls", none, lower, { description: "Call contracts traded this session." }); output("session_puts", none, lower, { description: "Put contracts traded this session." }); output("put_call", none, lower, { description: "The session's put/call ratio: put contracts per call contract. Above 1, more puts traded than calls." }); output("bull_share", none, lower, { description: "Bullish contracts as a percent of bullish plus bearish, trades with a clear side only. Above 50, bullish trades lead." }); output("missing_bars", none, lower, { description: "Regular-session bars this session with no options data. Above 0, read the sums as at least what they show." }); output("tone", none, lower, { description: "Which side traded more: 0 puts, 1 even or no reading, 2 calls." }); string("read", { max_bytes: 48 }); // the headline // The card: which side traded more leads. render.hud("volume_card", { position: "top_right", safe_area: true, title: "Options volume, this session", columns: 2, tiles: [ tile.pill("Session", "read", { headline: true }), tile.value("Calls", "session_calls", { format: "si" }), tile.value("Puts", "session_puts", { format: "si" }), tile.value("Put/call", "put_call", { format: "0.00" }), tile.value("Bullish share", "bull_share", { format: "%" }), tile.rows([["Bars with no options data", "missing_bars", "int"]]), ], }); let bySide = true; // setting, read in onStart() let day: f64 = NaN; // the trade date the card's sums run over let calls = 0.0; // the session's sums let puts = 0.0; let bull = 0.0; let bear = 0.0; let rows = 0; // bars of this session that carried a flow row let missing = 0; // regular-session bars of this session without one let runRows = 0; // flow rows over the whole run function onStart(): void { bySide = p_split() == 0.0; } function writeRead(): void { sb_clear(); if (runRows == 0) sb_text("No options flow on this chart yet"); else if (rows == 0) sb_text("No options flow yet this session"); else if (calls > puts) sb_text("More calls than puts"); else if (puts > calls) sb_text("More puts than calls"); else sb_text("Calls and puts even"); str_read_sb(); } // onBar() runs once per bar: a new trade date starts the card's sums again; the bar's row draws its column in the // split the setting picks and adds to the sums, or counts as missing on a regular-session bar. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; calls = 0.0; puts = 0.0; bull = 0.0; bear = 0.0; rows = 0; missing = 0; } const callAsk = in_call_ask(); const callBid = in_call_bid(); const callOther = in_call_mid() + in_call_none(); const putAsk = in_put_ask(); const putBid = in_put_bid(); const putOther = in_put_mid() + in_put_none(); const served = !isNaN(callAsk) && !isNaN(callBid) && !isNaN(callOther) && !isNaN(putAsk) && !isNaN(putBid) && !isNaN(putOther); if (served) { calls += callAsk + callBid + callOther; puts += putAsk + putBid + putOther; bull += callAsk + putBid; bear += putAsk + callBid; rows += 1; runRows += 1; } else if (in_session() == 1.0) missing += 1; const side = served && bySide; const sentiment = served && !bySide; out_calls_ask(side ? callAsk : NaN); out_calls_bid(side ? callBid : NaN); out_calls_other(side ? callOther : NaN); out_puts_ask(side ? -putAsk : NaN); out_puts_bid(side ? -putBid : NaN); out_puts_other(side ? -putOther : NaN); const neutral = callOther + putOther; out_bullish(sentiment ? callAsk + putBid : NaN); out_neutral_up(sentiment ? neutral * 0.5 : NaN); out_neutral_down(sentiment ? -neutral * 0.5 : NaN); out_bearish(sentiment ? -(putAsk + callBid) : NaN); const reading = rows > 0; out_session_calls(reading ? calls : NaN); out_session_puts(reading ? puts : NaN); out_put_call(reading && calls > 0.0 ? puts / calls : NaN); out_bull_share(reading && bull + bear > 0.0 ? (100.0 * bull) / (bull + bear) : NaN); out_missing_bars(f64(missing)); out_tone(reading ? (calls > puts ? 2.0 : puts > calls ? 0.0 : 1.0) : 1.0); if (bar.isLast()) writeRead(); } ``` ## How it works **The four sides.** Each `options_flow` row splits its contracts by the quote at the print: at the ask, at the bid, at the mid, and with no quote to side it, for calls and for puts. The package reads the eight fields and adds the mid and the no-quote contracts into one muted segment, since neither carries a side. On crypto and CME every print carries the taker's side, so the mid and no-quote contracts read 0 there and the muted segment stays empty. **Two splits, one stack.** All ten columns share the stack `contracts`, so the chart piles each bar's positive columns above zero and its negative ones below, in the order they are declared. By side writes the six side columns (the puts negated) and leaves the four sentiment columns `NaN`; Bullish and bearish does the opposite, so a column never draws in the split you did not pick. Each stack adds up to the bar's own totals: the calls' three segments to `call_contracts_total` and the puts' to `put_contracts_total`. **The session's numbers.** The card sums each session from its first bar (`time.trade_date` starts it again): the calls, the puts, their ratio (puts over calls) and the bullish share, bullish over bullish plus bearish contracts, the sided prints only. Its headline says which side traded more. ## What the settings do - **Split**: By side splits columns by ask, bid and no side, and Bullish and bearish sorts trades by their bet. - **Session**: Says whether more calls or more puts traded this session. - **Calls**: Call contracts traded this session. - **Puts**: Put contracts traded this session. - **Put/call**: The put/call ratio, put contracts per call contract, where above 1 more puts traded. - **Bullish share**: Bullish contracts as a percent of all trades with a clear side, where above 50 bulls lead. - **Bars with no options data**: Regular-session bars this session without data, so above 0 read the numbers as at least what they show. ## Where it runs It works on three kinds of charts. On a coin with listed options, it reads that coin's own options on its exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read it. The same goes for the charts of that stock's option contracts. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data runs 15 minutes behind unless you have real-time US options data. CME data runs 10 minutes behind unless you have real-time CME data. The legend shows which delay you get. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. Older bars draw no column. ## When data is missing A bar with no options data draws no column at all, never a zero. On crypto and CME, a bar with no trades inside the stored history reads as zeros instead. That bar draws no column and does not count as a gap. The card's headline reads "No options flow on this chart yet" while no bar has options data. It reads "No options flow yet this session" while the newest session has none. **Bars with no options data** counts this session's regular-session bars without data. Above 0, read the session's numbers as at least what they show. ## Customize it - **Premium instead of contracts.** Read the `_prem_` fields (`call_prem_ask`, ...) in place of the `_contracts_` ones and format the columns as `usd`. - **One expiry bucket.** Add `dte: "0dte"` or `dte: "week"` to the eight inputs to stack only those contracts; the knob is one read for all eight. - **Out of the money.** Add `moneyness: "otm"` to the inputs to count the out-of-the-money contracts alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options Volume** under **Order flow**. 2. Press **Run** on a BTC chart or a US stock chart: the columns draw under the chart and the card at the top right. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `put_call` and `bull_share` to read the session on the live bar, or `last 20 calls_ask` for the calls bought at the ask on the last 20 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class and its side fields - [Plotting](../presentation/plotting.md) for `bar` outputs and the `stack` word - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the card - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/greek-flow --> # Greek flow A line under the chart sums net share delta from this symbol's options trades, bought minus sold, each session. Share delta is how much stock dealers (the market makers who hedge options) must hold to hedge those trades. Rising delta means bullish bets lead, and falling delta means bearish bets lead. A pane below shows net vega (how much options gain as swings grow): above zero, traders bet on bigger swings. Use it to spot options bets against the price's move, on crypto, CME (Chicago futures exchange) or US stock charts. Under the hood: the recipe reads four `options_flow` fields, the share delta and vega at the ask and at the bid ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). Four more sit under `moneyness: "otm"` behind a setting gate. It draws the vega line in a named `pane` ([Plotting](../presentation/plotting.md#panes)) and puts up a `render.label` that says why when there is nothing to draw ([Plotting](../presentation/plotting.md#fixed-position-text)). It is also the `greek-flow` template, the **Greek Flow** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Greek Flow: a line under the chart sums net share delta from this symbol's options trades, bought minus sold, each // session. Share delta is how much stock dealers (the market makers who hedge options) must hold to hedge those trades. // Rising delta means bullish bets lead, and falling delta means bearish bets lead. A pane below shows net vega (how // much options gain as swings grow): above zero, traders bet on bigger swings. Use it to spot options bets against the // price's move, on crypto, CME (Chicago futures exchange) or US stock charts. // // Technical notes: the delta and the vega the options tape traded on the chart's underlying are signed by side and // summed through the session (each trade date starts again). Each print's share delta is its size times its delta in // the underlying's units (contracts times 100 shares on a US stock, coins on crypto, futures on CME), calls up and puts // down; a print bought at the ask counts as it is and one sold at the bid counts against, so the directional delta is // the share delta bought at the ask minus that sold at the bid: the pressure the tape puts on the underlying, close to // what the dealers on the other side end up hedging. The directional vega is the vega bought at the ask minus the vega // sold at the bid, in USD per IV point: above zero the tape is net buying volatility. Prints at the mid or with no // quote carry no side and count in neither line. The delta line sits under the chart (shares on a US stock, the chart's // own size unit elsewhere) and the vega line in a pane below it. Out of the money only reads the out-of-the-money // contracts alone (a second read, fetched only while it is on). The rows come from options_flow, one per bar: 1-minute // rows reach back 7 days and 5-minute rows 30 days, so older bars carry none; a bar without a row adds nothing, and the // regular-session bars that had none are counted, the sums a floor while that count is above 0. param.bool("otm", false, { label: "Out of the money only", description: "Reads only out-of-the-money options: calls whose strike (price level) is above the price, puts whose strike is below. It loads that extra data only while this is on." }); input("close", ohlcv.close); // the chart's own candles: the bar grid input("trade_date", time.trade_date); // the bar's trade date: the sums start again on each input("session", time.session); // 1 in the regular session: the bars a missing row is counted on input("delta_ask", options_flow.share_delta_ask, { missing: "nan", description: "Share delta (how many shares dealers hedge) bought at the ask in this bar. Each trade adds its size times its delta, with 100 shares per contract on a US stock." }); // NaN on a bar the class serves no row for input("delta_bid", options_flow.share_delta_bid, { missing: "nan", description: "Share delta sold at the bid in this bar." }); input("vega_ask", options_flow.vega_ask, { missing: "nan", description: "Vega (how much options gain as swings grow) bought at the ask in this bar, in dollars per volatility point." }); input("vega_bid", options_flow.vega_bid, { missing: "nan", description: "Vega sold at the bid in this bar, in dollars per volatility point." }); input("otm_delta_ask", options_flow.share_delta_ask, { moneyness: "otm", when: "otm", missing: "nan", description: "Share delta bought at the ask, out-of-the-money options only." }); input("otm_delta_bid", options_flow.share_delta_bid, { moneyness: "otm", when: "otm", missing: "nan", description: "Share delta sold at the bid, out-of-the-money options only." }); input("otm_vega_ask", options_flow.vega_ask, { moneyness: "otm", when: "otm", missing: "nan", description: "Vega bought at the ask, out-of-the-money options only." }); input("otm_vega_bid", options_flow.vega_bid, { moneyness: "otm", when: "otm", missing: "nan", description: "Vega sold at the bid, out-of-the-money options only." }); pane("vega", { title: "Vega bought minus sold", height_frac: 0.16, format: "usd" }); output("delta_flow", line, lower, { color: "theme.text", width: 2, label: "Net share delta", format: "si", unit: " sh", visible_by: { size_unit: [2] }, description: "Share delta (how many shares dealers hedge) bought at the ask minus sold at the bid since the session opened. In shares on a US stock chart. Rising means bullish bets lead, falling means bearish bets lead." }); output("delta_units", line, lower, { color: "theme.text", width: 2, label: "Net share delta", format: "si", visible_by: { size_unit: [0, 1, 3] }, description: "The same net share delta on every other chart, in that market's own unit. That is coins on crypto, futures contracts on CME and shares on an option contract's chart." }); output("delta_zero", line, lower, { color: "theme.muted", width: 1, legend: false, description: "The zero line: above it bullish bets lead, below it bearish bets lead." }); output("vega_flow", line, lower, { pane: "vega", color: "theme.text", width: 2, label: "Net vega", format: "usd", description: "Net vega (how much options gain as swings grow) since the session opened, in dollars per volatility point. It is vega bought at the ask minus vega sold at the bid. Above zero traders bet on bigger swings, below zero on calmer ones." }); output("vega_zero", line, lower, { pane: "vega", color: "theme.muted", width: 1, legend: false, description: "The zero line: above it traders bet on bigger swings, below it on calmer ones." }); // The readings, data-only: the Console reads them. output("delta_bar", none, lower, { description: "This bar's net share delta, empty on a bar with no options data." }); output("vega_bar", none, lower, { description: "This bar's net vega in dollars per volatility point, empty on a bar with no options data." }); output("delta_sided", none, lower, { description: "This bar's share delta at the ask plus at the bid: every trade with a clear side, either way." }); output("missing_bars", none, lower, { description: "Regular-session bars this session with no options data. Above 0, read the sums as at least what they show." }); string("note", { max_bytes: 64 }); // the one line while there is nothing to draw render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); let otm = false; // setting, read in onStart() let day: f64 = NaN; // the trade date the sums run over let delta = 0.0; // the session's sums let vega = 0.0; let rows = 0; // bars of this session that carried a flow row let missing = 0; // regular-session bars of this session without one let runRows = 0; // flow rows over the whole run function onStart(): void { otm = pb_otm(); } // onBar() runs once per bar: a new trade date starts the sums again; this bar's row adds its directional delta and // vega, or counts as missing on a regular-session bar; then the lines and the readings. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; delta = 0.0; vega = 0.0; rows = 0; missing = 0; } // The out-of-the-money inputs read NaN while the setting is off: their lane is never fetched. const deltaAsk = otm ? in_otm_delta_ask() : in_delta_ask(); const deltaBid = otm ? in_otm_delta_bid() : in_delta_bid(); const vegaAsk = otm ? in_otm_vega_ask() : in_vega_ask(); const vegaBid = otm ? in_otm_vega_bid() : in_vega_bid(); const served = !isNaN(deltaAsk) && !isNaN(deltaBid) && !isNaN(vegaAsk) && !isNaN(vegaBid); if (served) { delta += deltaAsk - deltaBid; vega += vegaAsk - vegaBid; rows += 1; runRows += 1; } else if (in_session() == 1.0) missing += 1; const reading = rows > 0; out_delta_flow(reading ? delta : NaN); out_delta_units(reading ? delta : NaN); // one of the two shows, by the market's size unit out_delta_zero(0.0); out_vega_flow(reading ? vega : NaN); out_vega_zero(0.0); out_delta_bar(served ? deltaAsk - deltaBid : NaN); out_vega_bar(served ? vegaAsk - vegaBid : NaN); out_delta_sided(served ? deltaAsk + deltaBid : NaN); out_missing_bars(f64(missing)); if (bar.isLast()) str_note(runRows == 0 ? "No options flow on this chart yet" : rows == 0 ? "No options flow yet this session" : ""); // an empty text draws no label } ``` ## How it works **The model sums.** Each `options_flow` row carries `share_delta_ask` and `share_delta_bid`, the sum of size times delta over the bar's priced prints at the ask and at the bid, in the underlying's units (shares on a US stock, contracts times 100; coins on crypto; futures contracts on CME), and `vega_ask` and `vega_bid`, the vega of the same prints in USD per IV point. A print the data plane could not price has no greeks and adds to neither; `n_priced` counts the ones it could. **Signed by side.** `delta_flow` adds the bar's share delta at the ask minus at the bid, so call buying and put selling push it up, put buying and call selling down. `vega_flow` does the same with vega. Prints at the mid or with no quote carry no side and count in neither. `delta_sided`, a data-only reading, is the bar's share delta at the ask plus at the bid: the sided prints' delta whichever way they traded. On crypto and CME every print carries the taker's side. **One line a market.** The delta line is a pair: `delta_flow` carries the unit `sh` and shows on a US stock (`visible_by: { size_unit: [2] }`), and `delta_units`, the same value without a unit, shows on every other chart, where the delta counts coins on crypto and futures contracts on CME ([Size units](../settings/sessions-and-units.md#the-dialog-and-the-lanes)). The chart mounts the one that fits its market; the Console reads both. **Sums by session.** Both lines start again on each trade date (`time.trade_date`). A bar without a row adds nothing, and a regular-session bar without one counts in `missing_bars`: while it is above 0 the sums are a floor. **Out of the money.** The setting reads the same four fields under `moneyness: "otm"`, the out-of-the-money contracts alone (a strike within 0.5% of the underlying counts as out of the money). Those inputs carry `when: "otm"`, so their rows load only while it is on. ## What the settings do - **Out of the money only**: Reads only out-of-the-money options, calls with a strike (price level) above the price and puts below it. ## Where it runs It works on three kinds of charts. On a coin with listed options, it reads that coin's own options on its exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read it. The same goes for the charts of that stock's option contracts. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data runs 15 minutes behind unless you have real-time US options data. CME data runs 10 minutes behind unless you have real-time CME data. The legend shows which delay you get. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. ## When data is missing A line with nothing to draw stays empty instead of flat at zero. A session with no options data draws no line. A label at the top says "No options flow on this chart yet" while no bar has options data. It says "No options flow yet this session" while the newest session has none. The Console (the editor's panel that prints values) can also count this session's regular-session bars without data (see Run it). ## Customize it - **Per bar instead of the session.** Draw `delta_bar` as a `histogram` in place of `delta_flow` to see each bar's pressure on its own. - **Dollar delta.** Multiply the bar's delta by `bar.close()` for the notional the tape moved; `notional()` adds a CME future's point value. - **One expiry bucket.** Add `dte: "0dte"` to the inputs to follow the same-day contracts, whose delta moves fastest. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Greek Flow** under **Order flow**. 2. Press **Run** on a BTC chart or a US stock chart: the delta line draws under the chart and the vega line below it. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `delta_flow` and `vega_flow` for the session's sums, `delta_sided` for the last bar's delta on both sides, or `missing_bars` for this session's regular-session bars without data. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` fields and the `moneyness` knob - [Plotting](../presentation/plotting.md#panes) for a second pane below the chart - [Plotting](../presentation/plotting.md#fixed-position-text) for the label at a corner - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/nope --> # NOPE A line under the chart shows NOPE (net options pricing effect): options share delta as a percent of volume. Share delta is how much stock dealers (the market makers who hedge options) must hold to hedge those options. Through each session, call buying lifts the line above zero and put buying pulls it below. The further from zero, the more that hedging can move the price. Use it to spot sessions where hedging may push price, on crypto, CME (Chicago futures exchange) or US stock charts. Under the hood: the recipe reads two `options_flow` fields, the share delta at the ask and at the bid ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It also reads the chart's own volume, the session from `time.session` ([Data sources](../core-concepts/data-sources.md#the-time-source)) and the market's clock from `market.zone()` ([The market's facts](../settings/sessions-and-units.md#the-markets-facts)). It draws a `split` line coloured around zero ([Styling](../presentation/styling.md)). It is also the `nope` template, the **NOPE** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // NOPE: a line under the chart shows NOPE (net options pricing effect): options share delta as a percent of volume. // Share delta is how much stock dealers (the market makers who hedge options) must hold to hedge those options. Through // each session, call buying lifts the line above zero and put buying pulls it below. The further from zero, the more // that hedging can move the price. Use it to spot sessions where hedging may push price, on crypto, CME (Chicago // futures exchange) or US stock charts. // // Technical notes: NOPE is the share delta the options traded on the chart's underlying carry, as a percent of the // chart's own volume, summed through the session (the regular session on a US stock, the whole trading day on CME; each // trade date starts again). A print's share delta is its size times its delta in the underlying's units (contracts // times 100 shares on a US stock, coins on crypto, futures on CME), calls up and puts down, so a session of call buying // reads above zero and one of put buying below. The idea is the dealers': whoever writes the options hedges that delta // in the underlying, so the larger the delta against its own volume, the harder the options lean on its price. Delta, // Both sides (the default) counts each print's delta once whichever side it traded on, as the standard NOPE does (the // dealers wrote every option); Bought minus sold counts a print bought at the ask as it is and one sold at the bid // against. Prints at the mid or with no quote carry no share delta in the flow rows, so they count in neither. The line // is in the up colour above zero and the down colour below. On CME it counts the whole trading day, from the 17:00 // Chicago open through the evening, the night and the hours after the regular window; on crypto, where every bar is in // session, the venue's option delta meets the chart's own volume (a Coinbase chart divides Deribit's delta by // Coinbase's coins). The rows come from options_flow, one per bar: 1-minute rows reach back 7 days and 5-minute rows 30 // days, so older bars carry none; a bar the session counts without a row adds no delta and no stock volume, and those // bars are counted. param.choice("delta", ["Both sides", "Bought minus sold"], "Both sides", { label: "Delta", description: "Both sides, the standard NOPE, counts every trade as if it were bought. Calls then lift the line and puts pull it down. Bought minus sold counts trades at the bid (the buyer's price, so the seller gave in) as sold. A call sold there pulls the line down." }); input("close", ohlcv.close); // the chart's own candles: the bar grid input("volume", ohlcv.volume); // the chart's own volume in the bar (shares on a US stock): NOPE's denominator input("trade_date", time.trade_date); // the bar's trade date (on CME the one that opens at 17:00 Chicago): the sums start again on each input("session", time.session); // 1 in the regular session, 2 before it, 3 after it, 0 closed: 1 counts, and 1 to 3 on CME market.zone(); // the market's clock, written by the chart: 2 Chicago (CME), whose whole trading day counts input("delta_ask", options_flow.share_delta_ask, { missing: "nan", description: "Share delta (how many shares dealers hedge) bought at the ask in this bar. Each trade adds its size times its delta, with 100 shares per contract on a US stock." }); // NaN on a bar the class serves no row for input("delta_bid", options_flow.share_delta_bid, { missing: "nan", description: "Share delta sold at the bid in this bar." }); output("nope", line, lower, { color: "theme.text", width: 2, split: "level", up_color: "theme.up", down_color: "theme.down", label: "NOPE", format: "0.00", unit: "%", description: "NOPE (net options pricing effect): the session's options share delta as a percent of this chart's own volume. A session of call buying reads above zero and put buying below. The further from zero, the more hedging could move the price." }); output("zero", line, lower, { color: "theme.muted", width: 1, legend: false, description: "The zero line: above it calls lead, below it puts lead." }); // The readings, data-only: the Console reads them. output("nope_bar", none, lower, { description: "This bar's options share delta as a percent of this bar's volume. Empty on a bar with no options data or no volume." }); output("option_delta", none, lower, { description: "The session's options share delta so far, in the chart's size unit, shares on a US stock." }); output("stock_volume", none, lower, { description: "This chart's own volume over the session's bars that had options data, shares on a US stock." }); output("missing_bars", none, lower, { description: "Bars the session counts that had no options data: regular-session bars, or every bar of the trading day on CME. They count in neither sum." }); string("note", { max_bytes: 64 }); // the one line while there is nothing to draw render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); let signed = false; // setting and the market's clock, read in onStart() let zone = 0; let day: f64 = NaN; // the trade date the sums run over let optionDelta = 0.0; // the session's sums let stockVolume = 0.0; let rows = 0; // counted bars of this session that carried a flow row let missing = 0; // counted bars of this session without one let runRows = 0; // flow rows over the whole run function onStart(): void { signed = p_delta() == 1.0; zone = i32(p_market_zone()); } // onBar() runs once per bar: a new trade date starts the sums again; a bar the session counts with a flow row adds its // share delta and the stock's volume, one without a row counts as missing; then the line and the readings. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; optionDelta = 0.0; stockVolume = 0.0; rows = 0; missing = 0; } // The bars the sums count: the regular session (time.session 1), and on CME (zone 2) its whole trading day, from the // 17:00 Chicago open through the evening, the night and the hours after the regular window (1 to 3). const regular = zone == 2 ? in_session() >= 1.0 : in_session() == 1.0; const ask = in_delta_ask(); const bid = in_delta_bid(); const shares = in_volume(); const served = !isNaN(ask) && !isNaN(bid); const barDelta = signed ? ask - bid : ask + bid; let barNope: f64 = NaN; if (regular && served && !isNaN(shares)) { optionDelta += barDelta; stockVolume += shares; rows += 1; runRows += 1; if (shares > 0.0) barNope = (100.0 * barDelta) / shares; } else if (regular && !served) missing += 1; const reading = rows > 0 && stockVolume > 0.0; out_nope(reading ? (100.0 * optionDelta) / stockVolume : NaN); out_zero(0.0); out_nope_bar(barNope); out_option_delta(rows > 0 ? optionDelta : NaN); out_stock_volume(rows > 0 ? stockVolume : NaN); out_missing_bars(f64(missing)); if (bar.isLast()) str_note(runRows == 0 ? "No options flow on this chart yet" : rows == 0 ? "No options flow yet this session" : ""); // an empty text draws no label } ``` ## How it works **The delta.** `share_delta_ask` and `share_delta_bid` sum size times delta over the bar's priced prints at the ask and at the bid (contracts times 100 shares on a US stock). Delta, Both sides (the default) adds the two: each print's delta counts once, whichever side it traded on, as the classic NOPE counts every option traded on the view that the dealers wrote them all. Bought minus sold takes the ask minus the bid instead, so a print sold at the bid counts against. Prints at the mid or with no quote carry no share delta in the flow rows and count in neither reading. **Over the stock's volume.** On each bar the session counts (`time.session` reads `1`, the regular session) with a flow row, the bar's share delta joins the session's sum and the bar's stock volume joins the denominator; `nope` is 100 times the one over the other. On a US stock pre-market and after-hours bars count in neither, even when they carry a row: the stock trades then while most options do not. The sums start again on each trade date. On CME (`market.zone()` 2) the sums count the whole trading day, from the 17:00 Chicago open through the evening, the night and the hours after the regular window (`time.session` reads `1` to `3`), because the futures and their options trade through all of it; the daily halt counts in neither sum. On crypto every bar is in session, and the chain's option delta meets the chart's own volume, so on a Coinbase chart it divides the chain venue's delta by Coinbase's coins. **Per bar.** `nope_bar` reads the same ratio on the bar alone, `option_delta` and `stock_volume` the session's two sums. ## What the settings do - **Delta**: Both sides, the standard NOPE, counts every trade as bought. Bought minus sold counts trades at the bid (the buyer's price, so the seller gave in) as sold. ## Where it runs It works on three kinds of charts. On a coin with listed options, it reads that coin's own options on its exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read it. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data runs 15 minutes behind unless you have real-time US options data. CME data runs 10 minutes behind unless you have real-time CME data. The legend shows which delay you get. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. ## When data is missing A session bar with no options data adds neither delta nor volume. So the ratio stays fair over the bars that have both. The Console (the editor's panel that prints values) counts the others (see Run it). The line stays empty before the session's first options data. A label at the top says "No options flow on this chart yet" while no bar has options data. It says "No options flow yet this session" while the newest session has none. ## Customize it - **The classic or the signed reading.** Switch Delta to Bought minus sold to see the hedge the aggressors leave with the dealers, rather than every option written. - **Same-day options.** Add `dte: "0dte"` to both flow inputs: the expiring contracts carry the delta that moves fastest into the close. - **A band.** Keep each session's closing `nope` in a ring and draw its average and spread as levels to tell an unusual day from an ordinary one. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **NOPE** under **Order flow**. 2. Press **Run** on a BTC chart or a US stock chart: the line draws under the chart. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `nope` for the session's reading, `last 20 nope_bar` for the last 20 bars on their own, or `missing_bars` for the session's bars without data. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` share delta fields - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.session` and `time.trade_date` - [The market's facts](../settings/sessions-and-units.md#the-markets-facts) for `market.zone()`, which counts CME's whole trading day - [Styling](../presentation/styling.md) for the `split` line - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/interval-flow --> # Interval flow Interval Flow lists the option contracts that traded on this symbol in one bar, biggest first, under the chart. Big orders often take many prints (single option trades) over minutes, so each line sums one contract over the bar. A high share at the ask (the seller's price) means buyers paid up for that contract. A histogram counts contracts passing your filters, and a strip scores each bar from -100 (bearish) to 100 (bullish). Use it on a US stock, coin or CME (Chicago futures exchange) future with options to see where money went. Under the hood: a celled `option_contract_flow.cells` input is read tuple by tuple ([Data sources](../core-concepts/data-sources.md#option_contract_flow)). `hasBit` reads the values a tuple may lack and `decodeSymbol` the contract's root ([Data sources](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). Each premium is the VWAP times the size times the market's option multiplier: 100 on a US stock, 50 on ES, 1 on a coin. Else it is the premium at the ask plus at the bid, a muted floor. The rows go into a styled `panel.table` ([Cards, frames and panels](../presentation/cards-frames-panels.md#panel-words)). A histogram output is coloured per bar by a data-only ladder output, beside an `out.inset` strip ([Cards, frames and panels](../presentation/cards-frames-panels.md#side-placement-and-windows)). The options kit's `flowSideCode`, `flowScore` and `optionsTradeDay` give the scores ([Flow score](../functions/options-kit.md#flow-score)). This is also the `interval-flow` template: the **Interval Flow** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Interval Flow: the option contracts that traded on this symbol in one bar, in a table under the chart. A print is // one option trade, and big orders often take many prints over minutes. So each line sums one contract over the bar: // a 5-minute chart reads 5-minute intervals. A line shows the size, the premium (the money paid) and a score. Its Ask // column is the share bought at the ask (the seller's price), where buyers paid up for that bet. Use it to see which // contracts drew the money in the last bar. // // Under the hood: the option contracts that traded on the chart's underlying in one bar's interval, one line per // contract, for spotting fills that take minutes rather than one print: a 5-minute chart reads 5-minute intervals. A // table under the chart lists the interval's top contracts by premium (or by volume) that pass the filters: the // contract, its size (contracts, or coins to four decimals), its premium, the share bought at the ask and sold at the // bid, the average fill, the last IV and the interval's share of the contract's volume so far this session. The // interval is the last closed bar by default (Forming reads the bar trading now), and a histogram under the table // counts every bar's contracts that pass. Premium is the VWAP times the size times the market's option multiplier (100 // on a US stock, 50 on ES, 1 on a coin); where the cells carry no VWAP (present bit 0 clear) or the host does not know // the multiplier, it is the premium at the ask plus at the bid, a floor, printed muted. The interval's time reads on // the market's own clock. The cells come from option_contract_flow, one tuple per contract that traded in each bar: an // interval whose block was cut down (the partial bit, 14) says so in the table's caption; a tuple whose contract is not // whole (a root the symbol codec refuses, no expiry, a side other than call or put, no strike) is skipped and counted. // 1-minute cells reach back 7 days and 5-minute cells 30 days. Each row also reads the contract's score, the options // kit's flowScore from -100 bearish to 100 bullish: its contracts' scores by the side of the quote they took // (flowSideCode's codes: above the ask, at it, at the bid, below it; the mid and unsided 0), averaged by size, call or // put, the moneyness against the bar's close (the cells carry no underlying) and the days to expiry from the bar's // trade date (no open interest and no repeat count: the size reads as past the open interest). Each bar's flow score, // the premium-weighted mean of the passing contracts' scores, draws as a column in a strip at the foot of the price // pane and tones the bar's Contracts passing column: the up colour from 20, the down colour from -20, between them the // strip's muted ink and the column's text colour. section("Filters"); param.choice("rank", ["premium", "volume"], "premium", { label: "Rank by", description: "Orders the table by premium (the money paid) or by contracts traded." }); param.number("min_premium", 25000, { min: 0, max: 10000000, step: 1000, label: "Smallest premium, USD", description: "A contract shows when its premium (the money paid) in the interval reaches this many USD." }); param.choice("side", ["any", "ask", "bid"], "any", { label: "Side", description: "any keeps every contract. ask keeps contracts with at least 55% bought at the ask (buyers paying up). bid keeps those with at least 55% sold at the bid (sellers giving in)." }); param.int("rows", 12, { min: 3, max: 30, label: "Contracts listed", description: "How many contracts the table shows." }); param.choice("shown", ["closed", "live"], "closed", { label: "Interval", description: "Pick the last finished bar (closed) or the bar trading now (live)." }); input("close", ohlcv.close); // the chart's own candles: the bar grid, one interval each input("trade_date", time.trade_date); // the bar's trade date: each contract's session volume starts again on each input("flow", option_contract_flow.cells, { max_cells: 6000, description: "Each contract that traded in the bar: [root_code, expiry_ms, side_cp, strike, vol_ask, vol_bid, vol_mid, vol_none, prem_ask, prem_bid, share_delta_net, vwap, last_price, iv_last, vol_above_ask, vol_below_bid, present]" }); // every expiry and strike of the chart's underlying market.zone(); // the market's clock: the interval's time and each expiry's date market.option_multiplier(); // the chain's USD per price unit and size unit: 100 on a US stock, 50 on ES, 1 on a coin; 0 unknown output("hits", histogram, lower, { color_by: "score_tone", colors: ["theme.down", "theme.up", "theme.text"], label: "Contracts passing", format: "int", description: "Contracts in this bar that pass your filters, coloured by their flow score." }); output("hit_premium", none, lower, { description: "Their premium (the money paid), in USD." }); output("partial", none, lower, { description: "1 on a bar whose contracts were cut short. Its counts are a minimum." }); output("skipped", none, lower, { description: "Entries in this bar skipped because their contract details were incomplete." }); output("score_tone", none, lower, { description: "The flow score's colour: 0 at -20 or below, 1 at 20 or above, 2 between. Blank on a bar where no contract passes." }); out.inset("flow_score", { dock: "bottom", height_px: 32, shape: "histogram", color_by: "score_tone", colors: ["theme.down", "theme.up", "theme.muted"] }); // the bar's flow score, -100 to 100: the premium-weighted mean score of the contracts that pass, a column in a strip with its own scale; NaN on a bar no contract passes string("note", { max_bytes: 64 }); // the one line while there is no contract flow to list render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const contract_rows = frame("contract_rows", { max_bytes: 16384 }); panel.table({ name: "contracts", title: "Interval flow", x: "category", place: "below", frame: contract_rows, height_frac: 0.3, font_size: 10, cell_padding: 3, grid_lines: "rows", header_text_color: "theme.muted", series: [ { name: "Contract" }, { name: "Volume", align: "right", format: "auto" }, { name: "Premium", align: "right", format: "usd" }, { name: "Ask", align: "right", format: "0", unit: "%" }, { name: "Bid", align: "right", format: "0", unit: "%" }, { name: "Avg price", align: "right", format: "0.00" }, { name: "IV", align: "right", format: "0.0", unit: "%" }, { name: "Of day", align: "right", format: "0", unit: "%" }, { name: "Score", align: "right", format: "0.0", signed: true }, ], }); const TUPLE = 17; // f64s per contract: OPTION_CONTRACT_FLOW_TUPLE const MAX_ROWS = 30; // the table's rows, the Rows setting's ceiling const CAP = 16384; // contracts a session's volume table holds (a power of two) const SIDE_SHARE = 55.0; // the Side filter's share, percent // The session's volume per contract: open addressing, a slot free when it belongs to an earlier session. const keyRoot = new StaticArray<f64>(CAP); const keyExpiry = new StaticArray<f64>(CAP); const keySide = new StaticArray<f64>(CAP); const keyStrike = new StaticArray<f64>(CAP); const slotSession = new StaticArray<i32>(CAP); const dayVolume = new StaticArray<f64>(CAP); // The top rows of this bar (cur) and of the bar before it (prev): one field per array, MAX_ROWS each. const ROW_FIELDS = 12; // root, expiry, side, strike, volume, premium, floor, ask %, bid %, vwap, iv, score const curRows = new StaticArray<f64>(MAX_ROWS * ROW_FIELDS); const prevRows = new StaticArray<f64>(MAX_ROWS * ROW_FIELDS); const curDay = new StaticArray<f64>(MAX_ROWS); // the interval's share of the contract's session volume, percent const prevDay = new StaticArray<f64>(MAX_ROWS); let timeClock = new Clock("UTC"); // the interval's open on the market's own clock, set in onStart() let byVolume = false; // settings, read in onStart() let minPremium = 25000.0; let sideFilter = 0; let rowLimit = 12; let forming = false; let zone = 0; // the market facts, read in onStart() let optMult: f64 = NaN; // NaN where the host does not know the multiplier: the premium falls back to the sided floor let day: f64 = NaN; // the trade date the volume table runs over let sessionId = 1; // the volume table's session: a slot holding another number is free (every slot starts at 0) let used = 0; // slots taken this session let curCount = 0; let prevCount = 0; let curTime: f64 = NaN; // the bars' opens, epoch seconds let prevTime: f64 = NaN; let curPartial = false; let prevPartial = false; let curHits = 0; let prevHits = 0; let curHitPremium = 0.0; // the premium of every contract that passes this bar, not only the listed ones let curScorePremium = 0.0; // their premium times their score, summed: over curHitPremium, the bar's flow score let runCells = 0; // tuples read over the whole run function onStart(): void { byVolume = p_rank() == 1.0; minPremium = p_min_premium(); sideFilter = i32(p_side()); rowLimit = i32(p_rows()); forming = p_shown() == 1.0; zone = i32(p_market_zone()); optMult = p_market_option_multiplier() > 0.0 ? p_market_option_multiplier() : NaN; timeClock = new Clock(SESSION_TZ_IDS[zone]); } // The symbol codec's rule without decoding: a whole number from 1 to 38^10 - 1 with no zero digit in base 38. function rootOk(code: f64): bool { if (!(code >= 1.0) || code > 6278211847988223.0 || code != Math.floor(code)) return false; let rest = code; while (rest > 0.0) { const digit = rest % 38.0; if (digit == 0.0) return false; rest = (rest - digit) / 38.0; } return true; } // A tuple counts when its contract is whole and its present mask is a whole number from 0 up. function contractOk(cells: StaticArray<f64>, i: i32): bool { const present = cells[i + 16]; const side = cells[i + 2]; return rootOk(cells[i]) && cells[i + 1] > 0.0 && (side == 1.0 || side == -1.0) && cells[i + 3] > 0.0 && present >= 0.0 && present == Math.floor(present); } function hashOf(root: f64, expiry: f64, side: f64, strike: f64): i32 { let h: i64 = i64(root % 1000000007.0); h = h * 31 + i64(expiry / 60000.0); h = h * 31 + i64(Math.round(strike * 100.0)); h = h * 2 + (side > 0.0 ? 1 : 0); h ^= h >> 17; h *= 0x2545f491; h ^= h >> 13; return i32(h & i64(CAP - 1)); } // The contract's slot in this session's volume table, claimed when new; -1 once the table is seven eighths full. function slotOf(root: f64, expiry: f64, side: f64, strike: f64): i32 { const h = hashOf(root, expiry, side, strike); for (let probe = 0; probe < CAP; probe += 1) { const at = (h + probe) & (CAP - 1); if (slotSession[at] != sessionId) { if (used >= CAP - CAP / 8) return -1; slotSession[at] = sessionId; keyRoot[at] = root; keyExpiry[at] = expiry; keySide[at] = side; keyStrike[at] = strike; dayVolume[at] = 0.0; used += 1; return at; } if (keyRoot[at] == root && keyExpiry[at] == expiry && keySide[at] == side && keyStrike[at] == strike) return at; } return -1; } // 0 out of the money, 1 at the money (the strike within 0.5% of the close), 2 in the money; out without a close. function moneynessOf(sideCp: f64, strike: f64, spot: f64): i32 { if (!(spot > 0.0)) return 0; if (Math.abs(strike - spot) <= spot * 0.005) return 1; return (sideCp > 0.0 ? strike > spot : strike < spot) ? 0 : 2; } // A contract's score in the interval (flowScore), its contracts' scores by the side of the quote they took averaged by // size: above the ask (vol_above_ask, at most the ask's) and the rest at the ask, at the bid and below it (vol_below_bid, // at most the bid's), each at flowSideCode's code for it, the mid and unsided at 0; call or put, the moneyness against // the bar's close and the days to expiry from the bar's trade date `day`, no open interest and no repeat count. function contractScore(cells: StaticArray<f64>, i: i32, volume: f64, close: f64, day: f64): f64 { const sideCp = cells[i + 2]; const m = moneynessOf(sideCp, cells[i + 3], close); const dte = optionsTradeDay(cells[i + 1], zone) - day; const volAsk = cells[i + 4]; const volBid = cells[i + 5]; const above = Math.min(Math.max(cells[i + 14], 0.0), volAsk); const below = Math.min(Math.max(cells[i + 15], 0.0), volBid); const atAsk = (volAsk - above) * flowScore(flowSideCode(1.0, 0.0), sideCp, m, dte, NaN, 0); const overAsk = above * flowScore(flowSideCode(1.0, 1.0), sideCp, m, dte, NaN, 0); const atBid = (volBid - below) * flowScore(flowSideCode(-1.0, 0.0), sideCp, m, dte, NaN, 0); const underBid = below * flowScore(flowSideCode(-1.0, -1.0), sideCp, m, dte, NaN, 0); return (atAsk + overAsk + atBid + underBid) / volume; } // One row into this bar's top rows, kept in rank order; a row ranking below a full table is dropped. function keepRow(cells: StaticArray<f64>, i: i32, volume: f64, premium: f64, floor: bool, askPct: f64, bidPct: f64, dayPct: f64, score: f64): void { const key = byVolume ? volume : premium; let at = curCount; while (at > 0) { const above = (at - 1) * ROW_FIELDS; const aboveKey = byVolume ? curRows[above + 4] : curRows[above + 5]; if (aboveKey >= key) break; at -= 1; } if (at >= rowLimit) return; const last = curCount < rowLimit ? curCount : rowLimit - 1; for (let k = last; k > at; k -= 1) { for (let f = 0; f < ROW_FIELDS; f += 1) curRows[k * ROW_FIELDS + f] = curRows[(k - 1) * ROW_FIELDS + f]; curDay[k] = curDay[k - 1]; } const o = at * ROW_FIELDS; const present = cells[i + 16]; curRows[o] = cells[i]; curRows[o + 1] = cells[i + 1]; curRows[o + 2] = cells[i + 2]; curRows[o + 3] = cells[i + 3]; curRows[o + 4] = volume; curRows[o + 5] = premium; curRows[o + 6] = floor ? 1.0 : 0.0; curRows[o + 7] = askPct; curRows[o + 8] = bidPct; curRows[o + 9] = hasBit(present, 0) ? cells[i + 11] : NaN; // the VWAP when the cells carry it curRows[o + 10] = hasBit(present, 1) ? cells[i + 13] : NaN; // the last IV, percent, when they carry it curRows[o + 11] = score; curDay[at] = dayPct; if (curCount < rowLimit) curCount += 1; } // One bar's block: every contract adds to its session volume; the ones that pass the filters count as hits, add their // premium times their score to the bar's flow score and compete for the bar's top rows. function fold(n: i32): i32 { const cells = in_flow_view(); const close = bar.close(); const barDay = optionsTradeDay(bar.time() * 1000.0, zone); // the bar's trade date on the market's calendar let skipped = 0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (!contractOk(cells, i)) { skipped += 1; continue; } runCells += 1; const present = cells[i + 16]; if (isPartial(present)) curPartial = true; const volAsk = cells[i + 4]; const volBid = cells[i + 5]; const volume = volAsk + volBid + cells[i + 6] + cells[i + 7]; if (!(volume > 0.0)) continue; const slot = slotOf(cells[i], cells[i + 1], cells[i + 2], cells[i + 3]); let dayPct: f64 = NaN; if (slot >= 0) { dayVolume[slot] += volume; dayPct = (100.0 * volume) / dayVolume[slot]; } const floor = !hasBit(present, 0) || isNaN(optMult); // no VWAP or no multiplier: the premium at the ask plus at the bid, a floor const premium = floor ? cells[i + 8] + cells[i + 9] : cells[i + 11] * volume * optMult; if (premium < minPremium) continue; const askPct = (100.0 * volAsk) / volume; const bidPct = (100.0 * volBid) / volume; if (sideFilter == 1 && askPct < SIDE_SHARE) continue; if (sideFilter == 2 && bidPct < SIDE_SHARE) continue; const score = contractScore(cells, i, volume, close, barDay); curHits += 1; curHitPremium += premium; curScorePremium += premium * score; keepRow(cells, i, volume, premium, floor, askPct, bidPct, dayPct, score); } return skipped; } function fbStrike(strike: f64): void { // "660", "662.5", "17.25": a whole strike prints bare if (strike == Math.floor(strike)) fb_int(i64(strike)); else if (strike * 10.0 == Math.floor(strike * 10.0)) fb_f64(strike, 1); else fb_f64(strike, 2); } function fbContract(o: i32, rows: StaticArray<f64>, nowMs: f64): void { // "SPY 16 Oct 660C", the expiry 15 Jan '27 in another year fb_text("\""); fb_text(decodeSymbol(rows[o])); fb_text(" "); fbExpiryLabel(rows[o + 1], nowMs, zone); fb_text(" "); fbStrike(rows[o + 3]); fb_text(rows[o + 2] > 0.0 ? "C\"" : "P\""); } // The table on the live bar: the interval the setting picks, its top rows in rank order. function writeTable(): void { const rows = forming ? curRows : prevRows; const dayPcts = forming ? curDay : prevDay; const count = forming ? curCount : prevCount; const t = forming ? curTime : prevTime; const partial = forming ? curPartial : prevPartial; const hits = forming ? curHits : prevHits; fb_clear(); fb_text("{\"title\":\"Interval flow"); if (!isNaN(t)) { timeClock.update(t); fb_text(", "); if (timeClock.hour() < 10) fb_text("0"); fb_int(timeClock.hour()); fb_text(":"); if (timeClock.minute() < 10) fb_text("0"); fb_int(timeClock.minute()); if (forming) fb_text(", live"); } fb_text("\",\"caption\":\""); if (partial) fb_text("Some contracts left out: the counts are a minimum"); else if (count == 0) fb_text("No contract passes the filters in this interval"); else { fb_int(hits); fb_text(hits == 1 ? " contract passes" : " contracts pass"); } fb_text("\",\"rows\":["); for (let k = 0; k < count; k += 1) { const o = k * ROW_FIELDS; if (k > 0) fb_text(","); fb_text("["); fbContract(o, rows, t * 1000.0); fb_text(","); fb_f64(rows[o + 4], rows[o + 4] == Math.floor(rows[o + 4]) ? 0 : 4); // whole contracts bare, a coin size to four decimals fb_text(","); if (rows[o + 6] > 0.0) { // a floor: muted fb_text("{\"value\":"); fb_f64(rows[o + 5], 0); fb_text(",\"text_color\":\"theme.muted\"}"); } else fb_f64(rows[o + 5], 0); fb_text(","); fb_f64(rows[o + 7], 1); fb_text(","); fb_f64(rows[o + 8], 1); fb_text(","); fb_f64(rows[o + 9], 2); fb_text(","); fb_f64(rows[o + 10], 1); fb_text(","); fb_f64(dayPcts[k], 1); fb_text(",{\"value\":"); // the score: the up colour above 0, the down colour below, muted at 0, bold from 60 either way fb_num(rows[o + 11]); fb_text(rows[o + 11] > 0.0 ? ",\"text_color\":\"theme.up\"" : rows[o + 11] < 0.0 ? ",\"text_color\":\"theme.down\"" : ",\"text_color\":\"theme.muted\""); fb_text(Math.abs(rows[o + 11]) >= 60.0 ? ",\"font_weight\":\"bold\"}]" : "}]"); } fb_text("]}"); writeFrameBuffer(contract_rows); } // onBar() runs once per bar: this bar's top rows become the previous bar's, a new trade date starts the session's // volume table again, then the bar's block is folded, the histogram drawn and, on the live bar, the table written. function onBar(): void { for (let k = 0; k < curCount * ROW_FIELDS; k += 1) prevRows[k] = curRows[k]; for (let k = 0; k < curCount; k += 1) prevDay[k] = curDay[k]; prevCount = curCount; prevTime = curTime; prevPartial = curPartial; prevHits = curHits; curCount = 0; curTime = bar.time(); curPartial = false; curHits = 0; curHitPremium = 0.0; curScorePremium = 0.0; const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; sessionId += 1; used = 0; } const n = in_flow_cells(); const skipped = n >= TUPLE ? fold(n) : 0; out_hits(n >= TUPLE ? f64(curHits) : NaN); out_hit_premium(curHits > 0 ? curHitPremium : NaN); out_partial(curPartial ? 1.0 : 0.0); out_skipped(f64(skipped)); const flowScoreNow = curHits > 0 && curHitPremium > 0.0 ? curScorePremium / curHitPremium : NaN; // the premium-weighted mean out_flow_score(flowScoreNow); out_score_tone(isNaN(flowScoreNow) ? NaN : flowScoreNow >= 20.0 ? 1.0 : flowScoreNow <= -20.0 ? 0.0 : 2.0); if (!bar.isLast()) return; if (runCells > 0) writeTable(); str_note(runCells > 0 ? "" : "No contract flow on this chart yet"); // an empty text draws no label } ``` ## How it works **One line per contract.** The bar's block holds one 17-value tuple per contract that traded in it. Its volume is the four sides added (`vol_ask`, `vol_bid`, `vol_mid`, `vol_none`); the ask and bid columns are those sides' shares of it. Premium is the contract's VWAP times its size times the market's option multiplier, the chart's market fact `market.option_multiplier()` (100 shares on a US stock, the point value on CME, 50 on ES, 1 on a coin chain whose prices are USD per coin). Volume prints whole contracts bare and a coin's size to four decimals: 2.5 BTC reads 2.5, never a whole contract. On crypto and CME the ask and bid columns are the taker's side: bought and sold. A tuple whose VWAP is not served (bit 0 of its present mask clear) has its premium at the ask plus at the bid instead, a floor, and the table prints it muted; its average fill stays blank. A chart that does not know the multiplier gets the same floor on every row, never a guessed 100. The last IV, in percent, needs bit 1. **The filters.** A contract shows when its interval premium reaches Smallest premium, USD and, under Side, when at least 55% of its contracts were bought at the ask (`ask`) or sold at the bid (`bid`). The passing contracts compete for the table's Contracts listed, ranked by premium or by volume; a tie keeps the contract the block listed first. **The flow score.** Each passing contract's score is the options kit's `flowScore` ([Flow score](../functions/options-kit.md#flow-score)) for its contracts by the side of the quote they took, averaged by size: the contracts above the ask (`vol_above_ask`, at most the ask's) at `flowSideCode`'s +2, the rest of the ask at +1, the rest of the bid at -1, the contracts below the bid (`vol_below_bid`, at most the bid's) at -2, and the mid and the unsided at 0. The score reads call or put, the moneyness against the bar's close (at the money within 0.5%; the cells carry no underlying, so on an option contract's own chart, whose close is the contract's price, read the score with care) and the days to expiry from the bar's trade date on the market's clock; the cells carry no open interest and no repeat count, so the size factor reads as past the open interest. A bought call or a sold put scores above 0, a sold call or a bought put below. The Score column prints it with one decimal and its sign, in the up colour above 0, the down colour below, muted at 0, bold from 60 either way. The bar's flow score, `flow_score`, is the premium-weighted mean of its passing contracts' scores (the sum of each premium times its score over their premium), `NaN` on a bar no contract passes; it draws as a column in a strip with its own scale at the foot of the price pane (`out.inset`), and its tone, `score_tone` (1 at 20 or above, 0 at -20 or below, 2 between), colours both that column and the bar's Contracts passing column: the up colour, the down colour, and between them the strip's muted ink and the histogram's text colour. **The share of the day.** Every contract's volume, filtered or not, runs into a session table keyed by the contract (root, expiry, side, strike) that a new trade date empties. Of day is the interval's volume over that running total: a contract printing 40% of its day in one interval is a fill worth a look. **Which interval.** Interval reads the last closed bar (`closed`) or the bar trading now (`live`). Its time and each expiry's date read on the market's clock (`market.zone()`: New York on a US stock); a row names its contract with the expiry's label, the kit's `fbExpiryLabel` (`SPY 16 Oct 660C`, or `SPY 15 Jan '27 660C` for an expiry in another year). The package keeps each bar's top rows as it passes, so the closed interval's table is ready on the live bar. ## What the settings do - **Rank by**: Orders the table by premium (the money paid) or by contracts traded. - **Smallest premium, USD**: Hides contracts with less premium (the money paid) in the interval than this. - **Side**: Keeps all contracts, or those at least 55% bought at the ask (seller's price) or sold at the bid. - **Contracts listed**: How many contracts the table shows, from 3 to 30. - **Interval**: Shows the last finished bar, or the bar trading now. ## Where it runs On crypto, it reads each coin's own listed options. A copy you run from the editor (where you write and run indicators) reads them too. On a US stock or ETF with listed options, every indicator in your browser can read them. That holds on its option contracts' charts too. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). There they are real time if you have real-time CME data, and 10 minutes behind otherwise. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. ## When data is missing The table's caption counts the contracts that pass, or reads "No contract passes the filters in this interval". It reads "Some contracts left out: the counts are a minimum" when the bar's list was cut short. A bar with no data draws no histogram column. An entry with an incomplete contract is never listed. In the Console (the editor's prompt that shows a reading by its name), `skipped` counts it. Incomplete means an unreadable symbol, no expiry date, no strike (the option's price level), or no option type. "No contract flow on this chart yet" means no bar on the chart carried a contract. ## Customize it - **The ask-side intervals.** Set Side to `ask` and Smallest premium, USD to 100,000 for the aggressive buyers only. - **Wider intervals.** Read a 15-minute chart for fills spread over a quarter hour; the histogram then counts per quarter hour. - **The one-sided intervals.** Set Side to `ask` and watch the strip: a tall column in the up colour is an interval of bought calls and sold puts, in the down colour bought puts and sold calls. - **Volume over open interest.** Join the `option_contract_state` cells on the live bar to compare each contract's day volume with its open interest. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Interval Flow** under **Order flow**. 2. Press **Run** on a five-minute chart of a coin with listed options or of a US stock: the last closed interval's contracts list under the chart. 3. At the editor's Console prompt, type `last 20 hits` for the last 20 intervals' passing contracts, `hit_premium` for the newest interval's premium and `last 20 flow_score` for the intervals' flow scores. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_contract_flow) for the `option_contract_flow` tuple - [Data sources](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit`, `isPartial` and the symbol codec - [Cards, frames and panels](../presentation/cards-frames-panels.md#panel-words) for the styled `panel.table` and its cells - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel` - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/premium-by-strike --> # Premium by strike A heat map behind the candles shows options money at each strike (the option's price level), bar by bar. Up-colour boxes hold premium (the money paid for an option) betting on a rise, down-colour boxes betting on a fall. A line marks the strike where each bar's money centres, and its band shows how widely the money spread. The profile (bars on the price axis) totals today's money per strike. Use it to find levels traders defend or target, on coins, CME (Chicago futures exchange) futures or US stocks. Under the hood: it reads `option_strike_flow.cells` grouped by strike with `strike_window_pct: 10` and `fold_types: true` ([Data sources](../core-concepts/data-sources.md#option_strike_flow)). It paints an `out.grid` through a `plot.heatmap` centred on 0 ([Price canvases](../presentation/price-canvases.md#a-grid-the-module-computes)). It docks a `plot.levels` profile coloured per strike ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)). It draws three lines and a shaded band for the premium centre (the `flow_vwap` line, [Plotting](../presentation/plotting.md#ranges-and-panels)) and marks incomplete bars with `isPartial` ([Data sources](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). This is also the `premium-by-strike` template: the **Premium by Strike** card under **Order flow** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Premium by Strike: where options money traded, strike by strike, as a heat map behind the candles. The heat map is a // grid of coloured boxes. Premium is the money paid for options. A strike is an option's price level. Each column is // one bar, and each box in it is one strike. A box in the chart's up colour holds money betting on a rise. Calls (bets // on a rise) bought at the ask (buyers paying the seller's price) count as up money. Puts (bets on a fall) sold at the // bid (sellers taking the buyer's price) count as up money too. Puts bought at the ask and calls sold at the bid count // as down money, in the down colour. Brighter boxes hold more money. Read one strike from left to right to see when its // money arrived. The profile (bars on the price axis) adds up today's money at each strike. A strike with heavy money // is a level traders defend or target. The premium centre line marks the strike where each bar's money centred. Use it // to find the prices options traders care about today. // // Under the hood: a strike's net premium is its bullish premium minus its bearish premium: calls bought at the ask and // puts sold at the bid are bullish, puts bought at the ask and calls sold at the bid bearish, so a cell in the chart's // up colour is money leaning up at that strike in that bar and one in its down colour money leaning down. Premium at // the mid or with no quote has no side and counts in neither. The rows are the chain's strike spacing (read off the // strikes that traded: the most common gap near the price) unless Strike step sets one, 48 of them centred on each // bar's close; the docked profile sums the session (each trade date starts again) over the strikes within Profile // window of the close. The cells come from option_strike_flow, the data plane's sums of each bar's flow per strike // within 10% of the underlying, calls and puts in one row with the bullish side on the ask: a bar served in part (the // partial bit, 14) gets a muted dot under its candle, its column a floor; a row that is not whole (no strike) is // skipped and counted. 1-minute cells reach back 7 days and 5-minute cells 30 days. Every print takes a side, cross // trades and late prints too: the heat map's and the profile's hover say so. The premium centre (the flow_vwap line, // labelled Premium centre so no one takes it for the Flow VWAP indicator) is each bar's premium-weighted centre strike // over every strike of its flow (all premium, every side, mid and unquoted too), a line on price with a band one // premium-weighted standard deviation of the strikes either side, lightly shaded. // // Version 0.4 adds the premium centre: its two settings and three lines come after 0.3's, so every earlier slot keeps // its place. section("Strikes"); param.number("row_step", 0, { min: 0, max: 10000, step: 0.5, label: "Strike step", description: "How much price each level of the heat map covers. 0 uses the gap between listed strikes (option price levels), 500 to 5,000 on BTC." }); param.number("profile_pct", 8, { min: 1, max: 50, label: "Profile window, percent", description: "The profile shows today's options money per strike (option price level) on the price axis. This sets how far it reaches each way, in percent." }); section("Premium centre"); param.bool("flow_vwap", true, { label: "Premium centre", description: "A line at the price where each bar's options money centres. Each strike (option price level) counts by its premium (money paid)." }); param.bool("vwap_band", true, { label: "Premium centre band", when: "flow_vwap", description: "A light band one standard deviation (1σ) either side of the premium centre. A wide band means the money spread over many strikes." }); input("close", ohlcv.close); // the chart's own candles: the bar grid and each column's centre input("trade_date", time.trade_date); // the bar's trade date: the docked profile starts again on each input("flow", option_strike_flow.cells, { max_cells: 4000, group: "strike", strike_window_pct: 10, fold_types: true, description: "Each bar's options trades per strike within 10% of the price, calls and puts together, with bullish money on the ask side. Fields: [expiry_ms, strike, side_cp, dte_class, vol_ask, vol_bid, vol_mid, vol_none, vol_above_ask, vol_below_bid, prem_ask, prem_bid, prem_mid, prem_none, present]" }); output("partial_mark", shape, overlay, { color: "theme.muted", description: "A muted dot under a candle when only part of that bar's options data arrived. Its column is then a minimum." }); // first output on price: the package homes on the chart output("heat_low", none, overlay, { description: "The price at the bottom edge of the heat map on this bar" }); // data-only: the heatmap reads it output("heat_step", none, overlay, { description: "How much price each level of the heat map covers on this bar" }); out.grid("heat", { rows: 48 }); // 48 data-only outputs heat_0..heat_47, one per row, written with out_heat(row, value) plot.heatmap({ name: "net_heat", grid: "heat", price_low: "heat_low", price_step: "heat_step", center: 0, auto_quantile: 0.98, opacity: 0.7, behind_candles: true, label: "Net premium by strike", tooltip: "{{value:usd}} net premium at the {{price}} strike. Includes cross and late trades" }); // the diverging default: the chart's down colour, its background, its up colour // The readings, data-only: the Console reads them. output("session_net", none, overlay, { description: "Today's bullish minus bearish premium (money paid for options) over every strike, in USD. Includes cross and late trades" }); output("top_bull_strike", none, overlay, { description: "The strike (option price level) holding today's largest bullish net premium" }); output("top_bull_net", none, overlay, { description: "That strike's net premium (money paid for options) today, in USD. Includes cross and late trades" }); output("top_bear_strike", none, overlay, { description: "The strike (option price level) holding today's largest bearish net premium" }); output("top_bear_net", none, overlay, { description: "That strike's net premium (money paid for options) today, in USD, below zero. Includes cross and late trades" }); output("skipped", none, overlay, { description: "Strike entries on this bar left out because they were incomplete" }); // Version 0.4's premium centre (the flow_vwap line), after the readings, so every output before it keeps its slot. output("flow_vwap", line, overlay, { color: "theme.text", width: 2, format: "price", label: "Premium centre", description: "The strike (option price level) where this bar's premium (money paid for options) centres. It is the premium-weighted average strike, every side counted." }); output("vwap_hi", line, overlay, { color: "theme.muted", width: 1, line_style: "dotted", format: "price", label: "Premium centre +1σ", description: "The premium centre plus one standard deviation (1σ) of the bar's strikes, weighted by premium" }); output("vwap_lo", line, overlay, { color: "theme.muted", width: 1, line_style: "dotted", format: "price", label: "Premium centre -1σ", description: "The premium centre minus one standard deviation (1σ) of the bar's strikes, weighted by premium" }); fill("vwap_hi", "vwap_lo", { color: "theme.muted", opacity: 0.08 }); // the band, lightly shaded string("note", { max_bytes: 64 }); // the one line while there is nothing to draw const strike_rows = frame("strike_rows", { max_bytes: 24576 }); plot.levels({ name: "session_by_strike", frame: strike_rows, dock: "right", width_frac: 0.14, baseline: "center", labels: false, thickness_px: 8, hover: true, format: "usd" }); render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const TUPLE = 15; // f64s per row: OPTION_STRIKE_FLOW_TUPLE const ROWS = 48; // the heat map's rows, the grid's declared count const MAX_SEEN = 1024; // distinct strikes kept over the run, the nearest the close: the spacing reads them const MAX_STRIKES = 512; // the session's strikes, the nearest the close const MAX_PROFILE = 256; // rows docked on the axis const STEPS: StaticArray<f64> = [0.5, 1.0, 2.0, 2.5, 5.0, 10.0, 20.0, 25.0, 50.0, 100.0, 200.0, 250.0, 500.0, 1000.0, 2000.0, 2500.0, 5000.0]; // the listed strike spacings, a coin's too const stepCount = new StaticArray<i32>(STEPS.length); const seen = new StaticArray<f64>(MAX_SEEN); // the run's distinct strikes, ascending const strikeAt = new StaticArray<f64>(MAX_STRIKES); // the session's strikes, ascending, and their net premium const netAt = new StaticArray<f64>(MAX_STRIKES); const rowHeat = new StaticArray<f64>(ROWS); // this bar's column const rowTouched = new StaticArray<bool>(ROWS); let fixedStep = 0.0; // settings, read in onStart() let profilePct = 0.08; let vwapOn = true; let bandOn = true; let day: f64 = NaN; // the trade date the profile sums let seenCount = 0; let strikeCount = 0; let runCells = 0; // rows read over the whole run let close: f64 = NaN; // this bar function onStart(): void { fixedStep = p_row_step(); profilePct = p_profile_pct() / 100.0; vwapOn = p_flow_vwap() > 0.5; bandOn = p_vwap_band() > 0.5; } // A row's premium, every side: at the ask and the bid (either lean), at the mid and with no quote. function premiumOf(cells: StaticArray<f64>, i: i32): f64 { const premium = cells[i + 10] + cells[i + 11] + cells[i + 12] + cells[i + 13]; return premium > 0.0 ? premium : 0.0; } function clearVwap(): void { // no premium centre on this bar out_flow_vwap(NaN); out_vwap_hi(NaN); out_vwap_lo(NaN); } // The premium centre of the bar's whole rows: the premium-weighted mean strike and one premium-weighted standard deviation // of the strikes either side; none where the bar holds no premium or the setting is off. function writeVwap(cells: StaticArray<f64>, n: i32): void { let weight = 0.0; let moment = 0.0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (!rowOk(cells, i)) continue; const premium = premiumOf(cells, i); weight += premium; moment += premium * cells[i + 1]; } if (!vwapOn || !(weight > 0.0)) { clearVwap(); return; } const centre = moment / weight; let spread = 0.0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (!rowOk(cells, i)) continue; const gap = cells[i + 1] - centre; spread += premiumOf(cells, i) * gap * gap; } const sigma = Math.sqrt(spread / weight); out_flow_vwap(centre); out_vwap_hi(bandOn ? centre + sigma : NaN); out_vwap_lo(bandOn ? centre - sigma : NaN); } // A row counts when it names a strike, calls and puts in one row, and its present mask is a whole number from 0 up // (the all-zero row of a bar served in part with no flow does not). function rowOk(cells: StaticArray<f64>, i: i32): bool { const present = cells[i + 14]; return cells[i + 1] > 0.0 && cells[i + 2] == 0.0 && present >= 0.0 && present == Math.floor(present); } // Where a strike sits in an ascending table: its index when listed, else the index it would take. function lowerBound(keys: StaticArray<f64>, count: i32, key: f64): i32 { let lo = 0; let hi = count; while (lo < hi) { const mid = (lo + hi) >> 1; if (keys[mid] < key) lo = mid + 1; else hi = mid; } return lo; } // Which end of a full table leaves for a new strike: 0 the low end, 1 the high end, -1 the new strike itself (it is // the farthest from the close). function evict(keys: StaticArray<f64>, count: i32, strike: f64): i32 { const dLow = Math.abs(keys[0] - close); const dHigh = Math.abs(keys[count - 1] - close); const dNew = Math.abs(strike - close); if (dNew >= dLow && dNew >= dHigh) return -1; return dLow >= dHigh ? 0 : 1; } // One more distinct strike into the run's table, the nearest the close kept. function noteSeen(strike: f64): void { let at = lowerBound(seen, seenCount, strike); if (at < seenCount && seen[at] == strike) return; if (seenCount >= MAX_SEEN) { const end = evict(seen, seenCount, strike); if (end < 0) return; if (end == 0) { for (let k = 1; k < seenCount; k += 1) seen[k - 1] = seen[k]; at -= 1; } seenCount -= 1; if (at > seenCount) at = seenCount; } for (let k = seenCount; k > at; k -= 1) seen[k] = seen[k - 1]; seen[at] = strike; seenCount += 1; } // A contract's net premium onto its strike for the session, the nearest strikes to the close kept. function addNet(strike: f64, net: f64): void { let at = lowerBound(strikeAt, strikeCount, strike); if (at < strikeCount && strikeAt[at] == strike) { netAt[at] += net; return; } if (strikeCount >= MAX_STRIKES) { const end = evict(strikeAt, strikeCount, strike); if (end < 0) return; if (end == 0) { for (let k = 1; k < strikeCount; k += 1) { strikeAt[k - 1] = strikeAt[k]; netAt[k - 1] = netAt[k]; } at -= 1; } strikeCount -= 1; if (at > strikeCount) at = strikeCount; } for (let k = strikeCount; k > at; k -= 1) { strikeAt[k] = strikeAt[k - 1]; netAt[k] = netAt[k - 1]; } strikeAt[at] = strike; netAt[at] = net; strikeCount += 1; } // The chain's strike spacing: the most common gap between neighbouring strikes within 10% of the close, matched to // a listed spacing (the smaller on a tie); the smallest gap when none matches; NaN with fewer than two strikes. function spacing(): f64 { for (let c = 0; c < STEPS.length; c += 1) stepCount[c] = 0; let smallest: f64 = NaN; let prev: f64 = NaN; for (let k = 0; k < seenCount; k += 1) { const strike = seen[k]; if (Math.abs(strike - close) > close * 0.1) continue; if (!isNaN(prev)) { const gap = strike - prev; if (gap > 0.0 && (isNaN(smallest) || gap < smallest)) smallest = gap; for (let c = 0; c < STEPS.length; c += 1) { if (Math.abs(gap - STEPS[c]) <= STEPS[c] * 0.01) { stepCount[c] += 1; break; } } } prev = strike; } let best = -1; for (let c = 0; c < STEPS.length; c += 1) if (stepCount[c] > 0 && (best < 0 || stepCount[c] > stepCount[best])) best = c; return best >= 0 ? STEPS[best] : smallest; } function writeProfile(): void { const lo = close * (1.0 - profilePct); const hi = close * (1.0 + profilePct); let first = 0; while (first < strikeCount && strikeAt[first] < lo) first += 1; let last = first; while (last < strikeCount && strikeAt[last] <= hi) last += 1; while (last - first > MAX_PROFILE) { // a wide window on a fine ladder: drop the row farther from the close if (close - strikeAt[first] >= strikeAt[last - 1] - close) first += 1; else last -= 1; } if (last <= first) return; // no strike inside the window: the profile stays absent fb_clear(); fb_text("{\"prices\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(strikeAt[k]); } fb_text("],\"values\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_f64(netAt[k], 0); } fb_text("],\"colors\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_text(netAt[k] > 0.0 ? "\"theme.up\"" : netAt[k] < 0.0 ? "\"theme.down\"" : "\"theme.muted\""); // bullish up, bearish down } fb_text("],\"tooltips\":["); // each row's hover hint for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_text("\"Includes cross and late trades\""); } fb_text("]}"); writeFrameBuffer(strike_rows); } // onBar() runs once per bar: a new trade date starts the profile again; the bar's rows add each strike's net // premium to the strike for the session and to its heat row for this bar's column, and weigh its strikes by premium // for the premium centre; then the readings, the column and, on the live bar, the docked profile. function onBar(): void { close = bar.close(); const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; strikeCount = 0; } for (let r = 0; r < ROWS; r += 1) { rowHeat[r] = 0.0; rowTouched[r] = false; } const n = in_flow_cells(); let skipped = 0; let partial = false; if (n >= TUPLE && !isNaN(close)) { const cells = in_flow_view(); for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { // the strikes first: the spacing reads them if (rowOk(cells, i)) noteSeen(cells[i + 1]); } const step = fixedStep > 0.0 ? fixedStep : spacing(); const gridLow = isNaN(step) ? NaN : (Math.round(close / step) - f64(ROWS / 2)) * step - step * 0.5; // rows centred on the spacing's multiples for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (!rowOk(cells, i)) { skipped += 1; continue; } runCells += 1; if (isPartial(cells[i + 14])) partial = true; const strike = cells[i + 1]; const net = cells[i + 10] - cells[i + 11]; // folded: bullish (the ask columns) minus bearish (the bid columns) addNet(strike, net); if (isNaN(gridLow)) continue; const r = i32(Math.floor((strike - gridLow) / step)); if (r < 0 || r >= ROWS) continue; // off this bar's column rowHeat[r] += net; rowTouched[r] = true; } out_heat_low(gridLow); out_heat_step(step); writeVwap(cells, n); } else { out_heat_low(NaN); out_heat_step(NaN); clearVwap(); } for (let r = 0; r < ROWS; r += 1) out_heat(r, rowTouched[r] ? rowHeat[r] : NaN); // NaN = an empty cell out_partial_mark(partial ? bar.low() : NaN); out_skipped(f64(skipped)); let sessionNet = 0.0; let bullStrike: f64 = NaN; let bullNet: f64 = NaN; let bearStrike: f64 = NaN; let bearNet: f64 = NaN; for (let k = 0; k < strikeCount; k += 1) { const net = netAt[k]; sessionNet += net; if (net > 0.0 && (isNaN(bullNet) || net > bullNet)) { bullNet = net; bullStrike = strikeAt[k]; } if (net < 0.0 && (isNaN(bearNet) || net < bearNet)) { bearNet = net; bearStrike = strikeAt[k]; } } out_session_net(strikeCount > 0 ? sessionNet : NaN); out_top_bull_strike(bullStrike); out_top_bull_net(bullNet); out_top_bear_strike(bearStrike); out_top_bear_net(bearNet); if (!bar.isLast()) return; if (strikeCount > 0 && !isNaN(close)) writeProfile(); str_note(runCells == 0 ? "No contract flow on this chart yet" : strikeCount == 0 ? "No contract flow yet this session" : ""); // an empty text draws no label } ``` ## How it works **Net premium per strike.** The data plane sums each bar's prints per strike, calls and puts in one row with the bullish side on the ask (`fold_types`): `prem_ask` holds the calls' premium at the ask and the puts' at the bid, `prem_bid` the calls' at the bid and the puts' at the ask. A strike's net is the ask premium minus the bid premium, so it reads bullish above zero. Premium at the mid or with no quote has no side and counts in neither. On crypto and CME a print carries the taker's side, so the ask is what the taker bought and the bid what the taker sold. **The rows.** The heat map's 48 rows sit on the chain's strike spacing: the package keeps every distinct strike that traded, and the spacing is the most common gap between neighbouring strikes within 10% of the close, matched to a listed spacing (0.5, 1, 2, 2.5, 5 and up to 100 on a stock, and 200, 250, 500, 1,000, 2,000, 2,500 and 5,000 on a coin's chain, so BTC's 1,000 ladder reads 1,000, never the 500 one strike between leaves); **Strike step** sets one by hand, up to 10,000. Each bar's rows are centred on its close, one row per spacing step with a strike in the middle of each, so a strike's flow lands on the row holding it. The rows of a bar sum its strikes there; a row no strike touched draws nothing. **The session by strike.** The same nets add into a table of the session's strikes, which a new trade date empties; on the live bar the strikes within Profile window of the close dock on the price axis, in the up colour above zero and the down colour below. `top_bull_strike` and `top_bear_strike` name the session's strongest strikes either way. **The premium centre.** On every bar with strike flow, `flow_vwap` is the bar's premium-weighted centre strike: each whole row's premium on every side (`prem_ask`, `prem_bid`, `prem_mid` and `prem_none`, so the mid and unquoted prints count here though they take no lean) times its strike, summed, over the premium summed. `vwap_hi` and `vwap_lo` sit one premium-weighted standard deviation of the bar's strikes either side, the square root of the premium-weighted mean of each strike's squared distance from the centre, and `fill` shades between them. A row that is not whole is left out, as it is from the heat map; a bar with no premium, or no block, draws no line. **Premium centre** turns the three lines off, **Premium centre band** the band alone. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the heat map's hover, each docked row's hover and the descriptions of the net readings. ## What the settings do - **Strike step**: How much price each heat map level covers, where 0 uses the gap between listed strikes (option price levels). - **Profile window, percent**: How far the profile on the price axis reaches above and below the price. - **Premium centre**: Draws a line at the strike where each bar's premium (money paid for options) centres. - **Premium centre band**: Shades one standard deviation (1σ) either side of that line, wider when the money spreads out. ## Where it runs It runs on coins with listed options and reads the coin's own options. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read this data. The charts of that stock's option contracts work the same way. US options data is 15 minutes behind unless you have real-time US options data. On a futures chart from CME, the Chicago exchange, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. It reads the strikes within 10% of the price. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. ## When data is missing When only part of a bar's options data arrives, a muted dot sits under its candle. That column then shows a minimum, so the real amount may be higher. A bar with no options data shows an empty column. Incomplete entries are left out: no strike, calls and puts not added together, or an unreadable data flag. To count them, open the Console (the editor's panel that prints values) and type `skipped`. A label at the top says "No contract flow on this chart yet" until a bar has an options trade. It says "No contract flow yet this session" while today has none. ## Customize it - **Coarser rows.** Set **Strike step** to 5 on a stock whose strikes crowd, or to 2,000 on BTC, so each row sums a few strikes. - **The profile's reach.** Widen Profile window to see the far strikes the session's money reached. - **The centre alone.** Turn **Premium centre band** off to keep the line and drop the band. - **Today's expiries.** Add `expiries: "0dte"` to the input to paint the contracts expiring on the bar's trade date alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Premium by Strike** under **Order flow**. 2. Press **Run** on a chart of a coin with listed options or of a US stock: the heat map paints behind the candles and the session's profile docks on the price axis. 3. At the editor's Console prompt, type `session_net`, `top_bull_strike` and `top_bear_strike` to read the session, and `flow_vwap` for the live bar's centre strike. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_strike_flow) for the `option_strike_flow` tuple, `strike_window_pct` and `fold_types` - [Price canvases](../presentation/price-canvases.md#a-grid-the-module-computes) for `out.grid` and `plot.heatmap` - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels` and per-row colours - [Plotting](../presentation/plotting.md#ranges-and-panels) for the premium centre's band - [Data sources](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for the partial bit - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/market-hud --> # Market HUD One card at the bottom of the price pane that reads the market in one glance and follows every tick, in the chart's default look. The trend word leads as the headline: Bullish when the close is above the EMA and RSI is above 50, Bearish when it is below both, else Mixed, in the up, down or muted colour. Under it, three activity rings read RSI, the taker buy share of the last 20 bars and this bar's volume so far against its 20-bar average, each value printed beside its ring; then ATR as a percent of price, and the open-interest change over the last 20 bars, counted in contracts, as a sparkline. The EMA is drawn on price, and the legend names the lengths in use. The card is one `render.hud` declaration of four tiles and no `look` word ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)): a headline `tile.pill` coloured by a ladder output, a `tile.rings` of three outputs, a `tile.value` and a `tile.spark`, each reading data-only outputs written on every bar. It reads side-split `trades.volume`, an `oi.close` input that reads NaN where the market has none and a `funding.rate_close` input that reads NaN off perpetuals ([Data sources](../core-concepts/data-sources.md)), with the `Ema`, `Rsi`, `Atr` and `Roc` helpers ([TA library](../functions/ta-library.md)). This is also the `market-hud` template: the **Market HUD** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Market HUD: one card in a corner of the price pane that reads the market in one glance, drawn by the chart in its // default look. The trader sees the trend word first, large (Bullish when the close is above the EMA and RSI is above // its midline, Bearish when it is below both, else Mixed, in the up, down or muted colour), then three activity // rings with their readings beside them (RSI, the taker buy share over the flow window, and this bar's volume so far // against its average over the same window), then ATR as a percent of price and the open-interest change over the // flow window as a filled line, counted in contracts: coins on a perpetual (the dollar reading over the bar's close, so // a price move alone never moves it), the reading as served on a prediction market (already a count of YES and NO // pairs). The EMA itself is drawn on price. A tile whose market has no data prints a dash: // open interest on spot, stocks and FX; the taker share where the venue has no sided trades. Every number on the card // is a data-only output written on every bar, so the line has history and the Console or a watch reads the same // values the card shows (the close's distance from the EMA too). // Settings: every length is a whole number with bounds; the flow window also spans the open-interest change. The // trend word's RSI midline is a setting too, and the last section holds the EMA line's colour. section("Lengths"); param.int("ema_len", 50, { min: 2, max: 400, label: "EMA length, bars", description: "EMA length in bars, the trend reference" }); param.int("rsi_len", 14, { min: 2, max: 200, label: "RSI length, bars", description: "RSI length in bars (Wilder smoothing)" }); param.int("atr_len", 14, { min: 2, max: 200, label: "ATR length, bars", description: "ATR length in bars (Wilder smoothing)" }); param.int("flow_len", 20, { min: 2, max: 200, label: "Flow window, bars", description: "Bars in the flow window and in the open-interest change" }); section("Trend word"); param.number("rsi_mid", 50, { min: 1, max: 99, step: 1, label: "RSI midline", description: "RSI midline: Bullish needs RSI above it and the close above the EMA, Bearish needs both below" }); section("Look"); param.color("ema_color", "#38bdf8", { label: "EMA line" }); // The legend reads the lengths after the name ("Market HUD 50 14 14 20"): a tile label is a fixed string, so the // card's labels name what they read in words and the settings in use ride the legend. legend({ title: "{{ema_len}} {{rsi_len}} {{atr_len}} {{flow_len}}" }); // Inputs: the chart's own candles set the grid; flow reads sided trades (a bar with no prints reads 0); open // interest reads NaN on a bar without a reading and where the market has none; funding is served on perpetuals only // (NaN elsewhere), which tells the file its open interest is dollars to turn into coins. input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero" }); input("sell", trades.volume, { side: "SELL", missing: "zero" }); input("oi", oi.close, { missing: "nan" }); input("funding", funding.rate_close, { missing: "nan" }); // Outputs: the EMA is drawn on price; the rest are data-only, one value per bar behind the card's tiles. The first // five keep their names and order from the earlier card; the trend rung, the EMA distance and the buy share are new. // A static colour on a data-only output is the colour its dial, sparkline or meter draws in. const emaLine = output("ema", line, overlay, { color: "@ema_color", width: 1, label: "EMA", format: "price", description: "EMA of the close over ema_len bars" }); // the colour setting paints it; the handle names it for the hover card output("rsi", none, overlay, { color: "theme.text", format: "0.0", description: "RSI of the close over rsi_len bars" }); output("atr_pct", none, overlay, { format: "%", description: "ATR over atr_len bars as a percent of the close" }); output("flow", none, overlay, { description: "Buy minus sell volume over flow_len bars, as a percent of their sum" }); output("oi_change", none, overlay, { color: "theme.text", format: "%", description: "Open-interest change over flow_len bars in contracts (coins on a perpetual, as served on a prediction market), percent" }); output("trend", none, overlay, { description: "The trend word as a ladder rung: 0 bearish, 1 mixed, 2 bullish" }); output("ema_dist", none, overlay, { format: "%", description: "Close minus the EMA, as a percent of the EMA" }); output("buy_share", none, overlay, { color: "theme.muted", format: "%", description: "Taker buy volume over flow_len bars, as a percent of all taker volume" }); output("volume_ratio", none, overlay, { format: "%", description: "Bar volume as a percent of its average over flow_len bars; on the live bar, its volume so far" }); hover(emaLine, [block.value("EMA", "ema", { format: "price" }), block.rows([["RSI", "rsi", "0.0"], ["ATR %", "atr_pct", "0.00"], ["Flow %", "flow", "0.0"], ["OI change in contracts %", "oi_change", "0.00"]])]); // the card the EMA line opens under the cursor: its value and the card's numbers // The trend word (or the bars the card still needs), written on the live bar into a bounded string slot the first // tile reads. string("trend_word", { max_bytes: 16 }); // The card: the trend word leads as the headline across both columns, its colour following the trend rung (down, // muted, up); the rings span the card under it, RSI on the outer ring; ATR and the open-interest line pair up below. render.hud("market", { position: "bottom_center", title: "Market", columns: 2, tiles: [ tile.pill("Trend", "trend_word", { headline: true, color_by: "trend", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.rings("Momentum, flow and volume", [ ["RSI", "rsi", { min: 0, max: 100 }], ["Buy share", "buy_share", { min: 0, max: 100 }], ["Volume so far", "volume_ratio", { min: 0, max: 200 }], ]), tile.value("ATR, % of price", "atr_pct", { format: "%" }), tile.spark("OI in contracts", "oi_change", { bars: 64 }), ] }); // The flow window is a ring of the last bars' buy and sell volume, sized for the largest window at load; onStart() // reads the window in use. const MAX_WINDOW = 200; const buys = new StaticArray<f64>(MAX_WINDOW); const sells = new StaticArray<f64>(MAX_WINDOW); const vols = new StaticArray<f64>(MAX_WINDOW); let volBars = 0; let flowLen = 20; let rsiMid = 50.0; let warmBars = 50; // the bars the EMA, RSI and ATR need before the card answers let ema = new Ema(50); let rsi = new Rsi(14); let atr = new Atr(14); let rawChange = new Roc(20); // the open-interest change as served, and in coins: the funding feed picks one let coinChange = new Roc(20); let oiRaw: f64 = NaN; // the last open-interest reading and its coins; a new bar keeps them until its own reading lands let oiCoins: f64 = NaN; let perp = false; // funding seen: a perpetual, whose dollar open interest moves with price let head = 0; // onStart() runs once before the first bar: read the settings and size the helpers to them. function onStart(): void { flowLen = i32(p_flow_len()); rsiMid = p_rsi_mid(); warmBars = i32(Math.max(p_ema_len(), Math.max(p_rsi_len() + 1.0, p_atr_len()))); ema = new Ema(i32(p_ema_len())); rsi = new Rsi(i32(p_rsi_len())); atr = new Atr(i32(p_atr_len())); rawChange = new Roc(flowLen); coinChange = new Roc(flowLen); } // onBar() runs once per bar: fold the bar into every helper and the flow ring, then write the outputs; the trend // word is written on the live bar only. function onBar(): void { const close = bar.close(); const emaValue = ema.update(close); const rsiValue = rsi.update(close); const atrPct = (atr.update(bar.high(), bar.low(), close) / close) * 100.0; // The ring's sums are recounted from its slots: a running sum that adds and subtracts keeps a rounding crumb // after a quiet stretch, and a crumb over a crumb would read as a share. buys[head] = in_buy(); sells[head] = in_sell(); vols[head] = bar.volume(); head = (head + 1) % flowLen; if (volBars < flowLen) volBars += 1; let buySum = 0.0; let sellSum = 0.0; let volSum = 0.0; for (let i = 0; i < flowLen; i += 1) { buySum += buys[i]; sellSum += sells[i]; volSum += vols[i]; } const total = buySum + sellSum; const flowPct = total > 0.0 ? ((buySum - sellSum) / total) * 100.0 : NaN; // NaN where the venue has no sided trades const buyShare = total > 0.0 ? (buySum / total) * 100.0 : NaN; const oiNow = in_oi(); if (!isNaN(oiNow)) { oiRaw = oiNow; oiCoins = oiNow / close; // dollars over the close: the coins, whatever price did } if (!isNaN(in_funding())) perp = true; const rawPct = rawChange.update(oiRaw); const coinPct = coinChange.update(oiCoins); const oiPct = perp ? coinPct : rawPct; // NaN on markets without open interest, and until the window is full const volAvg = volSum / f64(volBars); if (isNaN(emaValue) || isNaN(rsiValue) || isNaN(atrPct)) { // warm-up rows write nothing; the live bar says why if (bar.isLast()) { sb_clear(); sb_text("Needs "); sb_int(warmBars); sb_text(" bars"); str_trend_word_sb(); } return; } const bullish = close > emaValue && rsiValue > rsiMid; const bearish = close < emaValue && rsiValue < rsiMid; out_ema(emaValue); out_rsi(rsiValue); out_atr_pct(atrPct); out_flow(flowPct); out_oi_change(oiPct); out_trend(bearish ? 0.0 : bullish ? 2.0 : 1.0); out_ema_dist(((close - emaValue) / emaValue) * 100.0); out_buy_share(buyShare); out_volume_ratio(volAvg > 0.0 ? (bar.volume() / volAvg) * 100.0 : NaN); // on the live bar, its volume so far if (bar.isLast()) { sb_clear(); sb_text(bullish ? "Bullish" : bearish ? "Bearish" : "Mixed"); str_trend_word_sb(); } } ``` ## How it works **One declaration is the card.** `render.hud("market", { position: "bottom_center", title: "Market", columns: 2, tiles: [...] })` names the anchor, the title and four tiles; the chart draws the card, keeps it at its anchor while the chart pans, and opens any tile as a hover card under the pointer. `headline: true` gives the trend pill the whole first row, where the answer reads before anything else. The rings are a wide tile that spans the card under it, and the ATR value and the open-interest sparkline share the last row. **No look word, the default look.** With no `look`, the chart draws the card in its default look: near black and translucent (white paper on a light chart) with a hairline border and 12 px corners, the title in sentence case, the headline at 17 px bold with its label hidden, the pill as its word in its colour with no capsule and no dot, and the spark as a line. A word declared on the card wins over the default ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). **Three rings in one tile.** `tile.rings` takes up to three `[label, output, { min, max, color }]` entries, outermost first: RSI from 0 to 100, the buy share from 0 to 100 and volume against its average from 0 to 200. Each ring fills the share of its own range its output holds, so a ring closes at RSI 100, at a window of nothing but taker buys, or on a bar with twice its average volume. With no `color` of their own, the rings draw in the card's accent at full, 70 and 45 percent strength, and the legend beside them prints each value in its output's format. **Every number is an output.** `trend`, `rsi`, `buy_share`, `volume_ratio`, `atr_pct` and `oi_change` are data-only outputs (`none`), one value per bar. A tile reads the newest row and the sparkline the last 64. Each output's `format` word prints it (`%` adds a percent sign to a value already in percent units, so 0.09 reads 0.09%), and the static `color` on `oi_change` is the colour its sparkline draws in. `flow` (buy minus sell volume as a percent of their sum) rides the hover card the EMA line opens, and `ema_dist` (the close's distance from the EMA, percent) is written beside them for anything that reads it. **The trend word is a slot and a ladder.** The word is written into a bounded string slot on the live bar only. The pill's colour follows the `trend` output: 0 bearish, 1 mixed and 2 bullish pick the down, muted and up colours from its `colors`. Until the EMA, RSI and ATR have the bars they need, the slot says so instead ("Needs 50 bars", the longest of the three lengths). **Open interest is counted in contracts.** On a perpetual the `oi` source serves open interest in dollars, which rise and fall with price even when no position opens or closes, so each reading is divided by the bar's close and the sparkline and its tile ("OI in contracts") move only when positions do: price up 2% with fewer coins open reads as a fall. The funding input tells a perpetual apart, since only a perpetual serves funding. A prediction market's open interest is its collateral, one dollar per YES and NO pair, so it is already a count of contracts and is read as served. A new bar keeps the last reading until its own lands, so the tile does not blink to a dash at each bar's open. **The windows are fixed arrays.** Buy, sell and total volume of the last `flow_len` bars sit in three arrays sized at load, each bar writing over the slot of the bar that leaves the window, and their sums are recounted from the slots on every bar, so a quiet stretch reads as no trades rather than as a rounding crumb. The buy share is buy volume over all taker volume in the window. Volume against its average is a bar's volume over the mean of the window, that bar included; on the live bar that is its volume so far, as the ring's label says ("Volume so far"), so the ring starts low at each bar's open and fills as the bar trades. Until the window fills, the mean counts only the bars seen so far. **The lengths ride the legend.** A tile's label is a fixed string, so `legend({ title: "{{ema_len}} {{rsi_len}} {{atr_len}} {{flow_len}}" })` prints the lengths in use after the name ("Market HUD 50 14 14 20") and the labels say in words what each tile reads. ## Where it runs Every market with candles: crypto perpetuals and spot, Hyperliquid, a prediction market's single outcome, US stocks and FX. Open interest needs a perpetual (counted in coins) or a prediction market (its collateral, read as served), the taker share needs sided trades and the volume ring needs volume, so the open-interest sparkline prints a dash on spot, stocks and FX, the buy share ring on stocks and FX, and the volume ring on FX, whose candles carry no volume. The card sits at the bottom centre of the price pane, away from the legend, the High and Low tags, the price axis, the newest candles at the right edge and the round button at the bottom left; on a chart whose candles dip into the bottom middle it covers them, and `position` moves it. ## When data is missing A tile whose output has no number prints a dash, and a ring without a reading stays empty with a dash beside it: open interest where the market has none, the taker share where the venue serves no sided trades, volume against its average where the candles carry no volume. The trend word, ATR and RSI need only candles, so the card always answers. The first `ema_len` bars are warm-up rows that write nothing, so the sparkline starts after them; on a chart with fewer bars than the lengths need (an `ema_len` of 400 on a short history), the headline reads "Needs 400 bars" instead of leaving the card blank. ## Customize it - **Another window.** `flow_len` (20) sets the taker window, the volume average and the open-interest change together; the legend shows the new length. - **Another corner.** Set `position` to any of the nine anchors, `top_left` to `bottom_right`; `columns: 1` stacks every tile in a narrow card. - **Another tile.** Declare a data-only output, write it in `onBar()`, and add a tile that reads it, such as `tile.value("Close vs EMA", "ema_dist", { format: "%" })` for the distance already computed. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Market HUD** under **HUDs**. 2. Press **Run**: the EMA draws on price and the card appears at the bottom of the price pane. Rest the pointer on a tile to open it as a hover card. 3. At the editor's Console prompt, type `outputs` to read the newest value of every output the card shows. ## Concepts used - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors and its columns - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline pill, `tile.rings`, their options and the format words - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Hover cards](../presentation/hud-and-hover-cards.md#hover-cards) for the card the EMA line and each tile open - [Legend](../presentation/legend.md) for `legend({ title })` and its `{{setting}}` placeholders - [Data sources](../core-concepts/data-sources.md) for the `trades` and `oi` sources and their `missing` policies - [TA library](../functions/ta-library.md) for `Ema`, `Rsi`, `Atr` and `Roc` <!-- source: https://openmarket.xyz/wrun/cookbook/decision-board --> # Decision board One card at the bottom of the price pane that grades the market factor by factor and says which side is ahead, so the chart keeps its full height. It is drawn in the chart's default look. A headline the script writes from the six factors leads: "Buyers Ahead, 3 to 1" when the bullish factors lead the bearish ones by two or more, "Sellers Ahead" when the bearish ones do, else "Signals Split", each followed by the two counts. Under it, the net score (bullish factors minus bearish ones) of the last 64 bars runs as a sparkline, then the six readings the score comes from, one row each: the close against the EMA, RSI, this bar's volume so far against its 20-bar average, taker flow, the open-interest change in contracts and the longs' share of liquidations. The EMA is drawn on price, and the legend names the lengths in use. The card is one `render.hud` declaration of three tiles in one column 300 px wide, with no `look` word ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)): a headline `tile.pill` over a string slot, a `tile.spark` and a `tile.rows` list, each reading data-only outputs written on every bar. It reads side-split `trades.volume`, `oi.close` reading NaN where the market has none, `funding.rate_close` reading NaN off perpetuals, and `liquidations` split by side ([Data sources](../core-concepts/data-sources.md)), with the `Ema`, `Rsi`, `Sma` and `Roc` helpers ([TA library](../functions/ta-library.md)). This is also the `decision-board` template: the **Decision Board** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Decision Board: one card in a corner of the price pane that grades the market factor by factor and says which // way it leans. The trader reads a headline first, written by the script // from the count ("Buyers Ahead, 4 to 1", "Sellers Ahead, 3 to 1" or "Signals Split, 2 to 2": the leading side's // factors against the other side's), then the net score (bullish factors minus bearish ones, -6 to +6) over the last // 64 bars as a sparkline, then the six readings behind it in rows: the close against the EMA, RSI, // volume against its average (the live bar's volume so far), taker flow, the open-interest change in contracts (coins // on a perpetual, as served on a prediction market) and the longs' share of liquidations. A factor whose market has no data prints a dash and leaves the count: open interest and // liquidations on spot, stocks and FX; flow and volume on FX. The EMA is drawn on price, and every number on the // card is a data-only output written on every bar, so the Console or a watch reads the same values the card shows. // Settings: the lengths, one threshold per factor rule, the margin the lean needs, and the EMA line's colour. section("Lengths"); param.int("ema_len", 50, { min: 2, max: 500, label: "EMA length, bars", description: "EMA length in bars, the trend reference" }); param.int("rsi_len", 14, { min: 2, max: 200, label: "RSI length, bars", description: "RSI length in bars" }); param.int("window", 20, { min: 2, max: 200, label: "Window, bars", description: "Bars in the volume, flow, open-interest and liquidation windows" }); section("Factor thresholds"); param.number("rsi_bull", 55, { min: 50, max: 100, step: 1, label: "RSI bullish above", description: "RSI above this level reads bullish momentum" }); param.number("rsi_bear", 45, { min: 0, max: 50, step: 1, label: "RSI bearish below", description: "RSI below this level reads bearish momentum" }); param.number("volume_spike", 1.2, { min: 1, max: 10, step: 0.1, label: "Volume spike, times average", description: "Volume at this multiple of its average or more counts: bullish on an up bar, bearish on a down bar (the live bar counts its volume so far)" }); param.number("flow_edge", 5, { min: 0, max: 100, step: 0.5, label: "Flow edge, percent", description: "Taker flow above this percent reads bullish, below minus this percent bearish" }); param.number("oi_flat", 0.05, { min: 0, max: 10, step: 0.01, label: "Minimum OI rise, percent", description: "Open interest rising more than this percent counts in the direction price moved (new positions); flat or falling open interest reads neutral (positions closing). Counted in coins on a perpetual" }); param.number("liq_heavy", 65, { min: 50, max: 100, step: 1, label: "Heavy long share, percent", description: "Longs over this percent of liquidations read bearish; longs under 100 minus it read bullish" }); param.int("lean_margin", 2, { min: 1, max: 6, label: "Lean margin, factors", description: "Bullish factors over bearish ones needed to lean Long (and the reverse to lean Short)" }); section("Look"); param.color("ema_color", "#38bdf8", { label: "EMA line" }); // The legend reads the lengths after the name ("Decision Board 50 14 20"): a tile label is a fixed string, so the // card's labels name what they read in words and the settings in use ride the legend. legend({ title: "{{ema_len}} {{rsi_len}} {{window}}" }); // Inputs: the chart's own candles set the grid; flow and liquidations read 0 on a bar without prints; open // interest reads NaN on a bar without a reading and where the market has none; funding is served on perpetuals only // (NaN elsewhere), which tells the file its open interest is dollars to turn into coins. input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero" }); input("sell", trades.volume, { side: "SELL", missing: "zero" }); input("oi", oi.close, { missing: "nan" }); input("funding", funding.rate_close, { missing: "nan" }); input("liq_buy", liquidations.liquidations, { side: "BUY", missing: "zero" }); // shorts liquidated: forced buying input("liq_sell", liquidations.liquidations, { side: "SELL", missing: "zero" }); // longs liquidated: forced selling // Outputs: the EMA on price; the rest are data-only, one value per bar behind the card's tiles. The first three keep // their names and order from the earlier board; the bearish count, the net score, the lean rung and the six // readings are new. A static colour on a data-only output is the colour its meter draws in. const emaLine = output("ema", line, overlay, { color: "@ema_color", width: 1, label: "EMA", format: "price", description: "EMA of the close over ema_len bars" }); // the colour setting paints it; the handle names it for the hover card output("score", none, overlay, { format: "int", description: "Bullish factors on this bar" }); output("factors", none, overlay, { format: "int", description: "Factors with data on this bar" }); output("bearish", none, overlay, { format: "int", description: "Bearish factors on this bar" }); output("net", none, overlay, { format: "int", description: "Bullish minus bearish factors, -6 to +6" }); output("lean", none, overlay, { description: "The lean as a ladder rung: 0 short, 1 neutral, 2 long" }); output("ema_dist", none, overlay, { format: "%", description: "Close minus the EMA, as a percent of the EMA" }); output("rsi", none, overlay, { format: "0.0", description: "RSI of the close over rsi_len bars" }); output("volume_ratio", none, overlay, { format: "0.00", unit: "x", description: "Bar volume over its average across the window; on the live bar, its volume so far" }); output("flow", none, overlay, { format: "%", description: "Taker buy minus sell volume over the window, as a percent of their sum" }); output("oi_change", none, overlay, { format: "%", description: "Open-interest change over the window in contracts (coins on a perpetual, as served on a prediction market), percent" }); output("long_share", none, overlay, { format: "%", description: "Longs liquidated as a percent of all liquidations in the window" }); hover(emaLine, [block.value("EMA", "ema", { format: "price" }), block.rows([["Bullish factors", "score", "int"], ["Bearish factors", "bearish", "int"], ["Factors with data", "factors", "int"]])]); // the card the EMA line opens under the cursor // The lean word, written on the live bar into a bounded string slot the first tile reads. string("lean_word", { max_bytes: 8 }); string("headline_text", { max_bytes: 48 }); // the headline sentence, written on the live bar // The card: one column 300 px wide, the headline sentence first, then the score's sparkline and the six readings. The // lean word (Long, Neutral or Short) still rides its own slot for a hover card or a watch. render.hud("decision", { position: "bottom_center", title: "Decision board", columns: 1, width: 300, tiles: [ tile.pill("Lean", "headline_text", { headline: true }), tile.spark("Net score, 64 bars", "net", { bars: 64 }), tile.rows([["Close vs EMA", "ema_dist", "%"], ["RSI", "rsi", "0.0"], ["Volume so far", "volume_ratio", "0.00"], ["Taker flow", "flow", "%"], ["OI change, contracts", "oi_change", "%"], ["Long share of liquidations", "long_share", "%"]]), ] }); const FACTORS = 6; const NA = 9; // a factor without data on this market const MAX_WINDOW = 200; // the rings are sized for the largest window at load; onStart() reads the one in use const buys = new StaticArray<f64>(MAX_WINDOW); const sells = new StaticArray<f64>(MAX_WINDOW); const liqBuys = new StaticArray<f64>(MAX_WINDOW); const liqSells = new StaticArray<f64>(MAX_WINDOW); const tones = new StaticArray<i32>(FACTORS); // per factor: 1 bullish, -1 bearish, 0 neutral, NA without data let window = 20; let rsiBull = 55.0; let rsiBear = 45.0; let volumeSpike = 1.2; let flowEdge = 5.0; let oiFlat = 0.05; let liqHeavy = 65.0; let leanMargin = 2; let ema = new Ema(50); let rsi = new Rsi(14); let volumeMean = new Sma(20); let rawChange = new Roc(20); // the open-interest change as served, and in coins: the funding feed picks one let coinChange = new Roc(20); let priceChange = new Roc(20); let head = 0; let tradesSeen = false; // the venue has served sided trades at least once let liqSeen = false; // the venue has served liquidations at least once let close: f64 = NaN; let prev: f64 = NaN; let emaV: f64 = NaN; let rsiV: f64 = NaN; let volumeRatio: f64 = NaN; let oiRaw: f64 = NaN; // the last open-interest reading and its coins; a new bar keeps them until its own reading lands let oiCoins: f64 = NaN; let perp = false; // funding seen: a perpetual, whose dollar open interest moves with price let flowPct: f64 = NaN; let oiPct: f64 = NaN; let pricePct: f64 = NaN; let longShare: f64 = NaN; // longs liquidated as a percent of all liquidations in the window let bullish = 0; let bearish = 0; let withData = 0; // Judge each factor from this bar's readings. A helper still warming up, or a market without the data, reads NA // and stays out of both counts. Open interest rising confirms the price move (new positions behind it); flat or // falling open interest is positions closing, which confirms nothing. function judge(): void { tones[0] = !isFinite(emaV) ? NA : close > emaV ? 1 : close < emaV ? -1 : 0; tones[1] = !isFinite(rsiV) ? NA : rsiV > rsiBull ? 1 : rsiV < rsiBear ? -1 : 0; tones[2] = !isFinite(volumeRatio) ? NA : volumeRatio >= volumeSpike && isFinite(prev) ? (close > prev ? 1 : close < prev ? -1 : 0) : 0; tones[3] = !tradesSeen ? NA : !isFinite(flowPct) ? 0 : flowPct > flowEdge ? 1 : flowPct < -flowEdge ? -1 : 0; tones[4] = !isFinite(oiPct) || !isFinite(pricePct) ? NA : oiPct <= oiFlat ? 0 : pricePct > 0.0 ? 1 : pricePct < 0.0 ? -1 : 0; tones[5] = !liqSeen ? NA : !isFinite(longShare) ? 0 : longShare > liqHeavy ? -1 : longShare < 100.0 - liqHeavy ? 1 : 0; bullish = 0; bearish = 0; withData = 0; for (let i = 0; i < FACTORS; i += 1) { if (tones[i] == NA) continue; withData += 1; if (tones[i] > 0) bullish += 1; else if (tones[i] < 0) bearish += 1; } } // onStart() runs once before the first bar: read the settings and size every helper to them. function onStart(): void { window = i32(p_window()); rsiBull = p_rsi_bull(); rsiBear = p_rsi_bear(); volumeSpike = p_volume_spike(); flowEdge = p_flow_edge(); oiFlat = p_oi_flat(); liqHeavy = p_liq_heavy(); leanMargin = i32(p_lean_margin()); ema = new Ema(i32(p_ema_len())); rsi = new Rsi(i32(p_rsi_len())); volumeMean = new Sma(window); rawChange = new Roc(window); coinChange = new Roc(window); priceChange = new Roc(window); } // onBar() runs once per bar: read the bar, update every helper and window, judge the factors, then write the // outputs; the lean word is written on the live bar only. function onBar(): void { prev = close; close = bar.close(); emaV = ema.update(close); rsiV = rsi.update(close); const volume = bar.volume(); const volumeAvg = volumeMean.update(volume); volumeRatio = volumeAvg > 0.0 ? volume / volumeAvg : NaN; // NaN on markets without volume (FX); the live bar's so far // The windows are rings of the last bars, their sums recounted from the slots: a running sum that adds and // subtracts keeps a rounding crumb after a quiet stretch, and a crumb over a crumb would read as a share. const buy = in_buy(); const sell = in_sell(); const liqBuy = in_liq_buy(); const liqSell = in_liq_sell(); buys[head] = buy; sells[head] = sell; liqBuys[head] = liqBuy; liqSells[head] = liqSell; head = (head + 1) % window; if (buy + sell > 0.0) tradesSeen = true; if (liqBuy + liqSell > 0.0) liqSeen = true; let buySum = 0.0; let sellSum = 0.0; let liqBuySum = 0.0; let liqSellSum = 0.0; for (let i = 0; i < window; i += 1) { buySum += buys[i]; sellSum += sells[i]; liqBuySum += liqBuys[i]; liqSellSum += liqSells[i]; } const flowTotal = buySum + sellSum; flowPct = flowTotal > 0.0 ? ((buySum - sellSum) / flowTotal) * 100.0 : NaN; const liqTotal = liqBuySum + liqSellSum; longShare = liqTotal > 0.0 ? (liqSellSum / liqTotal) * 100.0 : NaN; const oiNow = in_oi(); if (!isNaN(oiNow)) { oiRaw = oiNow; oiCoins = oiNow / close; // dollars over the close: the coins, whatever price did } if (!isNaN(in_funding())) perp = true; const rawPct = rawChange.update(oiRaw); const coinPct = coinChange.update(oiCoins); oiPct = perp ? coinPct : rawPct; pricePct = priceChange.update(close); judge(); if (isNaN(emaV)) return; // the first ema_len bars are warm-up rows: nothing written const net = bullish - bearish; out_ema(emaV); out_score(f64(bullish)); out_factors(f64(withData)); out_bearish(f64(bearish)); out_net(f64(net)); out_lean(net >= leanMargin ? 2.0 : net <= -leanMargin ? 0.0 : 1.0); out_ema_dist((close / emaV - 1.0) * 100.0); out_rsi(rsiV); out_volume_ratio(volumeRatio); out_flow(flowPct); out_oi_change(oiPct); out_long_share(longShare); if (bar.isLast()) { sb_clear(); sb_text(net >= leanMargin ? "Long" : net <= -leanMargin ? "Short" : "Neutral"); str_lean_word_sb(); sb_clear(); // A headline, short enough for one line: the leading side and the signal count, bullish to bearish. sb_text(net >= leanMargin ? "Buyers Ahead, " : net <= -leanMargin ? "Sellers Ahead, " : "Signals Split, "); if (net <= -leanMargin) { sb_int(i64(bearish)); sb_text(" to "); sb_int(i64(bullish)); } else { sb_int(i64(bullish)); sb_text(" to "); sb_int(i64(bearish)); } str_headline_text_sb(); } } ``` ## How it works **Each factor is a rule.** Trend is bullish with the close above the EMA (`ema_len` 50) and bearish below; RSI (`rsi_len` 14) is bullish above 55 and bearish below 45; volume is bullish at 1.2 times its `window` average on an up bar and bearish on a down bar (on the live bar its volume so far, so the factor can join the count as the bar trades); taker flow is bullish above +5% and bearish below -5%; open interest counted in contracts (on a perpetual the dollar reading over the close, so a price move alone never moves it; on a prediction market the collateral as served) that rose more than 0.05% over the window confirms the price move, bullish when price rose over the same window and bearish when it fell, while flat or falling open interest is positions closing and reads neutral; liquidations read longs over 65% of what was flushed as bearish and under 35% as bullish. Every threshold is a setting in the **Factor thresholds** section. **The score and the headline.** The score is the bullish factors minus the bearish ones; the market leans long at +2 or more and short at -2 or less (`lean_margin`). A factor the market has no data for is left out of both counts. On the live bar the script writes the headline into the bounded `headline_text` slot from the same counts: "Buyers Ahead" and the bullish count first when the score reaches the margin, "Sellers Ahead" and the bearish count first when it reaches minus the margin, else "Signals Split" with the bullish count first. **One declaration is the card.** `render.hud("decision", { position: "bottom_center", title: "Decision board", columns: 1, width: 300, tiles: [...] })` names the anchor, the title and three tiles; the chart draws the card and keeps it at its anchor while the chart pans. `headline: true` sets the pill in the card's headline type, and `width: 300` gives the one-column card room for the longest row (a one-column card is 180 px unless it says otherwise). **No look word, the default look.** With no `look`, the chart draws the card in its default look: near black and translucent (white paper on a light chart) with a hairline border and 12 px corners, the title in sentence case, the headline at 17 px bold with its label hidden, the spark as a line, and each row 22 px tall with a hairline between rows and no leader marks. A word declared on the card wins over the default ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). **Every number is an output.** The six readings (`ema_dist`, `rsi`, `volume_ratio`, `flow`, `oi_change`, `long_share`), the counts (`score` for bullish, `bearish`, `factors` with data), `net` and the `lean` rung (0 short, 1 neutral, 2 long) are data-only outputs written on every bar. The spark reads the last 64 values of `net`, and the rows print each reading with its format word (`%` adds a percent sign to a value already in percent units; `volume_ratio` adds its `unit`, so it reads `1.35x`). The lean is also written as a word, Long, Neutral or Short, into the `lean_word` slot, which no tile reads until you add one (below). **The windows are rings.** Buy, sell and liquidation volume of the last `window` bars sit in fixed rings sized at load, their sums recounted from the slots on every bar, so a quiet stretch reads as no prints rather than as a rounding crumb. Open interest is kept in contracts, and a new bar keeps the last reading until its own lands, so the factor count does not drop at each bar's open. A perpetual is told apart by its funding input, which only a perpetual serves. **The lengths ride the legend.** A tile's label is a fixed string, so `legend({ title: "{{ema_len}} {{rsi_len}} {{window}}" })` prints the lengths in use after the name ("Decision Board 50 14 20") and the row labels say in words what each reading is. ## Where it runs Every market with candles, a prediction market's single outcome included. Crypto perpetuals have all six factors, their open interest counted in coins. Spot has no open interest or liquidations, and prediction markets no liquidations, their open interest read as served (one dollar of collateral per YES and NO pair, already a count of contracts); US stocks keep the trend, RSI and volume, and FX only the trend and RSI (its candles carry no volume). The card sits at the bottom centre of the price pane, away from the legend, the High and Low tags, the price axis, the newest candles at the right edge and the round button at the bottom left; on a chart whose candles dip into the bottom middle it covers them, and `position` moves it. ## When data is missing A factor without data prints a dash in its row and leaves both counts, so the score's reach shrinks with the market: four factors on spot, two on FX, where the headline reads at most 2 to 0. Flow and liquidations count only once the venue has served one print; after that a window without prints reads neutral (the row shows a dash because there is no share to print). The first `ema_len` bars are warm-up rows that write nothing, so the sparkline starts after them. ## Customize it - **Other thresholds.** Every cut-off is a setting under **Factor thresholds**; the lengths are under **Lengths**. - **A seventh factor.** Add an input, a rule in `judge()` (raise `FACTORS`), an output and a row; the headline counts it with the others. - **The lean as a word.** `tile.pill("Lean", "lean_word", { color_by: "lean", colors: ["theme.down", "theme.muted", "theme.up"] })` puts Long, Neutral or Short on the card in the down, muted or up colour, read from the slot and the rung the file already writes. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Decision Board** under **HUDs**. 2. Press **Run**: the EMA draws on price and the card appears at the bottom of the price pane. Rest the pointer on a tile to open it as a hover card. 3. At the editor's Console prompt, type `last 20 net` to read the score of the last 20 bars. ## Concepts used - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, its columns and its width - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline pill, the spark, the rows and the format words - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Plotting](../presentation/plotting.md) for data-only outputs and the string slots the headline and the lean word are written into - [Legend](../presentation/legend.md) for `legend({ title })` and its `{{setting}}` placeholders - [Data sources](../core-concepts/data-sources.md) for the `trades`, `oi` and `liquidations` sources and their `missing` policies - [TA library](../functions/ta-library.md) for `Ema`, `Rsi`, `Sma` and `Roc` <!-- source: https://openmarket.xyz/wrun/cookbook/order-flow-hud --> # Order flow HUD A card at the bottom centre of the price pane that says who is pushing price, read from the exchange's own taker side and kept current on the live bar. It is drawn in the chart's default look, under the title "Tug of war". It answers in a word first, as the headline: Buyers pushing, Sellers pushing or Balanced, in the up, down or muted colour. Under the word, a sparkline traces each of the last 24 bars' taker buy share, the part of that bar's taker volume that taker buys made up; the taker buy share of the last 20 bars sits on a meter around 50, the net taker delta of those bars reads in dollars with this bar's own delta in the capsule beside it, and two rows count the longs and the shorts liquidated over the same 20 bars. Nothing is drawn on price. The card is one `render.hud(...)` of five tiles in one column 300 px wide, with no `look` word: a headline pill, a spark, a meter, a value and rows ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)). Its numbers are data-only outputs written on every bar and its first word a string slot written on the live bar ([Plotting](../presentation/plotting.md)). The inputs are side-split `trades.volume` and `liquidations.liquidations`, both read with `missing: "zero"` ([Data sources](../core-concepts/data-sources.md)), and the sums are the delta and cumulative delta of the [Order flow kit](../functions/order-flow-kit.md), written out by hand. This is also the `order-flow-hud` template: the **Order Flow HUD** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Order Flow HUD: who is pushing price, read from the exchange's own taker side, drawn by the chart in its default // look. One card answers in a word first (Buyers pushing, Sellers pushing or Balanced, in the up, down or muted colour), // then charts each bar's taker buy share as a sparkline (the tug of war), shows the window's buy share on // a meter around 50, the window's net taker delta in dollars with this bar's own delta beside it, and the longs and // shorts liquidated over the window. Nothing is drawn on price: the card is the whole indicator, and every number on // it is also a data-only output the Console and a watch can read (the cumulative delta too). A market without sided // trades (FX, stocks) says so in the first tile; a spot market has no liquidations, so those two rows stay empty. // Settings: the window every sum covers, and how far from even the buy share must sit before the card names a side. section("Flow window"); param.int("flow_len", 20, { min: 2, max: 200, label: "Flow window in bars", description: "Bars the net delta, the buy share and the liquidations are summed over" }); param.number("lean", 5.0, { min: 0.5, max: 25.0, step: 0.5, label: "Balanced band in points", description: "Points the taker buy share must sit above or below 50 before the card names buyers or sellers; inside the band it reads Balanced" }); legend({ title: "({{flow_len}})" }); // the window after the name in the legend // Inputs: the chart's own candles set the grid. Taker buys and sells arrive in coins and read 0 on a bar without // prints; liquidations arrive in dollars, longs as forced sells and shorts as forced buys, 0 on a quiet bar. input("close", ohlcv.close); input("buy", trades.volume, { side: "BUY", missing: "zero" }); input("sell", trades.volume, { side: "SELL", missing: "zero" }); input("long_liq", liquidations.liquidations, { side: "SELL", missing: "zero" }); input("short_liq", liquidations.liquidations, { side: "BUY", missing: "zero" }); // Outputs: all data-only, one value per bar; the card reads the newest row of each. A colour on an output paints the // mark that reads it: the meter's fill, the sparkline, the dot beside a liquidation row. output("side", none, overlay, { description: "0 sellers pushing, 1 balanced or no data, 2 buyers pushing: the first tile's colour" }); output("buy_share", none, overlay, { color: "theme.up", format: "%", description: "Taker buys as a percent of all taker volume over the window" }); output("bar_buy_share", none, overlay, { format: "%", description: "This bar's taker buys as a percent of its taker volume" }); output("net_delta", none, overlay, { format: "si", description: "Taker buys minus taker sells over the window, in dollars" }); output("bar_delta", none, overlay, { format: "si", description: "This bar's taker buys minus taker sells, in dollars" }); output("cvd", none, overlay, { color: "theme.text", format: "si", description: "Cumulative taker delta since the first loaded bar, in dollars" }); output("long_liqs", none, overlay, { color: "theme.down", format: "si", description: "Longs liquidated over the window, in dollars" }); output("short_liqs", none, overlay, { color: "theme.up", format: "si", description: "Shorts liquidated over the window, in dollars" }); output("window_bars", none, overlay, { format: "int", description: "The flow window in bars, read by the card's title" }); string("who", { max_bytes: 40 }); // the first tile's words, written on the live bar // The card: one column 300 px wide, the deciding word first, then the tug-of-war sparkline, the meter, the delta and // the liquidation rows. render.hud("order_flow", { position: "bottom_center", title: "Tug of war", columns: 1, width: 300, tiles: [ tile.pill("Who is pushing", "who", { headline: true, color_by: "side", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.spark("Each bar's buy share, %", "bar_buy_share", { bars: 24 }), tile.meter("Taker buy share over the window", "buy_share", { min: 0, max: 100, marks: [50] }), tile.value("Net taker delta, USD", "net_delta", { format: "si", delta: "bar_delta" }), tile.rows("Liquidations, USD", [["Longs", "long_liqs", "si"], ["Shorts", "short_liqs", "si"]]), ] }); const MAX_WINDOW = 200; // the flow_len ceiling: the rings are sized for it once, at load const buys = new StaticArray<f64>(MAX_WINDOW); // each bar's taker buys in dollars, one slot per bar of the window const sells = new StaticArray<f64>(MAX_WINDOW); const longs = new StaticArray<f64>(MAX_WINDOW); // each bar's liquidations in dollars const shorts = new StaticArray<f64>(MAX_WINDOW); const SELLERS = 0.0; // the first tile's ladder rungs, in the colours' order: down, muted, up const BALANCED = 1.0; const BUYERS = 2.0; let flowLen = 20; // settings, read in onStart() let lean = 5.0; let head = 0; // the ring slot the next bar writes: it holds the bar that is leaving the window let filled = 0; // bars in the window so far, up to flowLen let buySum = 0.0; // the window's sums, kept by adding the new bar and taking out the one that left let sellSum = 0.0; let longSum = 0.0; let shortSum = 0.0; let cvd = 0.0; // the running delta since the first loaded bar let sidedSeen = 0.0; // every sided dollar seen: 0 means the market serves no sided trades let liquidationsSeen = 0.0; // every liquidated dollar seen: 0 means the market serves none function onStart(): void { flowLen = i32(p_flow_len()); lean = p_lean(); } // onBar() runs once per bar: price the bar's taker volume in dollars at its close, roll the window, write every // output, and on the live bar write the first tile's words. function onBar(): void { const close = bar.close(); const buyCoins = in_buy(); const sellCoins = in_sell(); const longRaw = in_long_liq(); const shortRaw = in_short_liq(); const buy = isFinite(buyCoins) && isFinite(close) ? buyCoins * close : 0.0; const sell = isFinite(sellCoins) && isFinite(close) ? sellCoins * close : 0.0; const longLiq = isFinite(longRaw) ? longRaw : 0.0; const shortLiq = isFinite(shortRaw) ? shortRaw : 0.0; sidedSeen += buy + sell; liquidationsSeen += longLiq + shortLiq; cvd += buy - sell; // Roll the window: take out the bar this slot held, put this bar in its place. buySum += buy - buys[head]; sellSum += sell - sells[head]; longSum += longLiq - longs[head]; shortSum += shortLiq - shorts[head]; buys[head] = buy; sells[head] = sell; longs[head] = longLiq; shorts[head] = shortLiq; head = (head + 1) % flowLen; if (filled < flowLen) filled += 1; // The readings: nothing until the window is full, nothing on a market that never served the feed. const hasTrades = sidedSeen > 0.0; const hasLiquidations = liquidationsSeen > 0.0; const warm = filled >= flowLen; const total = buySum + sellSum; const share = hasTrades && warm && total > 0.0 ? (buySum / total) * 100.0 : NaN; let side = BALANCED; if (share >= 50.0 + lean) side = BUYERS; else if (share <= 50.0 - lean) side = SELLERS; // a NaN share passes neither test and stays Balanced out_side(side); out_buy_share(share); out_bar_buy_share(hasTrades && buy + sell > 0.0 ? (buy / (buy + sell)) * 100.0 : NaN); out_net_delta(hasTrades && warm ? buySum - sellSum : NaN); out_bar_delta(hasTrades ? buy - sell : NaN); out_cvd(hasTrades ? cvd : NaN); out_long_liqs(hasLiquidations && warm ? Math.max(0.0, longSum) : NaN); // the floor clears rounding left by the rolling sum out_short_liqs(hasLiquidations && warm ? Math.max(0.0, shortSum) : NaN); out_window_bars(f64(flowLen)); // The first tile's words, on the live bar only: the deciding word, or why there is none. if (bar.isLast()) { sb_clear(); if (!hasTrades) sb_text("No sided trades on this market"); else if (!warm) sb_text("Not enough bars yet"); else if (isNaN(share)) sb_text("No trades in the window"); else if (side == BUYERS) sb_text("Buyers pushing"); else if (side == SELLERS) sb_text("Sellers pushing"); else sb_text("Balanced"); str_who_sb(); } } ``` ## How it works **Taker volume, in dollars.** `trades.volume` with `side: "BUY"` and `side: "SELL"` hands each bar the coins that takers bought and sold, the side that crossed the spread. Each bar's coins are priced at its close, so the deltas are in dollars like the liquidations, and read the same way on any coin. **One window, kept as a ring.** The last `flow_len` (20) bars of taker buys, taker sells and liquidations sit in rings sized once for the largest setting. Each bar adds itself and takes out the bar that left, so the sums cost the same at 20 bars or 200. The buy share is buys over buys plus sells and the net delta is buys minus sells; both, and the liquidation sums, read a dash until the window is full. **The deciding word.** A buy share at or above 50 plus `lean` (5) reads Buyers pushing, at or below 50 minus `lean` reads Sellers pushing, and anything between reads Balanced. A data-only `side` output (0, 1 or 2) picks the pill's colour from its ladder: the down, muted and up colours. **Each bar's share as a line.** `bar_buy_share` is one bar's taker buys as a percent of its taker volume. The default look draws a spark as a line, so the spark traces, bar by bar, how large a part of the taker volume the buyers took. `bars: 24` keeps the last 24, and the number beside the spark's label is the newest bar's share. **This bar in the capsule.** The net delta's capsule is the live bar's own buys minus sells, with an up or down arrow, so the card shows the window and the bar at once. **The cumulative delta stays an output.** `cvd` is a running sum of each bar's dollar delta, written on every bar for the Console, though no tile draws it. It counts from the first loaded bar, so its number moves when more history loads: read its slope, not its level. **Liquidations.** Longs are liquidated by forced sells and shorts by forced buys, so `side: "SELL"` reads the longs and `side: "BUY"` the shorts, already in dollars. The two rows sum the window; the dots beside them, in the down and up colours, are the two outputs' own colours. **No look word, the default look.** With no `look`, the chart draws the card in its default look: near black and translucent (white paper on a light chart) with a hairline border and 12 px corners, the title in sentence case, the headline as its word alone in its colour with no capsule and no dot, the spark as a line and the meter as a bar. A word declared on the card wins over the default ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). **Live.** Every tile reads the newest row of its output, and the chart folds live prints into the live bar as they arrive, so the card refreshes about once a second while the bar is open. ## Where it runs Every market with sided trades: crypto perpetuals and spot on the venues the chart carries (Binance, Hyperliquid and the rest) and prediction markets. The liquidation rows fill on perpetuals with a liquidations feed; a spot market has none, so they stay empty there. FX and stocks have no sided trades: the first tile reads "No sided trades on this market". ## When data is missing - A market with no sided trades at all: the first tile says so and every number reads a dash, never a fake zero. - A market with sided trades but none inside the window: the first tile reads "No trades in the window". - No liquidation seen on any loaded bar (spot, a prediction market): both rows read a dash rather than 0. A perpetual that served liquidations earlier but none inside the window reads 0. - A chart with fewer bars than `flow_len`: the first tile reads "Not enough bars yet", and the share, the net delta and the liquidation sums read a dash. The capsule and each bar's own share start on the first bar. ## Customize it - **Another window.** `flow_len` sets the window of the share, the net delta and the liquidations; the legend shows it after the name. - **A wider middle.** Raise `lean` so the card names a side only on a clear lean. - **More or fewer bars.** `bars: 24` on the spark sets how many bars the line covers, up to 64; `draw: "bars"` on the spark draws them as columns from the card's first meter mark, 50. - **The cumulative delta on the card.** `tile.spark("Cumulative delta", "cvd", { bars: 64 })` draws the running delta the file already writes. - **Another corner.** Change `position: "bottom_center"` to any of the nine anchors, `top_left` to `bottom_right`. - **Coins instead of dollars.** Drop `* close` from the two volume lines; the liquidation rows stay in dollars. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Order Flow HUD** under **HUDs**. 2. Press **Run** on a crypto chart: the card appears at the bottom centre and follows the live bar. 3. At the editor's Console prompt, type `outputs` to read the newest value of every output: the side, the buy share, this bar's share, both deltas, the cumulative delta and the two liquidation sums. ## Concepts used - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for `render.hud`, the five tiles, the headline, the pill's colour ladder and the capsule - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Data sources](../core-concepts/data-sources.md) for side-split `trades` and `liquidations` and the `missing` policy - [Order flow kit](../functions/order-flow-kit.md) for delta and cumulative delta - [Plotting](../presentation/plotting.md) for data-only outputs and string slots <!-- source: https://openmarket.xyz/wrun/cookbook/order-book-hud --> # Order book HUD A card at the middle left of the price pane that shows what is resting near the price, read from the exchange's own order book and kept current on the live bar. It is drawn in the chart's default look. It names the heavier side first, as the headline: Bids heavier in the up colour, Asks heavier in the down colour, Balanced muted. Under the word, the bids' share of the dollars resting within 1% of the mid reads on a bar marked at 50; three rows give the dollars bid and offered within 0.25%, 0.5% and 1% of the mid, and two rows name the biggest bid and ask within 2%: where each wall sits and how many dollars rest there. The two walls are also drawn on price as thin dotted lines, the bid wall in the up colour under the price and the ask wall in the down colour over it. The card is one `render.hud(...)` of four tiles and no `look` word: a headline pill, a meter and two rows tiles whose lines are words written on the live bar ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)). The book arrives as `book.cells`, one `[price, size, side]` row per level ([Data sources](../core-concepts/data-sources.md), [Order flow](../functions/order-flow-kit.md#what-the-chart-serves)); the numbers are data-only outputs written on every bar, the first word a string slot written on the live bar ([Plotting](../presentation/plotting.md)), and the walls two line handles ([Drawing objects](../presentation/drawing-objects.md#handles)). This is also the `order-book-hud` template: the **Order Book HUD** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Order Book HUD: what is resting near the price, read from the exchange's own order book, drawn by the chart in its // default look. One card names the heavier side first (Bids heavier in the up colour, Asks heavier in the down colour, // Balanced muted), then the bids' share of the dollars resting within 1% of the mid on a bar (50 marked), the dollars // bid and offered within 0.25%, 0.5% and 1% of the mid (one row per distance), and the biggest bid and ask walls within // 2%: where each sits and how many dollars rest there (one row per wall). The imbalance and its change since the last // bar stay data-only outputs for the Console and a watch. The two walls are also drawn on price as thin dotted lines, // in the up colour under the price and the down colour over it, from line_bars bars back to the live bar and on to the // price axis. A market without an order book (FX, stocks) says so in the first tile. The book arrives as one snapshot // per bar, refreshed about once a second on the live bar, so the card follows the live book. // Settings: how far the imbalance must lean before the card names a side, and how far back the wall lines reach. // The distances the rows name (0.25%, 0.5%, 1% and the 2% wall reach) are constants below, because a tile's label is // fixed text: change a distance and its label together. section("Reading"); param.number("lean", 10.0, { min: 1.0, max: 50.0, step: 1.0, label: "Balanced band in points", description: "Imbalance points either side of zero before the card names the heavier side; inside the band it reads Balanced" }); section("Wall lines"); param.int("line_bars", 30, { min: 2, max: 300, label: "Wall line length, bars", description: "Bars the two wall lines reach back from the live bar" }); // Inputs: the chart's own candles set the grid (a file whose first feed is a block starts with them), then the book: // one [price, size, side] row per price level, side +1 a bid and -1 an ask, sizes in coins. The chart serves its own // book at its own price grouping, up to 500 levels a side, so 1000 rows hold any bar; block_size is required by the // declaration, and the chart does not read it. input("close", ohlcv.close); input("book", book.cells, { max_cells: 1000, block_size: 10 }); // Outputs: all data-only, one value per bar, so a watch or an alert can read them too; the card shows the words the // slots below carry, written from these numbers on the live bar. output("side", none, overlay, { description: "0 asks heavier, 1 balanced or no book, 2 bids heavier: the first tile's colour" }); output("imbalance", none, overlay, { format: "%", description: "Bids minus asks over their sum within 1% of the mid, percent" }); output("imbalance_change", none, overlay, { format: "%", description: "The imbalance's change since the previous bar's snapshot, points" }); output("bid_share", none, overlay, { color: "theme.up", format: "%", description: "Bids as a percent of all dollars resting within 1% of the mid" }); output("bids_near", none, overlay, { color: "theme.up", format: "si", description: "Dollars bid within 0.25% of the mid" }); output("asks_near", none, overlay, { color: "theme.down", format: "si", description: "Dollars offered within 0.25% of the mid" }); output("bids_mid", none, overlay, { color: "theme.up", format: "si", description: "Dollars bid within 0.5% of the mid" }); output("asks_mid", none, overlay, { color: "theme.down", format: "si", description: "Dollars offered within 0.5% of the mid" }); output("bids_far", none, overlay, { color: "theme.up", format: "si", description: "Dollars bid within 1% of the mid" }); output("asks_far", none, overlay, { color: "theme.down", format: "si", description: "Dollars offered within 1% of the mid" }); output("bid_wall", none, overlay, { color: "theme.up", format: "price", description: "The price of the biggest bid within 2% of the mid" }); output("bid_wall_size", none, overlay, { format: "si", description: "Dollars resting at the bid wall" }); output("ask_wall", none, overlay, { color: "theme.down", format: "price", description: "The price of the biggest ask within 2% of the mid" }); output("ask_wall_size", none, overlay, { format: "si", description: "Dollars resting at the ask wall" }); string("heavier", { max_bytes: 40 }); // the first tile's words, written on the live bar string("depth_near", { max_bytes: 24 }); // "48.9M / 61.7M": dollars bid / offered within 0.25%, written on the live bar string("depth_mid", { max_bytes: 24 }); string("depth_far", { max_bytes: 24 }); string("bid_wall_text", { max_bytes: 32 }); // "84000 · 262.0M": the wall's price and the dollars resting there string("ask_wall_text", { max_bytes: 32 }); handles.line({ width: 1, lineStyle: "dotted" }); // the two wall lines, in chart time and price // The card: the deciding word leads as the headline, the bid-share bar spans the card under it, then one row per // distance (dollars bid / offered) and one row per wall (price and dollars). Two columns give the rows room for both // numbers. render.hud("order_book", { position: "middle_left", title: "Order book", columns: 2, tiles: [ tile.pill("Heavier side, within 1%", "heavier", { headline: true, color_by: "side", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.meter("Bid share within 1%", "bid_share", { min: 0, max: 100, marks: [50] }), tile.rows("Bids / asks, USD", [["Within 0.25%", "depth_near"], ["Within 0.5%", "depth_mid"], ["Within 1%", "depth_far"]]), tile.rows("Walls within 2%, price and USD", [["Bid wall", "bid_wall_text"], ["Ask wall", "ask_wall_text"]]), ] }); const NEAR_PCT = 0.25; // the three depth bands and the wall reach, percent from the mid (the rows' labels name them) const MID_PCT = 0.5; const FAR_PCT = 1.0; // also the band the imbalance reads const WALL_PCT = 2.0; const BID_INK = theme.UP; // the chart's up colour, the bid wall line const ASK_INK = theme.DOWN; // the chart's down colour, the ask wall line const bidLine = draw.line(0); // handle objects allocate once; ids are one space across kinds const askLine = draw.line(1); const ASKS_HEAVIER = 0.0; // the first tile's ladder rungs, in the colours' order: down, muted, up const BALANCED = 1.0; const BIDS_HEAVIER = 2.0; let lean = 10.0; // settings, read in onStart() let lineBars = 30; let bookSeen = false; // a snapshot with both sides has arrived on some bar: the market has a book let prevImbalance: f64 = NaN; // the previous bar's imbalance, for the capsule let prevTime: f64 = NaN; // the previous bar's open time, for the bar's width in seconds let barSeconds: f64 = NaN; // This bar's readings, set by readBook(): NaN when the bar has no usable snapshot. let bidsNear: f64 = NaN; let asksNear: f64 = NaN; let bidsMid: f64 = NaN; let asksMid: f64 = NaN; let bidsFar: f64 = NaN; let asksFar: f64 = NaN; let bidWall: f64 = NaN; let bidWallSize: f64 = NaN; let askWall: f64 = NaN; let askWallSize: f64 = NaN; function clearReadings(): void { bidsNear = NaN; asksNear = NaN; bidsMid = NaN; asksMid = NaN; bidsFar = NaN; asksFar = NaN; bidWall = NaN; bidWallSize = NaN; askWall = NaN; askWallSize = NaN; } // readBook() walks this bar's snapshot twice: first for the touch (the highest bid and the lowest ask: the chart hands // the asks over from the highest price down, so position says nothing), then for the dollars in each band and the // biggest level on each side within the wall reach. A level's dollars are its price times its size in coins. It // answers false when the bar has no usable snapshot: none delivered, a side missing, or a crossed book. function readBook(): bool { clearReadings(); const n = in_book_cells(); // numbers delivered this bar: 0 when the block is empty, -1 when the bar has none if (n < 3) return false; const cells = in_book_view(); let bestBid = -Infinity; let bestAsk = Infinity; for (let i = 0; i + 2 < n; i += 3) { const price = cells[i]; if (!(price > 0.0) || !(cells[i + 1] > 0.0)) continue; // an empty level is served but rests nothing if (cells[i + 2] > 0.0) bestBid = Math.max(bestBid, price); else if (cells[i + 2] < 0.0) bestAsk = Math.min(bestAsk, price); } if (!(bestBid > 0.0) || !(bestAsk < Infinity) || !(bestAsk > bestBid)) return false; // one side missing, or a crossed book bookSeen = true; const mid = (bestBid + bestAsk) * 0.5; bidsNear = 0.0; asksNear = 0.0; bidsMid = 0.0; asksMid = 0.0; bidsFar = 0.0; asksFar = 0.0; bidWallSize = 0.0; askWallSize = 0.0; for (let i = 0; i + 2 < n; i += 3) { const price = cells[i]; const size = cells[i + 1]; if (!(price > 0.0) || !(size > 0.0)) continue; const dollars = price * size; if (cells[i + 2] > 0.0) { const away = ((mid - price) / mid) * 100.0; // percent below the mid if (away <= NEAR_PCT) bidsNear += dollars; if (away <= MID_PCT) bidsMid += dollars; if (away <= FAR_PCT) bidsFar += dollars; if (away <= WALL_PCT && dollars > bidWallSize) { bidWallSize = dollars; bidWall = price; } } else if (cells[i + 2] < 0.0) { const away = ((price - mid) / mid) * 100.0; // percent above the mid if (away <= NEAR_PCT) asksNear += dollars; if (away <= MID_PCT) asksMid += dollars; if (away <= FAR_PCT) asksFar += dollars; if (away <= WALL_PCT && dollars > askWallSize) { askWallSize = dollars; askWall = price; } } } if (isNaN(bidWall)) bidWallSize = NaN; // no bid within the reach: no wall to name if (isNaN(askWall)) askWallSize = NaN; return true; } // One wall line: from lineBars bars back to the live bar at the wall's price, extended to the price axis; deleted when // there is no wall (a delete on a line that was never drawn does nothing). function drawWall(line: LineHandle, price: f64, t: f64, color: i32): void { if (isNaN(price) || isNaN(barSeconds)) { line.delete(); return; } line.set(t - f64(lineBars) * barSeconds, price, t, price).color(color).style(LineStyle.Dotted).extend(Extend.Right); } // Money as text: 48.9M, 262.0M, 950.0K, one decimal, in the row's slot. function sbUsd(x: f64): void { if (x >= 1.0e9) { sb_f64(x / 1.0e9, 1); sb_text("B"); } else if (x >= 1.0e6) { sb_f64(x / 1.0e6, 1); sb_text("M"); } else { sb_f64(x / 1.0e3, 1); sb_text("K"); } } // One depth row: "<bid dollars> / <ask dollars>", or a dash while the bar has no snapshot. function sbDepth(bids: f64, asks: f64): void { sb_clear(); if (isNaN(bids) || isNaN(asks)) sb_text("-"); else { sbUsd(bids); sb_text(" / "); sbUsd(asks); } } // One wall row: "<price> · <dollars>", or a dash when no level sits within the reach. function sbWall(price: f64, dollars: f64): void { sb_clear(); if (isNaN(price) || isNaN(dollars)) sb_text("-"); else { sb_f64(price, 2); sb_text(" · "); sbUsd(dollars); } } function onStart(): void { lean = p_lean(); lineBars = i32(p_line_bars()); } // onBar() runs once per bar: read the snapshot, write every output, and on the live bar write the first tile's words // and draw the two wall lines. function onBar(): void { const t = bar.time(); if (!isNaN(prevTime) && t > prevTime && (isNaN(barSeconds) || t - prevTime < barSeconds)) barSeconds = t - prevTime; // the smallest step is one bar prevTime = t; const hasSnapshot = readBook(); const depth = bidsFar + asksFar; const imbalance = depth > 0.0 ? ((bidsFar - asksFar) / depth) * 100.0 : NaN; let side = BALANCED; if (imbalance >= lean) side = BIDS_HEAVIER; else if (imbalance <= -lean) side = ASKS_HEAVIER; // a NaN imbalance passes neither test and stays Balanced out_side(side); out_imbalance(imbalance); out_imbalance_change(imbalance - prevImbalance); // NaN until two bars in a row have a book out_bid_share(depth > 0.0 ? (bidsFar / depth) * 100.0 : NaN); out_bids_near(bidsNear); out_asks_near(asksNear); out_bids_mid(bidsMid); out_asks_mid(asksMid); out_bids_far(bidsFar); out_asks_far(asksFar); out_bid_wall(bidWall); out_bid_wall_size(bidWallSize); out_ask_wall(askWall); out_ask_wall_size(askWallSize); prevImbalance = imbalance; if (bar.isLast()) { sb_clear(); if (!bookSeen) sb_text("No order book on this market"); else if (!hasSnapshot) sb_text("Waiting for the book"); else if (isNaN(imbalance)) sb_text("Nothing resting within 1%"); else if (side == BIDS_HEAVIER) sb_text("Bids heavier"); else if (side == ASKS_HEAVIER) sb_text("Asks heavier"); else sb_text("Balanced"); str_heavier_sb(); sbDepth(bidsNear, asksNear); str_depth_near_sb(); sbDepth(bidsMid, asksMid); str_depth_mid_sb(); sbDepth(bidsFar, asksFar); str_depth_far_sb(); sbWall(bidWall, bidWallSize); str_bid_wall_text_sb(); sbWall(askWall, askWallSize); str_ask_wall_text_sb(); drawWall(bidLine, bidWall, t, BID_INK); drawWall(askLine, askWall, t, ASK_INK); } } ``` ## How it works **One snapshot per bar.** `input("book", book.cells, { max_cells: 1000, block_size: 10 })` hands each bar the book the chart loads for its own market, at its own price grouping, up to 500 levels a side. History bars carry the snapshot of their bar; the live bar's book is refreshed about once a second. `block_size` is required by the declaration and the chart does not read it. **The touch first.** The chart hands the bids over best first and the asks from the highest price down, so the first pass looks for the highest bid and the lowest ask by price, never by position, and skips empty levels. The mid is halfway between them; a book missing a side, or crossed, reads as no snapshot. **Dollars by distance.** The second pass prices each level (its price times its size in coins) and adds it to every band it sits inside: 0.25%, 0.5% and 1% from the mid. The 1% band also gives the imbalance, bids minus asks over their sum in percent, and the bid share, bids over that sum. The biggest level on each side within 2% is that side's wall. **The deciding word.** An imbalance at or above `lean` (10 points) reads Bids heavier, at or below minus `lean` reads Asks heavier, and anything between reads Balanced. A data-only `side` output (0, 1 or 2) picks the pill's colour from its ladder: the down colour for Asks heavier, the muted colour for Balanced and the up colour for Bids heavier, so the colour gives the lean's sign before the word is read. The imbalance and its change since the previous bar's book, in points, are written on every bar as `imbalance` and `imbalance_change` for the Console. **The bid share on a bar.** The meter reads `bid_share` from 0 to 100 with a mark at 50; the default look draws a meter as a bar (a track with a knob), so a knob on the 50 mark is an even book. The number beside the label is the share itself. **No look word, the default look.** With no `look`, the chart draws the card in its default look: near black and translucent (white paper on a light chart) with a hairline border and 12 px corners, the title in sentence case, the headline at 17 px bold with its label hidden, the pill as its word in its colour with no capsule and no dot, the meter as a bar and the rows 22 px tall with a hairline between them. A word declared on the card wins over the default ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). **The walls on price.** Two line handles, made once at load, are set on the live bar at the two wall prices, reaching back `line_bars` (30) bars and extended to the price axis, dotted, the bid wall in the up colour and the ask wall in the down colour. A side with no level inside 2% deletes its line. ## Where it runs Every market whose order book the chart serves to an indicator: crypto perpetuals and spot such as Binance Futures BTCUSDT and Binance ETHUSDT. FX and stocks have no order book, and some thin perpetuals have none on the chart either: there the first tile reads "No order book on this market" and nothing is drawn. On a prediction market the chart serves a book in coarse price steps, wider than 1% of a mid in the tens of cents, so the card reads "Nothing resting within 1%" and names no wall. ## When data is missing - A market with no order book on the chart: the first tile says so, every number reads a dash and no line is drawn. - A bar whose snapshot has not arrived yet, or arrived with one side empty or crossed: that bar writes no numbers, and on the live bar the first tile reads "Waiting for the book" until it does. - A book with no level inside 1% of the mid: the first tile reads "Nothing resting within 1%", every band reads 0 (the bands nest) and the bid share reads a dash with an empty bar; a level within 2% is still named as a wall. - A band with no level inside it reads 0; a side with no level within 2% names no wall and draws no line. ## Customize it - **A wider middle.** Raise `lean` so the card names a side only on a clear lean. - **Longer or shorter wall lines.** `line_bars` sets how far back the two lines reach from the live bar. - **Other distances.** The bands and the wall reach are the constants `NEAR_PCT`, `MID_PCT`, `FAR_PCT` and `WALL_PCT`; change one together with the row labels that name it, since a tile label is fixed text. - **The imbalance as a number.** `tile.value("Imbalance within 1%", "imbalance", { format: "%", delta: "imbalance_change" })` puts the imbalance on the card with its change since the last bar's book beside it. - **Another corner.** Change `position: "middle_left"` to any of the nine anchors, `top_left` to `bottom_right`. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Order Book HUD** under **HUDs**. 2. Press **Run** on a crypto chart: the card appears at the middle left and the two walls draw on price. 3. At the editor's Console prompt, type `outputs` to read the newest value of every output: the imbalance and its change, the bid share, the six depth sums and the two walls with their sizes. ## Concepts used - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for `render.hud`, the four tiles, the headline and the pill's colour ladder - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Data sources](../core-concepts/data-sources.md) and [Order flow](../functions/order-flow-kit.md#what-the-chart-serves) for `book.cells`, its row shape and its order - [Drawing objects](../presentation/drawing-objects.md#handles) for line handles made once and set on the live bar - [Plotting](../presentation/plotting.md) for data-only outputs and string slots <!-- source: https://openmarket.xyz/wrun/cookbook/session-hud --> # Session HUD Where the day stands, in one card at the bottom of the price pane, drawn in the chart's default look. It names the session trading now as the headline (Asia, London, New York or Closed), how much of that session has passed on a gauge, and the session up next with a countdown ("London in 2 h 5 min"); then how much of an average day's range today has already used, on a meter that runs to one and a half average days; where the close sits inside today's range, on a gauge from the low (0) to the high (100); how far the close is from the day's VWAP; and how far it is from the prior day's high and low, in percent. On price, the day's VWAP draws in the text colour, starting again each day, and the prior day's high and low run as dotted muted lines from today's first bar to the right edge. The parts are three `param.session` windows read with `inSession` and a `Clock` per zone ([Sessions and units](../settings/sessions-and-units.md), [Clock and sessions kit](../functions/time-and-sessions-kit.md)), the bar's `time.trade_date` for the day ([Data sources](../core-concepts/data-sources.md)), a `candles` stream of daily candles kept by a `CandleList` for the average daily range ([Multi-timeframe](../core-concepts/multi-timeframe.md), [Higher-timeframe kit](../functions/higher-timeframe-kit.md)), a line output for the VWAP ([Plotting](../presentation/plotting.md)), two line handles for the prior day ([Drawing objects](../presentation/drawing-objects.md#handles)), and a two-column `render.hud` card with no `look` word, of two pills, two gauges, a meter, a value and a rows tile ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)). This is also the `session-hud` template: the **Session HUD** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Session HUD: where the day stands, in one card at the bottom of the price pane, drawn by the chart in its default // look. The trader sees the session trading now (Asia, London, New York, or Closed) as the headline, how much of that // session has passed, which session opens next and when, how much of an average day's range today has already used, // where the close sits inside today's range, and how far the close is from the day's VWAP and from the prior day's // high and low (the minutes left ride an output). On price: the day's VWAP in the text ink, and the prior day's high // and low as dotted muted lines across today. Every market with candles: crypto, stocks and forex. // Settings: the three session windows, each in its own zone (daylight saving follows the zone, bar by bar), and the // number of days in the average daily range. section("Sessions"); param.session("asia", "00:00-08:00", { tz: "UTC", label: "Asia" }); param.session("london", "07:00-16:00", { tz: "UTC", label: "London" }); param.session("new_york", "13:30-20:00", { tz: "UTC", label: "New York" }); section("Range"); param.int("adr_days", 14, { min: 2, max: 30, label: "Days in average range", description:"Days in the average daily range that today's range is measured against" }); chart.interval_sec(); // the chart's bar interval in seconds, written by the chart: a 4h or coarser chart gets words instead input("close", ohlcv.close); // the chart's own candles: the grid input("trade_date", time.trade_date); // the bar's trade date, one number per day: the UTC date on crypto and forex, the New York date on US stocks input("days", candles.cells, { interval: "1d", bars: 30, description: "The newest 30 closed daily candles: the average daily range and the prior day" }); // On price: the day's VWAP, starting again with each trade date. output("vwap", line, overlay, { color: "theme.text", width: 2, label: "Day VWAP", format: "price", description: "The day's volume-weighted average price; on a market without volume every bar weighs the same" }); // The readings, data-only and written on every bar: the card's tiles read the newest one, the Console reads them all. output("session_now", none, overlay, { description: "The session trading now: 0 closed, 1 Asia, 2 London, 3 New York (the later one where two overlap)" }); output("session_done", none, overlay, { format: "0", description: "Percent of the session trading now that has passed; NaN while no session trades" }); output("minutes_left", none, overlay, { description: "Minutes from the bar's open to the session's close; NaN while no session trades" }); output("range_used", none, overlay, { format: "0", description: "Today's high-low range as a percent of the average daily range" }); output("range_position", none, overlay, { description: "Where the close sits in today's range: 0 at the low, 100 at the high" }); output("vs_vwap", none, overlay, { color: "theme.text", description: "Close against the day's VWAP, percent" }); // the line's ink output("vs_prior_high", none, overlay, { color: "theme.muted", description: "Close against the prior day's high, percent" }); output("vs_prior_low", none, overlay, { color: "theme.muted", description: "Close against the prior day's low, percent" }); string("up_next", { max_bytes: 32 }); // the next session to open and when, written on the live bar string("session", { max_bytes: 32 }); // the card's first tile: the session's name, or why there is none handles.line({ color: "theme.muted", width: 1, lineStyle: "dotted", extend: "right" }); // the prior day's high and low, from today's first bar to the right edge // The card: two columns at the bottom centre of the pane, clear of the legend at the top left, the price axis and its // tags on the right, and the floating button at the bottom left. The session's name leads as the headline; every tile // reads the newest row. render.hud("session", { position: "bottom_center", title: "Session", columns: 2, tiles: [ tile.pill("Trading now", "session", { headline: true }), tile.gauge("Session passed, %", "session_done", { min: 0, max: 100, format: "0" }), tile.pill("Up next", "up_next"), tile.meter("Day range vs average, %", "range_used", { min: 0, max: 150, marks: [100] }), tile.gauge("Close in today's range", "range_position", { min: 0, max: 100, format: "0" }), tile.value("Close vs day VWAP", "vs_vwap", { format: "%" }), tile.rows("Close vs prior day", [ ["High", "vs_prior_high", "%"], ["Low", "vs_prior_low", "%"], ]), ], }); const SESSIONS = 3; // Asia, London, New York, in the order a later one wins an overlap const NAMES = ["Asia", "London", "New York"]; const MAX_DAYS = 30; // the daily stream's depth: adr_days is at most this const starts = new StaticArray<f64>(SESSIONS); // each window's start and end in minutes from midnight, and its zone, read in onStart() const ends = new StaticArray<f64>(SESSIONS); const zones = new StaticArray<i32>(SESSIONS); let clocks: Clock[] = []; // one clock per session, in the zone its window is written in, built in onStart() const days = new CandleList(MAX_DAYS); // the newest closed daily candles, kept from the stream const priorHighLine: LineHandle = draw.line(0); // handle objects allocate once, at module load const priorLowLine: LineHandle = draw.line(1); let adrDays = 14; // settings, read in onStart() let coarse = false; let dayKey: f64 = NaN; // today's trade date, and the open of its first bar let dayStart: f64 = NaN; let dayWhole = false; // today began inside the loaded history: the first day may have started before it let dayHigh: f64 = NaN; // today so far let dayLow: f64 = NaN; let pv = 0.0; // today's VWAP sums: price times volume, volume, and the plain sum and count for a market without volume let vol = 0.0; let typicalSum = 0.0; let typicalCount = 0; let chartPriorHigh: f64 = NaN; // the prior day from the chart's own bars, where the daily stream is not served let chartPriorLow: f64 = NaN; // onStart() runs once before the first bar: the settings, and a clock per session zone. function onStart(): void { starts[0] = p_asia_start(); ends[0] = p_asia_end(); zones[0] = i32(p_asia_tz()); starts[1] = p_london_start(); ends[1] = p_london_end(); zones[1] = i32(p_london_tz()); starts[2] = p_new_york_start(); ends[2] = p_new_york_end(); zones[2] = i32(p_new_york_tz()); clocks = [new Clock(SESSION_TZ_IDS[zones[0]]), new Clock(SESSION_TZ_IDS[zones[1]]), new Clock(SESSION_TZ_IDS[zones[2]])]; adrDays = i32(p_adr_days()); if (adrDays > MAX_DAYS) adrDays = MAX_DAYS; coarse = p_chart_interval_sec() >= 14400.0; // 4h and coarser: a session is a bar or two, its minutes would say nothing } // Minutes from a bar's open to its session's close, on the session's own clock; a window may wrap midnight. function minutesLeft(s: i32, t: f64): f64 { const clock = clocks[s]; clock.update(t); const minute = f64(clock.hour() * 60 + clock.minute()); const start = unchecked(starts[s]); const end = unchecked(ends[s]); if (end > start || minute < end) return end - minute; return 1440.0 - minute + end; // a window that wraps midnight, before midnight: it closes tomorrow } // The share of a session that has passed at a bar's open, percent. function sessionDone(s: i32, t: f64): f64 { const start = unchecked(starts[s]); const end = unchecked(ends[s]); const length = end > start ? end - start : 1440.0 - start + end; return Math.max(0.0, Math.min(100.0, (1.0 - minutesLeft(s, t) / length) * 100.0)); } // Minutes from a bar's open to a session's next start, on the session's own clock. function minutesToStart(s: i32, t: f64): f64 { const clock = clocks[s]; clock.update(t); const minute = f64(clock.hour() * 60 + clock.minute()); const start = unchecked(starts[s]); return start > minute ? start - minute : 1440.0 - minute + start; } // The prior day's level across today, or nothing while it is unknown. function drawPrior(line: LineHandle, price: f64, t: f64): void { if (isNaN(price) || isNaN(dayStart)) { line.delete(); // a no-op when never drawn return; } line.set(dayStart, price, t, price); } // onBar() runs once per bar: feed the daily stream, place the bar in its session and its day, then write the // readings; the session's name and the two prior-day lines on the live bar only. function onBar(): void { const t = bar.time(); days.load(in_days_view(), in_days_cells(), t); // every bar feeds its block, an empty one too const close = bar.close(); if (isNaN(close)) return; if (coarse) { if (bar.isLast()) { sb_clear(); sb_text("Needs a chart under 4h"); str_session_sb(); } return; } // The session: the later window wins where two overlap (London over Asia, New York over London). let now = -1; for (let s = 0; s < SESSIONS; s += 1) if (inSession(t, unchecked(starts[s]), unchecked(ends[s]), unchecked(zones[s]))) now = s; out_session_now(f64(now + 1)); out_minutes_left(now >= 0 ? minutesLeft(now, t) : NaN); out_session_done(now >= 0 ? sessionDone(now, t) : NaN); // The day: a new trade date starts a new one, and the day that ends becomes the prior day if it was seen whole. const high = bar.high(); const low = bar.low(); const key = in_trade_date(); const fresh = key != dayKey; if (fresh) { if (dayWhole) { chartPriorHigh = dayHigh; chartPriorLow = dayLow; } dayWhole = !isNaN(dayKey); dayKey = key; dayStart = t; dayHigh = high; dayLow = low; pv = 0.0; vol = 0.0; typicalSum = 0.0; typicalCount = 0; } else { if (high > dayHigh) dayHigh = high; if (low < dayLow) dayLow = low; } const typical = (high + low + close) / 3.0; const volume = bar.volume(); if (volume > 0.0) { pv += typical * volume; vol += volume; } typicalSum += typical; typicalCount += 1; const vwap = !dayWhole ? NaN : vol > 0.0 ? pv / vol : typicalSum / f64(typicalCount); out_vwap(fresh ? NaN : vwap); // the day's first bar draws nothing, so each day's line starts on its own // The average daily range of the newest closed days, and the prior day: the stream's newest closed day where it // is served, else the chart's own bars. The day's last bar is handed the daily candle that closes at its end, the // day's own: a held candle that opened on today's trade date or later is skipped, never read as a prior day. let held = days.count(); while (held > 0 && days.openSec(held - 1) >= key) held -= 1; let adr: f64 = NaN; if (held >= adrDays) { let sum = 0.0; for (let i = held - adrDays; i < held; i += 1) sum += days.high(i) - days.low(i); adr = sum / f64(adrDays); } const priorHigh = held > 0 ? days.high(held - 1) : chartPriorHigh; const priorLow = held > 0 ? days.low(held - 1) : chartPriorLow; const range = dayHigh - dayLow; out_range_used(dayWhole && adr > 0.0 ? (100.0 * range) / adr : NaN); out_range_position(dayWhole && range > 0.0 ? (100.0 * (close - dayLow)) / range : NaN); out_vs_vwap(vwap > 0.0 ? 100.0 * (close / vwap - 1.0) : NaN); out_vs_prior_high(priorHigh > 0.0 ? 100.0 * (close / priorHigh - 1.0) : NaN); out_vs_prior_low(priorLow > 0.0 ? 100.0 * (close / priorLow - 1.0) : NaN); if (bar.isLast()) { sb_clear(); sb_text(now >= 0 ? NAMES[now] : "Closed"); str_session_sb(); let next = -1; let wait = 1441.0; for (let s = 0; s < SESSIONS; s += 1) { if (s == now) continue; const m = minutesToStart(s, t); if (m < wait) { wait = m; next = s; } } sb_clear(); if (next >= 0) { const h = i64(Math.floor(wait / 60.0)); sb_text(NAMES[next]); sb_text(" in "); if (h > 0) { sb_int(h); sb_text(" h "); } sb_int(i64(wait) - h * 60); sb_text(" min"); } str_up_next_sb(); drawPrior(priorHighLine, priorHigh, t); drawPrior(priorLowLine, priorLow, t); } } ``` ## How it works **The session is cut from the clock.** Each window is a `param.session` (Asia 00:00 to 08:00, London 07:00 to 16:00, New York 13:30 to 20:00, all UTC by default), read in `onStart()` as a start, an end and a zone. Per bar, `inSession(...)` says whether the bar's open falls inside each window, daylight saving included; where two overlap, the later one in the list wins (London over Asia from 07:00, New York over London from 13:30). `session_now` carries the answer as a number, 0 closed to 3 New York. **Time from the bar's open.** No wall clock reaches an indicator: the newest bar's open is its clock. `minutes_left` counts from the live bar's open to the session's close on the session's own clock (a `Clock` built in the window's zone), and `session_done` turns it into the share of the session that has passed, 0 at its open and 100 at its close. Both step once per bar: on a 15m chart the gauge can sit up to 15 minutes behind, on a 1h chart up to an hour. **Up next.** On the live bar the script measures, on each other session's own clock, the minutes from the bar's open to that session's next start, and writes the nearest one into the bounded `up_next` slot as words: "London in 2 h 5 min", or "New York in 45 min" under an hour. It steps once per bar too, so it can read up to one bar long. **The day is the trade date.** `time.trade_date` gives each bar its trading day: the UTC date on crypto, the 17:00 New York trade day on forex and gold, the New York date on US stocks. A new trade date starts a new day: today's high, low and VWAP sums start again, and the day that ended becomes the prior day when the chart saw it from its first bar. The first day of the loaded history may have begun before it, so its readings stay empty until the next day starts. **The VWAP.** Each bar adds its typical price (high plus low plus close, over 3) weighted by its volume, and the VWAP is that sum over the day's volume. On a market that reports no volume every bar weighs the same, so the line is the day's average typical price. The day's first bar draws nothing, so each day's line starts on its own instead of joining the day before. **The average day.** `input("days", candles.cells, { interval: "1d", bars: 30 })` streams the closed daily candles and a `CandleList` keeps the newest 30. The average daily range is the mean of high minus low over the newest `adr_days` (14) of them, and `range_used` is today's high minus low as a percent of it: 100 is an average day's whole range, and the meter runs to 150. The prior day's high and low come from the newest closed daily candle where the stream is served, else from the chart's own bars. A day's candle closes at the end of the day's last bar, so that bar (23:00 on a 1h crypto chart) is handed today's own candle: every held candle that opened on today's trade date or later (`days.openSec(i)` at or past `in_trade_date()`) is skipped before either reading, so the 23:00 bar still measures against yesterday's high and low and an average of the days before today. **The card reads the outputs.** `render.hud("session", { position: "bottom_center", columns: 2, tiles })` pins a 300 px card of two columns: the headline pill over the `session` slot on the first row; a gauge of `session_done` (0 to 100) beside a pill over the `up_next` slot; a meter of `range_used` (0 to 150) across the card; a gauge of `range_position` (0 to 100) beside a value of `vs_vwap` in `%`; and a rows tile of the distances from the prior day's high and low in `%`. The distances are already percents: the card prints two decimals, a minus sign below the level and no sign above it. Each distance output carries its line's colour: the text colour for the VWAP, muted for the prior day. Every tile reads the newest row; the session's name, the up-next words and the two dotted lines are written on the live bar only, the numbers on every bar. **No look word, the default look.** With no `look`, the chart draws the card in its default look: near black and translucent (white paper on a light chart) with a hairline border and 12 px corners, the title in sentence case and the headline at 17 px bold with its label hidden. A gauge draws as an arc, the meter as a bar with its mark at 100, a pill as its words alone with no capsule and no dot, and the rows 22 px tall with a hairline between them. A word declared on the card wins over the default ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). **Where the card sits.** At the bottom centre: the legend holds the top left, the action bar and the High and Low tags the top right, the VWAP tag and the newest candles the right edge, and the app's floating button the bottom left. ## Where it runs Every market with candles, on charts finer than 4h: crypto perpetuals and spot (Binance Futures BTCUSDT, Binance spot ETHUSDT, Hyperliquid PURR), US stocks and forex (gold). The windows are clock windows in their zones, so on crypto they run every day, weekends included; a forex chart has no bars over the weekend, so on a Saturday it shows Friday's last bar, after New York's close: "Closed". The average daily range needs the chart's daily candle stream, which crypto charts serve and forex and US stock charts do not (below). ## When data is missing - **Forex and US stocks: no daily stream.** The chart does not serve a `candles` stream on those markets, so `days` reads no candles: the range meter prints "-", the prior day's high and low come from the chart's own bars, and the Console and the legend show the chart's warning, which names the input: `Input 'days' pins interval '1d' on an index-mode chart (FX_OTC): pinned legs are served on timestamp-mode markets only, so the input reads its missing fill (NaN) on every bar.` Everything else on the card reads as usual. - **No volume.** Forex reports no volume, so the VWAP weighs every bar the same there: the line is the day's average typical price. - **Between sessions.** Outside the three windows the headline reads "Closed", the session-passed gauge prints "-", and Up next counts down to the next session to open. - **Coarse charts.** On a 4h or coarser chart a session is a bar or two, so the headline reads "Needs a chart under 4h", the other tiles print "-", and nothing is drawn on price. - **The first loaded day.** The chart's history may start inside a day; that day's VWAP, range and position stay empty, and the next day starts clean. On a short chart (a few hours of 1m bars) today itself can be that first day: the session word, the session-passed gauge and Up next still read. - **A flat day.** A day whose high equals its low leaves the close-in-range gauge reading "-". ## Customize it - **Other sessions.** The three windows are settings, each with its own zone; a window that crosses midnight (`22:00-04:00`) wraps on its own, and the gauge and the countdown count across midnight. - **A longer or shorter average.** `adr_days` goes from 2 to 30; the stream holds 30 days, so past that raise `bars` on the `days` input and `MAX_DAYS` with it. - **The minutes as a number.** `tile.value("Minutes to close", "minutes_left", { format: "int" })` puts the minutes left in the session on the card beside the gauge's share. - **Another place for the card.** Change `position` to another of the nine anchors (`middle_left` works too); keep the right edge free for the VWAP tag and the newest candles. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Session HUD** under **HUDs**. 2. Press **Run** on a chart finer than 4h, such as 15m: the VWAP draws on price, the prior day's high and low run across today, and the card appears at the bottom centre. 3. At the editor's Console prompt, type `session_done` and `range_used` to read the newest values, or `last 60 session_now` for the session on each of the last 60 bars. ## Concepts used - [Sessions and units](../settings/sessions-and-units.md) for `param.session`, its zones and `inSession` - [Clock and sessions kit](../functions/time-and-sessions-kit.md) for `Clock` - [Higher-timeframe kit](../functions/higher-timeframe-kit.md) for `CandleList` - [Data sources](../core-concepts/data-sources.md) for `time.trade_date` - [Multi-timeframe](../core-concepts/multi-timeframe.md) for the `candles` stream and where the chart serves it - [Drawing objects](../presentation/drawing-objects.md#handles) for line handles from today's first bar to the right edge - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the card, its tiles and the headline - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code <!-- source: https://openmarket.xyz/wrun/cookbook/greek-exposure --> # Greek exposure A snapshot of now: the longer a bar, the more dealers (the market makers who hedge options) must hedge there. Bars beside the prices show each strike (the option's price level), bars below each expiry (the day the option ends). Labels mark the biggest strike (top) and the biggest below price (floor), above it (ceiling) and before the top (gate). Hedging there can pin price or speed it up. Use it before big expiries to see where hedging piles up. Under the hood: it reads this symbol's whole options list on the live bar (`options_chain.cells`, [Data sources](../core-concepts/data-sources.md#options-chain)). It prices the greeks and each expiry's time left with [`Greeks`, `optionsAsOfMs`, `optionsLiveUntilMs`, `optionsYearsToGo` and `optionsTradeDay`](../functions/options-kit.md#pricing-the-chain). The gamma lens, the regime and the flip come from [`GammaCurve` and `bsGamma`](../functions/options-kit.md#the-canonical-numbers). They follow the open-interest model, where dealers are long the calls and short the puts. It labels strikes with [`NodeBoard`](../functions/options-kit.md#node-roles) and counts presets with [`expiryPresetCount`](../functions/options-kit.md#expiry-presets). It docks three `plot.levels` frames on the price axis and one `panel.bars` frame under the chart ([Cards, frames and panels](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets)). It draws a `render.hud` card in the default look. It is the `greek-exposure` template: **Greek Exposure** under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Greek Exposure: a snapshot of where dealers (the market makers who hedge options) must hedge most in this symbol's // options. Gamma (how fast dealers must hedge as price moves) is the default view. Long gamma (dealers calm price): // they sell rallies and buy dips, so price tends to calm. Short gamma (dealers chase price): they buy rallies and sell // dips, so price tends to trend. Bars on the price axis show each strike (the option's price level). Bars under the // chart show each expiry (the day the option ends). A longer bar means more hedging at that price, which can pin price // or push it. Labels mark the biggest strike (top) and the biggest below price (floor), above it (ceiling) and before // the top (gate). Other views show delta, vanna, charm, vega or open interest (contracts still held open). Use it // before key levels or expiries to see where dealer hedging piles up. // // Under the hood: The Lens setting picks gamma (the default), delta, vanna, charm or vega, or the open interest // itself and IV times open interest; the Expiries setting counts every live expiry, the one settling today, those // within 7 or 30 trade days, the N nearest, or every expiry stacked by days to go (0, 1-7, 8-30, 31-60, 61-120, // 121+). The exposure by strike docks on the price axis (net, calls against puts, or the stacked days), the exposure // by expiry stands in bars under the chart, and a card reads the lens in one plain line first (Long gamma: dealers // calm price), then the net, the calls, the puts, the same-day expiry, the strikes that matter and the gamma flip. // The gamma lens and the flip are the options kit's GammaCurve over the counted expiries, the rule every card reads: // gamma priced at the chain's as-of (optionsAsOfMs: the live bar's close time) to each expiry's end // (optionsYearsToGo: 16:15 New York on OPRA), the regime the sign of net GEX at spot, the flip the curve's zero // nearest spot. The gamma lens's totals count every contract the curve reads; every other lens counts the strike // table's (the 1,024 strikes nearest spot), as the data plane's exposure fold does. The convention is the // open-interest model: dealers long the calls and short the puts, so calls add and puts subtract on every lens but // delta, which keeps each option's own sign as delta views do. Units: dollars, or units of the underlying (shares on // a US stock, contracts on CME, coins on crypto) for gamma per 1% move of spot, delta held, vanna per IV point and // charm per calendar day (never times 365); vega in dollars per IV point. The chain rides the live bar only: history // bars draw nothing, everything is measured on the last bar. The node words name the lens's nodes over the strike // table (the options kit's NodeBoard over each strike's net, read against spot): the top (the largest |net|, // starred), the gate (the largest between spot and the top, at 35% of the top or more), the floor (the largest below // spot) and the ceiling (the largest above it) label their rows in whichever docked profile the settings draw. Expiry // preset picks the expiries by the calendar (the front one, to this or next Friday, to the monthly or quarterly opex, // all) in place of the Expiries setting's range; count keeps that range. section("Lens"); param.choice("lens", ["gamma", "delta", "vanna", "charm", "vega", "iv_x_oi", "oi"], "gamma", { label: "Lens", description: "What the bars measure. gamma: hedging per 1% move. delta: stock dealers hold to hedge. charm, vanna: how that hedge changes with time or option prices. vega: gain as option prices rise. iv_x_oi: implied volatility times open interest. oi: open interest." }); param.choice("units", ["dollars", "underlying"], "dollars", { label: "Units", when: "lens in 0,1,2,3", description: "dollars: in dollars. underlying: in this symbol's own units (shares, contracts or coins). It applies to gamma, delta, vanna and charm." }); param.choice("split", ["net", "calls_puts"], "net", { label: "By strike", when: "scope!=5", description: "net: one bar per strike, calls minus puts. calls_puts: the calls one way, the puts the other." }); section("Expiries and strikes"); param.choice("scope", ["all", "0dte", "week", "month", "nearest", "buckets"], "all", { label: "Expiries", description: "Which expiries count while Expiry preset is count. all: every live one. 0dte: the one that expires today. week: within 7 trade days. month: within 30. nearest: the N soonest. buckets: all of them, stacked by days left, under every preset." }); param.int("nearest", 4, { min: 1, max: 24, label: "Nearest expiries", when: "scope=4", description: "How many of the soonest live expiries count when Expiries is nearest." }); param.number("window_pct", 8, { min: 1, max: 50, label: "Strike window, percent", description: "How far the strikes on the price axis reach above and below the price, in percent." }); param.number("rate_pct", 4, { min: 0, max: 20, step: 0.25, label: "Rate, percent", when: "lens in 2,3,4", description: "The interest rate used to price vanna, charm and vega on US stock and CME options. Crypto options use 0." }); input("close", ohlcv.close); // the chart's own close: spot where a contract reports no underlying, and the window's centre input("chain", options_chain.cells, { max_cells: 4000, venue: "auto", description: "This symbol's options: US listed options on a US stock, CME options on futures, Deribit on BTC and ETH." }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega] per contract market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME): the calendar, the model and the unit word chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The expiry preset, after the market's clock and the bar's length, which the chart fills, so every setting before // them keeps its slot. param.choice("expiry_preset", ["front", "to_friday", "to_next_friday", "to_opex", "to_next_opex", "to_q_opex", "all", "count"], "count", { label: "Expiry preset", description: "Picks expiries by the calendar. front: the nearest. to_friday, to_next_friday: through this or next Friday. to_opex, to_next_opex: through this or next monthly expiry (third Friday). to_q_opex: the next quarterly one. all: every one. count: use Expiries." }); // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("net_exposure", none, overlay, { description: "The lens over the counted expiries: calls add, puts subtract, and delta keeps each option's own sign. In the title's unit, on the live bar only." }); output("calls_exposure", none, overlay, { color: "theme.up", description: "The calls' part of the net" }); output("puts_exposure", none, overlay, { color: "theme.down", description: "The puts' part of the net, signed as it counts" }); output("today_exposure", none, overlay, { description: "The net of the expiry that settles today. Blank when none is listed or counted." }); output("top_strike", none, overlay, { description: "The strike with the largest net exposure, either way. On the gamma lens it is the magnet, which tends to pull price." }); output("top_exposure", none, overlay, { description: "That strike's net exposure" }); output("zero_cross", none, overlay, { description: "The gamma flip for the counted expiries, on every lens: the price nearest now where dealer gamma crosses zero. Blank when none lies within 50%." }); output("above_spot", none, overlay, { description: "The net over the strikes above the price." }); output("below_spot", none, overlay, { description: "The net over the strikes at or below the price." }); output("tone", none, overlay, { description: "The headline's colour code: 0 net below zero, 1 no reading, 2 net above zero. Live bar only." }); output("expiries_counted", none, overlay, { description: "The live expiries the Expiries setting counts" }); string("read", { max_bytes: 64 }); // the headline: the lens's one plain line, or why there is no reading string("title", { max_bytes: 64 }); // the card's title: the lens, its unit and the expiries counted // The docked profiles, one per shape; only the one the settings pick is written, so the other two stay absent. const net_rows = frame("net_rows", { max_bytes: 24576 }); const split_rows = frame("split_rows", { max_bytes: 32768 }); const day_rows = frame("day_rows", { max_bytes: 65536 }); const expiry_rows = frame("expiry_rows", { max_bytes: 8192 }); // Each frame's labels_text names the nodes on their rows, every other row bare. plot.levels({ name: "by_strike", frame: net_rows, dock: "right", width_frac: 0.14, baseline: "center", color: "theme.muted", thickness_px: 10, hover: true, format: "si" }); plot.levels({ name: "calls_puts", frame: split_rows, dock: "right", width_frac: 0.14, baseline: "center", thickness_px: 10, hover: true, format: "si", series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }] }); plot.levels({ name: "by_days", frame: day_rows, dock: "right", width_frac: 0.16, baseline: "center", thickness_px: 10, hover: true, format: "si", series: [{ name: "0d", color: "#f43f5e" }, { name: "1-7d", color: "#f59e0b" }, { name: "8-30d", color: "#eab308" }, { name: "31-60d", color: "#22c55e" }, { name: "61-120d", color: "#38bdf8" }, { name: "121d+", color: "#a78bfa" }] }); panel.bars({ name: "by_expiry", title: "Net by expiry", x: "category", place: "below", frame: expiry_rows, orientation: "vertical", color_mode: "sign", positive_color: "theme.up", negative_color: "theme.down", series: [{ name: "Net" }], format: "si", hover_card: true, legend_style: "title", height_frac: 0.18 }); // The card: the lens's plain line leads as the headline, the title names the lens, its unit and the expiries counted. render.hud("exposure", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Dealers", "read", { headline: true }), tile.value("Net", "net_exposure", { format: "si" }), tile.value("Same-day expiry", "today_exposure", { format: "si" }), tile.value("Calls", "calls_exposure", { format: "si" }), tile.value("Puts", "puts_exposure", { format: "si" }), tile.rows([ ["Largest strike", "top_strike", "price"], ["Its exposure", "top_exposure", "si"], ["Gamma flip", "zero_cross", "price"], ["Above price", "above_spot", "si"], ["At or below price", "below_spot", "si"], ]), ], }); const TUPLE = 10; // f64s per contract: strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega const MAX_STRIKES = 1024; // distinct strikes the table keeps (the profile, the largest strike, every lens's totals but gamma's), the nearest spot when the chain lists more const MAX_EXPIRIES = 64; // live expiries kept, the nearest when the chain lists more const MAX_ROWS = 256; // rows in the docked profile, the strikes nearest spot inside the window const DAYS = 6; // the stacked buckets: 0, 1-7, 8-30, 31-60, 61-120, 121+ days to go const MIN_T_MS = 900000.0; // 15 minutes: a contract closer to its expiry prices no time left, as the chart's greeks do const GAMMA = 0; const DELTA = 1; const VANNA = 2; const CHARM = 3; const VEGA = 4; const IV_X_OI = 5; const SCOPE_ALL = 0; const SCOPE_TODAY = 1; const SCOPE_WEEK = 2; const SCOPE_MONTH = 3; const SCOPE_NEAREST = 4; const SCOPE_BUCKETS = 5; const LENS_NAMES: String[] = ["Gamma", "Delta", "Vanna", "Charm", "Vega", "IV x OI", "Open interest"]; const LENS_WORDS: String[] = ["gamma", "delta", "vanna", "charm", "vega", "implied volatility", "open interest"]; // the no-reading line const strikePrice = new StaticArray<f64>(MAX_STRIKES); // the strike table, ascending const callAt = new StaticArray<f64>(MAX_STRIKES); // the calls' exposure per strike const putAt = new StaticArray<f64>(MAX_STRIKES); // the puts' exposure per strike, signed as it counts const dayAt = new StaticArray<f64>(MAX_STRIKES * DAYS); // the net per strike and bucket: [strike * DAYS + bucket] const expiryAt = new StaticArray<f64>(MAX_EXPIRIES); // the live expiries, ascending const expiryDays = new StaticArray<f64>(MAX_EXPIRIES); // days to go on the market's calendar, 0 on the expiry day const expiryNet = new StaticArray<f64>(MAX_EXPIRIES); const contractValue = new StaticArray<f64>(in_chain_max_cells); // each contract's exposure on the lens; NaN when it does not count const expiryKept = new StaticArray<bool>(MAX_EXPIRIES); // counted by the Expiries setting const greeks = new Greeks(); // prices vanna, charm and vega per contract; allocated once let curve = new GammaCurve(1); // the counted expiries' gamma curve: the regime and the flip; built in onStart() const netAt = new StaticArray<f64>(MAX_STRIKES); // each kept strike's net on the lens, the nodes' reading let board = new NodeBoard(1); // the lens's nodes over the strike table; built in onStart() let preset = EXPIRY_PRESET_COUNT; // Expiry preset: an EXPIRY_PRESET_* code; count reads the Expiries setting let lens = GAMMA; // settings, read in onStart() let inUnderlying = false; let splitSides = false; let scope = SCOPE_ALL; let nearestCount = 4; let windowPct = 0.08; let rate = 0.04; let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds, read in onStart(); 0 where the host writes none let close: f64 = NaN; // this bar let t: f64 = NaN; let strikeCount = 0; let expiryCount = 0; let counted = 0; // expiries the setting counts let readings = 0; // contracts that carried a nonzero reading for the lens let net: f64 = NaN; // the readings, measured on the live bar let calls: f64 = NaN; let puts: f64 = NaN; let today: f64 = NaN; let topStrike: f64 = NaN; let topValue: f64 = NaN; let zeroCross: f64 = NaN; let regime: f64 = NaN; // the sign of net GEX at spot over the counted expiries: 1, -1 or 0 let above: f64 = NaN; let below: f64 = NaN; function onStart(): void { curve = new GammaCurve(in_chain_max_cells); // a slot per contract the block can carry, so a load is never refused lens = i32(p_lens()); inUnderlying = p_units() == 1.0; splitSides = p_split() == 1.0; scope = i32(p_scope()); nearestCount = i32(p_nearest()); windowPct = p_window_pct() / 100.0; zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; rate = zone == 0 ? 0.0 : p_rate_pct() / 100.0; // crypto chains are quoted at a rate of 0 // A host that serves no Expiry preset hands NaN: it then reads count (the Expiries setting's range, whatever a code // 0 would pick). const presetArg = p_expiry_preset(); preset = presetArg >= 0.0 && presetArg <= f64(EXPIRY_PRESET_COUNT) ? i32(presetArg) : EXPIRY_PRESET_COUNT; board = new NodeBoard(MAX_STRIKES); // the per-strike buffers are its only allocation } // ── The tables: sorted insertion, the nearest kept when full ── function noteExpiry(ms: f64): void { let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryAt[mid] < ms) lo = mid + 1; else hi = mid; } if (lo < expiryCount && expiryAt[lo] == ms) return; if (expiryCount >= MAX_EXPIRIES) { if (lo >= expiryCount) return; // later than every kept expiry expiryCount -= 1; // the latest makes room } for (let k = expiryCount; k > lo; k -= 1) expiryAt[k] = expiryAt[k - 1]; expiryAt[lo] = ms; expiryCount += 1; } function findExpiry(ms: f64): i32 { let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryAt[mid] < ms) lo = mid + 1; else hi = mid; } return lo < expiryCount && expiryAt[lo] == ms ? lo : -1; } function copyRow(from: i32, to: i32): void { strikePrice[to] = strikePrice[from]; callAt[to] = callAt[from]; putAt[to] = putAt[from]; for (let b = 0; b < DAYS; b += 1) dayAt[to * DAYS + b] = dayAt[from * DAYS + b]; } function findStrike(strike: f64): i32 { // the row of a kept strike, -1 when the table does not hold it let lo = 0; let hi = strikeCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } return lo < strikeCount && strikePrice[lo] == strike ? lo : -1; } function strikeSlot(strike: f64): i32 { // the row of this strike, inserted when new; -1 when the table is full and it is the farthest from spot let lo = 0; let hi = strikeCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } if (lo < strikeCount && strikePrice[lo] == strike) return lo; if (strikeCount >= MAX_STRIKES) { // full: the strike farthest from spot leaves, the lower one on a tie const dLow = Math.abs(strikePrice[0] - close); const dHigh = Math.abs(strikePrice[strikeCount - 1] - close); const dNew = Math.abs(strike - close); if (dLow >= dHigh) { if (dNew > dLow || (dNew == dLow && strike < strikePrice[0])) return -1; for (let k = 1; k < strikeCount; k += 1) copyRow(k, k - 1); strikeCount -= 1; if (lo > 0) lo -= 1; } else { if (dNew > dHigh || (dNew == dHigh && strike < strikePrice[strikeCount - 1])) return -1; strikeCount -= 1; if (lo > strikeCount) lo = strikeCount; } } for (let k = strikeCount; k > lo; k -= 1) copyRow(k - 1, k); strikePrice[lo] = strike; callAt[lo] = 0.0; putAt[lo] = 0.0; for (let b = 0; b < DAYS; b += 1) dayAt[lo * DAYS + b] = 0.0; strikeCount += 1; return lo; } function bucketOf(days: f64): i32 { // 0, 1-7, 8-30, 31-60, 61-120, 121+ days to go return days <= 0.0 ? 0 : days <= 7.0 ? 1 : days <= 30.0 ? 2 : days <= 60.0 ? 3 : days <= 120.0 ? 4 : 5; } // ── One contract's exposure on the lens, in the setting's unit, signed as it counts ── function exposureOf(cells: StaticArray<f64>, i: i32, nowMs: f64): f64 { const side = cells[i + 2] > 0.0 ? 1.0 : -1.0; // dealers long the calls, short the puts const oi = cells[i + 3]; if (lens == IV_X_OI) return side * cells[i + 6] * oi; // IV points times open interest if (lens > IV_X_OI) return side * oi; // open interest const under = cells[i + 7] > 0.0 ? cells[i + 7] : close; const multiplier = cells[i + 8] > 0.0 ? cells[i + 8] : 1.0; let perUnit: f64 = NaN; // the delta change (or delta) one unit of the underlying carries per unit of open interest if (lens == GAMMA) perUnit = side * bsGamma(under, cells[i], cells[i + 6] / 100.0, optionsYearsToGo(cells[i + 1], nowMs, zone)) * under * 0.01; // the delta change for a 1% move of spot, the gamma priced at the chain's as-of with the kit's time to go (to the expiry's end, a second at least on OPRA), as GammaCurve prices it else if (lens == DELTA) perUnit = cells[i + 5]; // each option's own sign, as delta views read it else { const left = optionsLiveUntilMs(cells[i + 1], zone) - nowMs; // the time to the expiry's end: 16:15 New York on OPRA const years = left < MIN_T_MS ? 0.0 : left / OPTIONS_YEAR_MS; const sigma = cells[i + 6] / 100.0; // mark IV rides the chain in percentage points if (zone == 1) greeks.spot(side, under, cells[i], years, sigma, rate); // a US stock: Black-Scholes on spot else greeks.forward(side, under, cells[i], years, sigma, rate); // futures and crypto: the underlying is the forward if (lens == VEGA) return side * (cells[i + 9] > 0.0 ? cells[i + 9] : greeks.vega) * oi * multiplier; // dollars per IV point perUnit = side * (lens == VANNA ? greeks.vanna : greeks.charm); } const dollars = perUnit * oi * multiplier * under; if (!inUnderlying) return dollars; return zone == 2 ? dollars / (under * multiplier) : dollars / under; // CME: futures contracts; else shares or coins } // ── The chain, measured on the live bar ── function measure(n: i32): void { const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer const nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the live bar's close time const todayKey = optionsTradeDay(nowMs, zone); strikeCount = 0; expiryCount = 0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) if (cells[i] > 0.0 && optionsLiveUntilMs(cells[i + 1], zone) > nowMs) noteExpiry(cells[i + 1]); // the live expiries counted = 0; // Expiry preset: count keeps the Expiries setting's range; any other preset keeps a run of the live expiries from the // front (the kit's expiryPresetCount on the market's trade days at the as-of). const presetKept = preset == EXPIRY_PRESET_COUNT ? 0 : expiryPresetCount(expiryAt, expiryCount, nowMs, zone, preset, 0); for (let e = 0; e < expiryCount; e += 1) { const days = optionsTradeDay(expiryAt[e], zone) - todayKey; // a calendar question: 0 on the expiry day, never the hours left expiryDays[e] = days; expiryNet[e] = 0.0; const kept = preset != EXPIRY_PRESET_COUNT ? e < presetKept : scope == SCOPE_TODAY ? days <= 0.0 : scope == SCOPE_WEEK ? days <= 7.0 : scope == SCOPE_MONTH ? days <= 30.0 : scope == SCOPE_NEAREST ? e < nearestCount : true; expiryKept[e] = kept; if (kept) counted += 1; } // The counted expiries are always the nearest ones (every scope keeps a run from the front), so the curve reads them // as its nearest N: the regime and the flip over the same contracts the card counts. if (counted > 0) curve.load(cells, n, nowMs, counted < expiryCount ? counted : 0, close, zone); regime = counted > 0 ? curve.regime() : NaN; zeroCross = counted > 0 ? curve.flip() : NaN; readings = 0; calls = 0.0; puts = 0.0; above = 0.0; below = 0.0; // Two passes. The first notes each counted contract's exposure and fills the strike table (the MAX_STRIKES nearest // spot when the chain lists more); the second adds the exposures of the contracts whose strike was kept to the table's // strikes and day buckets, so the table reads the same strikes whatever order the chain arrives in. The gamma lens is // the curve's: the first pass adds each exposure to its totals, its expiries and its sums each side of spot, over // every contract, the set the curve reads. Every other lens counts the table's strikes, as the data plane's exposure // fold does: its expiries in the second pass, its totals from the table's rows. const curveSet = lens == GAMMA; const count = n / TUPLE < contractValue.length ? n / TUPLE : contractValue.length; for (let c = 0; c < count; c += 1) { const i = c * TUPLE; contractValue[c] = NaN; const strike = cells[i]; if (!(strike > 0.0) || !(cells[i + 3] > 0.0) || !(optionsLiveUntilMs(cells[i + 1], zone) > nowMs)) continue; const e = findExpiry(cells[i + 1]); if (e < 0 || !expiryKept[e]) continue; const v = exposureOf(cells, i, nowMs); if (!isFinite(v)) continue; // no reading for this lens (no IV to price, a NaN greek) contractValue[c] = v; if (curveSet) { if (cells[i + 2] > 0.0) calls += v; else puts += v; if (strike > close) above += v; else below += v; expiryNet[e] += v; if (v != 0.0) readings += 1; } strikeSlot(strike); } for (let c = 0; c < count; c += 1) { const v = contractValue[c]; if (isNaN(v)) continue; const i = c * TUPLE; const slot = findStrike(cells[i]); if (slot < 0) continue; // left out of the full table: out of its rows (and, off the gamma lens, out of the totals) const e = findExpiry(cells[i + 1]); if (cells[i + 2] > 0.0) callAt[slot] += v; else putAt[slot] += v; dayAt[slot * DAYS + bucketOf(expiryDays[e])] += v; if (!curveSet) { expiryNet[e] += v; if (v != 0.0) readings += 1; } } // The table's largest strike, ascending, and every lens's totals but gamma's. topStrike = NaN; topValue = NaN; let best = 0.0; for (let k = 0; k < strikeCount; k += 1) { const row = callAt[k] + putAt[k]; if (!curveSet) { calls += callAt[k]; puts += putAt[k]; if (strikePrice[k] > close) above += row; else below += row; } if (Math.abs(row) > best) { best = Math.abs(row); topStrike = strikePrice[k]; topValue = row; } } net = calls + puts; today = NaN; for (let e = 0; e < expiryCount; e += 1) if (expiryKept[e] && expiryDays[e] <= 0.0) today = (isNaN(today) ? 0.0 : today) + expiryNet[e]; // The nodes of the lens over the table's strikes, read against spot (the chart's close). for (let k = 0; k < strikeCount; k += 1) netAt[k] = callAt[k] + putAt[k]; board.load(strikePrice, netAt, strikeCount, close); } // ── The frames: the docked profile and the bars by expiry, built in the kit's frame buffer without allocating ── function fbGrouped(n: i64): void { // 84210 -> 84,210 if (n >= 1000) { fbGrouped(n / 1000); fb_text(","); const r = n % 1000; if (r < 100) fb_text("0"); if (r < 10) fb_text("0"); fb_int(r); } else fb_int(n); } function fbStrike(v: f64): void { // a whole strike without decimals (660, 6,650, 67,000), else at the decimals its size takes if (v >= 1000.0) fbGrouped(i64(Math.round(v))); else if (v >= 1.0 && v == Math.floor(v)) fb_int(i64(v)); else fb_f64(v, v >= 100.0 ? 2 : v >= 1.0 ? 3 : 5); } function fbNodeLabel(k: i32): void { // a profile row's node word, quoted: "103 ★ top", "101 gate 36%", "97 floor 60%"; "" for none fb_text("\""); const role = board.role(k); if (role >= NODE_ROLE_CEILING) { // the top, the gate, the floor and the ceiling fbStrike(strikePrice[k]); if (role == NODE_ROLE_TOP) fb_text(" ★ top"); else { fb_text(" "); fb_text(roleWord(role)); fb_text(" "); fb_int(i64(Math.round(board.pctOfTop(k)))); // its share of the top's size, a whole percent fb_text("%"); } } fb_text("\""); } function writeProfile(): void { const lo = close * (1.0 - windowPct); const hi = close * (1.0 + windowPct); let first = 0; // the window's rows: [first, last) while (first < strikeCount && strikePrice[first] < lo) first += 1; let last = first; while (last < strikeCount && strikePrice[last] <= hi) last += 1; while (last - first > MAX_ROWS) { // a wide window on a fine ladder: drop the row farther from spot if (close - strikePrice[first] >= strikePrice[last - 1] - close) first += 1; else last -= 1; } if (last <= first) return; // no strike inside the window: the profile stays absent fb_clear(); fb_text("{\"prices\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(strikePrice[k]); } fb_text("],\"values\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(callAt[k] + putAt[k]); } fb_text("],\"labels_text\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fbNodeLabel(k); // the top, the gate, the floor and the ceiling by name; "" elsewhere } if (scope == SCOPE_BUCKETS) { fb_text("],\"series\":["); for (let b = 0; b < DAYS; b += 1) { fb_text(b > 0 ? ",[" : "["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(dayAt[k * DAYS + b]); } fb_text("]"); } fb_text("]}"); writeFrameBuffer(day_rows); } else if (splitSides) { fb_text("],\"series\":[["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(callAt[k]); } fb_text("],["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); fb_num(putAt[k]); } fb_text("]]}"); writeFrameBuffer(split_rows); } else { fb_text("],\"colors\":["); for (let k = first; k < last; k += 1) { if (k > first) fb_text(","); const row = callAt[k] + putAt[k]; fb_text(row > 0.0 ? "\"theme.up\"" : row < 0.0 ? "\"theme.down\"" : "\"theme.muted\""); // above zero up, below down } fb_text("]}"); writeFrameBuffer(net_rows); } } function writeExpiries(): void { fb_clear(); fb_text("{\"title\":"); fb_text("\""); fb_text(LENS_NAMES[lens]); fb_text(" by expiry\",\"rows\":["); let wrote = 0; const nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: an expiry in another year names it for (let e = 0; e < expiryCount; e += 1) { if (!expiryKept[e]) continue; if (wrote > 0) fb_text(","); fb_text("[\""); fbExpiryLabel(expiryAt[e], nowMs, zone); // the expiry's trade date: 16 Oct, or 15 Jan '27 in another year fb_text(" "); fb_int(i64(expiryDays[e])); fb_text("d\","); fb_num(expiryNet[e]); fb_text("]"); wrote += 1; } fb_text("]}"); writeFrameBuffer(expiry_rows); } // ── The card's words ── function headlineSign(): f64 { // the headline's sign: the dealer regime on the gamma lens (the kit's curve), the net's on every other if (lens == GAMMA) return regime; return net > 0.0 ? 1.0 : net < 0.0 ? -1.0 : 0.0; } function writeRead(): void { sb_clear(); if (readings == 0 || isNaN(net)) { sb_text("No "); sb_text(LENS_WORDS[lens]); sb_text(" in this symbol's options"); } else if (lens == GAMMA) sb_text(regime > 0.0 ? "Long gamma: dealers calm price" : regime < 0.0 ? "Short gamma: dealers chase price" : "Neutral gamma: no dealer hedging"); else if (lens == DELTA) sb_text(net >= 0.0 ? "Net long delta: the calls outweigh the puts" : "Net short delta: the puts outweigh the calls"); else if (lens == VANNA) sb_text(net >= 0.0 ? "Long vanna: an IV rise makes dealers sell" : "Short vanna: an IV rise makes dealers buy"); else if (lens == CHARM) sb_text(net >= 0.0 ? "Charm: each day passing makes dealers sell" : "Charm: each day passing makes dealers buy"); else if (lens == VEGA) sb_text(net >= 0.0 ? "Dealers long vega: an IV rise pays them" : "Dealers short vega: an IV rise costs them"); else if (lens == IV_X_OI) sb_text(net >= 0.0 ? "The calls hold the richer open interest" : "The puts hold the richer open interest"); else sb_text(net >= 0.0 ? "More call than put open interest" : "More put than call open interest"); str_read_sb(); } function writePreset(): void { // the expiries the preset keeps, in words, with how many if (preset == EXPIRY_PRESET_ALL) { sb_text("all "); sb_int(expiryCount); sb_text(" expiries"); return; } sb_text(preset == EXPIRY_PRESET_FRONT ? "front" : preset == EXPIRY_PRESET_TO_FRIDAY ? "to Friday" : preset == EXPIRY_PRESET_TO_NEXT_FRIDAY ? "to next Friday" : preset == EXPIRY_PRESET_TO_OPEX ? "to monthly opex" : preset == EXPIRY_PRESET_TO_NEXT_OPEX ? "to next opex" : "to quarterly opex"); sb_text(" ("); sb_int(counted); sb_text(counted == 1 ? " expiry)" : " expiries)"); } function unitWord(): String { return zone == 1 ? "shares" : zone == 2 ? "contracts" : "coins"; } function writeTitle(): void { sb_clear(); sb_text(LENS_NAMES[lens]); sb_text(", "); if (lens == IV_X_OI) sb_text("IV points x OI"); else if (lens > IV_X_OI) sb_text(zone == 0 ? "coins" : "contracts"); // open interest in the venue's own unit else if (lens == VEGA) sb_text("$ per IV point"); else { sb_text(inUnderlying ? unitWord() : "$"); sb_text(lens == GAMMA ? " per 1% move" : lens == DELTA ? " held" : lens == VANNA ? " per IV point" : " per day"); } sb_text(", "); if (preset != EXPIRY_PRESET_COUNT) { // the preset in place of the Expiries setting's range writePreset(); str_title_sb(); return; } if (scope == SCOPE_TODAY) sb_text("same day"); else if (scope == SCOPE_WEEK) sb_text("within 7 days"); else if (scope == SCOPE_MONTH) sb_text("within 30 days"); else if (scope == SCOPE_NEAREST && nearestCount < expiryCount) { sb_text("nearest "); sb_int(nearestCount); sb_text(" of "); sb_int(expiryCount); sb_text(" expiries"); str_title_sb(); return; } else { sb_text("all "); sb_int(expiryCount); sb_text(" expiries"); str_title_sb(); return; } sb_text(" ("); sb_int(counted); sb_text(counted == 1 ? " expiry)" : " expiries)"); str_title_sb(); } // onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar measures the chain, writes // the readings (NaN on history rows), the profile, the bars by expiry and the card's words. function onBar(): void { close = bar.close(); t = bar.time(); let measured = false; // the live bar carried a chain with a live expiry the setting counts let chainCells = -1; if (bar.isLast()) { chainCells = in_chain_cells(); if (chainCells >= TUPLE && !isNaN(close) && !isNaN(t)) { measure(chainCells); measured = counted > 0; } } const reading = measured && readings > 0; out_net_exposure(reading ? net : NaN); out_calls_exposure(reading ? calls : NaN); out_puts_exposure(reading ? puts : NaN); out_today_exposure(reading ? today : NaN); out_top_strike(reading ? topStrike : NaN); out_top_exposure(reading ? topValue : NaN); out_zero_cross(reading ? zeroCross : NaN); out_above_spot(reading ? above : NaN); out_below_spot(reading ? below : NaN); out_tone(reading ? 1.0 + headlineSign() : bar.isLast() ? 1.0 : NaN); out_expiries_counted(measured ? f64(counted) : NaN); if (measured) { if (reading) writeProfile(); writeExpiries(); writeRead(); writeTitle(); } else if (bar.isLast()) { // The live bar carried nothing to measure: the headline says why, so the card is never a row of blanks. sb_clear(); sb_text(chainCells < TUPLE ? "Waiting for this symbol's options" : expiryCount == 0 ? "No expiry is still trading" : "No expiry in this setting's range"); str_read_sb(); sb_clear(); sb_text(LENS_NAMES[lens]); sb_text(", no options data yet"); str_title_sb(); } } ``` ## How it works **One lens at a time.** Every contract the Expiries setting counts adds one number to its strike and to its expiry. The strike table behind the profile and the largest strike keeps at most the 1,024 strikes nearest spot when a chain lists more. On the gamma lens the totals (the net, the calls, the puts, the same-day expiry, each expiry's bar and the sums each side of spot) read every counted contract, the same set the gamma curve reads; on every other lens they read the table's strikes, as the data plane's exposure fold sums them. Per contract, before the sign, with `oi` its open interest, `multiplier` its multiplier (100 on a US listed option, the point value on CME, 1 on Deribit) and `spot` its underlying: | Lens | Per contract | Unit in dollars | | --- | --- | --- | | `gamma` | `bsGamma(spot, strike, iv, years) * oi * multiplier * spot * spot * 0.01` | the dealers' delta change for a 1% move of spot, in dollars | | `delta` | `delta * oi * multiplier * spot` | the delta held, in dollars | | `vanna` | `vanna * oi * multiplier * spot` | the delta change for one IV point | | `charm` | `charm * oi * multiplier * spot` | the delta change as one calendar day passes | | `vega` | `vega * oi * multiplier` | the value change for one IV point | | `iv_x_oi` | `mark_iv * oi` | IV points times open interest (where the expensive open positions sit) | | `oi` | `oi` | open interest, contracts (coins on crypto) | **The sign: dealers long the calls, short the puts.** That is the open-interest model the gamma map uses: customers sell the calls dealers hold and buy the puts dealers write, so the calls add and the puts subtract on gamma, vanna, charm, vega, IV times open interest and open interest. Delta keeps each option's own sign (a call's delta is positive, a put's negative), the way delta views read the chain. On the gamma lens the headline is the dealer regime of the options kit's `GammaCurve` over the counted expiries, the sign of net GEX at spot: above zero is long gamma (hedging leans against moves), below zero short gamma, exactly zero neutral; it is the same regime Gamma Map and the Options Dashboard print over the same expiries ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)). Net vanna above zero means an IV rise lifts the dealers' delta, so they sell to stay hedged; below zero they buy. Charm above zero means each day passing lifts their delta, so they sell; below zero they buy. **Priced greeks.** Delta is the chain's own. Gamma is priced as the kit's `GammaCurve` prices it, `bsGamma()` from the contract's mark IV and underlying at the chain's as-of with no rate, so the gamma lens's net over every expiry is the net GEX every options card reads. Vanna, charm and, where a venue serves none, vega are priced per contract by the kit's `Greeks`: Black-Scholes on spot on a US stock, at the Rate setting (4% by default); Black-76 on the underlying on futures and crypto, whose underlying is already the forward (crypto at a rate of 0). The chain's as-of is the live bar's close time, `optionsAsOfMs(bar.time() * 1000, chart.interval_sec() * 1000)`: the block names the moment it was served to no module, and the bar's close is the clock [Spot exposures](spot-exposures.md) reads its strike rows at on the same bar, never a time solved back from a gamma (two solves of one minute named two times, and a same-day gamma scales with 1 / sqrt(T)). Each contract's time to go runs from the as-of to its expiry's end in 365-day years, `optionsYearsToGo()`: on a US stock to 15 minutes past the stamp (a PM expiry stamped 16:00 New York trades until 16:15) and never under a second while it trades, so the same-day book keeps its gamma until 16:15; on CME and crypto to the stamp itself. For vanna, charm and vega a contract within 15 minutes of its expiry's end prices no time left. Charm is per calendar day: tools that multiply it by 365 print a yearly figure 365 times larger. **Units.** `dollars` is the table above. `underlying` divides the four delta lenses by spot: shares on a US stock, coins on crypto, and on CME by spot times the point value, which is futures contracts. Vega stays in dollars per IV point, and the last two lenses keep their own units. The card's title names the unit in use (`Gamma, $ per 1% move, all 11 expiries`). **Expiries by the calendar.** An expiry counts while it trades: on a US stock until 15 minutes past its stamp (`optionsLiveUntilMs()`), on CME and crypto until the stamp. `0dte` counts the expiry whose trade date is today's on the market's own clock (`optionsTradeDay()`: New York on a US stock, Chicago on CME, UTC on crypto), never the one under 24 hours away, so at 16:05 New York the expiry stamped 16:00 is still today's; `week` and `month` count the expiries 7 and 30 trade days out or less on the same calendar (the difference of the two `optionsTradeDay()` dates; `week` is the rule Spot Exposures keeps its strike rows by, so the two cards count one set of expiries); `nearest` the N nearest live expiries; `buckets` every expiry, stacked by days to go: 0, 1 to 7, 8 to 30, 31 to 60, 61 to 120 and 121 or more. A tall bar built from the near buckets is exposure that decays within days; one built from the far buckets persists. **Expiry preset** (`count`) counts by the calendar in place of that range ([Expiry presets](../functions/options-kit.md#expiry-presets)): `front` the nearest live expiry, `to_friday` and `to_next_friday` every expiry on or before this Friday or the next one, `to_opex` and `to_next_opex` every expiry to this month's third Friday (next month's once it has passed) or to the one after, `to_q_opex` every expiry to the next quarterly third Friday, and `all` every one, each day a trade day on the market's clock; `count` keeps the Expiries setting, and `buckets` still stacks the counted expiries by days to go. The title then names the preset and how many it counts (`Gamma, $ per 1% move, to Friday (3 expiries)`). **By strike.** The strikes within `window_pct` (8) percent of the chart's close dock on the price axis, at most 256, one row per strike, centred on zero: net above zero to one side in the up colour, below zero to the other in the down colour. `split: calls_puts` draws the calls one way and the puts the other; `buckets` stacks the six day buckets. Each shape has its own `plot.levels`, and only the one the settings pick gets a frame, so the other two stay absent. Whichever is drawn names the lens's nodes on their rows through the frame's `labels_text` ([Node roles](../functions/options-kit.md#node-roles)): the kit's `NodeBoard` loads each strike's net of the table against spot, the top is the largest net either way (on a tie the strike nearest spot, then the lower) and carries a star, the gate is the largest strictly between spot and the top at 35% of the top or more, and the floor and the ceiling are the largest strictly below and above spot, each with its share of the top as a whole percent (`103 ★ top`, `101 gate 36%`, `97 floor 60%`). Every other row stays bare, and the card keeps its numbers. **By expiry.** One bar per counted expiry under the chart, labelled by its date and its days to go (`16 Oct 1d`, the kit's `fbExpiryLabel`; an expiry in another year reads its year, `15 Jan '27`), in the up colour above zero and the down colour below. The panel's title names the lens. **The card reads the outputs.** The headline is the lens's plain line; under it the net, the same-day expiry, the calls and the puts in `si` (`1.24B`), then five rows: the strike holding the largest net either way (the gamma magnet on the gamma lens), its exposure, the gamma flip over the counted expiries on every lens (the kit curve's zero nearest spot, walked out up to 50% each side; `zero_cross` reads NaN when none lies within 50%), and the sums over the strikes above and at or below spot. ## What the settings do - **Lens**: what the bars measure. gamma: what dealers trade per 1% move. delta: how much stock dealers must hold to hedge. charm, vanna: how that hedge changes with time (charm) or with option prices (vanna). vega: how much dealers gain or lose when option prices rise. iv_x_oi: implied volatility (how big a move option prices expect) times open interest. oi: open interest (contracts still held open). - **Units**: dollars: in dollars. underlying: in this symbol's own units (shares, contracts or coins), for gamma, delta, vanna and charm. - **By strike**: net: one bar per strike, calls minus puts. calls_puts: calls drawn one way, puts the other. - **Expiries**: which expiries (the days the options end) count. all: every one still trading. 0dte: the one that expires today. week: within 7 trade days. month: within 30. nearest: the N soonest. buckets: all of them, stacked by days left. - **Nearest expiries**: how many of the soonest expiries count when Expiries is set to nearest. - **Strike window, percent**: how far the strikes on the price axis reach above and below the price, 8% by default. - **Rate, percent**: the interest rate used to price vanna, charm and vega on US stock and CME options, while crypto uses 0. - **Expiry preset**: picks expiries by the calendar, up to the date each choice names. front: the nearest expiry. to_friday, to_next_friday: this or next Friday. to_opex, to_next_opex: this or next monthly expiry, on the third Friday. to_q_opex: the next quarterly expiry (March, June, September or December). all: every expiry. count: follow the Expiries setting. - **Dealers**: the lens in one plain line, such as whether dealers calm or chase price on gamma. - **Net**: the lens summed over the counted expiries, calls adding and puts subtracting. On gamma, above zero means dealers calm price. - **Same-day expiry**: the net of the expiry that settles today. - **Calls**: the calls' part of the net. - **Puts**: the puts' part of the net. - **Largest strike**: the strike with the largest net either way. On gamma it is the magnet, a strike that tends to pull price. - **Its exposure**: that strike's net. - **Gamma flip**: the price where dealers switch from calming price to pushing it, for the counted expiries. - **Above price**: the net of the strikes above the price. - **At or below price**: the net of the strikes at or below the price. ## Where it runs It runs on coins with options on Deribit (a crypto options exchange), such as BTC, ETH and SOL. There a copy you run from the editor (where you write and run your own indicators) reads the coin's options. On a US stock chart it reads the stock's US listed options. On a futures chart from CME (Chicago futures exchange), it reads that future's options. Every indicator can read US listed options, 15 minutes behind unless you have real-time US options data. Every indicator in your browser can read CME options too, once you accept the CME market data terms. They run 10 minutes behind unless you have real-time CME data, and the legend names the source. Copies you run from the editor, publish yourself or run as a Cloud (Protected) copy all read US listed options. A Protected copy runs on OpenMarket's servers and keeps its code hidden. It does not run on a CME chart. ## When data is missing The card's headline says why instead of going blank. It reads "Waiting for this symbol's options" while the live bar has none. It reads "No expiry is still trading" when every listed expiry has stopped trading. It reads "No expiry in this setting's range" when **Expiries** counts none. 0dte does that on a day with no expiry. It reads "No gamma in this symbol's options", or the lens's own word, when no counted contract has a reading. That happens on an index whose option risk numbers (greeks) are not published yet. It also happens on options without implied volatility. The card's numbers then read - and the strike bars do not draw. The bars by expiry still stand while expiries are counted. ## Customize it - **Another greek.** Set Lens to `vanna` before an event that moves implied volatility, or to `charm` into the close and over a weekend. - **Shares instead of dollars.** Set Units to `underlying` to read the hedge in the market's own units. - **What decays and what stays.** Set Expiries to `buckets` and read which days build each strike's bar. - **This week's exposure.** Set Expiry preset to `to_friday`; `to_q_opex` counts through the next quarterly expiry. - **A wider ladder.** Raise `window_pct` on a volatile underlying; the window narrows the profile, never the totals. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Greek Exposure** under **HUDs**. 2. Press **Run** on a BTC chart: the profile docks on the price axis once the chain arrives, the bars by expiry stand under the chart and the card appears at the bottom centre. 3. At the editor's Console prompt, type `net_exposure` and `zero_cross` to read the net and the gamma flip on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#options-chain) for the `options_chain` celled class, its tuple and the `venue` word - [Options kit](../functions/options-kit.md#pricing-the-chain) for `Greeks`, `optionsAsOfMs`, `optionsLiveUntilMs`, `optionsYearsToGo` and `optionsTradeDay` - [Node roles](../functions/options-kit.md#node-roles) for `NodeBoard` and [Expiry presets](../functions/options-kit.md#expiry-presets) for `expiryPresetCount` - [Cards, frames and panels](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets) for frames, `plot.levels` with series and `panel.bars`, and [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its tiles, the slot in the title and what a card with no `look` draws <!-- source: https://openmarket.xyz/wrun/cookbook/skew --> # Risk reversal skew Risk reversal skew shows whether puts, which pay when price falls, cost more than calls, which pay when it rises. It compares their implied volatility (how big a move option prices expect), on options ending about 30 days out. A reading below zero means puts cost more and traders fear a drop, above zero the reverse. Bars under the chart show the gap at nine distances from the price, and a card names the verdict. Use it to gauge fear before a move, on any chart whose symbol has listed options. Under the hood: the recipe reads `options_chain.cells` on the live bar with the `atm` and `delta_band` page views ([Data sources](../core-concepts/data-sources.md#options-chain), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). So the chart reads only each expiry's at-the-money contracts and, on the expiry nearest **Days to expiry**, those from 7.5 to 27.5 delta. It finds each wing with the options kit's `IvTerm` at the chain's as-of, `optionsAsOfMs` ([Options kit](../functions/options-kit.md#the-at-the-money-term)). It names the expiry with `TextBuilder.expiry` and `fbExpiryLabel` ([A second builder](../functions/text-formatting.md#a-second-builder), [Panel frames](../presentation/cards-frames-panels.md#panel-frames)). It draws a `panel.bars` frame with a per-run title ([Cards, frames and panels](../presentation/cards-frames-panels.md#bars)). A `render.hud` card with no `look` word sits beside it ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `skew` template, the **Risk Reversal Skew** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Risk Reversal Skew: whether traders pay more for puts or for calls on this symbol's options, right now. A put pays // when price falls, and a call pays when it rises. The risk reversal is the call's implied volatility (how big a move // option prices expect) minus the put's. It compares options at the same distance from the price, on one expiry (the // day the option ends). Below zero, puts cost more: traders pay up to protect against a drop. Above zero, calls cost // more: traders chase a rise. Bars under the chart show this gap at nine distances from the price, and a card names the // verdict. Use it to gauge fear or greed before a move. // // Technical notes: how the chart's own option chain prices its two wings for one expiry, the one nearest 30 days out by // default. The risk reversal is the call's implied volatility minus the put's at the same distance from the money, in // vol points: below zero the puts are richer (downside protection costs more), above zero the calls. Bars under the // chart read it at nine deltas, from 27.5 near the money to 7.5 in the wings; a card reads the skew in one plain line // first (Puts rich: protection against a drop costs more), then the 25 and 10 delta risk reversals, the four wing IVs, // the at-the-money IV and the smile's asymmetry. Each wing is the strike where the contract's delta, read off its own // IV at the expiry's forward, equals the target, interpolated between the two listed strikes around it. This reads call // minus put; some tools quote put minus call, the same number with the sign flipped. Where the expiry lists no 25 delta // wing, the asymmetry falls back to the calls' mean IV within 7% above spot minus the puts' within 7% below. The chain // rides the live bar only: history bars draw nothing; it is read at its as-of, the live bar's close (optionsAsOfMs), so // a coarse bar's open never stretches the time to expiry. section("Expiry"); param.number("days", 30, { min: 1, max: 400, step: 1, label: "Days to expiry", description: "Reads the expiry nearest this many calendar days away. An expiry that ends today never counts." }); param.number("flat_points", 1, { min: 0, max: 10, step: 0.25, label: "Flat band, IV points", description: "The card calls the skew flat while the call and put IVs sit this close to each other." }); param.number("rate_pct", 4, { min: 0, max: 20, step: 0.25, label: "Interest rate, percent", description: "The interest rate that projects a US stock's price to the expiry. Futures and crypto options do not need it." }); input("close", ohlcv.close); // the chart's own close: spot where a contract reports no underlying input("chain", options_chain.cells, { max_cells: 16000, venue: "auto", page_views: ["atm", "delta_band"], expiry: "@days", lo: 0.075, hi: 0.275, rate: "@rate_pct", description: "This symbol's options: US listed options on a stock, CME options on a future, Deribit options on BTC and ETH. It reads each expiry's at-the-money contracts and, on the chosen expiry, those from 7.5 to 27.5 delta." }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega] per contract, in the chain's order market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME): the expiry's date and the forward chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("rr25", none, overlay, { description: "The 25 delta risk reversal: the call's IV minus the put's, in IV points. Below zero, puts cost more. Live bar only." }); output("rr10", none, overlay, { description: "The 10 delta risk reversal: the call's IV minus the put's, in IV points" }); output("call25_iv", none, overlay, { color: "theme.up", description: "The 25 delta call's IV, in percent" }); output("put25_iv", none, overlay, { color: "theme.down", description: "The 25 delta put's IV, in percent" }); output("call10_iv", none, overlay, { color: "theme.up", description: "The 10 delta call's IV, in percent" }); output("put10_iv", none, overlay, { color: "theme.down", description: "The 10 delta put's IV, in percent" }); output("atm_iv", none, overlay, { description: "The expiry's at-the-money IV, in percent: the mean of the call and put IV at the strike nearest the price" }); output("asymmetry", none, overlay, { description: "The smile's tilt in IV points: the 25 delta risk reversal. Without 25 delta options, it compares calls up to 7% above the price with puts up to 7% below." }); output("asymmetry_fallback", none, overlay, { description: "1 when the tilt uses the 7% fallback, 0 when it is the 25 delta risk reversal" }); output("expiry_days", none, overlay, { description: "Days until the chosen expiry, on the market's own calendar" }); output("tone", none, overlay, { description: "The headline's verdict: 0 puts rich, 1 flat or no reading, 2 calls rich. Live bar only." }); string("read", { max_bytes: 64 }); // the headline: the skew in one plain line, or why there is no reading string("title", { max_bytes: 48 }); // the card's title: the expiry, its days to go and the convention const rr_rows = frame("rr_rows", { max_bytes: 2048 }); // the bars: [delta, call minus put] per delta, near the money first // Under the chart: one bar per delta, the up colour where the call side is richer, the down colour where the put side // is, the expiry in the title (written per run into the frame); the card's headline names the verdict. panel.bars({ name: "rr_by_delta", title: "Call minus put by delta", x: "category", place: "below", frame: rr_rows, orientation: "vertical", color_mode: "sign", positive_color: "theme.up", negative_color: "theme.down", series: [{ name: "Call minus put" }], format: "0.00", unit: "pts", x_title: "Delta", hover_card: true, legend_style: "title", height_frac: 0.18 }); // The card: the plain line leads as the headline, the title names the expiry and the convention. render.hud("skew", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Skew", "read", { headline: true }), tile.value("25 delta, call minus put", "rr25", { format: "0.00" }), tile.value("10 delta, call minus put", "rr10", { format: "0.00" }), tile.rows([ ["25 delta call IV", "call25_iv", "0.00"], ["25 delta put IV", "put25_iv", "0.00"], ["10 delta call IV", "call10_iv", "0.00"], ["10 delta put IV", "put10_iv", "0.00"], ["At-the-money IV", "atm_iv", "0.00"], ["Smile asymmetry", "asymmetry", "0.00"], ]), ], }); const TUPLE = 10; // f64s per contract: strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega const MAX_EXPIRIES = 64; // live expiries the term keeps, the nearest when the chain lists more const WING_SHARE = 0.07; // the asymmetry fallback's strikes: within 7% of spot const DELTAS: f64[] = [0.275, 0.25, 0.225, 0.2, 0.175, 0.15, 0.125, 0.1, 0.075]; // the bars, near the money first const DELTA_LABELS: String[] = ["27.5", "25", "22.5", "20", "17.5", "15", "12.5", "10", "7.5"]; const expiryText = new TextBuilder(16); // the expiry's label, the kit's spelling, copied into the title let term = new IvTerm(1); // the chain's expiries and their wings, built in onStart() let days = 30.0; // settings, read in onStart() let flatPoints = 1.0; let rate = 0.04; let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let nowMs: f64 = NaN; // the chain's as-of, the live bar's close let row = -1; // the expiry read on the live bar; -1 when there is none let rr25: f64 = NaN; // the readings, measured on the live bar let rr10: f64 = NaN; let call25: f64 = NaN; let put25: f64 = NaN; let call10: f64 = NaN; let put10: f64 = NaN; let atm: f64 = NaN; let asymmetry: f64 = NaN; let fallback = false; function onStart(): void { term = new IvTerm(MAX_EXPIRIES); // the per-expiry buffers are the module's only allocation days = p_days(); flatPoints = p_flat_points(); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; rate = zone == 1 ? p_rate_pct() / 100.0 : 0.0; // a futures or crypto underlying already is the forward } // ── The expiry's wings ── function riskReversal(e: i32, delta: f64): f64 { // the call's IV minus the put's at |delta|, vol points; NaN where a wing is missing return (term.deltaIv(e, 1.0, delta) - term.deltaIv(e, -1.0, delta)) * 100.0; } function wingAsymmetry(cells: StaticArray<f64>, n: i32, e: i32): f64 { // the calls' mean IV within 7% above spot minus the puts' within 7% below, vol points const expiry = term.expiry(e); const spot = term.underlying(e); let callSum = 0.0; let callCount = 0; let putSum = 0.0; let putCount = 0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const strike = cells[i]; if (cells[i + 1] != expiry || !(strike > 0.0) || !(cells[i + 6] > 0.0)) continue; if (Math.abs(strike / spot - 1.0) > WING_SHARE) continue; if (cells[i + 2] > 0.0) { if (strike > spot) { callSum += cells[i + 6]; // mark IV rides the chain in vol points already callCount += 1; } } else if (strike < spot) { putSum += cells[i + 6]; putCount += 1; } } if (callCount == 0 || putCount == 0) return NaN; return callSum / f64(callCount) - putSum / f64(putCount); } function measure(cells: StaticArray<f64>, n: i32, e: i32): void { rr25 = riskReversal(e, 0.25); rr10 = riskReversal(e, 0.1); call25 = term.deltaIv(e, 1.0, 0.25) * 100.0; put25 = term.deltaIv(e, -1.0, 0.25) * 100.0; call10 = term.deltaIv(e, 1.0, 0.1) * 100.0; put10 = term.deltaIv(e, -1.0, 0.1) * 100.0; atm = term.atmIv(e) * 100.0; fallback = isNaN(rr25); asymmetry = fallback ? wingAsymmetry(cells, n, e) : rr25; } // ── The bars and the card's words ── function writeBars(e: i32): void { fb_clear(); fb_text("{\"title\":\"Call minus put by delta, "); fbExpiryLabel(term.expiry(e), nowMs, zone); // the expiry's trade date: 21 Nov, or 15 Jan '27 in another year fb_text("\",\"rows\":["); for (let k = 0; k < DELTAS.length; k += 1) { if (k > 0) fb_text(","); fb_text("["); fb_str(DELTA_LABELS[k]); fb_text(","); fb_num(riskReversal(e, DELTAS[k])); // null where a wing is missing fb_text("]"); } fb_text("]}"); writeFrameBuffer(rr_rows); } function writeWords(e: i32): void { sb_clear(); if (isNaN(asymmetry)) sb_text("No puts and calls to compare on this expiry"); else if (asymmetry < -flatPoints) sb_text("Puts rich: protection against a drop costs more"); else if (asymmetry > flatPoints) sb_text("Calls rich: bets on a rise cost more"); else sb_text("Flat: puts and calls cost about the same"); str_read_sb(); sb_clear(); expiryText.clear().expiry(term.expiry(e), nowMs, zone); for (let i = 0; i < expiryText.length(); i += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>i)); sb_text(", "); const left = i64(term.days(e)); sb_int(left); sb_text(left == 1 ? " day, call minus put" : " days, call minus put"); str_title_sb(); } // onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar loads the chain into the // term, picks the expiry nearest the setting's days and reads its wings. Then the readings (NaN on history rows), the // bars and the card's words on the live bar only. function onBar(): void { const close = bar.close(); const t = bar.time(); row = -1; let chainCells = -1; let kept = 0; if (bar.isLast() && !isNaN(close) && !isNaN(t)) { chainCells = in_chain_cells(); if (chainCells >= TUPLE) { const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the live bar's close time kept = term.load(cells, chainCells, nowMs, close, zone, rate); row = term.nearest(days); // an expiry after today with an at-the-money IV, nearest the setting's days if (row >= 0) measure(cells, chainCells, row); } } const reading = row >= 0; out_rr25(reading ? rr25 : NaN); out_rr10(reading ? rr10 : NaN); out_call25_iv(reading ? call25 : NaN); out_put25_iv(reading ? put25 : NaN); out_call10_iv(reading ? call10 : NaN); out_put10_iv(reading ? put10 : NaN); out_atm_iv(reading ? atm : NaN); out_asymmetry(reading ? asymmetry : NaN); out_asymmetry_fallback(reading && !isNaN(asymmetry) ? (fallback ? 1.0 : 0.0) : NaN); out_expiry_days(reading ? term.days(row) : NaN); out_tone(reading && !isNaN(asymmetry) ? (asymmetry < -flatPoints ? 0.0 : asymmetry > flatPoints ? 2.0 : 1.0) : bar.isLast() ? 1.0 : NaN); if (reading) { writeBars(row); writeWords(row); } else if (bar.isLast()) { // Nothing to read on the live bar: the headline says why, so the card is never a row of blanks. sb_clear(); sb_text(chainCells < TUPLE ? "Waiting for the options chain" : kept == 0 ? "No expiry is still trading" : "No expiry with an at-the-money IV"); str_read_sb(); sb_clear(); sb_text("Skew, nothing to read yet"); str_title_sb(); } } ``` ## How it works **One expiry, picked by its distance.** The chain loads into an `IvTerm` on the live bar, and `term.nearest(days)` picks the expiry whose time to expiry is nearest the **Days to expiry** setting (30), among the expiries after today that carry an at-the-money IV: an expiry settling today never counts, because its implied volatility swings with the hours left. Its time to expiry counts from the chain's as-of, `optionsAsOfMs()`: the live bar's close time, never its open. The card's title names it by its label, its trade date on the market's own calendar (`TextBuilder.expiry`), and its days to go. **A wing is a strike at a delta.** For each target, 0.25 for the 25 delta wing, `term.deltaIv(e, side, delta)` finds the strike on the calls (or the puts) where the contract's delta, read off its own IV at the expiry's forward with no discount (N(d1) for a call, N(-d1) for a put, the convention skew is quoted in), equals the target, and interpolates the IV linearly in delta between the two listed strikes around it. The forward is the underlying times `e^(rate * years)` on a US stock, at the **Interest rate** setting (4%), and the underlying itself on futures and crypto, which already quote the forward. A target the expiry lists no strike beyond reads `-`: a narrow chain has no 10 delta wing. **The risk reversal is call minus put.** `rr25` is the 25 delta call's IV minus the 25 delta put's, `rr10` the same at 10 delta, both in vol points; `call25_iv`, `put25_iv`, `call10_iv` and `put10_iv` are the four wings in percent, and `atm_iv` the expiry's at-the-money IV (the mean of the call and put IV at the strike nearest its forward). On most equity and index chains the puts are richer and the number is negative, steeper at 10 delta than at 25; a positive number means the market pays more for upside calls than for downside puts. **The smile's asymmetry.** `asymmetry` is the 25 delta risk reversal. Where the expiry lists no 25 delta wing on one side, it falls back to the calls' mean IV over the strikes up to 7% above spot minus the puts' mean IV over the strikes up to 7% below, in vol points, and `asymmetry_fallback` reads 1. **The headline.** Within the **Flat band** (1 vol point) of zero the card reads "Flat: puts and calls cost about the same"; below it, "Puts rich: protection against a drop costs more"; above it, "Calls rich: bets on a rise cost more". `tone` carries the same three answers as 0, 1 and 2 for the Console; the headline itself draws in the card's text colour. **The bars.** One bar per delta under the chart, 27.5 nearest the money on the left out to 7.5 on the right, each the call's IV minus the put's at that delta; the frame carries the expiry's label in the panel's title (`fbExpiryLabel`: `Call minus put by delta, 20 Nov`), and the verdict reads on the card's headline only. ## What the settings do - **Days to expiry**: The card reads the expiry nearest this many calendar days away, never one that ends today. - **Flat band, IV points**: The card calls the skew flat while the call and put IVs sit this close to each other. - **Interest rate, percent**: The rate that projects a US stock's price to the expiry, which futures and crypto options do not need. - **Skew**: The verdict in words: puts rich, calls rich or flat. - **25 delta, call minus put**: The call's IV minus the put's, both a moderate distance from the price (some tools flip the sign). - **10 delta, call minus put**: The same gap for options far from the price, where crash fear shows most. - **25 delta call IV**: The implied volatility of the call a moderate distance above the price. - **25 delta put IV**: The implied volatility of the put a moderate distance below the price. - **10 delta call IV**: The implied volatility of the call far above the price. - **10 delta put IV**: The implied volatility of the put far below the price. - **At-the-money IV**: The implied volatility at the strike nearest the price, the expiry's baseline. - **Smile asymmetry**: How lopsided the IV curve across strikes is, in IV points: below zero, the downside costs more. ## Where it runs It works on charts of coins that Deribit (a crypto options exchange) lists options for. Those are BTC, ETH, SOL and the rest of its list. A copy you run from the editor (the code panel beside the chart) reads those coins' options. On a US stock chart it reads that stock's US listed options. On a CME (Chicago futures exchange) futures chart it reads the options on that future. Every indicator reads US listed options, 15 minutes behind unless you have real-time US options data. Every indicator in your browser reads CME options too, once you accept the CME market data terms. They run 10 minutes behind unless you have real-time CME data, and the legend names the source. Editor copies, your published copies and Protected copies (their code stays on OpenMarket's servers) all read US listed options. So does a copy run with Run on Cloud (the editor switch that runs it on OpenMarket's servers). A Protected copy and a Run on Cloud copy do not run on a CME chart. ## When data is missing The headline always says why it has no verdict, so the card never goes blank. It reads "Waiting for the options chain" while the live bar has no options data yet. It reads "No expiry is still trading" when every listed expiry has passed. It reads "No expiry with an at-the-money IV" when the live expiries all end today or lack an IV. It reads "No puts and calls to compare on this expiry" when the expiry has no strikes to compare. That happens when neither the 25 delta options nor the 7% fallback have a strike on both sides. A distance the expiry does not reach shows "-" on its line and leaves its bar out. ## Customize it - **Another horizon.** Set Days to expiry to 7 for the weekly smile or 90 for the quarterly; the title names the expiry it reads. - **A tighter verdict.** Lower the Flat band to call a smaller tilt rich, or raise it to keep the headline flat through ordinary equity skew. - **The other convention.** Negate `rr25`, `rr10` and the bars where you want put minus call; the risk reversal is the same number with its sign flipped. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Risk Reversal Skew** under **HUDs**. 2. Press **Run** on a BTC chart: the bars stand under the chart once the chain arrives and the card appears at the bottom centre, titled by the expiry nearest 30 days. 3. At the editor's Console prompt, type `rr25` and `asymmetry` to read the 25 delta risk reversal and the smile's asymmetry on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#options-chain) for the `options_chain` celled class, its tuple and the `venue` word - [Options kit](../functions/options-kit.md#the-at-the-money-term) for `IvTerm`, `nearest`, `deltaIv` and the expiry's forward, and `optionsAsOfMs` - [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry` and [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel`, the expiry's label in the card's title and the panel's - [Cards, frames and panels](../presentation/cards-frames-panels.md#bars) for frames and `panel.bars` with a per-run title - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its tiles, the slot in the title and what a card with no `look` draws <!-- source: https://openmarket.xyz/wrun/cookbook/expected-move --> # 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](../functions/options-kit.md#book-folds), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). The daily candles come through `CandleList` ([Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists)). It draws four guide outputs tagged on the price axis ([Lines, areas, columns, dots, marks](../presentation/plotting.md#lines-areas-columns-dots-marks)). The cone and the levels draw as handles ([Drawing objects](../presentation/drawing-objects.md#handles)), and the levels' pills through `plot.levels` ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)). A `render.hud` card in the chart's default look sits beside them ([HUD cards](../presentation/hud-and-hover-cards.md#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 ```typescript // 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](../functions/options-kit.md#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 `7d` or `30d` for 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 `Words` for each rail's price on the axis and its name in words just above its line. - **One horizon.** Set **Cone horizons** to `week` and **Cones** to `1s` for the 1σ cone to Friday's close. - **Up and down tint.** Set **Cone style** to `Up and down tint` for 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 `near` for the prices of the two nearest horizons alone, or `off` for 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 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Expected Move** under **HUDs**. 2. 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. 3. At the editor's Console prompt, type `em_pct`, `sd_pct` and `iv_30d` to read the expected move, the 1σ range and the 30-day IV on the live bar. 4. 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_pct` and `front_realized_pct` to read the front horizon's checks. ## Concepts used - [Data sources](../core-concepts/data-sources.md#options-chain) for the `options_chain` celled class and the `venue` word - [The market's own calendar](../core-concepts/time-and-sessions.md#the-markets-own-calendar) for `time.trade_date` - [Book folds](../functions/options-kit.md#book-folds) for `BookStamp`, `OptionNumbers`, `VolTerm` and `ExpectedMoves.loadNumbers`, [The canonical numbers](../functions/options-kit.md#the-canonical-numbers) for `ExpectedMoves.horizonIv`, [the expected move](../functions/options-kit.md#the-expected-move) for `straddleExpectedMove` and `oneSigmaMove`, and [the market's own date](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` - [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry`, each expiry's label - [Lines, areas, columns, dots, marks](../presentation/plotting.md#lines-areas-columns-dots-marks) for the rails as guides tagged on the price axis (`axis_label`, `axis_look`), and [The Style page](../settings/style-page.md#declare-it) for binding `axis_look` to **Rail labels** through `style_values` - [Drawing objects](../presentation/drawing-objects.md#handles) for the levels' line handles extended across the chart and their right-anchored texts, set just above each line with `valign` - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels` and its frame's `labels_text`, the levels' pills - [Every look a handle takes](../presentation/drawing-objects.md#every-look-a-handle-takes) for `anchor`, `valign` and the box and emblem looks on the cone's chips and dots - [Paths built point by point](../presentation/drawing-objects.md#paths-built-point-by-point) for the cone's legs and filled bands, and [Colors on a handle](../functions/colors-kit.md#colors-on-a-handle) for `alpha` on a theme colour - [Chain page views](../core-concepts/data-sources.md#chain-page-views) for the `numbers` and `vol_term` book folds and the hosted runs' refusal - [The clock](../functions/time-and-sessions-kit.md#the-clock) for `Clock.epochSec`, and [Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) for `CandleList` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its tiles, the slot in the title and what a card with no `look` draws <!-- source: https://openmarket.xyz/wrun/cookbook/vol-context --> # Volatility context Volatility context is a start-of-day summary card for this symbol's options, not a history. Its headline answers: do later-ending options cost more, do puts (bets on a fall) cost more, are options pricey? Later-ending options costing more (contango) is the calm shape, and pricier puts mean traders fear a drop. The third weighs implied volatility (how big a move option prices expect) against realized volatility (how much price actually moved). Use it for a quick read before you trade options, on any chart whose symbol has listed options. Under the hood: the recipe reads `options_chain.cells` on the live bar with the `atm` and `delta_band` page views ([Data sources](../core-concepts/data-sources.md#options-chain), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). So the chart reads only the two strikes around each expiry's price and, on the expiry nearest 30 days, the contracts around 25 delta. The options kit's `ExpectedMoves` gives the at-the-money term and the front expected move ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)). `IvTerm` gives the 25 delta wings and the 9 and 30-day IVs. It also uses `oneSigmaMove`, `optionsAsOfMs` and `optionsTradeDay` ([Options kit](../functions/options-kit.md#the-at-the-money-term)). `TextBuilder.expiry` writes the front expiry's label ([A second builder](../functions/text-formatting.md#a-second-builder)). A `CandleList` of the chart's own daily candles gives the realized volatility ([Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists)). A `render.hud` card with no `look` word shows it all ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `vol-context` template, the **Volatility Context** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volatility Context: a start-of-day summary card for this symbol's options, not a history. Its headline answers three // questions in words. Do later-ending options cost more? Contango is that calm, usual shape, and backwardation means // near-term stress. Do puts (bets on a fall) cost more than calls (bets on a rise)? Puts rich means traders pay up to // guard against a drop. Are options pricey? Implied volatility (how big a move option prices expect) above realized // volatility (how much price actually moved) flags pricey options. Tiles add the expected move (how far option prices // say the stock can move). It runs to the next expiry (the day the option ends). They also show today's move in 1σ // moves (one standard deviation), and which side, puts or calls, is cheap. Use it for a quick read before you trade // options. // // Technical notes: one card that reads the chart's own option chain the way a volatility desk opens its day. The term // structure: the 30-day and 90-day at-the-money IV at constant maturity (the options kit's ExpectedMoves, interpolated // in total variance between the expiries around it) and their slope, contango when the 90-day sits more than 1% over // the 30-day, backwardation when it sits more than 1% under, flat between. The skew: the 25 delta put IV minus the 25 // delta call IV at the expiry nearest 30 days, over the 30-day IV: puts rich above 0.06, calls rich below 0, flat // between; the risk reversal beside it in vol points, call minus put. IV against realized: the 30-day IV over the // realized volatility of the last 21 daily log returns of the chart's own daily candles (the sample standard deviation, // annualized over 252 trading days a year, 365 on crypto, which trades every day). The front expiry: the first after // today on the market's own calendar, its days to go and its expected move (0.85 of the at-the-money straddle, // ExpectedMoves' rule, the one every options card reads). A card at the bottom of the pane leads with one plain line // (Contango, puts rich, IV over realized). The chain rides the live bar only: history bars draw nothing; it is read at // its as-of, the live bar's close, an OPRA expiry live and priced until 15 minutes past its 16:00 stamp. // // Three readings beside them from the same chain. Sigma: today's close against the session's open (the open of the // trade day's first bar on the market's clock: the UTC day on crypto, the CME trade date, the New York date) over the // day's 1σ move, the open x the chain's 1-day ATM IV (ExpectedMoves.horizonIv) x sqrt(1/252) (oneSigmaMove), with the // budget left. Term 9 over 30: IvTerm's 9-day over its 30-day constant-maturity ATM IV, each interpolated in total // variance between the expiries around it, none with fewer than two: contango under 0.99, backwardation over 1.01, flat // between. The tilt: the 25 delta put IV minus the call IV at the expiry nearest 30 days, in vol points (the risk // reversal turned round), naming the cheap side: calls cheap at +0.5 or more, puts cheap at -0.5 or less, balanced // between. section("Volatility"); param.int("rv_days", 21, { min: 5, max: 60, label: "Realized vol, days", description: "How many daily price changes the realized volatility measures. 21 is about a month of trading days." }); param.choice("rv_year", ["auto", "252", "365"], "auto", { label: "Realized vol year", description: "Days a year the daily moves scale to. Auto picks 365 on crypto, which trades every day, and 252 elsewhere." }); param.number("rate_pct", 4, { min: 0, max: 20, step: 0.25, label: "Interest rate, percent", description: "The interest rate that projects a US stock's price to each expiry. Futures and crypto options do not need it." }); input("close", ohlcv.close); // the chart's own close: spot where a contract reports no underlying input("chain", options_chain.cells, { max_cells: 16000, venue: "auto", page_views: ["atm", "delta_band"], center: 0, expiry: 30, rate: "@rate_pct", description: "This symbol's options: US listed options on a stock, CME options on a future, Deribit options on BTC and ETH. It reads each expiry's two strikes around the price and, on the expiry nearest 30 days, those around 25 delta." }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega] per contract, in the chain's order input("daily", candles.cells, { interval: "1d", bars: 64, description: "The newest 64 closed daily candles, for the realized volatility" }); // [offset_ms, open, high, low, close, volume] per candle, oldest first market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME): the calendar, the liveness, the rate and the year chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("iv30", none, overlay, { description: "The 30-day at-the-money IV, in percent. Live bar only." }); output("iv90", none, overlay, { description: "The 90-day at-the-money IV, in percent. Past the last expiry, it reads that expiry's IV." }); output("term_slope", none, overlay, { description: "How far the 90-day IV sits above or below the 30-day IV, in percent" }); output("term_regime", none, overlay, { description: "The term structure: 0 backwardation (slope under -1%), 1 flat or no reading, 2 contango (slope over +1%)" }); output("rr25", none, overlay, { description: "The 25 delta risk reversal at the expiry nearest 30 days: call IV minus put IV, in IV points" }); output("skew_scaled", none, overlay, { description: "The 25 delta put IV minus the call IV, divided by the 30-day IV: the number behind the skew verdict" }); output("skew_regime", none, overlay, { description: "The skew: 0 calls rich (under 0), 1 flat or no reading, 2 puts rich (over 0.06)" }); output("skew_days", none, overlay, { description: "Days until the expiry the skew reads, the one nearest 30 days" }); output("rv21", none, overlay, { description: "How much the price actually moved over the last 21 trading days by default, as a yearly percent" }); output("iv_rv_ratio", none, overlay, { description: "The 30-day IV divided by the realized volatility" }); output("ivrv_regime", none, overlay, { description: "IV against realized: 0 under, 1 at it or no reading, 2 over" }); output("front_days", none, overlay, { description: "Days until the front expiry, the first after today on the market's calendar" }); output("front_move", none, overlay, { description: "The front expiry's expected move, in price: 0.85 of its at-the-money straddle (a call plus a put at one strike)" }); output("front_move_pct", none, overlay, { description: "The front expiry's expected move, in percent of the price" }); output("sigma", none, overlay, { description: "Today's move from the session's open, in 1σ moves (one standard deviation) of the 1-day IV" }); output("sigma_left", none, overlay, { description: "How much of today's 1σ move is left: 1 minus the size of Sigma, never below 0" }); output("sigma_band", none, overlay, { description: "The Sigma tile's colour: 0 under 0.5, 1 under 1, 2 down 1 or more, 3 up 1 or more" }); output("term_9_30", none, overlay, { description: "The 9-day at-the-money IV divided by the 30-day one. Empty with fewer than two expiries." }); output("tilt", none, overlay, { description: "The 25 delta put IV minus the call IV at the expiry nearest 30 days, in IV points. At +0.5 or more, calls are the cheap side." }); string("read", { max_bytes: 64 }); // the headline: the three verdicts in one line, or why there is no reading string("title", { max_bytes: 64 }); // the card's title: the front expiry and its days to go string("term_text", { max_bytes: 40 }); // the term tile: the word and the slope string("skew_text", { max_bytes: 40 }); // the skew tile: the word and the scaled skew string("ivrv_text", { max_bytes: 40 }); // the realized tile: the word and the ratio string("short_term_text", { max_bytes: 40 }); // the 9 over 30 tile: the word and the ratio string("tilt_text", { max_bytes: 40 }); // the tilt tile: the cheap side and the tilt // The card: the headline, each verdict as its own tile, the numbers under them as rows. render.hud("vol_context", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Volatility", "read", { headline: true }), tile.pill("Term, 90 over 30 days", "term_text"), tile.pill("25 delta skew", "skew_text"), tile.pill("IV against realized", "ivrv_text"), tile.value("Front expected move", "front_move", { format: "price" }), tile.pill("Term, 9 over 30 days", "short_term_text"), tile.pill("Tilt, put minus call", "tilt_text"), tile.value("Sigma today", "sigma", { format: "0.00", color_by: "sigma_band", colors: ["theme.muted", "theme.text", "theme.down", "theme.up"] }), tile.rows([ ["IV, 30 days", "iv30", "0.00"], ["IV, 90 days", "iv90", "0.00"], ["Term slope, %", "term_slope", "0.00"], ["Risk reversal, call minus put", "rr25", "0.00"], ["Skew over IV, put minus call", "skew_scaled", "0.000"], ["Realized vol", "rv21", "0.00"], ["IV over realized", "iv_rv_ratio", "0.00"], ["Front move, %", "front_move_pct", "0.00"], ["Sigma budget left", "sigma_left", "0.00"], ]), ], }); const TUPLE = 10; // f64s per contract: strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega const MAX_DAYS = 64; // the daily candles kept: the stream's depth const CONTANGO = 0.01; // the slope past which the term is contango (and under minus it, backwardation) const PUT_RICH = 0.06; // the scaled skew past which puts are rich (under 0, calls are) const SIGMA_YEARS: f64 = 1.0 / 252.0; // one trading day: the day's 1σ move is the open x the 1-day IV x sqrt(1/252) const DAY_MS: f64 = 86400000.0; const FLAT_TERM = 0.01; // the 9 over 30 ratio's flat band, each side of 1 const BALANCED = 0.5; // the tilt, vol points, under which neither side is cheap const days = new CandleList(MAX_DAYS); // the newest closed daily candles, kept from the stream const term = new IvTerm(64); // the chain's 25 delta wings at the expiry nearest 30 days const expiryText = new TextBuilder(16); // the front expiry's label, the kit's spelling, copied into the title let moves = new ExpectedMoves(1); // every live expiry's forward, at-the-money IV and expected move; built in onStart() let rvDays = 21; // settings, read in onStart() let yearDays = 252.0; let rate = 0.04; let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let coarse = false; // a chart coarser than a day: a bar is no session, so Sigma reads none let nowMs: f64 = NaN; // the chain's as-of, the live bar's close let close: f64 = NaN; // this bar let t: f64 = NaN; let atm30: f64 = NaN; // the readings, measured on the live bar, as decimals let atm90: f64 = NaN; let slope: f64 = NaN; let callWing: f64 = NaN; let putWing: f64 = NaN; let skewScaled: f64 = NaN; let skewDays: f64 = NaN; let realized: f64 = NaN; let overRealized: f64 = NaN; let front = -1; let frontDays: f64 = NaN; let frontMove: f64 = NaN; let frontMovePct: f64 = NaN; let sessionDay: f64 = NaN; // the trade day the newest bar sits in, on the market's clock let sessionOpen: f64 = NaN; // the open of that trade day's first bar; NaN while the run opened inside it let sigma: f64 = NaN; // the three readings beside the chain's, live bar only let sigmaLeft: f64 = NaN; let term930: f64 = NaN; let tilt: f64 = NaN; function onStart(): void { moves = new ExpectedMoves(in_chain_max_cells); // its buffers are its only allocation rvDays = i32(p_rv_days()); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; coarse = intervalMs > DAY_MS; const year = i32(p_rv_year()); yearDays = year == 1 ? 252.0 : year == 2 ? 365.0 : zone == 0 ? 365.0 : 252.0; // crypto trades every day of the year rate = zone == 1 ? p_rate_pct() / 100.0 : 0.0; // only a stock's spot needs carrying to each forward } // ── Realized volatility: the sample standard deviation of the last rvDays daily log returns, annualized ── function realizedVol(): f64 { const held = days.count(); if (held < rvDays + 1) return NaN; // rvDays returns need rvDays + 1 closes let sum = 0.0; for (let k = held - rvDays; k < held; k += 1) { const before = days.close(k - 1); const after = days.close(k); if (!(before > 0.0) || !(after > 0.0)) return NaN; sum += Math.log(after / before); } const mean = sum / f64(rvDays); let squares = 0.0; for (let k = held - rvDays; k < held; k += 1) { const r = Math.log(days.close(k) / days.close(k - 1)) - mean; squares += r * r; } return Math.sqrt(squares / f64(rvDays - 1)) * Math.sqrt(yearDays); } // ── The chain, measured on the live bar ── function measure(n: i32): void { const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the live bar's close time moves.load(cells, n, nowMs, close, zone); term.load(cells, n, nowMs, close, zone, rate); atm30 = moves.horizonIv(30.0 / 365.0); atm90 = moves.horizonIv(90.0 / 365.0); slope = atm30 > 0.0 && atm90 > 0.0 ? atm90 / atm30 - 1.0 : NaN; const e = term.nearest(30.0); // the anchor whose time to expiry is nearest 30 days callWing = term.deltaIv(e, 1.0, 0.25); putWing = term.deltaIv(e, -1.0, 0.25); skewScaled = atm30 > 0.0 ? (putWing - callWing) / atm30 : NaN; // put minus call over the 30-day IV, as the label reads it skewDays = term.days(e); realized = realizedVol(); overRealized = realized > 0.0 && atm30 > 0.0 ? atm30 / realized : NaN; const todayKey = optionsTradeDay(nowMs, zone); front = -1; // the first expiry after today on the market's calendar, whatever its IV for (let e = 0; e < moves.expiries(); e += 1) { if (optionsTradeDay(moves.expiry(e), zone) > todayKey) { front = e; break; } } frontDays = front >= 0 ? optionsTradeDay(moves.expiry(front), zone) - todayKey : NaN; frontMove = moves.expectedMove(front); // NaN with no front frontMovePct = (frontMove / moves.forward(front)) * 100.0; } // ── The three readings beside the chain's, on the live bar ── function anchorCount(): i32 { // IvTerm's anchors: expiries after today with an at-the-money IV let held = 0; for (let e = 0; e < term.expiries(); e += 1) { if (term.days(e) >= 1.0 && term.years(e) > 0.0 && !isNaN(term.atmIv(e))) held += 1; } return held; } function bandOf(s: f64): f64 { // 0 under 0.5, 1 under 1, 2 at 1 or more down, 3 at 1 or more up; NaN with no sigma if (isNaN(s)) return NaN; const a = Math.abs(s); return a < 0.5 ? 0.0 : a < 1.0 ? 1.0 : s < 0.0 ? 2.0 : 3.0; } function measureMore(): void { if (!coarse) { sigma = (close - sessionOpen) / oneSigmaMove(sessionOpen, moves.horizonIv(1.0 / 365.0), SIGMA_YEARS); // NaN without an open or an IV sigmaLeft = isNaN(sigma) ? NaN : Math.max(0.0, 1.0 - Math.abs(sigma)); } term930 = anchorCount() >= 2 ? term.iv(9.0) / term.iv(30.0) : NaN; tilt = (putWing - callWing) * 100.0; // NaN without both wings } // ── The card's words ── function termCode(): f64 { // 0 backwardation, 1 flat, 2 contango; NaN with no slope if (isNaN(slope)) return NaN; return slope > CONTANGO ? 2.0 : slope < -CONTANGO ? 0.0 : 1.0; } function skewCode(): f64 { // 0 calls rich, 1 flat, 2 puts rich; NaN with no skew if (isNaN(skewScaled)) return NaN; return skewScaled > PUT_RICH ? 2.0 : skewScaled < 0.0 ? 0.0 : 1.0; } function ratioCode(): f64 { // 0 under realized, 1 at it, 2 over; NaN with no ratio if (isNaN(overRealized)) return NaN; return overRealized > 1.0 ? 2.0 : overRealized < 1.0 ? 0.0 : 1.0; } function sbSigned(v: f64): void { // +6.20 / -3.10, two decimals; a value that rounds to zero reads +0.00 if (Math.abs(v) < 0.005) { sb_text("+0.00"); return; } if (v > 0.0) sb_text("+"); sb_f64(v, 2); } function writeWords(): void { const termAt = termCode(); const skewAt = skewCode(); const ratioAt = ratioCode(); // The headline: the verdicts that have a reading, the first one capitalized. sb_clear(); let parts = 0; if (!isNaN(termAt)) { sb_text(termAt == 2.0 ? "Contango" : termAt == 0.0 ? "Backwardation" : "Flat term"); parts += 1; } if (!isNaN(skewAt)) { if (parts > 0) sb_text(", "); if (skewAt == 2.0) sb_text(parts > 0 ? "puts rich" : "Puts rich"); else if (skewAt == 0.0) sb_text(parts > 0 ? "calls rich" : "Calls rich"); else sb_text(parts > 0 ? "skew flat" : "Skew flat"); parts += 1; } if (!isNaN(ratioAt)) { if (parts > 0) sb_text(", "); sb_text(ratioAt == 2.0 ? "IV over realized" : ratioAt == 0.0 ? "IV under realized" : "IV at realized"); parts += 1; } if (parts == 0) sb_text("No implied volatility in this symbol's options"); str_read_sb(); // The tiles. sb_clear(); if (isNaN(termAt)) sb_text("No term"); else { sb_text(termAt == 2.0 ? "Contango, " : termAt == 0.0 ? "Backwardation, " : "Flat, "); sbSigned(slope * 100.0); sb_text("%"); } str_term_text_sb(); sb_clear(); if (isNaN(skewAt)) sb_text("No 25 delta wing"); else { sb_text(skewAt == 2.0 ? "Puts rich, " : skewAt == 0.0 ? "Calls rich, " : "Flat, "); sb_f64(skewScaled, 3); } str_skew_text_sb(); sb_clear(); if (realized == 0.0) sb_text("Realized vol is zero"); else if (isNaN(realized)) { sb_text("Needs "); sb_int(rvDays + 1); sb_text(" daily closes"); } else if (isNaN(ratioAt)) sb_text("No 30-day IV"); else { sb_text(ratioAt == 2.0 ? "IV over realized, " : ratioAt == 0.0 ? "IV under realized, " : "IV at realized, "); sb_f64(overRealized, 2); sb_text("x"); } str_ivrv_text_sb(); // The title: the front expiry and its days to go. sb_clear(); sb_text("Volatility context, "); if (front < 0) sb_text("no expiry after today"); else { sb_text("front "); expiryText.clear().expiry(moves.expiry(front), nowMs, zone); // the expiry's trade date: 16 Oct, or 15 Jan '27 in another year for (let i = 0; i < expiryText.length(); i += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>i)); sb_text(" in "); sb_int(i64(frontDays)); sb_text(frontDays == 1.0 ? " day" : " days"); } str_title_sb(); } function writeMoreWords(): void { // the 9 over 30 tile and the tilt tile, n/a without their reading sb_clear(); if (isNaN(term930)) sb_text("n/a"); else { sb_text(term930 > 1.0 + FLAT_TERM ? "Backwardation, " : term930 < 1.0 - FLAT_TERM ? "Contango, " : "Flat, "); sb_f64(term930, 2); } str_short_term_text_sb(); sb_clear(); if (isNaN(tilt)) sb_text("n/a"); else { sb_text(tilt >= BALANCED ? "Calls cheap, " : tilt <= -BALANCED ? "Puts cheap, " : "Balanced, "); sbSigned(tilt); sb_text(" pts"); } str_tilt_text_sb(); } // onBar() runs once per bar: every bar feeds its daily block to the list (an empty one too) and notes its session; the // live bar measures the chain and writes the readings (NaN on history rows) and the card's words. function onBar(): void { close = bar.close(); t = bar.time(); days.load(in_daily_view(), in_daily_cells(), t); // The session: the first bar of each trade day opens it; the run's first trade day opened before the run did. const day = optionsTradeDay(t * 1000.0, zone); if (isFinite(day) && day != sessionDay) { sessionOpen = isNaN(sessionDay) ? NaN : bar.open(); sessionDay = day; } let measured = false; let chainCells = -1; if (bar.isLast()) { chainCells = in_chain_cells(); if (chainCells >= TUPLE && !isNaN(close) && !isNaN(t)) { measure(chainCells); measured = moves.expiries() > 0; } } out_iv30(measured ? atm30 * 100.0 : NaN); out_iv90(measured ? atm90 * 100.0 : NaN); out_term_slope(measured ? slope * 100.0 : NaN); out_rr25(measured ? (callWing - putWing) * 100.0 : NaN); out_skew_scaled(measured ? skewScaled : NaN); out_skew_days(measured ? skewDays : NaN); out_rv21(measured ? realized * 100.0 : NaN); out_iv_rv_ratio(measured ? overRealized : NaN); out_front_days(measured ? frontDays : NaN); out_front_move(measured ? frontMove : NaN); out_front_move_pct(measured ? frontMovePct : NaN); const live = bar.isLast(); out_term_regime(measured && !isNaN(termCode()) ? termCode() : live ? 1.0 : NaN); out_skew_regime(measured && !isNaN(skewCode()) ? skewCode() : live ? 1.0 : NaN); out_ivrv_regime(measured && !isNaN(ratioCode()) ? ratioCode() : live ? 1.0 : NaN); if (measured) writeWords(); else if (live) { // The live bar carried nothing to measure: the headline says why, so the card is never a row of blanks. sb_clear(); sb_text(chainCells < TUPLE ? "Waiting for the options chain" : "No expiry is still trading"); str_read_sb(); sb_clear(); sb_text("Volatility context, nothing to read yet"); str_title_sb(); } sigma = NaN; sigmaLeft = NaN; term930 = NaN; tilt = NaN; if (measured) measureMore(); out_sigma(sigma); out_sigma_left(sigmaLeft); out_sigma_band(bandOf(sigma)); out_term_9_30(term930); out_tilt(tilt); if (live) writeMoreWords(); } ``` ## How it works **The at-the-money term.** `ExpectedMoves` reads every live expiry's forward, the median underlying its contracts quote, and its at-the-money IV: the mean of the mark IVs listed at the strike nearest that forward. It loads at the chain's as-of, `optionsAsOfMs()`: the live bar's close time, never its open, on the market's zone, so an OPRA expiry stays live and priced until 15 minutes past its 16:00 stamp. `horizonIv(30 / 365)` and `horizonIv(90 / 365)` interpolate between the expiries around each horizon in total variance (IV squared times years), the same at-the-money IV the Expected Move card reads at those horizons. Past the last listed expiry a horizon reads the last expiry's IV. `term_slope` is `iv90 / iv30 - 1` in percent: over +1% is contango (the further month richer, the calm shape), under -1% backwardation (the near month richer, the stressed shape), flat between. **The 25 delta skew.** At the expiry whose time to expiry is nearest 30 days, `deltaIv()` reads the call IV and the put IV where each side's delta is 0.25, interpolated between the two listed strikes around it. `skew_scaled` is the put IV minus the call IV, over the 30-day IV: above 0.06 the puts are rich (protection costs more than upside), below 0 the calls are rich, flat between. `rr25` is the same pair the other way round, call IV minus put IV in vol points, the risk reversal as a desk quotes it: a negative `rr25` and a positive `skew_scaled` say the same thing. **IV against realized.** The `daily` input is the chart's own daily candles, the newest 64 closed ones, kept in a `CandleList` that every bar feeds. On the live bar the realized volatility is the sample standard deviation of the last `rv_days` (21) daily log returns, annualized over 252 trading days a year, or over 365 on crypto, which trades every day (the Realized vol year setting picks either by hand). `iv_rv_ratio` is the 30-day IV over it: above 1 the options price more movement than the market delivered. **The front expiry.** The first expiry after today on the market's own calendar (`optionsTradeDay()`: New York on a US stock, Chicago on CME, UTC on crypto), its days to go, and its expected move: `ExpectedMoves.expectedMove()`, 0.85 of its at-the-money straddle on its forward at the chain's as-of, in price and in percent of the forward. **Sigma.** Every bar notes its trade day on the market's clock (`optionsTradeDay()`), and the first bar of each trade day opens a session at its open; the run's first trade day opened before the run did, so it has none. On the live bar `sigma` is the live close minus the session's open over `oneSigmaMove(open, iv, 1 / 252)`, the open times the chain's 1-day IV (`ExpectedMoves.horizonIv(1 / 365)`) times the square root of one trading day; `sigma_left` is the budget left (1 minus its size, floored at 0) and `sigma_band` the band that colours the Sigma tile: muted under 0.5, the text ink under 1, the up or down colour from 1 on. The strip of the past 60 sessions is drawn by [Skew history](skew-history.md), which reads the daily statistics each past session needs. **Term 9 over 30.** `IvTerm.iv(9)` over `IvTerm.iv(30)`: each constant-maturity at-the-money IV interpolated in total variance between the two anchors around it (expiries after today with an at-the-money IV; before the first anchor its IV, past the last its IV), and none with fewer than two anchors. Under 0.99 is contango (the near IV under the far, the calm shape), over 1.01 backwardation, flat between, the tile naming it beside the ratio (`Backwardation, 1.20`). **The tilt.** The 25 delta put IV minus the call IV at the expiry nearest 30 days, the same `deltaIv()` pair the skew reads, in vol points: the risk reversal turned round, so `tilt` is minus `rr25`. The tile names the cheap side: calls cheap at +0.5 or more (the puts are dearer), puts cheap at -0.5 or less, balanced between (`Calls cheap, +1.20 pts`). **The card reads the outputs.** The headline joins the three verdicts that have a reading, in plain words; the three tiles under it carry each verdict with its number (`Contango, +6.20%`, `Puts rich, 0.083`, `IV over realized, 1.24x`), then the front expected move in price, the 9 over 30 tile, the tilt tile and the Sigma tile, and nine rows: the two IVs, the slope, the risk reversal, the scaled skew, the realized volatility, the ratio, the front move in percent and Sigma's budget left. The title names the front expiry by its label and its days to go (`Volatility context, front 16 Oct in 1 day`); an expiry in another year reads its year (`15 Jan '27`). ## What the settings do - **Realized vol, days**: How many daily price changes the realized volatility measures: 21 is about a month of trading days. - **Realized vol year**: Days a year the moves scale to: auto picks 365 on crypto, which trades every day, and 252 elsewhere. - **Interest rate, percent**: The rate that projects a US stock's price to each expiry, which futures and crypto options do not need. - **Volatility**: Three verdicts in one line: the term structure, the skew and IV against realized. - **Term, 90 over 30 days**: Contango, the calm and usual shape: 90-day implied volatility tops 30-day by over 1%. Backwardation, the stressed shape with near dates pricier: it trails by over 1%. Flat in between. - **25 delta skew**: Puts rich (pricier) when the put's implied volatility tops the call's by over 6% of the 30-day level. Calls rich when the put's is lower. Flat in between. - **IV against realized**: The 30-day IV divided by realized volatility: over 1x, options charge more than recent moves. - **Front expected move**: How far options expect the price to move by the next expiry, in price terms. - **Term, 9 over 30 days**: The 9-day IV over the 30-day IV: under 0.99 is contango, over 1.01 backwardation. - **Tilt, put minus call**: The 25 delta put's implied volatility minus the call's: the reverse of the risk reversal line. At +0.5 or more, calls are the cheap side. At -0.5 or less, puts are. In between, it reads balanced. - **Sigma today**: Today's move from the open in 1σ moves (one standard deviation), the size the 1-day IV calls normal. - **IV, 30 days**: The 30-day implied volatility, as a yearly percent. - **IV, 90 days**: The 90-day implied volatility, as a yearly percent. - **Term slope, %**: How far the 90-day IV sits above or below the 30-day IV, in percent. - **Risk reversal, call minus put**: The 25 delta call's IV minus the put's, in IV points: below zero, puts cost more. - **Skew over IV, put minus call**: The put's IV minus the call's, divided by the 30-day IV: the number behind the skew verdict. - **Realized vol**: How much the price actually moved over the last 21 trading days by default, as a yearly percent. - **IV over realized**: The 30-day IV divided by realized volatility. - **Front move, %**: The expected move to the next expiry, in percent of the price. - **Sigma budget left**: How much of a normal day's 1σ move is left, from 1 down to 0. ## Where it runs It works on charts of coins that Deribit (a crypto options exchange) lists options for. Those are BTC, ETH, SOL and the rest of its list. A copy you run from the editor (the code panel beside the chart) reads those coins' options. On a US stock chart it reads that stock's US listed options. On a CME (Chicago futures exchange) futures chart it reads the options on that future. Every indicator reads US listed options, 15 minutes behind unless you have real-time US options data. Every indicator in your browser reads CME options too, once you accept the CME market data terms. They run 10 minutes behind unless you have real-time CME data, and the legend names the source. Editor copies, your published copies and Protected copies (their code stays on OpenMarket's servers) all read US listed options. So does a copy run with Run on Cloud (the editor switch that runs it on OpenMarket's servers). A Protected copy and a Run on Cloud copy do not run on a CME chart. The daily candles come from this chart's own market on every chart. ## When data is missing The headline always says why it has no verdict. It reads "Waiting for the options chain" while the live bar has no options data yet. It reads "No expiry is still trading" when every listed expiry has stopped trading. It reads "No implied volatility in this symbol's options" when no expiry has an at-the-money IV. Each tile says what it lacks. "No term" means the term structure has no reading. "No 25 delta wing" means the expiry nearest 30 days lacks a strike on one side of 25 delta. That happens when the options list only strikes near the price. "Needs 22 daily closes" means there are too few daily candles yet. "Realized vol is zero" means every daily move was the same. The 9 over 30 tile reads "n/a" with fewer than two expiries after today that have an at-the-money IV. The tilt tile reads "n/a" when the expiry nearest 30 days lacks a 25 delta strike on one side. Sigma shows nothing until today has an open, and on charts with bars longer than a day. Lines with no reading show "-". ## Customize it - **A shorter or longer realized window.** Set `rv_days` to 10 for the last two weeks or 60 for a quarter; the stream holds 64 closed days. - **Another year.** Set Realized vol year to `365` on a market that trades every day, or `252` to compare a crypto chart with a stock's numbers. - **A calendar day on crypto.** Sigma prices one trading day as 1/252 of a year on every venue; on a coin that trades every day, set `SIGMA_YEARS` to `1.0 / 365.0`. - **Another rate.** Change Interest rate, percent when short rates move; it only moves a US stock's forwards, so the at-the-money strike and the wings' deltas. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volatility Context** under **HUDs**. 2. Press **Run** on a BTC chart: the card appears at the bottom centre once the chain arrives, titled by the front expiry. 3. At the editor's Console prompt, type `iv30`, `term_slope` and `iv_rv_ratio` to read the term and the realized ratio on the live bar, and `sigma`, `term_9_30` and `tilt` for the three readings beside them. ## Concepts used - [Data sources](../core-concepts/data-sources.md#options-chain) for the `options_chain` celled class, its tuple and the `venue` word - [Options kit](../functions/options-kit.md#the-canonical-numbers) for `ExpectedMoves`, and [the at-the-money term](../functions/options-kit.md#the-at-the-money-term) for `IvTerm`'s wings and constant maturities, `optionsAsOfMs` and `optionsTradeDay`, and `oneSigmaMove` for Sigma - [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry`, the front expiry's label - [Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) for the `candles` stream and `CandleList` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its pills and rows and the slot in the title <!-- source: https://openmarket.xyz/wrun/cookbook/contract-odds --> # Contract odds Before you trade one option, Contract Odds answers two questions: will it make money, and how much should you stake? Pick a call (a bet on a rise) or put (a bet on a fall), long (bought) or short (sold). Then set its strike (the option's price level) and expiry (the day the option ends), or leave them at 0. A card leads with the chance of profit and a stake from the Kelly rule (a bet-size formula). It needs this symbol's options, and its odds are the market's price, not a forecast. Under the hood: the probability of profit is lognormal from the contract's IV. On a stock it adds a risk-neutral drift at the rate, and none on a futures or crypto forward. The premium is the Premium setting, else the chart's close on the contract's own chart, else the Black-Scholes or Black-76 model price. Kelly is `p - (1 - p) / odds`, with odds the most it can make over the most it can lose and no volatility adjustment. It reads the `options_chain.cells` `contract` page view on the live bar ([Data sources](../core-concepts/data-sources.md#options-chain), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). It keeps only the contracts at the strike nearest the one set, of the type and the expiry set. It prices them with the options kit's `Greeks`, `normCdf`, `optionsAsOfMs`, `optionsLiveUntilMs`, `optionsYearsToGo` and `optionsTradeDay` ([Options kit](../functions/options-kit.md#pricing-the-chain)). It names the expiry through `TextBuilder.expiry` ([A second builder](../functions/text-formatting.md#a-second-builder)). It takes the contract from a price and a date setting ([Kinds of setting](../settings/kinds.md)). It draws a `render.hud` card with no `look` word over data-only outputs and five text slots ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `contract-odds` template, the **Contract Odds** card under **HUDs** in the editor's starter list, which compiles as written. ## The wrun indicator ```typescript // Contract Odds: the odds that one option trade makes money, read from this symbol's options. You pick its strike (the // option's price level), expiry (the day the option ends), call or put, long or short. A card leads with the chance of // profit and the bankroll share the Kelly rule (a bet-size formula) stakes. Under it come the breakeven, the premium // (the money paid for an option) and the best and worst case. The breakeven is the price where the trade neither wins // nor loses at expiry. The chance comes from implied volatility (how big a move option prices expect). Use it before // you place a trade: its odds are the market's, not a forecast. // // Technical notes: one option contract of the chart's own chain held to its expiry, read as odds. A card at the bottom // of the pane answers one question first: what are the odds this trade makes money, and how much of a bankroll would // Kelly put on it? Under the answer: the probability of profit at expiry, the breakeven, the premium and where it came // from, the most the position can make and lose per contract, the odds ratio and the Kelly fractions (full, half and // quarter). // The chart does not tell an indicator which contract it shows, so the settings name it: the strike (0 = the strike // nearest the expiry's forward), the expiry (0 = the first expiry after today), call or put, long or short, and the // premium (0 = the chart's close on the contract's own chart, else the model price from the contract's IV). The // probability is lognormal from the contract's IV, with a risk-neutral drift at the rate on a stock (none on a futures // or crypto forward). Kelly is p - (1 - p) / odds, odds the most it can make over the most it can lose: an unlimited // gain reads p, an unlimited loss no edge; full Kelly here takes no volatility adjustment (1). The chain rides the // live bar only: history bars draw nothing, and everything is measured on the last bar at the chain's as-of (the live // bar's close), an OPRA contract live and priced until 15 minutes past its 16:00 stamp. section("Contract"); param.price("strike", 0.0, { min: 0, label: "Strike", description: "The strike, the option's price level. 0 picks the listed strike nearest the forward price, today's price carried to that expiry." }); param.time("expiry", 0, { label: "Expiry date", description: "The expiry, the date the option ends. 0 picks the first expiry after today." }); param.choice("type", ["call", "put"], "call", { label: "Type" }); param.choice("position", ["long", "short"], "long", { label: "Position", description: "long: you buy the option and pay the premium (the money paid for an option). short: you sell it and collect the premium." }); param.number("premium", 0, { min: 0, label: "Premium", description: "The premium (the money paid for an option), per unit, that you paid or got. At 0 it uses the close when this chart is the option's own. Elsewhere 0 uses a formula price from implied volatility." }); param.number("rate_pct", 4, { min: 0, max: 20, step: 0.25, label: "Rate, percent", description: "The interest rate for the model price and a stock's expected drift. Crypto options always price at 0." }); input("close", ohlcv.close); // the chart's own close: the premium on the contract's own chart, spot where a contract reports none input("chain", options_chain.cells, { max_cells: 16000, venue: "auto", page_view: "contract", expiry_day: "@expiry", side: "@type", strike: "@strike", rate: "@rate_pct", description: "This symbol's options. US listed options on a US stock or its options, CME options on a future, Deribit on BTC and ETH. Only the contracts at the strike nearest yours, of your type and expiry." }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega] per contract, in the chain's order market.zone(); // the market's clock: 0 UTC (crypto), 1 New York (US stocks), 2 Chicago (CME): the calendar, the liveness and the model chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("matched_strike", none, overlay, { description: "The strike of the option the card reads. Live candle only." }); output("expiry_days", none, overlay, { description: "Days to the option's expiry on the market's own calendar, 0 on the expiry day." }); output("contract_iv", none, overlay, { description: "The option's implied volatility (IV), the yearly move size its price assumes, in percent." }); output("premium_used", none, overlay, { description: "The premium (the option's price per unit) the card uses. premium_source says where it came from." }); output("premium_source", none, overlay, { description: "Where the premium came from: 0 the Premium setting, 1 the chart's close, 2 the model price" }); output("breakeven", none, overlay, { description: "The market's price at expiry where the trade breaks even. It is the strike plus the premium on a call, minus it on a put." }); output("prob_profit", none, overlay, { description: "The odds this trade makes money at expiry, in percent, from the option's IV. Market odds, not a forecast." }); output("max_gain", none, overlay, { description: "The most one contract can make at expiry, in dollars. Empty when unlimited." }); output("max_loss", none, overlay, { description: "The most one contract can lose at expiry, in dollars. Empty when unlimited." }); output("odds_ratio", none, overlay, { description: "Max gain divided by max loss. Empty when either is unlimited." }); output("kelly_full", none, overlay, { description: "Full Kelly: the share of your bankroll the Kelly rule stakes on this edge, in percent. It is p - (1 - p) / odds, with no volatility adjustment. Empty when the loss is unlimited." }); output("kelly_half", none, overlay, { description: "Half of full Kelly, in percent." }); output("kelly_quarter", none, overlay, { description: "A quarter of full Kelly, in percent." }); output("tone", none, overlay, { description: "The headline's tone: 0 no edge (Kelly at or below 0), 1 no reading, 2 an edge. Live candle only." }); string("read", { max_bytes: 64 }); // the headline: the position, its odds and half Kelly, or why there is no reading string("title", { max_bytes: 48 }); // the card's title: the contract, its expiry and the days to go string("premium_text", { max_bytes: 40 }); // the premium and where it came from string("gain_text", { max_bytes: 24 }); // dollars, or unlimited string("loss_text", { max_bytes: 24 }); // The card: the odds lead as the headline; the title names the contract. A tile's label is fixed text, so the // premium's source and an unlimited gain or loss ride string slots. render.hud("odds", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Odds", "read", { headline: true }), tile.value("Probability of profit", "prob_profit", { format: "%" }), tile.value("Breakeven", "breakeven", { format: "price" }), tile.rows([ ["Premium", "premium_text"], ["Max gain", "gain_text"], ["Max loss", "loss_text"], ["Odds ratio", "odds_ratio", "0.00"], ["Full Kelly", "kelly_full", "%"], ["Half Kelly", "kelly_half", "%"], ["Quarter Kelly", "kelly_quarter", "%"], ["Implied volatility", "contract_iv", "%"], ]), ], }); const TUPLE = 10; // f64s per contract: strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega const MIN_T_MS = 900000.0; // 15 minutes: a contract closer to its expiry prices no time left, as the chart's greeks do const greeks = new Greeks(); // the model price; allocated once const expiryText = new TextBuilder(16); // the expiry's label, the kit's spelling, copied into the title let pickStrike = 0.0; // settings, read in onStart() let pickDay: f64 = NaN; // the picked expiry's date, days since 1970-01-01; NaN = the first expiry after today let isCall = true; let isLong = true; let pickPremium = 0.0; let rate = 0.04; let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let nowMs: f64 = NaN; // the chain's as-of, the live bar's close let close: f64 = NaN; // this bar let t: f64 = NaN; let why = ""; // the no-reading line, set by measure() let matched = false; // a contract was matched on the live bar let strike: f64 = NaN; // the readings, measured on the live bar let expiryMs: f64 = NaN; let days: f64 = NaN; let ivPoints: f64 = NaN; let premium: f64 = NaN; let source = 0; let breakeven: f64 = NaN; let prob: f64 = NaN; let gain: f64 = NaN; // dollars; Infinity when unlimited let loss: f64 = NaN; let kelly: f64 = NaN; // raw Kelly as a fraction; -Infinity when the loss is unlimited function onStart(): void { pickStrike = p_strike(); pickDay = p_expiry() > 0.0 ? Math.floor(p_expiry() / 86400.0) : NaN; // the picker's UTC date isCall = p_type() == 0.0; isLong = p_position() == 0.0; pickPremium = p_premium(); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; rate = zone == 0 ? 0.0 : p_rate_pct() / 100.0; // crypto chains are quoted at a rate of 0 } function fin(v: f64): f64 { // an output never carries an infinity: NaN stands for "unlimited" and "none" return isFinite(v) ? v : NaN; } // ── The contract: the expiry, then the strike on the picked side ── function pickExpiry(cells: StaticArray<f64>, n: i32, nowMs: f64, todayKey: f64): f64 { // the expiry the settings name; NaN when the chain lists none let best = Infinity; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const e = cells[i + 1]; if (!(cells[i] > 0.0) || !(optionsLiveUntilMs(e, zone) > nowMs) || e >= best) continue; // live: still trading at the as-of const day = optionsTradeDay(e, zone); // a calendar question: the expiry's trade date on the market's own clock if (isNaN(pickDay) ? day > todayKey : day == pickDay) best = e; } return best == Infinity ? NaN : best; } function pickContract(cells: StaticArray<f64>, n: i32, expiry: f64, nowMs: f64): i32 { // the cell index of the contract; -1 when the side lists none let at = -1; let gap = Infinity; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (cells[i + 1] != expiry || !(cells[i] > 0.0) || (cells[i + 2] > 0.0) != isCall) continue; let target = pickStrike; if (!(target > 0.0)) { // the strike nearest the expiry's forward: spot carried at the rate on a stock, the underlying itself elsewhere const under = cells[i + 7] > 0.0 ? cells[i + 7] : close; target = zone == 1 ? under * Math.exp(rate * optionsYearsToGo(expiry, nowMs, zone)) : under; } const d = Math.abs(cells[i] - target); if (d < gap || (d == gap && at >= 0 && cells[i] < cells[at])) { gap = d; at = i; } } return at; } // ── The odds, measured on the live bar ── function measure(n: i32): void { const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the live bar's close time const todayKey = optionsTradeDay(nowMs, zone); matched = false; let live = false; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) if (cells[i] > 0.0 && optionsLiveUntilMs(cells[i + 1], zone) > nowMs) live = true; if (!live) { why = "No options still trading"; return; } expiryMs = pickExpiry(cells, n, nowMs, todayKey); if (isNaN(expiryMs)) { why = isNaN(pickDay) ? "No expiry after today" : "No expiry on the picked date"; return; } const at = pickContract(cells, n, expiryMs, nowMs); if (at < 0) { why = isCall ? "No call listed at that expiry" : "No put listed at that expiry"; return; } matched = true; strike = cells[at]; days = optionsTradeDay(expiryMs, zone) - todayKey; ivPoints = cells[at + 6] > 0.0 ? cells[at + 6] : NaN; // mark IV rides the chain in percentage points const spot = cells[at + 7] > 0.0 ? cells[at + 7] : close; const multiplier = cells[at + 8] > 0.0 ? cells[at + 8] : 1.0; const left = optionsLiveUntilMs(expiryMs, zone) - nowMs; // to the expiry's end: 16:15 New York on OPRA const years = left < MIN_T_MS ? 0.0 : left / OPTIONS_YEAR_MS; const sigma = ivPoints / 100.0; const side = isCall ? 1.0 : -1.0; // The premium: the setting, else the chart's close on the contract's own chart (a close far from the underlying is // the option's own price), else the model price from the contract's IV. if (pickPremium > 0.0) { premium = pickPremium; source = 0; } else if (close > 0.0 && Math.abs(close / spot - 1.0) > 0.2) { premium = close; source = 1; } else { premium = zone == 1 ? greeks.spot(side, spot, strike, years, sigma, rate) : greeks.forward(side, spot, strike, years, sigma, rate); source = 2; } breakeven = isCall ? strike + premium : strike - premium; // The probability the underlying ends past the breakeven: lognormal at the IV, drifting at the rate on a stock's spot, // not at all on a forward; at expiry the answer is spot's own side of it. const drift = zone == 1 ? rate : 0.0; let above: f64 = NaN; // P(underlying at expiry > breakeven) if (isNaN(breakeven)) above = NaN; // no premium (a contract without IV on the underlying's chart): unavailable else if (breakeven <= 0.0) above = 1.0; else if (years == 0.0) above = spot > breakeven ? 1.0 : 0.0; else if (sigma > 0.0) above = normCdf((Math.log(spot / breakeven) + (drift - 0.5 * sigma * sigma) * years) / (sigma * Math.sqrt(years))); const longWins = isCall ? above : 1.0 - above; prob = isLong ? longWins : 1.0 - longWins; // Per contract at expiry: a long pays the premium and a short collects it; a call's upside has no ceiling, a put's // stops at the strike less the premium. const capped = (strike - premium) * multiplier; // a put held to a worthless underlying const paid = premium * multiplier; if (isLong) { gain = isCall ? Infinity : capped; loss = paid; } else { gain = paid; loss = isCall ? Infinity : capped; } const odds = gain / loss; if (isNaN(prob) || isNaN(odds)) kelly = NaN; else if (odds == Infinity) kelly = prob; // nothing to lose against an unlimited gain: Kelly reads p else if (!(odds > 0.0)) kelly = -Infinity; // nothing to win, or an unlimited loss: no edge else kelly = prob - (1.0 - prob) / odds; } // ── 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: 67,000 / 660.50 / 4.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 sbDollars(v: f64): void { // $65,590, or unlimited if (!isFinite(v)) { sb_text("unlimited"); return; } if (v < 0.0) { sb_text("-"); v = -v; } sb_text("$"); sbGrouped(i64(Math.round(v))); } function sbContract(): void { // 660 call, 662.50 put if (strike == Math.floor(strike)) sbGrouped(i64(strike)); else sbPrice(strike); sb_text(isCall ? " call" : " put"); } function writeWords(): void { sb_clear(); sb_text(isLong ? "Long " : "Short "); sbContract(); if (isNaN(prob)) sb_text(": no implied volatility"); else { sb_text(": "); sb_f64(prob * 100.0, 1); sb_text("% to profit, "); if (kelly > 0.0) { sb_text("half Kelly "); sb_f64(kelly * 50.0, 1); sb_text("%"); } else sb_text("no edge"); } str_read_sb(); sb_clear(); expiryText.clear().expiry(expiryMs, nowMs, zone); // the expiry's trade date: 16 Oct, or 15 Jan '27 in another year for (let i = 0; i < expiryText.length(); i += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>i)); sb_text(" "); sbContract(); sb_text(", "); sb_int(i64(days)); sb_text("d"); str_title_sb(); sb_clear(); if (isNaN(premium)) sb_text("no price"); else { sbPrice(premium); sb_text(source == 0 ? ", your premium" : source == 1 ? ", the chart's close" : ", the model price"); } str_premium_text_sb(); sb_clear(); if (isNaN(gain)) sb_text("-"); else sbDollars(gain); str_gain_text_sb(); sb_clear(); if (isNaN(loss)) sb_text("-"); else sbDollars(loss); str_loss_text_sb(); } // onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar matches the contract and // measures its odds, then writes the readings (NaN on history rows) and the card's words. function onBar(): void { close = bar.close(); t = bar.time(); let chainCells = -1; matched = false; if (bar.isLast()) { chainCells = in_chain_cells(); if (chainCells >= TUPLE && !isNaN(t)) measure(chainCells); else why = "Waiting for this symbol's options"; } const full = kelly * 100.0; // percent of the bankroll; the volatility adjustment is 1 out_matched_strike(matched ? strike : NaN); out_expiry_days(matched ? days : NaN); out_contract_iv(matched ? ivPoints : NaN); out_premium_used(matched ? fin(premium) : NaN); out_premium_source(matched && !isNaN(premium) ? f64(source) : NaN); out_breakeven(matched ? fin(breakeven) : NaN); out_prob_profit(matched ? fin(prob * 100.0) : NaN); out_max_gain(matched ? fin(gain) : NaN); out_max_loss(matched ? fin(loss) : NaN); out_odds_ratio(matched ? fin(gain / loss) : NaN); out_kelly_full(matched ? fin(full) : NaN); out_kelly_half(matched ? fin(full * 0.5) : NaN); out_kelly_quarter(matched ? fin(full * 0.25) : NaN); out_tone(matched && !isNaN(kelly) ? (kelly > 0.0 ? 2.0 : 0.0) : bar.isLast() ? 1.0 : NaN); if (matched) writeWords(); else if (bar.isLast()) { // Nothing to read: the headline says why, so the card is never a row of blanks. sb_clear(); sb_text(why); str_read_sb(); sb_clear(); sb_text("no contract read"); str_title_sb(); } } ``` ## How it works **The settings name the contract.** An indicator reads the chart's market, never which listed contract a chart shows, so the contract is four settings. **Expiry date** picks the expiry whose trade date, on the market's own clock (`optionsTradeDay()`: New York on a US stock, Chicago on CME, UTC on crypto), is the picked date; left at 0 it is the first expiry after today, the trade date of the chain's as-of (`optionsAsOfMs()`, the live bar's close). Either way the expiry is a live one, still trading at the as-of: on a US listed option until 15 minutes past its stamp (`optionsLiveUntilMs()`: a PM expiry stamped 16:00 New York trades until 16:15), on CME and crypto until the stamp. **Strike** picks the listed strike nearest the setting at that expiry; left at 0 it is the strike nearest the expiry's forward (spot carried at the rate on a US stock, the underlying itself on futures and crypto). **Type** is call or put, **Position** long (bought, paying the premium) or short (sold, collecting it). The title names what was matched, the expiry by its label: `20 Nov 680 call, 36d` (an expiry in another year reads its year, `15 Jan '27`). **The premium, and where it came from.** The **Premium** setting wins when it is above 0. Left at 0, a chart whose close sits more than 20% from the contract's underlying is taken for the contract's own chart, and its close is the premium; on the underlying's chart the premium is the model price, the contract's IV priced by Black-Scholes on spot on a US stock and by Black-76 on the underlying on futures and crypto, at the **Rate** setting (4% by default, 0 on crypto). The first row says which: `4.250, the chart's close`, `4.105, the model price` or `5.000, your premium`. A deep in-the-money contract whose price sits within 20% of its underlying reads as the underlying's chart; set the premium there. **The breakeven and the probability.** The breakeven is the strike plus the premium on a call and the strike minus it on a put. The probability of profit is the chance the underlying ends past it at expiry, lognormal at the contract's IV over the time left to its end (from the as-of to `optionsLiveUntilMs()`, in 365-day years): a stock's spot drifts at the rate, a futures or crypto forward does not drift. A long call profits above its breakeven, a long put below it; a short position profits exactly where the long one does not, so the two probabilities sum to 100%. A contract within 15 minutes of its end has no time left: the answer is which side of the breakeven the underlying is on. **Max gain and max loss, per contract.** In dollars, times the multiplier (100 on a US listed option, the point value on CME, 1 on crypto): a long pays the premium and can lose no more; a long call's upside has no ceiling (`unlimited`), a long put's stops at the strike less the premium. A short collects the premium as its most; a short call's loss has no ceiling, a short put's stops at the strike less the premium. **Kelly.** The odds ratio is the most it can make over the most it can lose, and Kelly's fraction of the bankroll is `p - (1 - p) / odds` with `p` the probability of profit. An unlimited gain against a capped loss reads `p` itself; an unlimited loss, or nothing to win, has no edge, and so does any fraction at or below zero. Some tools scale full Kelly by a volatility adjustment they do not publish; this card takes none, so full Kelly is the raw fraction, half Kelly half of it and quarter Kelly a quarter. The headline names half Kelly with an edge and says "no edge" without one. **The card reads the outputs.** The headline pill over `read`, the probability in percent and the breakeven at the chart's price digits, then rows: the premium and its source, max gain and max loss (`$65,500` or `unlimited`), the odds ratio, the three Kelly fractions in percent and the contract's IV. Each output is a number on the live bar (`prob_profit`, `kelly_half`, `breakeven`) for the Console and for a watch; an unlimited gain or loss reads `NaN` there, never an infinity. ## What the settings do - **Strike**: The strike, the option's price level. 0 picks the listed strike nearest today's price carried forward to the expiry. - **Expiry date**: The expiry (the day the option ends). 0 picks the first expiry after today. - **Type**: call: an option that pays when price rises. put: one that pays when price falls. - **Position**: long: you bought the option and paid its premium (the money paid for an option). short: you sold it and collected the premium. - **Premium**: The option's price per unit that you paid or got. At 0 it uses the close when this chart is the option's own, else a formula price. - **Rate, percent**: The interest rate the formula price uses, with crypto options always at 0. - **Odds**: The trade in words: the chance of profit and half the Kelly stake. It reads no edge when Kelly stakes nothing. - **Probability of profit**: The chance the trade makes money at expiry. It comes from the option's implied volatility (how big a move option prices expect): market odds, not a forecast. - **Breakeven**: The price the market must pass at expiry for the trade to make money. - **Premium**: The option's price per unit, and whether it came from you, the chart's close or the formula. - **Max gain**: The most one contract can make at expiry, or unlimited. - **Max loss**: The most one contract can lose at expiry, or unlimited. - **Odds ratio**: The max gain divided by the max loss. - **Full Kelly**: The share of your bankroll the Kelly rule (a bet-size formula from odds and payoff) would stake on this trade. - **Half Kelly**: Half the full Kelly stake, a common safer size. - **Quarter Kelly**: A quarter of the full Kelly stake. - **Implied volatility**: The option's implied volatility, the yearly move size its price assumes. ## Where it runs It works on charts of coins with options on Deribit (a crypto options exchange), such as BTC, ETH and SOL. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock chart, or the chart of one of its options, it reads that stock's US listed options. The data is 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), it reads that future's options, 10 minutes behind unless you have real-time CME data. The legend names where the options come from. Copies you run from the editor, publish yourself or run as a Cloud (Protected) copy all read US listed options. A Protected copy runs on OpenMarket's servers and keeps its code hidden. Copies you run from the editor or publish yourself read CME options too, once you accept the CME market data terms. A Protected copy does not run on a CME chart. ## 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 listed expiry has stopped trading. It reads "No expiry on the picked date" when no option ends that day. A weekend or a past expiry does this. It reads "No expiry after today" when only today's expiry is left. It reads "No put listed at that expiry" (or call) when that side lists none. An option with no implied volatility reads "no implied volatility" after its name. Then the card's probability and Kelly lines read -. On the chart these options are on, with no Premium set, it has no formula price either. Then the card's **Premium** line reads "no price" and **Breakeven** stays empty, instead of a false 100% or 0%. ## Customize it - **Your own fill.** Type the price you paid or received into Premium: the breakeven, the probability and Kelly follow it. - **The contract on screen.** On the contract's own chart, set its strike, expiry date and type; the close is its premium. - **A short premium seller.** Set Position to `short` on a put: a capped loss gives a finite Kelly; a short call has none. - **Another rate.** Change Rate when rates move; crypto chains stay at 0. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Contract Odds** under **HUDs**. 2. Press **Run** on a BTC chart: the card appears at the bottom centre over the at-the-money call of the first expiry after today. 3. Set Strike, Expiry date, Type and Position to the trade you are weighing; at the editor's Console prompt, type `prob_profit` and `kelly_half` to read them on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#options-chain) for the `options_chain` celled class, its tuple and the `venue` word - [Options kit](../functions/options-kit.md#pricing-the-chain) for `Greeks`, `normCdf`, `optionsAsOfMs`, `optionsLiveUntilMs`, `optionsYearsToGo` and `optionsTradeDay` - [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry`, the expiry's label in the title - [Kinds of setting](../settings/kinds.md) for `param.price` and `param.time` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its rows and the slot in the title <!-- source: https://openmarket.xyz/wrun/cookbook/options-stats --> # Options stats A card at the bottom of the chart sums up today's options trading on this symbol. Its headline says which side leads: calls (bets on a rise) or puts (bets on a fall). Below it sit contracts, premium (money paid for options) and open interest (contracts still open), each with a put/call ratio. A put/call ratio under 1 means calls lead, and over 1 means puts lead. Use it on a coin, US stock or CME (Chicago futures exchange) future for a quick read of today's mood. Under the hood: it sums sixteen `options_flow` fields over today's bars. Each bar's flow counts over every expiry and over the same-day expiries alone (`dte: "0dte"`, [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It reads `option_contract_state.cells` on the live bar for the open interest through its `present` mask ([Data sources](../core-concepts/data-sources.md#option_contract_state), [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). It takes today's date and the same-day expiry from `optionsTradeDay` ([the options functions](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). It draws a `render.hud` card with no `look` word over data-only values and two text strings ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). This is also the `options-stats` template: the **Options Stats** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Options Stats: today's options trading on this symbol in one card, calls against puts. Calls are bets on a rise, and // puts are bets on a fall. The card first says which side leads, as in "Calls lead: put/call 0.62". The put/call ratio // is put contracts per call contract, so below 1 means calls lead. Then it shows today's call and put contracts and // their ratio. Next come the premium (money paid for options) on each side and its ratio. Net premium is calls bought // minus calls sold, minus puts bought minus puts sold. The bullish share is how much of today's bought or sold premium // bet on a rise. Last come open interest (contracts still open) on each side, its ratio and its change since yesterday. // Use it for a quick read of whether options traders lean up or down today. // // Under the hood: a card at the bottom of the pane says first which side leads (Calls lead: put/call 0.62), then // today's call and put contracts and their ratio, the premium of each side and its ratio, the net premium (calls bought // minus calls sold, minus puts bought minus puts sold, by premium at the ask and at the bid), the bullish share of the // premium that hit a side of the quote (calls at the ask and puts at the bid), and the open interest of each side with // its ratio and its change since the prior day. Contracts (coins on a crypto chain) and premium are the underlying's // option flow of each of today's bars, summed: every expiry, the same-day expiries (0DTE) or the ones after today. // Today is the trade date on the market's own clock. A bar with no flow row adds nothing. Open interest comes from the // chain summary on the newest bar, over the twelve nearest expiries and the strikes within 25% of the underlying (a // whole chain can hold more contracts than one read carries), its 0DTE on crypto the next 24 hours (dailies expire at // 08:00 UTC). Trade counts are not served. It reads the chart's own underlying (on an option contract's chart, the // contract's). Net premium and the bullish share count every print, cross trades and late prints too: the card says so. param.choice("expiries", ["every expiry", "0DTE only", "after today"], "every expiry", { label: "Expiries", description: "Which expiry dates count. 0DTE only keeps options that expire today, or within 24 hours on crypto. After today leaves those out." }); input("close", ohlcv.close); // the chart's own candles: the grid the flow lines up on // The underlying's option flow of each bar (the ticker scope), every expiry, then the same-day expiries alone. input("call_volume", options_flow.call_contracts_total, { missing: "nan" }); input("put_volume", options_flow.put_contracts_total, { missing: "nan" }); input("call_premium", options_flow.call_prem_total, { missing: "nan" }); input("put_premium", options_flow.put_prem_total, { missing: "nan" }); input("call_ask", options_flow.call_prem_ask, { missing: "nan" }); input("call_bid", options_flow.call_prem_bid, { missing: "nan" }); input("put_ask", options_flow.put_prem_ask, { missing: "nan" }); input("put_bid", options_flow.put_prem_bid, { missing: "nan" }); input("call_volume_0dte", options_flow.call_contracts_total, { dte: "0dte", missing: "nan" }); input("put_volume_0dte", options_flow.put_contracts_total, { dte: "0dte", missing: "nan" }); input("call_premium_0dte", options_flow.call_prem_total, { dte: "0dte", missing: "nan" }); input("put_premium_0dte", options_flow.put_prem_total, { dte: "0dte", missing: "nan" }); input("call_ask_0dte", options_flow.call_prem_ask, { dte: "0dte", missing: "nan" }); input("call_bid_0dte", options_flow.call_prem_bid, { dte: "0dte", missing: "nan" }); input("put_ask_0dte", options_flow.put_prem_ask, { dte: "0dte", missing: "nan" }); input("put_bid_0dte", options_flow.put_prem_bid, { dte: "0dte", missing: "nan" }); input("state", option_contract_state.cells, { max_cells: 16000, expiries: "nearest:12", strike_window_pct: 25, description: "This symbol's options summary on the newest bar: each contract's open interest and yesterday's. It covers the twelve nearest expiry dates and strikes within 25% of the price." }); // [root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present] per contract market.zone(); // the market's clock: today's trade date and the same-day expiries // The readings, data-only: today's sums through each bar; the open interest rows on the newest bar only. output("call_volume_today", none, overlay, { format: "si", description: "Call contracts (bets on a rise) traded today up to this bar, counted in coins on crypto" }); output("put_volume_today", none, overlay, { format: "si", description: "Put contracts (bets on a fall) traded today up to this bar, counted in coins on crypto" }); output("pc_volume", none, overlay, { format: "0.00", description: "Put contracts divided by call contracts today. Below 1 means calls lead." }); output("call_premium_today", none, overlay, { format: "usd", description: "Premium (money paid for options) traded on calls today, in USD" }); output("put_premium_today", none, overlay, { format: "usd", description: "Premium (money paid for options) traded on puts today, in USD" }); output("pc_premium", none, overlay, { format: "0.00", description: "Put premium divided by call premium today. Below 1 means more money went to calls." }); output("net_premium", none, overlay, { format: "usd", description: "Calls bought at the ask minus calls sold at the bid, less the same for puts, in USD. Includes cross and late trades" }); output("bull_share", none, overlay, { format: "%", decimals: 1, description: "The share of bought or sold premium that bet on a rise: calls bought plus puts sold, in percent" }); output("empty_bars", none, overlay, { description: "Bars today, up to this one, that had no options data" }); output("call_oi", none, overlay, { format: "si", description: "Call open interest (contracts still open) over the twelve nearest expiry dates and strikes within 25%. Counted in coins on crypto. Newest bar only." }); output("put_oi", none, overlay, { format: "si", description: "Put open interest (contracts still open) over the twelve nearest expiry dates and strikes within 25%. Counted in coins on crypto. Newest bar only." }); output("pc_oi", none, overlay, { format: "0.00", description: "Put open interest divided by call open interest. Newest bar only." }); output("oi_change", none, overlay, { format: "si", signed: true, description: "Open interest (contracts still open) now minus yesterday's, calls and puts together. Newest bar only." }); output("tone", none, overlay, { description: "Which side leads: 0 puts, 1 even or no reading, 2 calls" }); string("read", { max_bytes: 48 }); // the headline: which side leads, or why there is no reading string("title", { max_bytes: 48 }); // the card's title: the day and the expiries read render.hud("stats", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Who leads", "read", { headline: true }), tile.value("Call contracts", "call_volume_today", { format: "si" }), tile.value("Put contracts", "put_volume_today", { format: "si" }), tile.rows([ ["Put/call, contracts", "pc_volume", "0.00"], ["Call premium", "call_premium_today", "usd"], ["Put premium", "put_premium_today", "usd"], ["Put/call, premium", "pc_premium", "0.00"], ]), tile.rows("Includes cross and late trades", [ ["Net premium", "net_premium", "usd"], ["Bullish share", "bull_share", "%"], ]), tile.rows([ ["Open calls, 12 expiries", "call_oi", "si"], ["Open puts, 12 expiries", "put_oi", "si"], ["Put/call, open interest", "pc_oi", "0.00"], ["Open interest change", "oi_change", "si"], ]), ], }); const STATE = 13; // f64s per contract: OPTION_CONTRACT_STATE_TUPLE const EVEN_BAND = 0.1; // a put/call ratio within 10% of 1 reads even const MONTHS: StaticArray<string> = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const SCOPE_WORDS: StaticArray<string> = ["", ", 0DTE", ", after today"]; const dateClock = new Clock("UTC"); // a trade date's day and month let expiries = 0; // the setting, read in onStart() let zone = 0; // the market's clock, read in onStart() let day: f64 = NaN; // today's trade date on the market's clock, as a day number let callVolume = 0.0; // today's sums let putVolume = 0.0; let callPremium = 0.0; let putPremium = 0.0; let callAsk = 0.0; let callBid = 0.0; let putAsk = 0.0; let putBid = 0.0; let emptyBars = 0; function onStart(): void { expiries = i32(p_expiries()); zone = i32(p_market_zone()); } function ratio(top: f64, bottom: f64): f64 { return bottom > 0.0 ? top / bottom : NaN; } // A field under the expiries setting: every expiry, the same-day expiries, or every expiry minus them; a field the bar // carries no row for counts 0. function scoped(every: f64, sameDay: f64): f64 { const all = isNaN(every) ? 0.0 : every; const zero = isNaN(sameDay) ? 0.0 : sameDay; if (expiries == 1) return zero; if (expiries == 2) return all - zero > 0.0 ? all - zero : 0.0; return all; } // Whether a contract expiring at expiryMs counts: its same day is `today`, on crypto the next 24 hours from nowMs. function counts(expiryMs: f64, today: f64, nowMs: f64): bool { if (expiries == 0) return true; const sameDay = zone == 0 ? expiryMs > nowMs && expiryMs - nowMs <= 86400000.0 : optionsTradeDay(expiryMs, zone) == today; return expiries == 1 ? sameDay : !sameDay; } // The open interest rows from the chain summary on the newest bar. function writeOpenInterest(today: f64, nowMs: f64): void { const n = in_state_cells(); let callOi = 0.0; let putOi = 0.0; let change = 0.0; let changeSeen = false; let seen = false; if (n > 0) { const cells = in_state_view(); for (let i = 0; i + STATE - 1 < n; i += STATE) { const present = cells[i + 12]; if (!(cells[i + 3] > 0.0) || !counts(cells[i + 1], today, nowMs) || !hasBit(present, 10)) continue; // bit 10: the open interest seen = true; if (cells[i + 2] > 0.0) callOi += cells[i + 10]; else putOi += cells[i + 10]; if (hasBit(present, 11)) { // bit 11: the prior day's change += cells[i + 10] - cells[i + 11]; changeSeen = true; } } } out_call_oi(seen ? callOi : NaN); out_put_oi(seen ? putOi : NaN); out_pc_oi(seen ? ratio(putOi, callOi) : NaN); out_oi_change(changeSeen ? change : NaN); } // onBar() runs once per bar: a new trade date starts today's sums again; the bar's flow joins them; the readings on // every bar, the open interest, the headline and the title on the newest bar. function onBar(): void { const barMs = bar.time() * 1000.0; const today = optionsTradeDay(barMs, zone); if (today != day) { day = today; callVolume = 0.0; putVolume = 0.0; callPremium = 0.0; putPremium = 0.0; callAsk = 0.0; callBid = 0.0; putAsk = 0.0; putBid = 0.0; emptyBars = 0; } const calls = in_call_volume(); const puts = in_put_volume(); if (isNaN(calls) && isNaN(puts) && isNaN(in_call_volume_0dte()) && isNaN(in_put_volume_0dte())) emptyBars += 1; callVolume += scoped(calls, in_call_volume_0dte()); putVolume += scoped(puts, in_put_volume_0dte()); callPremium += scoped(in_call_premium(), in_call_premium_0dte()); putPremium += scoped(in_put_premium(), in_put_premium_0dte()); callAsk += scoped(in_call_ask(), in_call_ask_0dte()); callBid += scoped(in_call_bid(), in_call_bid_0dte()); putAsk += scoped(in_put_ask(), in_put_ask_0dte()); putBid += scoped(in_put_bid(), in_put_bid_0dte()); const pcVolume = ratio(putVolume, callVolume); const sidedPremium = callAsk + callBid + putAsk + putBid; out_call_volume_today(callVolume); out_put_volume_today(putVolume); out_pc_volume(pcVolume); out_call_premium_today(callPremium); out_put_premium_today(putPremium); out_pc_premium(ratio(putPremium, callPremium)); out_net_premium(callAsk - callBid - (putAsk - putBid)); out_bull_share(sidedPremium > 0.0 ? ((callAsk + putBid) / sidedPremium) * 100.0 : NaN); out_empty_bars(f64(emptyBars)); if (!bar.isLast()) { out_call_oi(NaN); out_put_oi(NaN); out_pc_oi(NaN); out_oi_change(NaN); out_tone(NaN); return; } writeOpenInterest(today, barMs); const traded = callVolume + putVolume > 0.0; out_tone(!traded ? 1.0 : isNaN(pcVolume) ? 0.0 : Math.abs(pcVolume - 1.0) <= EVEN_BAND ? 1.0 : pcVolume < 1.0 ? 2.0 : 0.0); // no call traded: the puts lead sb_clear(); if (!traded) sb_text("No contract traded yet today"); else if (isNaN(pcVolume)) sb_text("Puts only: no call traded yet"); else { sb_text(Math.abs(pcVolume - 1.0) <= EVEN_BAND ? "Even: put/call " : pcVolume < 1.0 ? "Calls lead: put/call " : "Puts lead: put/call "); sb_f64(pcVolume, 2); } str_read_sb(); dateClock.update(today * 86400.0); // a day number is its date at 00:00 UTC sb_clear(); sb_text("Options today, "); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); sb_text(SCOPE_WORDS[expiries]); str_title_sb(); } ``` ## How it works **Today's sums.** Each bar carries the underlying's option flow of that bar, split by calls and puts and by the side of the quote: the contracts, the premium, and the premium at the ask and at the bid, once over every expiry and once over the same-day expiries alone. Today is the trade date of the bar's open on the market's clock (`market.zone()`: the New York date on a US stock, the UTC day on crypto, the CME trade date that opens at 17:00 Chicago): on a new trade date every sum starts again, and each bar's flow joins them. A bar with no flow row (no print in it) adds nothing. **The expiries.** **Expiries** reads every expiry, only the contracts expiring today (`0DTE only`: the same-day fields), or the ones after today (every expiry minus the same-day fields, never below zero). The open interest rows follow the same choice, the same-day expiry being the one whose trade date on the same clock is today's; on crypto, whose dailies expire at 08:00 UTC, it is the one expiring within 24 hours of the newest bar, so after 08:00 the morning's expired daily leaves 0DTE and tomorrow's joins it. The flow's same-day fields are the data plane's own 0DTE bucket. **The sides of the quote.** The data plane judges each print against the national best bid and offer just before it, by the midpoint: above the mid it is at the ask, below it at the bid. On crypto and CME the venue names the taker's side instead: a print the taker bought is at the ask, one the taker sold at the bid, and none is at the mid. `net_premium` is the calls' premium at the ask minus at the bid, minus the puts' premium at the ask minus at the bid: calls bought and puts sold push it up. `bull_share` is the calls' premium at the ask plus the puts' at the bid, over all the premium at the ask or the bid, in percent; the mid and the unquoted prints count in neither. **The open interest.** On the live bar the chain summary carries each contract's open interest (`oi`, bit 10) and the prior observation (`oi_prev`, bit 11), over the twelve nearest expiries and the strikes within 25% of the underlying (`expiries: "nearest:12"`, `strike_window_pct: 25`, `max_cells: 16000`): a whole chain of a busy underlying holds more contracts than one read carries, so the rows say which expiries they cover. `call_oi` and `put_oi` sum the open interest of each side, `pc_oi` is their ratio, and `oi_change` sums the open interest now minus the prior observation over the contracts that carry both. **The headline.** The put/call ratio of contracts decides it: within 10% of 1 it reads "Even: put/call 1.03", below "Calls lead: put/call 0.62", above "Puts lead: put/call 1.43", and with puts traded but no call yet "Puts only: no call traded yet". `tone` carries the same answer as a number for the Console: 0 while the puts lead, 1 when even or with no reading, 2 while the calls lead. The title names today's date and the expiries read (`Options today, 16OCT, 0DTE`). **The card reads the outputs.** The headline pill over `read`, two tiles (call contracts and put contracts), then ten rows: the put/call ratio of contracts, call premium, put premium, the put/call premium ratio, the net premium, the bullish share, call open interest, put open interest, the put/call open interest ratio and the open interest change. Today's sums are outputs on every bar (`call_volume_today`, `put_volume_today`, `pc_volume`, `call_premium_today`, `put_premium_today`, `pc_premium`, `net_premium`, `bull_share`, and `empty_bars`, today's bars with no flow row), so the Console reads them through the day; the open interest rows are numbers on the live bar only. **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the line "Includes cross and late trades" over the net premium and bullish share rows, and the description of `net_premium`. ## What the settings do - **Expiries**: Every expiry, only 0DTE (options that expire today), or only those after today. - **Who leads**: Which side leads today by the put/call ratio of contracts, or why there is no reading yet. - **Call contracts**: Call contracts traded today, counted in coins on crypto. - **Put contracts**: Put contracts traded today, counted in coins on crypto. - **Put/call, contracts**: Put contracts divided by call contracts, so below 1 means calls lead. - **Call premium**: Money paid for calls today, in USD. - **Put premium**: Money paid for puts today, in USD. - **Put/call, premium**: Put premium divided by call premium. - **Net premium**: Calls bought minus calls sold, less the same for puts, in USD. - **Bullish share**: The share of bought or sold premium that bet on a rise, in percent. - **Open calls, 12 expiries**: Call open interest (contracts still open) over the twelve nearest expiry dates. - **Open puts, 12 expiries**: Put open interest over the twelve nearest expiry dates. - **Put/call, open interest**: Put open interest divided by call open interest. - **Open interest change**: Open interest now minus yesterday's, calls and puts together. ## Where it runs On crypto, it reads the coin's options on one exchange, usually Deribit. An exchange can list a coin's options in two sets, such as Deribit's BTC and BTC_USDC. It reads one set, the one named like the coin. A copy you run from the editor (where you write and run indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read this data. On a futures chart from CME, the Chicago exchange, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless you have real-time CME data. The chart's legend says which you see. Alerts, watches and Protected indicators (published ones that run on OpenMarket's servers) cannot read this data. They stop with an error that names it. On an option contract's chart, it reads the contract's stock or coin, so the card matches that symbol's chart. More than 16,000 contracts in the open interest summary stops the run rather than cutting data. ## When data is missing - **No options data.** A bar with no options data adds nothing to today's totals. In the Console (the editor's prompt that shows a reading by its name), `empty_bars` counts it. On a busy symbol, a run of such bars inside the session is a gap in the data. On a quiet one, it is a bar without a trade. - **No trade yet.** Before the first trade of the day, the headline reads "No contract traded yet today". - **No open interest summary.** Without it on the newest bar, the card's four open interest lines read `-`. ## Customize it - **The same-day crowd.** Set Expiries to 0DTE only on an index ETF: the ratio and the net premium of the contracts expiring today. - **The positioning that stays.** Set Expiries to after today to leave the same-day churn out of the ratios and the open interest. - **Another threshold.** Change `EVEN_BAND` (0.1) to widen or narrow the ratios the headline calls even. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options Stats** under **HUDs**. 2. Press **Run** on a BTC chart or on a US stock chart such as SPY: the card sits at the bottom centre, titled by today's date. On a US stock or a CME future the copy reads the chain at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `pc_volume` and `net_premium` to read today's put/call ratio and net premium through the newest bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` fields and their `dte` knob, and [`option_contract_state`](../core-concepts/data-sources.md#option_contract_state), its tuple and [its knobs](../core-concepts/data-sources.md#the-knobs), with [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit` - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, its tiles, the slot in the title and what a card with no `look` draws <!-- source: https://openmarket.xyz/wrun/cookbook/option-stance --> # Option stance Not a mood score: one card rates five common options trades With, Neutral or Against. The trades are selling options, betting option prices fall, buying for a move, buying long-dated and buying cheap far-out options. Stances weigh how pricey options are this past year and if dealers (the market makers who hedge options) calm price. Use it as a backdrop check before you trade options, not as a trade signal. It needs 60 trading days of data on a coin, a US stock or a CME (Chicago futures exchange) future. Under the hood: the volatility regime is the IV rank and percentile of the session's 30-day IV over the window. The positioning is dealer gamma on the open-interest basis, through the options kit's `dealerRegime`. Long gamma dampens moves, short gamma amplifies them, and exactly zero is neutral. It also reads spot against the data plane's gamma flip over all expiries, the gamma curve's zero nearest spot by the options kit's rule. The rest are the call and put walls, the put/call volume and open-interest ratios, the 25 delta risk reversal and the front expiry's implied move. It reads scalar `option_daily` inputs and the `market.earnings_next_ms()` fact through `earningsMs()` ([Earnings dates](../core-concepts/data-sources.md#earnings-dates)). It keeps the IV history in the options kit's `DayHistory` ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws a `render.hud` card of pill tiles, one per stance, in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `option-stance` template, the **Option Stance** card under **HUDs** in the editor's starter list, which compiles as written. ## The wrun indicator ```typescript // Option Stance: not a mood score. One card rates five common options trades With, Neutral or Against. The trades are // selling options, betting option prices fall, buying for a move, buying long-dated and buying cheap far-out options. // Implied volatility (how big a move option prices expect) sets how pricey options are. The card's IV rank says if it // is high or low against the past year. Dealers (the market makers who hedge options) can calm price or push it, and // the card says which. It also shows the call and put walls (the strikes with the most dealer hedging) and the put/call // ratios. Use it as a quick check of the backdrop before you trade options, not as a trade signal. // // Technical notes: one card over the daily options statistics (option_daily) and the issuer's next earnings date, // and which of five trade-idea stances that picture runs with. The volatility regime is the IV rank (where the // session's 30-day IV sits between the window's low and // high) and percentile; the positioning is dealer gamma on the open-interest basis (the regime the sign of net gamma, // the options kit's dealerRegime: long gamma dampens moves, short gamma amplifies them), spot against the data plane's // gamma flip over all expiries (the gamma curve's zero nearest spot, the options kit's rule), the call and put walls, // the put/call volume and open-interest // ratios, the 25 delta risk reversal and the front expiry's implied move. Each stance reads plain rules over those, and // the card says With, Neutral or Against for each: selling premium runs with a high IV rank, long dealer gamma and no // earnings report inside the earnings window, and against a low rank or a report inside it; selling vega with a high // rank and the term in contango, against a low rank; directional buying with short dealer gamma below a high rank, // against long gamma at a high rank; long-dated buying with a low rank, against a high one; cheap out-of-the-money // buying with a low rank and short gamma, against a high rank. The rules describe the regime, not a trade. The // statistics are short today (they start when the data plane switches the daily job on): the positioning reads from the // first session, but the IV rank, and with it every stance, needs Minimum history (60 sessions); until then the stances // read Needs history and the card says how many sessions there are. Crypto, CME and US stock charts, daily or finer. param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "How many past sessions (trading days) the IV rank and percentile compare today against. 252 is about a year." }); param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "How many sessions of daily data the IV rank needs before it shows. The five stances wait for it too." }); param.number("high_rank", 50, { min: 0, max: 100, step: 1, label: "High IV rank", description: "An IV rank (where IV sits in its past-year range) at or above this counts as high. Options are expensive then, which favors selling them." }); param.number("low_rank", 30, { min: 0, max: 100, step: 1, label: "Low IV rank", description: "An IV rank (where IV sits in its past-year range) at or below this counts as low. Options are cheap then, which favors buying them." }); param.int("earnings_days", 30, { min: 0, max: 120, label: "Earnings window, days", description: "An earnings report within this many days counts against selling premium (the money paid for an option). Earnings can jump the price." }); input("close", ohlcv.close); // the chart's own close: the grid input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of options at today's price, in percent, once per session (trading day)." }); // every daily input lands on the first bar of its day, NaN elsewhere input("iv90", option_daily.atm_iv_90d, { missing: "nan", description: "The 90-day IV (implied volatility) of options at today's price, in percent." }); input("rr25", option_daily.rr25_30d, { missing: "nan", description: "The 30-day risk reversal: the 25 delta call IV minus the 25 delta put IV, in volatility points. Positive means calls cost more." }); input("gex", option_daily.net_gex, { missing: "nan", description: "Dealers' net gamma over all expiries, in USD per 1% move. Gamma is how fast dealers (the market makers who hedge options) must hedge as price moves." }); input("flip", option_daily.gamma_flip, { missing: "nan", description: "The gamma flip over all expiries: the price nearest today's where dealer hedging turns from calming moves to pushing them." }); input("call_wall", option_daily.call_wall, { missing: "nan", description: "The call wall: the call strike with the most dealer hedging, often a ceiling." }); input("put_wall", option_daily.put_wall, { missing: "nan", description: "The put wall: the put strike with the most dealer hedging, often a floor." }); input("call_vol", option_daily.call_volume, { missing: "nan", description: "Calls traded per session (bets on a rise): contracts on US options and CME, coins on a crypto chain." }); input("put_vol", option_daily.put_volume, { missing: "nan", description: "Puts traded per session (bets on a fall): contracts on US options and CME, coins on a crypto chain." }); input("call_oi", option_daily.call_oi, { missing: "nan", description: "Call open interest (calls still open): contracts on US options and CME, coins on a crypto chain." }); input("put_oi", option_daily.put_oi, { missing: "nan", description: "Put open interest (puts still open): contracts on US options and CME, coins on a crypto chain." }); input("move", option_daily.implied_move_front, { missing: "nan", description: "The move the options price in for the nearest expiry, as a price distance." }); input("spot", option_daily.underlying_price, { missing: "nan", description: "The price of the stock, coin or future when the statistics were read." }); market.earnings_next_ms(); // the issuer's next earnings report, epoch ms (0 when the chart does not know it) output("iv_rank", none, overlay, { description: "Where the 30-day IV sits between the window's low (0) and high (100). Empty below Minimum history." }); output("iv_pct", none, overlay, { description: "The share of the window's earlier sessions with a lower 30-day IV, in percent." }); output("gex", none, overlay, { format: "usd", description: "Dealers' net gamma (how fast they must hedge as price moves), in USD per 1% move." }); output("gamma_code", none, overlay, { description: "Dealers' gamma side as a code. 0 short gamma (they push moves), 1 neutral (exactly zero), 2 long gamma (they calm moves)." }); output("flip_dist", none, overlay, { description: "How far today's price sits above (+) or below (-) the gamma flip over all expiries, in percent." }); output("wall_call", none, overlay, { format: "price", description: "The call wall: the call strike with the most dealer hedging." }); output("wall_put", none, overlay, { format: "price", description: "The put wall: the put strike with the most dealer hedging." }); output("pc_volume", none, overlay, { description: "Puts traded for each call traded. Above 1 means more puts." }); output("pc_oi", none, overlay, { description: "Open puts for each open call. Above 1 means more puts." }); output("rr25", none, overlay, { description: "The 30-day risk reversal: the 25 delta call IV minus the 25 delta put IV. Positive means calls cost more." }); output("move_pct", none, overlay, { description: "The move the options price in for the nearest expiry, in percent of the price." }); output("earnings_days", none, overlay, { description: "Days to the next earnings report. Empty when none is known." }); output("sell_premium", none, overlay, { description: "Selling premium (selling options for their price): 0 against, 1 neutral, 2 with. It reads 1 while the IV rank needs history." }); output("sell_vega", none, overlay, { description: "Selling vega (betting that option prices fall): 0 against, 1 neutral, 2 with." }); output("directional", none, overlay, { description: "Buying options for a price move: 0 against, 1 neutral, 2 with." }); output("long_dated", none, overlay, { description: "Buying options with a lot of time left: 0 against, 1 neutral, 2 with." }); output("cheap_options", none, overlay, { description: "Buying cheap options far from today's price: 0 against, 1 neutral, 2 with." }); output("status", none, overlay, { description: "0 the IV rank needs history, 1 every reading shows, 2 a chart coarser than a day. Empty before the first session." }); string("read", { max_bytes: 64 }); // the headline: the volatility regime string("gamma_text", { max_bytes: 48 }); // "Long gamma": the regime over all expiries, as the tile's label says; spot against the gamma flip has its own tile string("earnings_text", { max_bytes: 32 }); // "Earnings 28OCT, in 11 days" string("s_sell_premium", { max_bytes: 16 }); // each stance's word string("s_sell_vega", { max_bytes: 16 }); string("s_directional", { max_bytes: 16 }); string("s_long_dated", { max_bytes: 16 }); string("s_cheap_options", { max_bytes: 16 }); string("title", { max_bytes: 64 }); render.hud("stance_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Volatility", "read", { headline: true }), tile.pill("Gamma · all expiries", "gamma_text"), tile.value("vs gamma flip", "flip_dist", { format: "%" }), tile.pill("Sell premium", "s_sell_premium"), tile.pill("Sell vega", "s_sell_vega"), tile.pill("Directional", "s_directional"), tile.pill("Long-dated", "s_long_dated"), tile.pill("Cheap options", "s_cheap_options"), tile.pill("Earnings", "earnings_text"), tile.rows([ ["IV rank", "iv_rank", "0"], ["IV percentile", "iv_pct", "0"], ["Net gamma", "gex", "usd"], ["Call wall", "wall_call", "price"], ["Put wall", "wall_put", "price"], ["Put/call volume", "pc_volume", "0.00"], ["Put/call OI", "pc_oi", "0.00"], ["Risk reversal, 25 delta", "rr25", "0.00"], ["Next expiry move, %", "move_pct", "0.00"], ]), ], }); const DAY = 86400.0; const CAPACITY = 520; const WORDS: String[] = ["Against", "Neutral", "With"]; const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const ivs = new DayHistory(CAPACITY); // one 30-day IV per session const dateClock = new Clock("UTC"); let lookback = 252; // settings, read in onStart() let need = 60; let highRank = 50.0; let lowRank = 30.0; let earningsDays = 30.0; let nextEarningsMs: f64 = NaN; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let sessionDay: f64 = NaN; // the newest session, and what it carried, held let rankNow: f64 = NaN; let pctNow: f64 = NaN; let iv30: f64 = NaN; let iv90: f64 = NaN; let rr: f64 = NaN; let gex: f64 = NaN; let flip: f64 = NaN; let callWall: f64 = NaN; let putWall: f64 = NaN; let callVol: f64 = NaN; let putVol: f64 = NaN; let callOi: f64 = NaN; let putOi: f64 = NaN; let move: f64 = NaN; let spot: f64 = NaN; function onStart(): void { lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; highRank = p_high_rank(); lowRank = p_low_rank(); earningsDays = p_earnings_days(); nextEarningsMs = earningsMs(p_market_earnings_next_ms()); } function land(day: f64): void { sessionDay = day; iv30 = in_iv30(); iv90 = in_iv90(); rr = in_rr25(); gex = in_gex(); flip = in_flip(); callWall = in_call_wall(); putWall = in_put_wall(); callVol = in_call_vol(); putVol = in_put_vol(); callOi = in_call_oi(); putOi = in_put_oi(); move = in_move(); spot = in_spot(); if (iv30 > 0.0) ivs.push(day, iv30); const ready = ivs.span(lookback) >= need; rankNow = ready ? ivs.rank(lookback) : NaN; pctNow = ready ? ivs.percentile(lookback) : NaN; } function ratio(a: f64, b: f64): f64 { return b > 0.0 && !isNaN(a) ? a / b : NaN; } /** Days from the bar to the next earnings report; NaN when none is known or it has passed. */ function daysToEarnings(t: f64): f64 { if (isNaN(nextEarningsMs)) return NaN; const d = (nextEarningsMs - t * 1000.0) / (DAY * 1000.0); return d >= 0.0 ? d : NaN; } // ── The five stances, each 0 against, 1 neutral, 2 with; NaN while the IV rank needs history ── function sellPremium(t: f64): f64 { if (isNaN(rankNow)) return NaN; const e = daysToEarnings(t); const earningsSoon = !isNaN(e) && e <= earningsDays; if (rankNow <= lowRank || earningsSoon) return 0.0; return rankNow >= highRank && dealerRegime(gex) > 0.0 ? 2.0 : 1.0; } function sellVega(): f64 { if (isNaN(rankNow)) return NaN; if (rankNow <= lowRank) return 0.0; return rankNow >= highRank && iv90 >= iv30 ? 2.0 : 1.0; } function directional(): f64 { if (isNaN(rankNow) || isNaN(gex)) return NaN; const regime = dealerRegime(gex); if (regime > 0.0 && rankNow >= highRank) return 0.0; return regime < 0.0 && rankNow < highRank ? 2.0 : 1.0; } function longDated(): f64 { if (isNaN(rankNow)) return NaN; return rankNow <= lowRank ? 2.0 : rankNow >= highRank ? 0.0 : 1.0; } function cheapOptions(): f64 { if (isNaN(rankNow)) return NaN; if (rankNow >= highRank) return 0.0; return rankNow <= lowRank && dealerRegime(gex) < 0.0 ? 2.0 : 1.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function sbStance(code: f64): void { sb_clear(); if (isNaN(code)) sb_text("Needs history"); else sb_text(WORDS[i32(code)]); } function writeWords(coarse: bool, t: f64): void { const held = ivs.span(lookback); sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (isNaN(sessionDay)) sb_text("Waiting for the daily options statistics"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else if (isNaN(rankNow)) sb_text("No range: the IV has not moved in the window"); else { sb_text(rankNow >= highRank ? "High IV, rank " : rankNow <= lowRank ? "Low IV, rank " : "Middling IV, rank "); sb_f64(rankNow, 0); sb_text(", percentile "); sb_f64(pctNow, 0); } str_read_sb(); sb_clear(); if (coarse || isNaN(gex)) sb_text("No gamma reading"); else { const regime = dealerRegime(gex); sb_text(regime > 0.0 ? "Long gamma" : regime < 0.0 ? "Short gamma" : "Neutral gamma"); } str_gamma_text_sb(); sb_clear(); const e = daysToEarnings(t); if (isNaN(e)) sb_text("No report known"); else { sbDay(Math.floor(nextEarningsMs / (DAY * 1000.0))); sb_text(", in "); sb_int(i64(Math.floor(e))); sb_text(Math.floor(e) == 1.0 ? " day" : " days"); } str_earnings_text_sb(); sbStance(coarse ? NaN : sellPremium(t)); str_s_sell_premium_sb(); sbStance(coarse ? NaN : sellVega()); str_s_sell_vega_sb(); sbStance(coarse ? NaN : directional()); str_s_directional_sb(); sbStance(coarse ? NaN : longDated()); str_s_long_dated_sb(); sbStance(coarse ? NaN : cheapOptions()); str_s_cheap_options_sb(); sb_clear(); sb_text("Option stance"); if (!coarse && !isNaN(sessionDay)) { sb_text(", as of "); sbDay(sessionDay); } str_title_sb(); } // onBar() runs once per bar: the spacing, then the session's statistics when they land; every bar writes the held // readings and the stances, and the live bar the card's words. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; if (!coarse) { const day = Math.floor(t / DAY); const any = !isNaN(in_iv30()) || !isNaN(in_gex()) || !isNaN(in_spot()); if (any && (isNaN(sessionDay) || day >= sessionDay)) land(day); } const has = !coarse && !isNaN(sessionDay); out_iv_rank(has ? rankNow : NaN); out_iv_pct(has ? pctNow : NaN); out_gex(has ? gex : NaN); out_gamma_code(has && !isNaN(gex) ? 1.0 + dealerRegime(gex) : NaN); out_flip_dist(has && spot > 0.0 && flip > 0.0 ? (spot / flip - 1.0) * 100.0 : NaN); out_wall_call(has ? callWall : NaN); out_wall_put(has ? putWall : NaN); out_pc_volume(has ? ratio(putVol, callVol) : NaN); out_pc_oi(has ? ratio(putOi, callOi) : NaN); out_rr25(has ? rr : NaN); out_move_pct(has && spot > 0.0 && !isNaN(move) ? (move / spot) * 100.0 : NaN); out_earnings_days(daysToEarnings(t)); const sp = has ? sellPremium(t) : NaN; const sv = has ? sellVega() : NaN; const dr = has ? directional() : NaN; const ld = has ? longDated() : NaN; const co = has ? cheapOptions() : NaN; out_sell_premium(isNaN(sp) ? 1.0 : sp); out_sell_vega(isNaN(sv) ? 1.0 : sv); out_directional(isNaN(dr) ? 1.0 : dr); out_long_dated(isNaN(ld) ? 1.0 : ld); out_cheap_options(isNaN(co) ? 1.0 : co); out_status(coarse ? 2.0 : isNaN(sessionDay) ? NaN : ivs.span(lookback) >= need ? 1.0 : 0.0); if (bar.isLast()) writeWords(coarse, t); } ``` ## How it works **The five stances, by rule.** | Stance | With | Against | | --- | --- | --- | | Sell premium | IV rank at or over **High IV rank**, dealers long gamma, no earnings report within **Earnings window** | IV rank at or under **Low IV rank**, or a report within the window | | Sell vega | IV rank high and the 90-day IV at or over the 30-day (contango) | IV rank low | | Directional | dealers short gamma and the IV rank under high | dealers long gamma at a high IV rank | | Long-dated | IV rank low | IV rank high | | Cheap options | IV rank low and dealers short gamma | IV rank high | Anything else is **Neutral**. The weights a fit score would need are not public, so the card says which side of each rule the regime sits on instead of scoring contracts. **The positioning.** Every reading is the newest session's: net gamma's sign through `dealerRegime` (`gamma_code` is it plus 1: 0 short, 1 neutral, 2 long), spot over the gamma flip in percent (the data plane's, over all expiries; its own **vs gamma flip** tile, beside the **Gamma · all expiries** regime), the walls, the two put/call ratios, the risk reversal (call IV minus put IV) and the front move over the price. ## What the settings do - **Window, sessions**: How many past trading days today's implied volatility (how big a move option prices expect) is ranked against. 252 is about a year. - **Minimum history, sessions**: The IV rank and the five stances show only after this many trading days of data. - **High IV rank**: An IV rank at or above this counts as high, when options are expensive and selling them is favored. - **Low IV rank**: An IV rank at or below this counts as low, when options are cheap and buying them is favored. - **Earnings window, days**: A report within this many days counts against selling premium (the money paid for an option). Earnings can jump the price. - **Volatility**: Whether implied volatility is high, middling or low for the year, with its rank and percentile. - **Gamma · all expiries**: Whether dealers are in long gamma (dealers calm price), short gamma (dealers chase price) or neutral. - **vs gamma flip**: How far today's price sits from the gamma flip (the price where dealers switch from calming price to pushing it). - **Sell premium**: With, Neutral or Against for selling options, which pays when options are pricey and price stays calm. - **Sell vega**: Selling vega is a bet that option prices fall. This reads With, Neutral or Against for that bet. - **Directional**: With, Neutral or Against for buying options to catch a price move. - **Long-dated**: With, Neutral or Against for buying options with a lot of time left before they end. - **Cheap options**: With, Neutral or Against for buying cheap options far from today's price. - **Earnings**: The next earnings date and the days until it, or No report known. - **IV rank**: Where 30-day implied volatility sits between the window's low (0) and high (100). - **IV percentile**: The share of past trading days with lower implied volatility. - **Net gamma**: Dealers' net gamma in USD per 1% move: positive calms moves, negative pushes them. - **Call wall**: The call strike (the option's price level) with the most dealer hedging, often watched as a ceiling. - **Put wall**: The put strike with the most dealer hedging, often watched as a floor. - **Put/call volume**: Puts traded for each call: above 1 means more puts. - **Put/call OI**: Open puts for each open call, from open interest (contracts still held open). - **Risk reversal, 25 delta**: Calls' implied volatility minus puts', both a moderate distance (25 delta) from price. Positive means calls cost more. - **Next expiry move, %**: The move the options price in for the nearest expiry, in percent. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (where you write and run your own indicators) reads the same data. On a US stock chart, 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](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. The **Earnings** tile reads the chart's own earnings date for a US stock ([Earnings dates](../core-concepts/data-sources.md#earnings-dates)). Where the chart knows no date, it reads "No report known". ## When data is missing The daily data starts on the day OpenMarket began recording it. The dealer, wall and put/call readings show from the first trading day. The card's IV rank, and with it every stance, needs **Minimum history** (60 trading days). Until then each stance on the card reads **Needs history**. The card's headline reads "Not enough history yet: 12 of 60 sessions". An unknown earnings date reads "No report known" on the **Earnings** tile and never counts against a stance. Before the first trading day the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". US listed options' daily data through 2026-10-20 uses an older gamma flip rule and often has no flip. On those days the card's **vs gamma flip** tile stays empty ([Data sources](../core-concepts/data-sources.md#the-gamma-flip-and-older-rows)). ## Customize it - **Your own thresholds.** Move **High IV rank** and **Low IV rank** to where you sell and buy volatility. - **A wider earnings guard.** Set **Earnings window** to the expiries you trade. - **Another year.** `lookback` sets the sessions the IV rank reads. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Option Stance** under **HUDs**. 2. Press **Run** on a US stock's chart. 3. At the editor's Console prompt, type `iv_rank`, `sell_premium` and `earnings_days`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Earnings dates](../core-concepts/data-sources.md#earnings-dates) for `market.earnings_next_ms()` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card and its pills <!-- source: https://openmarket.xyz/wrun/cookbook/sentiment-gauge --> # Options sentiment gauge Against the past year, a dial reads fear (0) to greed (100) from this symbol's options and price. Heavy put buying (bets on a fall) and high implied volatility (how big a move option prices expect) mean fear. Six daily signals average into the dial: under 45 is fear, over 55 is greed. Use it to spot crowded fear or greed, not to time trades. It needs 30 trading days of data on a coin, a US stock or a CME (Chicago futures exchange) future. Under the hood: each of six inputs is scored by its percentile among the window's earlier sessions. The inputs are the put/call volume ratio, the put/call premium ratio, the 25 delta risk reversal and the 30-day IV. The others are the term's slope (the 90-day IV over the 30-day, minus 1) and momentum. Momentum is the close over its 125-day average, from the chart's own daily candles. The two put/call ratios and the 30-day IV score as 100 minus their percentile. The gauge is their mean once four of the six score. Under 25 is extreme fear, under 45 fear, to 55 neutral, to 75 greed, over 75 extreme greed. It reads scalar `option_daily` inputs and a `candles` stream of the chart's daily candles ([Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists)). It keeps one `DayHistory` per input ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws a step line with guides at the band edges and a `render.hud` card with a gauge tile ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)). It is also the `sentiment-gauge` template, the **Options Sentiment Gauge** card under **HUDs** in the editor's starter list, which compiles as written. ## The wrun indicator ```typescript // Options Sentiment Gauge: a dial from fear (0) to greed (100), against the past year, from options and price. Six // daily signals each score 0 (fear) to 100 (greed) against this symbol's own past. Heavy buying of puts (options that // pay when price falls) reads as fear. So does high implied volatility (how big a move option prices expect). Calls // (options that pay when price rises) costing more read as greed, and so does price above its 125-day average. The // gauge is the average of the signals that have a score, once four of the six do. Under 25 is extreme fear, under 45 // fear, 45 to 55 neutral, to 75 greed and over 75 extreme greed. On an index ETF it reads the whole market's mood. Use // it to spot crowded fear or greed, not as a timing signal. // // Technical notes: fear against greed on a 0 to 100 dial, read from the daily options statistics (option_daily) // and the chart's own price. Six inputs, each scored 0 (fear) to 100 (greed) by // where today sits among the window's earlier sessions (its percentile): the put/call volume ratio and the put/call // premium ratio (more puts reads as fear, so each scores 100 minus its percentile), the 25 delta risk reversal (calls // dearer reads as greed), the 30-day IV (a high IV reads as fear), the term's slope (the 90-day IV over the 30-day, // minus 1: contango reads as calm), and momentum (the close over its 125-day average, from the chart's own daily // candles). The gauge is the mean of the inputs that have a score, shown once at least four of the six have one: // under 25 extreme fear, under 45 fear, to 55 neutral, to 75 greed, over 75 extreme greed. A pane under the chart draws // it as a step line, with guides at the band edges, and a card at the bottom right reads the dial, // the band and each input's score. The statistics are short today (they start when the data plane switches the daily // job on): each options input needs Minimum history (30 sessions) of its own before it scores, and until four inputs // score the card says how many sessions there are. On an index ETF's chart the dial reads that market's mood. // Crypto, CME and US stock charts, daily or finer. param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "How many past sessions (trading days) each signal is ranked against. 252 is about a year." }); param.int("min_sessions", 30, { min: 10, max: 520, label: "Minimum history, sessions", description: "How many sessions of data a signal needs before it gets a score." }); param.int("momentum_days", 125, { min: 20, max: 250, label: "Momentum average, days", description: "How many daily closes the momentum signal averages. Price above that average reads as greed." }); input("close", ohlcv.close); // the chart's own close: the grid input("call_vol", option_daily.call_volume, { missing: "nan", description: "Calls traded per session (bets on a rise): contracts on US options and CME, coins on a crypto chain." }); // every daily input lands on the first bar of its day, NaN elsewhere input("put_vol", option_daily.put_volume, { missing: "nan", description: "Puts traded per session (bets on a fall): contracts on US options and CME, coins on a crypto chain." }); input("call_prem", option_daily.call_premium, { missing: "nan", description: "Money paid for calls in the session, in USD." }); input("put_prem", option_daily.put_premium, { missing: "nan", description: "Money paid for puts in the session, in USD." }); input("rr25", option_daily.rr25_30d, { missing: "nan", description: "The 30-day risk reversal: the 25 delta call IV minus the 25 delta put IV. Positive means calls cost more." }); input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of options at today's price, in percent." }); input("iv90", option_daily.atm_iv_90d, { missing: "nan", description: "The 90-day IV (implied volatility) of options at today's price, in percent." }); input("daily", candles.cells, { interval: "1d", bars: 400, description: "This chart's closed daily candles, for the momentum signal." }); // [offset_ms, open, high, low, close, volume] per candle, oldest first output("gauge", line, lower, { color: "theme.text", width: 2, step: true, label: "Sentiment", format: "0", description: "Fear (0) to greed (100): the average of the signals that have a score, once four of the six do." }); output("g75", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "75", description: "Above this line: extreme greed." }); output("g55", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "55", description: "Above this line: greed." }); output("g45", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "45", description: "Below this line: fear." }); output("g25", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "25", description: "Below this line: extreme fear." }); output("band", none, lower, { description: "The mood as a code: 0 extreme fear, 1 fear, 2 neutral, 3 greed, 4 extreme greed. It reads 2 while there is no gauge." }); output("s_pc_volume", none, lower, { description: "The put/call volume signal (puts traded for each call), scored 0 fear to 100 greed." }); output("s_pc_premium", none, lower, { description: "The put/call premium signal (money paid for puts against calls), scored 0 to 100." }); output("s_skew", none, lower, { description: "The risk reversal signal (calls priced over puts), scored 0 to 100." }); output("s_iv", none, lower, { description: "The IV level signal, scored 0 to 100: a high IV scores low, as fear." }); output("s_term", none, lower, { description: "The term slope signal (90-day IV over 30-day IV), scored 0 to 100." }); output("s_momentum", none, lower, { description: "The momentum signal (price against its average), scored 0 to 100." }); output("inputs", none, lower, { description: "How many of the six signals have a score, 0 to 6." }); output("sessions", none, lower, { description: "How many sessions (trading days) of daily data the gauge holds." }); output("status", none, lower, { description: "0 fewer than four signals have a score, 1 the gauge shows, 2 a chart coarser than a day." }); string("read", { max_bytes: 64 }); // the headline: the band and the number, or why there is none string("title", { max_bytes: 64 }); render.hud("sentiment_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Sentiment", "read", { headline: true }), tile.gauge("Fear to greed", "gauge", { min: 0, max: 100, format: "int" }), tile.rows([ ["Put/call volume", "s_pc_volume", "0"], ["Put/call premium", "s_pc_premium", "0"], ["Risk reversal", "s_skew", "0"], ["IV level", "s_iv", "0"], ["Term slope", "s_term", "0"], ["Momentum", "s_momentum", "0"], ["Signals scored", "inputs", "int"], ]), ], }); const DAY = 86400.0; const CAPACITY = 520; const MAX_CANDLES = 420; const BAND_WORDS: String[] = ["Extreme fear", "Fear", "Neutral", "Greed", "Extreme greed"]; const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const pcVolumes = new DayHistory(CAPACITY); // one reading per session and input const pcPremiums = new DayHistory(CAPACITY); const skews = new DayHistory(CAPACITY); const ivLevels = new DayHistory(CAPACITY); const slopes = new DayHistory(CAPACITY); const momenta = new DayHistory(CAPACITY); // one per daily candle const sessions = new DayHistory(CAPACITY); // every session that landed const days = new CandleList(MAX_CANDLES); // the chart's closed daily candles const dateClock = new Clock("UTC"); const scores = new StaticArray<f64>(6); // the six inputs' scores, blended on every bar let lookback = 252; // settings, read in onStart() let need = 30; let momentumDays = 125; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let lastCandleT: f64 = NaN; // the newest candle folded into the momentum history let sPcVolume: f64 = NaN; // the scores, held let sPcPremium: f64 = NaN; let sSkew: f64 = NaN; let sIv: f64 = NaN; let sTerm: f64 = NaN; let sMomentum: f64 = NaN; let gaugeNow: f64 = NaN; let scoring = 0; function onStart(): void { lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; momentumDays = i32(p_momentum_days()); } /** The input's score: its newest reading's percentile among the window's earlier ones (turned round when a high * reading means fear); NaN while it holds fewer than need readings. */ function scoreOf(h: DayHistory, fearHigh: bool): f64 { if (h.span(lookback) < need) return NaN; const p = h.percentile(lookback); if (isNaN(p)) return NaN; return fearHigh ? 100.0 - p : p; } function ratio(a: f64, b: f64): f64 { return b > 0.0 && !isNaN(a) ? a / b : NaN; } // ── Momentum: each closed daily candle's close over the average of the momentumDays closes ending at it ── function foldMomentum(): void { const n = days.count(); if (n == 0) return; const newestT = days.openSec(n - 1); if (newestT == lastCandleT) return; // Every candle closed since the last fold, oldest first. let first = n - 1; while (first > 0 && (isNaN(lastCandleT) || days.openSec(first - 1) > lastCandleT)) first -= 1; for (let i = first; i < n; i += 1) { if (i + 1 < momentumDays) continue; let sum = 0.0; for (let k = i + 1 - momentumDays; k <= i; k += 1) sum += days.close(k); const mean = sum / f64(momentumDays); const close = days.close(i); if (mean > 0.0 && close > 0.0) momenta.push(Math.floor(days.openSec(i) / DAY), close / mean - 1.0); } lastCandleT = newestT; sMomentum = scoreOf(momenta, false); } function land(day: f64): void { sessions.push(day, 1.0); pcVolumes.push(day, ratio(in_put_vol(), in_call_vol())); pcPremiums.push(day, ratio(in_put_prem(), in_call_prem())); skews.push(day, in_rr25()); const iv30 = in_iv30(); const iv90 = in_iv90(); ivLevels.push(day, iv30); slopes.push(day, iv30 > 0.0 && iv90 > 0.0 ? iv90 / iv30 - 1.0 : NaN); sPcVolume = scoreOf(pcVolumes, true); sPcPremium = scoreOf(pcPremiums, true); sSkew = scoreOf(skews, false); sIv = scoreOf(ivLevels, true); sTerm = scoreOf(slopes, false); } function blend(): void { let sum = 0.0; scoring = 0; scores[0] = sPcVolume; scores[1] = sPcPremium; scores[2] = sSkew; scores[3] = sIv; scores[4] = sTerm; scores[5] = sMomentum; for (let k = 0; k < 6; k += 1) { const s = scores[k]; if (isNaN(s)) continue; sum += s; scoring += 1; } gaugeNow = scoring >= 4 ? sum / f64(scoring) : NaN; } function bandOf(g: f64): f64 { if (isNaN(g)) return 2.0; if (g < 25.0) return 0.0; if (g < 45.0) return 1.0; if (g <= 55.0) return 2.0; if (g <= 75.0) return 3.0; return 4.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function writeWords(coarse: bool): void { sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (sessions.count() == 0) sb_text("Waiting for the daily options statistics"); else if (isNaN(gaugeNow) && sessions.count() < need) { sb_text("Not enough history yet: "); sb_int(sessions.count()); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else if (isNaN(gaugeNow)) { sb_text("Too few signals: "); sb_int(scoring); sb_text(" of 6 scored, 4 needed"); } else { sb_text(BAND_WORDS[i32(bandOf(gaugeNow))]); sb_text(", "); sb_f64(gaugeNow, 0); } str_read_sb(); sb_clear(); sb_text("Options sentiment"); if (!coarse && sessions.count() > 0) { sb_text(", as of "); sbDay(sessions.day(0)); } str_title_sb(); } // onBar() runs once per bar: the spacing; every closed daily candle into the momentum history; the session's statistics // when they land; then the blend, held on every bar. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; days.load(in_daily_view(), in_daily_cells(), t); if (!coarse) { foldMomentum(); const day = Math.floor(t / DAY); const any = !isNaN(in_call_vol()) || !isNaN(in_put_vol()) || !isNaN(in_iv30()) || !isNaN(in_rr25()); if (any && (sessions.count() == 0 || day >= sessions.day(0))) land(day); blend(); } out_g75(75.0); out_g55(55.0); out_g45(45.0); out_g25(25.0); out_gauge(coarse ? NaN : gaugeNow); out_band(coarse ? 2.0 : bandOf(gaugeNow)); out_s_pc_volume(coarse ? NaN : sPcVolume); out_s_pc_premium(coarse ? NaN : sPcPremium); out_s_skew(coarse ? NaN : sSkew); out_s_iv(coarse ? NaN : sIv); out_s_term(coarse ? NaN : sTerm); out_s_momentum(coarse ? NaN : sMomentum); out_inputs(coarse ? NaN : f64(scoring)); out_sessions(coarse ? NaN : f64(sessions.count())); out_status(coarse ? 2.0 : isNaN(gaugeNow) ? 0.0 : 1.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **A score per input.** Each input's reading joins its own `DayHistory` once per session; its score is `percentile()` over the window (or 100 minus it where a high reading means fear), once it holds **Minimum history** sessions. Momentum is measured on every closed daily candle, so it scores from the first bar. **The blend.** Equal weights over the inputs that score, shown once four do, so a dial never stands on one or two inputs. A missing input drops out instead of reading as neutral. ## What the settings do - **Window, sessions**: How many past trading days each signal is ranked against: 252 is about a year. - **Minimum history, sessions**: How many trading days of data each options signal needs before it gets a score. - **Momentum average, days**: How many daily closes the momentum signal averages: price above that average reads as greed. - **Sentiment**: The mood in words, from extreme fear to extreme greed, with the gauge's number. - **Fear to greed**: The gauge itself, from 0 (fear) to 100 (greed). - **Put/call volume**: The score for puts traded per call: more puts scores lower, as fear. - **Put/call premium**: The score for money paid on puts against calls: more on puts scores lower. - **Risk reversal**: The score for calls priced over puts: pricier calls score higher, as greed. - **IV level**: The score for 30-day implied volatility: high scores lower, as fear. - **Term slope**: The score for the term structure (near expiries' prices against far ones): 90-day over 30-day implied volatility. Far pricier than near is calm and scores higher, toward greed. - **Momentum**: The score for price against its 125-day average: above the average scores higher. - **Signals scored**: How many of the six signals have a score, out of 6. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (where you write and run your own indicators) reads the same data. On a US stock chart, every indicator that runs in your browser reads it. On an index ETF the dial shows the whole market's mood. 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](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. The daily candles are the chart's own. ## When data is missing The daily data starts on the day OpenMarket began recording it. So each options signal needs **Minimum history** (30 trading days) before it scores. Until four signals score, the dial stays empty. The card reads "Not enough history yet: 12 of 30 sessions" while the history is short. It reads "Too few signals: 3 of 6 scored, 4 needed" when the history is there but too few score. Before the first trading day the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". ## Customize it - **Another year.** `lookback` sets the sessions each percentile reads. - **Score sooner.** Lower **Minimum history**, knowing each score reads fewer sessions. - **Another momentum.** `momentum_days` of 50 reads a shorter trend. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Options Sentiment Gauge** under **HUDs**. 2. Press **Run** on SPY's chart for the market's mood, or any US stock's for its own. 3. At the editor's Console prompt, type `gauge`, `inputs` and `s_momentum`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) for the daily candles - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the gauge tile <!-- source: https://openmarket.xyz/wrun/cookbook/day-type --> # Day type Every 10 minutes the card reads Pinned (tight range), Trending (one way), Volatile (wide swings) or Unsettled (none of these). The card shows how often each state held 30 minutes to 2 hours later, and how far price moved. A dashed line marks the gamma flip, where dealers (options market makers) switch from calming price to pushing it. Two more mark the call and put walls (the strikes with the most dealer hedging). On a 10-minute or finer chart with live options, trade against Pinned moves and with Trending ones. Under the hood: it reads this symbol's price, its 1-day at-the-money implied volatility and the dealer gamma levels from the 10-minute options statistics. That is `option_stats_10m` with `missing: "nan"`, so each sample lands on its own bar ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It sizes each window's 1σ move with `oneSigmaMove` over the market's trading minutes. It counts the odds from outcomes in the loaded history rather than from a model. It draws the forward range as a box handle on the live bar ([Drawing objects](../presentation/drawing-objects.md)). It draws step lines for the walls and the gamma flip over all expiries, labelled `Gamma flip · all expiries`. It adds a ribbon shaded by state and a `render.hud` card. It is the `day-type` template: **Day Type** under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Day Type: what kind of session this is, and how often that kind has lasted. Every ten minutes it names a state from // the last hour of prices. Pinned: price stays in a narrow range. Trending: price keeps moving one way. Volatile: price // swings wide. Unsettled: none of these. Ranges are measured against the move option prices expect (one standard // deviation, the 1σ move). The card shows how often the state held 30 minutes to 2 hours later, and how far price // usually moved. A box ahead of the price shows that typical range. A dashed line marks the gamma flip, where dealers // (options market makers) switch from calming price to pushing it. Two more mark the call and put walls (the strikes // with the most dealer hedging). Use it to trade against moves on pinned days and follow them on trending days. // // Under the hood: the readings come from the 10-minute options statistics (option_stats_10m: the underlying's price, // its 1-day at-the-money IV and the dealer gamma levels every ten minutes, on the underlyings the data plane samples // that often). Each sample names a state from the last Window samples of the session: Volatile when the window's // high-low range is at least Volatile range times the window's 1σ move at the 1-day IV (the options kit's // oneSigmaMove over the market's trading minutes), Trending when the price kept going one way (its net move over the // path it took, at least Trend efficiency) over a range of at least Pinned range times that 1σ move, Pinned when the // range is under that, Unsettled otherwise. The odds that a state holds are counted, not modelled: every earlier // sample in the loaded history whose session reached 30, 60, 90 and 120 minutes further is an outcome, and the odds // are the share of those outcomes still in the same state, with the typical move (the mean absolute move, percent) // over the same horizons. The forward range is the price plus and minus the typical move at the longest horizon with // odds, boxed ahead of the live bar. The call wall, the put wall and the data plane's gamma flip over all expiries // (the gamma curve's zero nearest spot, the options kit's rule) ride the price as step lines, a ribbon under the // chart marks each sample's state in monochrome tiers (Pinned and Unsettled in the text colour, Trending muted, // Volatile in the grid colour), and a card at the bottom right reads the state, how firmly it holds (strong at 75% // over the next hour, moderate at 50%), the odds, the moves and the distance to each level. The state is inferred // from price and IV with the rules above; it is not a direction. The history is short today (the 10-minute statistics // start when the data plane switches the job on): odds need Minimum outcomes (20) per state and horizon, and until // then the card says how many there are. Charts of 10 minutes or finer on the sampled underlyings (every one whose // options quote live); an underlying with daily statistics (option_daily) and no 10-minute rows reads "No live option // quotes, daily numbers only". param.int("window_samples", 6, { min: 3, max: 18, label: "Window, samples", description: "How many 10-minute samples each state looks back over. 6 is the last hour." }); param.number("volatile_ratio", 1.5, { min: 0.5, max: 5, step: 0.1, label: "Volatile range", description: "A window is Volatile when its high-to-low range reaches this many 1σ moves. A 1σ move is one standard deviation, from the 1-day implied volatility (IV)." }); param.number("pinned_ratio", 0.6, { min: 0.1, max: 2, step: 0.05, label: "Pinned range", description: "A window is Pinned when its range stays under this many 1σ moves (one standard deviation, from the 1-day IV)." }); param.number("trend_efficiency", 0.6, { min: 0.1, max: 1, step: 0.05, label: "Trend efficiency", description: "A window is Trending when its net move, divided by the path it took, reaches this. Its range must not be Pinned." }); param.int("min_outcomes", 20, { min: 5, max: 500, label: "Minimum outcomes", description: "How many outcomes (earlier times the same state was seen) a state needs per horizon before its odds show." }); param.bool("show_levels", true, { label: "Levels", description: "Draw the call wall, the put wall and the gamma flip on the price chart." }); input("close", ohlcv.close); // the chart's own close: the grid input("spot", option_stats_10m.underlying_price, { missing: "nan", description: "This symbol's price at each 10-minute sample of the options statistics." }); // lands on the bar holding the sample, NaN elsewhere input("iv1d", option_stats_10m.atm_iv_1d, { missing: "nan", description: "The 1-day at-the-money implied volatility (IV), in percent. It sets each window's 1σ move." }); input("gex", option_stats_10m.net_gex, { missing: "nan", description: "Net gamma over all expiries: the dollars dealers must trade for each 1% move." }); input("flip", option_stats_10m.gamma_flip, { missing: "nan", description: "The gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); input("call_wall", option_stats_10m.call_wall, { missing: "nan", description: "The call wall: the call strike with the most dealer hedging, often a ceiling." }); input("put_wall", option_stats_10m.put_wall, { missing: "nan", description: "The put wall: the put strike with the most dealer hedging, often a floor." }); input("daily_spot", option_daily.underlying_price, { missing: "nan", description: "This symbol's price in the daily options statistics. Daily numbers with no 10-minute ones mean no live option quotes." }); // lands on the first bar of its UTC day, NaN elsewhere market.zone(); // the market's clock: the session a sample belongs to and the minutes a year the 1-day IV spans output("call_wall_line", line, overlay, { color: "theme.up", width: 1, step: true, label: "Call wall", format: "price", description: "The call wall, the call strike with the most dealer hedging. It holds until the next sample." }); output("put_wall_line", line, overlay, { color: "theme.down", width: 1, step: true, label: "Put wall", format: "price", description: "The put wall, the put strike with the most dealer hedging." }); output("flip_line", line, overlay, { color: "theme.muted", width: 1, step: true, line_style: "dashed", label: "Gamma flip · all expiries", format: "price", description: "The gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); output("ribbon", histogram, lower, { color_by: "state", colors: ["theme.text", "theme.muted", "theme.grid"], label: "State", format: "0", description: "1 on every bar with a state. Pinned and Unsettled use the text colour, Trending is muted, Volatile uses the grid colour." }); output("state", none, lower, { description: "0 Pinned, 1 Trending, 2 Volatile, 3 Unsettled. Blank until the session has enough samples." }); output("strength", none, lower, { description: "How firmly the state holds over the next hour: 0 weak, 1 moderate (50%), 2 strong (75%). Blank without odds." }); output("odds_30", none, lower, { format: "%", description: "How often this state was still in place 30 minutes later, in percent of earlier outcomes." }); output("odds_60", none, lower, { format: "%", description: "The same, 60 minutes later." }); output("odds_90", none, lower, { format: "%", description: "The same, 90 minutes later." }); output("odds_120", none, lower, { format: "%", description: "The same, 120 minutes later." }); output("move_30", none, lower, { description: "The typical move 30 minutes after this state, up or down, in percent." }); output("move_60", none, lower, { description: "The same, 60 minutes later, in percent." }); output("move_90", none, lower, { description: "The same, 90 minutes later, in percent." }); output("move_120", none, lower, { description: "The same, 120 minutes later, in percent." }); output("range_ratio", none, lower, { description: "The window's high-to-low range divided by its 1σ move from the 1-day IV." }); output("efficiency", none, lower, { description: "The window's net move divided by the path it took, 0 to 1. Near 1 means price went one way." }); output("gex", none, lower, { format: "usd", description: "Net gamma over all expiries at the sample, in dollars per 1% move." }); output("dist_call", none, lower, { description: "How far the call wall sits from the price, in percent. Positive means above." }); output("dist_put", none, lower, { description: "How far the put wall sits from the price, in percent. Negative means below." }); output("dist_flip", none, lower, { description: "How far the gamma flip sits from the price, in percent. Positive means above." }); output("outcomes", none, lower, { description: "How many outcomes the state has at 60 minutes." }); output("status", none, lower, { description: "0 waiting for samples or outcomes, 1 the odds show, 2 the chart is coarser than 10 minutes." }); string("read", { max_bytes: 64 }); // the headline: the state and how firmly it holds string("odds_text", { max_bytes: 64 }); // the odds, or why there are none string("title", { max_bytes: 64 }); handles.box({ opacity: 0.18, borderWidth: 1 }); // the forward range, boxed ahead of the live bar render.hud("day_type_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("State", "read", { headline: true }), tile.pill("Holds", "odds_text"), tile.rows([ ["Holds 30 min", "odds_30", "%"], ["Holds 1 hour", "odds_60", "%"], ["Holds 90 min", "odds_90", "%"], ["Holds 2 hours", "odds_120", "%"], ["Typical move, 1 hour, %", "move_60", "0.00"], ["Typical move, 2 hours, %", "move_120", "0.00"], ["To call wall, %", "dist_call", "0.00"], ["To put wall, %", "dist_put", "0.00"], ["To gamma flip, %", "dist_flip", "0.00"], ["Net gamma, all expiries", "gex", "usd"], ]), ], }); const DAY = 86400.0; const SAMPLE_SEC = 600.0; // the statistics' cadence const MAX_SESSION = 144; // samples a session can hold: crypto's 24-hour UTC day (09:30 to 16:15 New York is 41) const STATES = 4; const HORIZONS = 4; const HORIZON_MIN: StaticArray<f64> = [30.0, 60.0, 90.0, 120.0]; const STATE_WORDS: String[] = ["Pinned", "Trending", "Volatile", "Unsettled"]; const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const sesT = new StaticArray<f64>(MAX_SESSION); // the session's samples: time, price, state const sesP = new StaticArray<f64>(MAX_SESSION); const sesS = new StaticArray<f64>(MAX_SESSION); const outcomeN = new StaticArray<f64>(STATES * HORIZONS); // per state and horizon: outcomes, held, the moves summed const outcomeHeld = new StaticArray<f64>(STATES * HORIZONS); const outcomeMove = new StaticArray<f64>(STATES * HORIZONS); const rangeBox = draw.box(0); const dateClock = new Clock("UTC"); let windowN = 6; // settings, read in onStart() let volatileRatio = 1.5; let pinnedRatio = 0.6; let trendEfficiency = 0.6; let minOutcomes = 20; let showLevels = true; let zone = 0; // the market's clock, read in onStart() let minutesYear = 98280.0; // the year the 1-day IV is scaled over, in the market's trading minutes, read in onStart() let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let sesDay: f64 = NaN; // the session the arrays hold let sesN = 0; let stateNow: f64 = NaN; // the newest sample's readings, held let ratioNow: f64 = NaN; let effNow: f64 = NaN; let lastT: f64 = NaN; let lastP: f64 = NaN; let gex: f64 = NaN; let flip: f64 = NaN; let callWall: f64 = NaN; let putWall: f64 = NaN; let dailyRows = false; // a daily statistics row landed on a loaded bar: the underlying has daily numbers function onStart(): void { windowN = i32(p_window_samples()); volatileRatio = p_volatile_ratio(); pinnedRatio = p_pinned_ratio(); trendEfficiency = p_trend_efficiency(); minOutcomes = i32(p_min_outcomes()); showLevels = p_show_levels() > 0.5; zone = i32(p_market_zone()); // 365 days of 1,440 minutes on crypto (zone 0), 252 Globex sessions of 1,380 on CME (zone 2), 252 sessions of 390 // regular-hours minutes on a US stock. minutesYear = zone == 0 ? 525600.0 : zone == 2 ? 347760.0 : 98280.0; } /** The trade date a bar's time belongs to on the market's own clock: the UTC day on crypto, the New York date on a US * stock, the CME trade day that opens at 17:00 Chicago on CME, so a Globex session is never split at midnight. */ function sessionOf(t: f64): f64 { return sessionTradeDate(t, zone, zone == 2 ? 1020.0 : 0.0); } /** The state of the window ending at the newest sample (the rules in the header); NaN while it fills. */ function classify(iv: f64): f64 { ratioNow = NaN; effNow = NaN; if (sesN < windowN || !(iv > 0.0)) return NaN; const first = sesN - windowN; let lo = sesP[first]; let hi = lo; let path = 0.0; for (let k = first + 1; k < sesN; k += 1) { const p = sesP[k]; if (p < lo) lo = p; if (p > hi) hi = p; path += Math.abs(p - sesP[k - 1]); } const last = sesP[sesN - 1]; const minutes = (sesT[sesN - 1] - sesT[first]) / 60.0; const sigma = oneSigmaMove(last, iv / 100.0, minutes / minutesYear); // the window's 1σ move, over the market's trading minutes if (!(sigma > 0.0)) return NaN; ratioNow = (hi - lo) / sigma; effNow = path > 0.0 ? Math.abs(last - sesP[first]) / path : 0.0; if (ratioNow >= volatileRatio) return 2.0; if (ratioNow < pinnedRatio) return 0.0; if (effNow >= trendEfficiency) return 1.0; return 3.0; } /** Each earlier sample of the session exactly a horizon before the newest is an outcome of its state. */ function recordOutcomes(): void { const t = sesT[sesN - 1]; const p = sesP[sesN - 1]; const s = sesS[sesN - 1]; for (let k = sesN - 2; k >= 0; k -= 1) { const ago = (t - sesT[k]) / 60.0; if (ago > HORIZON_MIN[HORIZONS - 1]) break; const was = sesS[k]; if (isNaN(was) || isNaN(s)) continue; for (let h = 0; h < HORIZONS; h += 1) { if (Math.abs(ago - HORIZON_MIN[h]) > 0.5) continue; const at = i32(was) * HORIZONS + h; outcomeN[at] += 1.0; if (was == s) outcomeHeld[at] += 1.0; outcomeMove[at] += Math.abs(p / sesP[k] - 1.0) * 100.0; } } } function addSample(t: f64, p: f64, iv: f64): void { const day = sessionOf(t); if (day != sesDay) { sesDay = day; sesN = 0; } if (sesN >= MAX_SESSION) return; if (sesN > 0 && t <= sesT[sesN - 1]) return; // a sample the session already holds sesT[sesN] = t; sesP[sesN] = p; sesN += 1; const s = classify(iv); sesS[sesN - 1] = s; stateNow = s; lastT = t; lastP = p; recordOutcomes(); } function odds(h: i32): f64 { if (isNaN(stateNow)) return NaN; const at = i32(stateNow) * HORIZONS + h; return outcomeN[at] >= f64(minOutcomes) ? outcomeHeld[at] / outcomeN[at] : NaN; } function typicalMove(h: i32): f64 { if (isNaN(stateNow)) return NaN; const at = i32(stateNow) * HORIZONS + h; return outcomeN[at] >= f64(minOutcomes) ? outcomeMove[at] / outcomeN[at] : NaN; } function strengthOf(): f64 { const o = odds(1); if (isNaN(o)) return NaN; return o >= 0.75 ? 2.0 : o >= 0.5 ? 1.0 : 0.0; } function distance(level: f64): f64 { return lastP > 0.0 && level > 0.0 ? (level / lastP - 1.0) * 100.0 : NaN; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function sbPct(v: f64): void { // "71%" sb_f64(v * 100.0, 0); sb_text("%"); } function writeWords(coarse: bool): void { sb_clear(); const strength = strengthOf(); if (coarse) sb_text("Needs a 10-minute or finer chart"); else if (isNaN(lastT) && dailyRows) sb_text("No live option quotes, daily numbers only"); // daily rows, no 10-minute row loaded else if (isNaN(lastT)) sb_text("Waiting for the 10-minute options statistics"); else if (isNaN(stateNow)) { sb_text("Window filling: "); sb_int(sesN); sb_text(" of "); sb_int(windowN); sb_text(" samples this session"); } else { sb_text(STATE_WORDS[i32(stateNow)]); if (!isNaN(strength)) sb_text(strength == 2.0 ? ", holds strongly" : strength == 1.0 ? ", holds moderately" : ", holds weakly"); } str_read_sb(); sb_clear(); const n60 = isNaN(stateNow) ? 0.0 : outcomeN[i32(stateNow) * HORIZONS + 1]; if (coarse || isNaN(stateNow)) sb_text("No odds"); else if (isNaN(odds(1))) { sb_text("Not enough history yet: "); sb_int(i64(n60)); sb_text(" of "); sb_int(minOutcomes); sb_text(" outcomes"); } else { sb_text("30 min: "); if (isNaN(odds(0))) sb_text("-"); else sbPct(odds(0)); sb_text(", 1 hour: "); sbPct(odds(1)); sb_text(", 2 hours: "); if (isNaN(odds(3))) sb_text("-"); else sbPct(odds(3)); } str_odds_text_sb(); sb_clear(); sb_text("Day type"); if (!coarse && !isNaN(lastT)) { sb_text(", "); sbDay(Math.floor(lastT / DAY)); dateClock.update(lastT); sb_text(" "); if (dateClock.hour() < 10) sb_text("0"); sb_int(dateClock.hour()); sb_text(":"); if (dateClock.minute() < 10) sb_text("0"); sb_int(dateClock.minute()); sb_text(" UTC"); } str_title_sb(); } /** The forward range: the price plus and minus the typical move at the longest horizon with odds, from the live bar * to that horizon ahead; deleted without one. */ function drawRange(t: f64): void { let h = HORIZONS - 1; while (h >= 0 && isNaN(typicalMove(h))) h -= 1; if (h < 0 || !(lastP > 0.0)) { rangeBox.delete(); // every coordinate must be finite: no range, no box return; } const m = typicalMove(h) / 100.0; const ink = theme.MUTED; // the state is a word on the card, never a colour rangeBox.set(t, lastP * (1.0 + m), t + HORIZON_MIN[h] * 60.0, lastP * (1.0 - m)).fill(ink).color(ink).opacity(0.18).border(1.0); } // onBar() runs once per bar: the spacing, a daily row when one lands, then the 10-minute sample when it lands (its // state, the outcomes it settles, the levels); every bar writes the held readings, and the live bar boxes the forward // range and writes the card. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > SAMPLE_SEC + 1.0; if (!isNaN(in_daily_spot())) dailyRows = true; const p = in_spot(); if (!coarse && !isNaN(p) && p > 0.0) { addSample(t, p, in_iv1d()); gex = in_gex(); flip = in_flip(); callWall = in_call_wall(); putWall = in_put_wall(); } const levels = showLevels && !coarse; out_call_wall_line(levels ? callWall : NaN); out_put_wall_line(levels ? putWall : NaN); out_flip_line(levels ? flip : NaN); const live = !coarse && !isNaN(stateNow) && sessionOf(t) == sesDay; out_ribbon(live ? 1.0 : NaN); out_state(live ? stateNow : NaN); out_strength(live ? strengthOf() : NaN); // The odds are a share; the outputs and the card's rows read them in percent. out_odds_30(live ? odds(0) * 100.0 : NaN); out_odds_60(live ? odds(1) * 100.0 : NaN); out_odds_90(live ? odds(2) * 100.0 : NaN); out_odds_120(live ? odds(3) * 100.0 : NaN); out_move_30(live ? typicalMove(0) : NaN); out_move_60(live ? typicalMove(1) : NaN); out_move_90(live ? typicalMove(2) : NaN); out_move_120(live ? typicalMove(3) : NaN); out_range_ratio(live ? ratioNow : NaN); out_efficiency(live ? effNow : NaN); out_gex(coarse ? NaN : gex); out_dist_call(coarse ? NaN : distance(callWall)); out_dist_put(coarse ? NaN : distance(putWall)); out_dist_flip(coarse ? NaN : distance(flip)); out_outcomes(live ? outcomeN[i32(stateNow) * HORIZONS + 1] : NaN); out_status(coarse ? 2.0 : live && !isNaN(odds(1)) ? 1.0 : 0.0); if (bar.isLast()) { writeWords(coarse); if (live) drawRange(t); else rangeBox.delete(); } } ``` ## How it works **The window's 1σ move.** Over a window of n samples the price moves for (n - 1) times 10 minutes; the window's one-standard-deviation move at the 1-day IV is the options kit's `oneSigmaMove(price, IV, minutes / year)`, `price x IV x sqrt(minutes / year)`, named the 1σ move and never the expected move (which every OpenMarket card reserves for 0.85 of the at-the-money straddle), the year being the minutes the market trades in one, by its clock (`market.zone()`): 98,280 on a US stock (252 sessions of 390 minutes), 347,760 on a CME future (252 Globex sessions of 1,380) and 525,600 on crypto (365 days of 1,440). **Outcomes settle on the later sample.** When a sample arrives, each sample of the same session exactly 30, 60, 90 or 120 minutes before it becomes an outcome of that sample's state: held when the two states match, with the absolute move between them. So the odds on any bar use only what had happened by then. A session is the market's trade date (`sessionTradeDate`): the UTC day on crypto, the New York date on a US stock and the CME trade day that opens at 17:00 Chicago, so a Globex night is never split at midnight. A session holds up to 144 samples, a whole day of them. **Strength.** The share of outcomes that held an hour on: strong at 75% and over, moderate at 50%, weak under. ## What the settings do - **Window, samples**: how many 10-minute samples each state looks back over, 6 by default (the last hour). - **Volatile range**: the window is Volatile when its high-to-low range reaches this many 1σ moves, 1.5 by default. A 1σ move is one standard deviation of the move option prices expect. - **Pinned range**: the window is Pinned when its range stays under this many 1σ moves, 0.6 by default. - **Trend efficiency**: the window is Trending when its net move divided by the path it took reaches this, 0.6 by default. - **Minimum outcomes**: how many earlier cases of a state each horizon needs before its odds show, 20 by default. - **Levels**: draws the call and put walls (the strikes with the most dealer hedging) and the gamma flip on price. - **State**: the session's state now, and how firmly it tends to hold. - **Holds**: how often this state was still in place 30 minutes, 1 hour and 2 hours later. - **Holds 30 min**: the share of earlier cases still in this state 30 minutes later. - **Holds 1 hour**: the same share 1 hour later. - **Holds 90 min**: the same share 90 minutes later. - **Holds 2 hours**: the same share 2 hours later. - **Typical move, 1 hour, %**: how far price usually moved, up or down, in the hour after this state. - **Typical move, 2 hours, %**: how far price usually moved over the 2 hours after this state. - **To call wall, %**: how far the call wall sits from the price. - **To put wall, %**: how far the put wall sits from the price. - **To gamma flip, %**: how far the gamma flip sits from the price. - **Net gamma, all expiries**: the dollars dealers (the market makers who hedge options) must trade for each 1% move. Above zero, their hedging calms price. ## Where it runs It needs a chart of 10 minutes or finer. The 10-minute options statistics cover every symbol whose options quote live. On CME (Chicago futures exchange) they cover each futures contract whose options quote live. Other contracts have daily numbers only. Any other symbol has no 10-minute numbers, and the indicator's legend on the chart says so. On a crypto chart the chart reads the coin's own options statistics. So does a copy you run from the editor (where you write and run your own indicators). On a US stock chart every indicator in the browser can read them. They run 15 minutes behind unless you have real-time US options data. On a CME futures chart every indicator in the browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). They run 10 minutes behind unless you have real-time CME data. On a US stock the statistics come from delayed quotes. So the newest sample trails the market by about 15 minutes. ## When data is missing The 10-minute statistics start on the day OpenMarket began recording them, so the odds need history. Each state needs **Minimum outcomes** (20) at a horizon before its odds show. Until then the card's **Holds** line reads "Not enough history yet: 7 of 20 outcomes". Early in each session the window needs its samples first. Then the card's **State** line reads "Window filling: 3 of 6 samples this session". Before the first sample the card reads "Waiting for the 10-minute options statistics". It reads "No live option quotes, daily numbers only" when the symbol has daily statistics but no 10-minute ones. That means its options do not quote live. A chart coarser than 10 minutes reads "Needs a 10-minute or finer chart". Older 10-minute statistics follow an earlier gamma flip rule and often have no flip. The gamma flip line stays empty there. That covers US listed options before 2026-10-20, CME before 2026-10-21 12:10 UTC and a few coins' options ([Data sources](../core-concepts/data-sources.md#the-gamma-flip-and-older-rows)). ## Customize it - **A longer or shorter look.** `window_samples` of 3 reads the last half hour, 12 the last two hours. - **Your own edges.** **Volatile range**, **Pinned range** and **Trend efficiency** move the rules. - **Odds sooner.** Lower **Minimum outcomes**, knowing the counts are thinner. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Day Type** under **HUDs**. 2. Press **Run** on BTCUSDT's 5-minute chart. 3. At the editor's Console prompt, type `state`, `odds_60` and `move_60`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_stats_10m` - [Drawing objects](../presentation/drawing-objects.md) for the forward range's box - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/dealer-positioning --> # Estimated dealer positioning Every 10 minutes this card estimates whether dealers (the market makers who hedge options) calm price or push it. Long gamma (dealers calm price) tends to fade moves, and short gamma (dealers chase price) lets them run. A dashed line marks the gamma flip (the price where dealers switch from calming price to pushing it). Two more lines mark the call and put walls (the strikes with the most dealer hedging). On a 10-minute or finer chart with live options, use it to judge whether a move fades or runs. Under the hood: the card reads the 10-minute options statistics (`option_stats_10m`). They carry net gamma per 1% move, charm, vanna, the walls, the gamma flip over all expiries and the magnet. They follow the open-interest model, where dealers are long the calls and short the puts. It also reads today's trades on this symbol (`options_flow`): delta bought at the ask minus delta sold at the bid. Dealers take the other side, so the book is an estimate and never an observed position ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It keeps each sample by its 10-minute time in a [`DayHistory`](../functions/options-kit.md#a-history-of-daily-statistics). It reads the point value and clock through [`market.notional()`](../settings/sessions-and-units.md#size-units) and the market type through [`market.kind()`](../settings/sessions-and-units.md#the-markets-facts). It draws two named [panes](../presentation/plotting.md#panes) and a [`render.hud`](../presentation/hud-and-hover-cards.md#hud-cards) card. It is the `dealer-positioning` template: **Estimated Dealer Positioning** under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Estimated Dealer Positioning: every 10 minutes, will dealers (the market makers who hedge options) calm price or push // it? Gamma (how fast dealers must hedge as price moves) decides which. Long gamma (dealers calm price): they sell // rallies and buy dips, so price tends to calm. Short gamma (dealers chase price): they buy rallies and sell dips, so // price tends to trend. Lines on price mark the call and put walls (the strikes with the most dealer hedging). They // often act as a ceiling and a floor. A dashed line marks the gamma flip (the price where dealers switch from calming // price to pushing it). The magnet line marks the strike with the most dealer gamma, which tends to pull price. Two // panes under the chart track net gamma and the position today's options trades left dealers holding. Use it to judge // whether a move is likely to fade or run. Dealers' positions are an estimate from open interest (contracts still held // open) and today's trades, never seen directly. // // Under the hood: dealers' positions are not observed. The book is the open-interest model of the 10-minute options // statistics (option_stats_10m: dealers long the calls and short the puts, net gamma in USD per 1% move, charm in // dollar delta per day, vanna in dollar delta per volatility point, the walls, the gamma flip and the magnet), and // today's flow assumes dealers took the other side of every print at the ask or at the bid (options_flow on the // chart's underlying: the share delta bought at the ask minus the share delta sold at the bid, summed since the // session's first bar in view). From those the card reads: the gamma regime (the sign of net gamma, the options kit's // dealerRegime) and the hedge it implies (long gamma sells a rally and buys a drop, short gamma chases both), the // hedge per 1% move, the charm drift to the close (16:00 New York, the next day's from the evening session of a CME // index future; no close, so no drift, on any other CME root; on crypto the end of the UTC day), the hedge a // one-point IV drop calls for through vanna, the dealer delta today's flow left behind (in USD through the market's // point value), and net gamma against 10, 20 and 30 minutes ago and its percentile among the window's samples. A pane // under the chart draws net gamma as a step line, in the up colour when dealers are long gamma and the down colour // when short, and a second pane the dealer delta from today's flow; the walls, the data plane's gamma flip over all // expiries (the gamma curve's zero nearest spot, the options kit's rule) and the magnet ride the price. The history // is short today (the 10-minute statistics start when the data plane switches the job on): the percentile needs // Minimum history (40 samples, about a US session, under seven hours on crypto and CME, which trade around the // clock), and until then the card says how many there are. Charts of 10 minutes or finer on the underlyings the data // plane samples every ten minutes (every one whose options quote live, a coin from when its samples start); an // underlying with daily statistics (option_daily) and no 10-minute rows reads "No live option quotes, daily numbers // only". param.int("lookback", 400, { min: 40, max: 2000, label: "Window, samples", description: "How many past 10-minute samples the percentile ranks net gamma against. 400 is about ten US sessions, under three days on crypto and CME." }); param.int("min_samples", 40, { min: 10, max: 2000, label: "Minimum history, samples", description: "How many samples the percentile needs before it shows." }); param.bool("show_levels", true, { label: "Levels", description: "Draw the walls, the gamma flip and the magnet on price. The call and put walls are the strikes with the most dealer hedging. The magnet is the strike with the most dealer gamma, which tends to pull price." }); input("close", ohlcv.close); // the chart's own close: the grid input("gex", option_stats_10m.net_gex, { missing: "nan", description: "Net gamma: the dollars dealers must trade for each 1% move, from the options statistics every ten minutes." }); // lands on the bar holding the sample, NaN elsewhere input("charm", option_stats_10m.net_charm, { missing: "nan", description: "Net charm: how far the dealers' hedge drifts each day as time passes, in dollars." }); input("vanna", option_stats_10m.net_vanna, { missing: "nan", description: "Net vanna: how far the dealers' hedge shifts for each point of implied volatility, in dollars." }); input("call_wall", option_stats_10m.call_wall, { missing: "nan", description: "The call wall: the strike with the most call gamma, often a ceiling." }); input("put_wall", option_stats_10m.put_wall, { missing: "nan", description: "The put wall: the strike with the most put gamma, often a floor." }); input("flip", option_stats_10m.gamma_flip, { missing: "nan", description: "The gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); input("magnet", option_stats_10m.gamma_magnet, { missing: "nan", description: "The magnet: the strike with the most dealer gamma, which tends to pull price." }); input("spot", option_stats_10m.underlying_price, { missing: "nan", description: "This symbol's price when the sample was taken." }); input("daily_spot", option_daily.underlying_price, { missing: "nan", description: "This symbol's price in the daily options statistics. Daily numbers with no 10-minute ones mean no live option quotes." }); // lands on the first bar of its UTC day, NaN elsewhere input("delta_ask", options_flow.share_delta_ask, { missing: "zero", description: "Delta bought at the ask (buyers paying the seller's price) in this bar: customers buying." }); // the chart's underlying (scope ticker); a quiet bar reads 0 input("delta_bid", options_flow.share_delta_bid, { missing: "zero", description: "Delta sold at the bid (sellers taking the buyer's price) in this bar: customers selling." }); market.notional(); // the market's point value and clock: the flow delta in USD, the close the charm drifts to, the trade date market.kind(); // what the market trades: on CME only an index future (5) closes at 16:00 New York pane("gex", { title: "Dealer gamma, USD per 1% move", height_frac: 0.18, format: "usd" }); pane("flow", { title: "Dealer delta from today's flow, USD", height_frac: 0.14, format: "usd" }); output("call_wall_line", line, overlay, { color: "theme.up", width: 1, step: true, label: "Call wall", format: "price", description: "The call wall, the strike with the most call gamma. It holds until the next sample." }); output("put_wall_line", line, overlay, { color: "theme.down", width: 1, step: true, label: "Put wall", format: "price", description: "The put wall, the strike with the most put gamma." }); output("flip_line", line, overlay, { color: "theme.muted", width: 1, step: true, line_style: "dashed", label: "Gamma flip · all expiries", format: "price", description: "The gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); output("magnet_line", line, overlay, { color: "theme.muted", width: 1, step: true, label: "Magnet", format: "price", description: "The magnet, the strike with the most dealer gamma." }); output("net_gex", line, lower, { pane: "gex", width: 2, step: true, color_by: "gamma_code", colors: ["theme.down", "theme.muted", "theme.up"], label: "Net gamma", format: "usd", description: "Net dealer gamma in dollars per 1% move, every ten minutes. It draws in the up colour when dealers are long gamma, down when short." }); output("flow_delta", area, lower, { pane: "flow", color: "theme.text", width: 2, fill_opacity: 0.25, label: "Flow delta", format: "usd", description: "The delta today's options trades left dealers holding, in dollars. Dealers take the other side of what customers buy at the ask and sell at the bid." }); output("gamma_code", none, lower, { description: "The dealer regime as a code: 0 short gamma, 1 neutral (exactly zero), 2 long gamma." }); output("hedge_1pct", none, lower, { format: "usd", description: "What dealers trade if price rises 1%, in dollars. Negative means they sell, positive means they buy." }); output("charm_to_close", none, lower, { format: "usd", description: "What dealers trade by the close as time changes their hedge (charm), in dollars, negative to sell. The close is 16:00 New York, the next day's in a CME index future's evening session. On crypto it is the UTC day's end. Blank on other CME markets." }); output("vanna_iv_down", none, lower, { format: "usd", description: "What dealers trade if implied volatility drops one point, as their hedge changes with option prices (vanna), in dollars. Negative means they sell." }); output("chg_10", none, lower, { format: "usd", description: "Net gamma now minus net gamma 10 minutes ago, in dollars." }); output("chg_20", none, lower, { format: "usd", description: "The same against 20 minutes ago." }); output("chg_30", none, lower, { format: "usd", description: "The same against 30 minutes ago." }); output("gex_pct", none, lower, { description: "The percentile: the share of earlier samples in the window below net gamma now, 0 to 100." }); output("samples", none, lower, { description: "How many 10-minute samples the window holds." }); output("status", none, lower, { description: "0 not enough history for the percentile, 1 it shows, 2 the chart is coarser than 10 minutes." }); string("read", { max_bytes: 64 }); // the headline: the regime and what the hedge does string("flow_text", { max_bytes: 64 }); // "Flow left dealers short $1.20M since 13:30 UTC" string("history_text", { max_bytes: 48 }); string("title", { max_bytes: 64 }); render.hud("dealer_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Dealers, estimated", "read", { headline: true }), tile.pill("Today's flow", "flow_text"), tile.pill("Gamma vs its history", "history_text"), tile.rows([ ["Net gamma", "net_gex", "usd"], ["Hedge for a 1% rally", "hedge_1pct", "usd"], ["Charm hedge to the close", "charm_to_close", "usd"], ["Hedge if IV drops 1 point", "vanna_iv_down", "usd"], ["Dealer delta from flow", "flow_delta", "usd"], ["Gamma change, 10 min", "chg_10", "usd"], ["Gamma change, 20 min", "chg_20", "usd"], ["Gamma change, 30 min", "chg_30", "usd"], ["Percentile", "gex_pct", "0"], ]), ], }); const SAMPLE_SEC = 600.0; const CLOSE_MINUTE = 960.0; // 16:00 on New York's clock: the close of a US stock and of a CME index future's PM expiries const INDEX = 5; // market.kind() of an index: on CME an index future, the one root that closes at 16:00 New York const CAPACITY = 2000; const samples = new DayHistory(CAPACITY); // net gamma per 10-minute sample, keyed by the sample's own 10-minute slot const newYork = new Clock("America/New_York"); // the close the charm drift runs to, off crypto const utc = new Clock("UTC"); let lookback = 400; // settings, read in onStart() let need = 40; let showLevels = true; let pointValue = 0.0; // the market facts, read in onStart(): 0 where the host does not know the point value let zone = 0; let kind = 0; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let lastT: f64 = NaN; // the newest sample, and what it carried, held let gex: f64 = NaN; let charm: f64 = NaN; let vanna: f64 = NaN; let callWall: f64 = NaN; let putWall: f64 = NaN; let flip: f64 = NaN; let magnet: f64 = NaN; let spot: f64 = NaN; let pctNow: f64 = NaN; let dailyRows = false; // a daily statistics row landed on a loaded bar: the underlying has daily numbers let flowDay: f64 = NaN; // the session the flow sums, from its first bar in view let flowFirstT: f64 = NaN; let customerShares = 0.0; function onStart(): void { lookback = i32(p_lookback()); need = i32(p_min_samples()); if (need > lookback) need = lookback; showLevels = p_show_levels() > 0.5; pointValue = p_market_point_value(); zone = i32(p_market_zone()); kind = i32(p_market_kind()); } /** Net gamma's change from the sample minutes before the newest; NaN when the window holds none there. */ function changeFrom(minutes: f64): f64 { if (samples.count() < 2) return NaN; const ago = samples.agoOf(samples.day(0) - minutes / 10.0); return ago < 0 ? NaN : samples.value(0) - samples.value(ago); } /** Minutes from the bar to the close: 16:00 New York on a US stock (0 after it) and on a CME index future, whose * evening session runs to the next day's; NaN on any other CME root, whose close the statistics do not name; on * crypto, which trades around the clock, the end of the UTC day. */ function minutesToClose(t: f64): f64 { if (zone == 0) { utc.update(t); return 1440.0 - f64(utc.hour() * 60 + utc.minute()); } if (zone == 2 && kind != INDEX) return NaN; newYork.update(t); const now = f64(newYork.hour() * 60 + newYork.minute()); return now < CLOSE_MINUTE ? CLOSE_MINUTE - now : zone == 2 ? CLOSE_MINUTE + 1440.0 - now : 0.0; } function sbUsd(v: f64): void { // "$1.20M" sb_text("$"); const a = Math.abs(v); if (a >= 1.0e9) { sb_f64(a / 1.0e9, 2); sb_text("B"); } else if (a >= 1.0e6) { sb_f64(a / 1.0e6, 2); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 2); sb_text("K"); } else sb_f64(a, 0); } function sbClock(t: f64): void { // "13:30" utc.update(t); if (utc.hour() < 10) sb_text("0"); sb_int(utc.hour()); sb_text(":"); if (utc.minute() < 10) sb_text("0"); sb_int(utc.minute()); } function writeWords(coarse: bool): void { sb_clear(); if (coarse) sb_text("Needs a 10-minute or finer chart"); else if (isNaN(gex) && dailyRows) sb_text("No live option quotes, daily numbers only"); // daily rows, no 10-minute row loaded else if (isNaN(gex)) sb_text("Waiting for the 10-minute options statistics"); else { const regime = dealerRegime(gex); sb_text(regime > 0.0 ? "Long gamma: dealers calm price, " : regime < 0.0 ? "Short gamma: dealers chase price, " : "Neutral gamma: no dealer hedging, "); sbUsd(gex); sb_text(" per 1% move"); } str_read_sb(); sb_clear(); if (coarse || isNaN(flowFirstT)) sb_text("No options trades yet"); else { const dealerUsd = -notional(customerShares, spot > 0.0 ? spot : bar.close(), pointValue, zone); sb_text(dealerUsd >= 0.0 ? "Flow left dealers long " : "Flow left dealers short "); sbUsd(dealerUsd); sb_text(" since "); sbClock(flowFirstT); sb_text(" UTC"); } str_flow_text_sb(); sb_clear(); const held = samples.span(lookback); if (coarse || samples.count() == 0) sb_text("No history"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" samples"); } else { sb_text("Above "); sb_f64(pctNow, 0); sb_text("% of the last "); sb_int(held); sb_text(" samples"); } str_history_text_sb(); sb_clear(); sb_text("Estimated dealer positioning"); if (!coarse && !isNaN(lastT)) { sb_text(", "); sbClock(lastT); sb_text(" UTC"); } str_title_sb(); } // onBar() runs once per bar: the spacing; the bar's flow into the session's sum (a new trade date on the market's own // clock starts a new sum); a daily row when one lands; the 10-minute sample when it lands (its readings kept, net gamma // into the window); every bar writes the held readings. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > SAMPLE_SEC + 1.0; const day = sessionTradeDate(t, zone, zone == 2 ? 1020.0 : 0.0); // CME's trade day opens at 17:00 Chicago if (day != flowDay) { flowDay = day; flowFirstT = NaN; customerShares = 0.0; } const ask = in_delta_ask(); const bid = in_delta_bid(); if (!isNaN(ask) && !isNaN(bid)) { if (isNaN(flowFirstT)) flowFirstT = t; customerShares += ask - bid; } if (!isNaN(in_daily_spot())) dailyRows = true; const g = in_gex(); if (!coarse && !isNaN(g)) { lastT = t; gex = g; charm = in_charm(); vanna = in_vanna(); callWall = in_call_wall(); putWall = in_put_wall(); flip = in_flip(); magnet = in_magnet(); spot = in_spot(); samples.push(Math.floor(t / SAMPLE_SEC), g); // each sample's 10-minute slot: a gap of slots is a gap of time pctNow = samples.span(lookback) >= need ? samples.percentile(lookback) : NaN; } const levels = showLevels && !coarse; out_call_wall_line(levels ? callWall : NaN); out_put_wall_line(levels ? putWall : NaN); out_flip_line(levels ? flip : NaN); out_magnet_line(levels ? magnet : NaN); out_net_gex(coarse ? NaN : gex); out_gamma_code(coarse || isNaN(gex) ? NaN : 1.0 + dealerRegime(gex)); const price = spot > 0.0 ? spot : bar.close(); out_flow_delta(coarse || isNaN(flowFirstT) ? NaN : -notional(customerShares, price, pointValue, zone)); out_hedge_1pct(coarse ? NaN : -gex); out_charm_to_close(coarse || isNaN(charm) ? NaN : (-charm * minutesToClose(t)) / 1440.0); out_vanna_iv_down(coarse ? NaN : vanna); out_chg_10(coarse ? NaN : changeFrom(10.0)); out_chg_20(coarse ? NaN : changeFrom(20.0)); out_chg_30(coarse ? NaN : changeFrom(30.0)); out_gex_pct(coarse ? NaN : pctNow); out_samples(coarse ? NaN : f64(samples.span(lookback))); out_status(coarse ? 2.0 : samples.span(lookback) >= need ? 1.0 : 0.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **The hedges, signed as trades.** Negative sells, positive buys. A 1% rally moves dealer delta by net gamma, so dealers trade minus net gamma. Charm moves dealer delta by net charm a day, so over the minutes left to the close dealers trade minus net charm times that fraction of a day. On a CME index future (`market.kind()` 5, as on ES and NQ) the evening session from 17:00 Chicago belongs to the next trade date, so its close is the next day's 16:00 New York. Any other CME root closes on its own clock, which the 10-minute statistics do not name, so there the charm row reads `-`. A one-point IV drop moves dealer delta by minus net vanna, so dealers trade plus net vanna. **The flow.** Each bar's share delta at the ask minus at the bid is what customers bought; the sum since the session's first bar in view is their net, and dealers hold the opposite, in USD through `notional()`: the newest sample's price times the market's point value (50 on ES), and no reading on a CME chart whose point value the host does not hold. A bar with no prints reads 0 (`missing: "zero"`); a new trade date on the market's own clock starts a new sum (`sessionTradeDate()`: the New York date on a US stock, the UTC day on crypto, the CME trade date that opens at 17:00 Chicago). **The lookbacks.** Each sample joins a `DayHistory` under its 10-minute slot, so "10 minutes ago" is the slot before, and a gap in the samples is a gap, never a neighbour. ## What the settings do - **Window, samples**: how many past 10-minute samples the percentile ranks net gamma against, 400 by default (about ten US sessions). - **Minimum history, samples**: how many samples the percentile waits for before it shows, 40 by default. - **Levels**: draws the call and put walls (the strikes with the most dealer hedging) and the gamma flip on price. It also draws the magnet, the strike with the most dealer gamma, which tends to pull price. - **Dealers, estimated**: whether dealers calm price (long gamma) or chase it (short gamma), with the dollars they trade for each 1% move. - **Today's flow**: the position today's options trades left dealers holding, and the time it counts from. - **Gamma vs its history**: where net gamma ranks among past samples, or how many samples it still needs. - **Net gamma**: the dollars dealers must trade for each 1% move, above zero when their hedging calms price. - **Hedge for a 1% rally**: what dealers sell (negative) or buy (positive) if price rises 1%. - **Charm hedge to the close**: what dealers trade from now to the close as time alone changes their hedge (charm), if price stays put. - **Hedge if IV drops 1 point**: what dealers trade if implied volatility (how big a move option prices expect) falls one point. Their hedge changes with option prices (vanna). - **Dealer delta from flow**: what today's options trades left dealers holding, in dollars of delta (how much stock dealers must hold to hedge). - **Gamma change, 10 min**: how much net gamma moved in the last 10 minutes. - **Gamma change, 20 min**: how much net gamma moved in the last 20 minutes. - **Gamma change, 30 min**: how much net gamma moved in the last 30 minutes. - **Percentile**: the share of past samples below net gamma now, from 0 to 100. ## Where it runs It needs a chart of 10 minutes or finer. The 10-minute options statistics cover every symbol whose options quote live. For a coin they start on the day OpenMarket began recording them. On CME (Chicago futures exchange) they cover each futures contract whose options quote live. Other contracts have daily numbers only. Any other symbol has no 10-minute numbers, and the indicator's legend on the chart says so. On a coin with listed options the chart reads the coin's own options. So does a copy you run from the editor (where you write and run your own indicators). On a US stock every indicator in the browser can read them. They run 15 minutes behind unless you have real-time US options data. On a CME futures chart every indicator in the browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). They run 10 minutes behind unless you have real-time CME data. On a US stock the statistics come from delayed quotes. So the newest sample trails the market by about 15 minutes. ## When data is missing The 10-minute statistics start on the day OpenMarket began recording them. The numbers show from the first sample. The percentile waits for **Minimum history**: 40 samples, about one US session, or under seven hours on crypto and CME. Until then the card's **Gamma vs its history** line reads "Not enough history yet: 12 of 40 samples". The flow adds up from the session's first bar on screen, and the card's **Today's flow** line names that time. Before the first sample the card reads "Waiting for the 10-minute options statistics". It reads "No live option quotes, daily numbers only" when the symbol has daily statistics but no 10-minute ones. That means its options do not quote live. A chart coarser than 10 minutes reads "Needs a 10-minute or finer chart". Older 10-minute statistics follow an earlier gamma flip rule and often have no flip. The gamma flip line stays empty there. That covers US listed options before 2026-10-20, CME before 2026-10-21 12:10 UTC and a few coins' options ([Data sources](../core-concepts/data-sources.md#the-gamma-flip-and-older-rows)). ## Customize it - **Another window.** `lookback` sets the samples the percentile reads (400 is about ten US sessions, under three days on crypto and CME, which trade around the clock). - **A clean price pane.** Turn **Levels** off. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Estimated Dealer Positioning** under **HUDs**. 2. Press **Run** on SPY's 5-minute chart: the levels and the card draw at your own tier, and the legend names the tier. 3. At the editor's Console prompt, type `net_gex`, `hedge_1pct` and `flow_delta`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_stats_10m` and `options_flow` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [The market's facts](../settings/sessions-and-units.md#the-markets-facts) for `market.kind()`, which tells a CME index future from the other roots - [Panes](../presentation/plotting.md#panes) for the two panes - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/spot-exposures --> # Spot exposures Bar by bar, a heat map behind the candles shows where dealers (the market makers who hedge options) hedge most. Up colour marks strikes (the option's price levels) where calls dominate, down colour where puts do. Lines mark the gamma flip (the price where dealers switch from calming price to pushing it). Two more mark the call and put walls (the strikes with the most dealer hedging). On an intraday chart with listed options, use it to see where hedging sits and how it shifts. Under the hood: the headline reads net gamma, delta and vega over every expiry from the 10-minute options statistics (`option_stats_10m`). Those run up to 15 minutes behind the map. The map, the walls, the flip and the top node read the server's measure of each bar's strikes for the expiries within 7 trade days. That is `option_strikes` with `fold: "kit"`, `levels` and `curve` ([Data sources](../core-concepts/data-sources.md#option-strikes)). It loads them through [`OptionStrikes.loadLevels`](../functions/options-kit.md#chain-page-views), with its gamma curve read by [the canonical numbers](../functions/options-kit.md#the-canonical-numbers). It declares `market.zone()`, `market.kind()`, `market.option_multiplier()` and `chart.interval_sec()` for that measure. It ranks strikes with [`NodeBoard`](../functions/options-kit.md#node-roles) and paints an [`out.grid`](../presentation/price-canvases.md#a-grid-the-module-computes) heat map. It restarts the change on each `time.trade_date`. It is the `spot-exposures` template: **Spot Exposures** under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Spot Exposures: bar by bar, a heat map shows where dealers (the market makers who hedge options) hedge most. Each // band is a strike (the option's price level), painted behind the candles. Up colour means calls dominate a strike, // down colour means puts do. Gamma (how fast dealers must hedge as price moves) leads the card. Long gamma (dealers // calm price): they sell rallies and buy dips, so price tends to calm. Short gamma (dealers chase price): they buy // rallies and sell dips, so price tends to trend. A dashed line marks the gamma flip (the price where dealers switch // from calming price to pushing it). Two more lines mark the call and put walls (the strikes with the most dealer // hedging). A dotted line marks the top node, the strike with the largest exposure. A line under the chart follows net // exposure through the day. Use it to see where dealer hedging sits and how it shifts. // // Under the hood: the headline reads every expiry: net gamma, delta and vega from the 10-minute options statistics // (the option_stats_10m source: every live expiry and strike at open interest, gamma by Black-Scholes with no rate at // each contract's stored mark IV, a row every ten minutes of the session), the newest row held on the bars after it // until the next lands. The map and the levels read the strike rows the data plane folds every minute (the // option_strikes source: each bar's newest minute of strike rows inside it, about seven days back) over the week // Greek Exposure counts: the expiries live and 7 or fewer trade days out. The data plane measures each bar's week for // the chart (the strike kit fold with its curve row), so a bar arrives as its levels, its gamma curve's readings and // the lens at each strike, never the minutes' rows. A line under the chart follows the headline's net exposure (gamma // per 1% move by default, delta held, or vega per IV point, in dollars), three step lines on the price chart follow // the week's gamma flip and call and put walls, and a heat map behind the candles paints the lens strike by strike on // every bar with strike rows (Map values shows each strike's level, or its change from the previous bar with strike // rows). A card reads the gamma regime in one plain line, then the three nets, the change in net gamma since the // session's first reading, the week's net gamma, the levels and the put/call open interest. Both sources share one // convention: dealers long the calls and short the puts (calls add, puts subtract), delta in each option's own sign. // The statistics run up to 15 minutes behind the strike rows (Statistics age counts the bars since the newest row, // Strike data age the bars since the newest strike rows), and an underlying the data plane does not sample every ten // minutes has none: until a row lands the headline reads the week's strike rows, and the card's title says so. The // week's net gamma, its regime and the flip are the options kit's GammaCurve over each bar's week at its as-of // (optionsAsOfMs: the bar's close time, the chain's clock too), each expiry live and priced to its chain's last trade // (optionsLiveUntilMs on the market's zone and kind: a US stock or ETF expiry until 15 minutes past its stamp, a US // index, CME or crypto expiry until its stamp), which the fold's curve row carries; only a bar with strike rows // paints the map. // // Version 0.5 reads the headline over every expiry from the 10-minute statistics, where 0.4 read the week's strike // rows; the week's net gamma stays an output of its own (net_gex_week). // // Version 0.6 marks the top node of each bar's strike rows (the options kit's NodeBoard over the lens by strike, read // against the map's spot: the strike with the largest |exposure|) with a step line starred in its label and reads the // net above spot and below it in the card. // // Version 0.7 reads the data plane's measure of each bar, where 0.6 downloaded every minute's strike rows and // measured them itself, and declares the market's kind, so a US index chain's expiries leave at their stamp. 0.6's // Expiry preset leaves with it: the fold counts the soonest expiries, never the calendar (Nearest expiries 1 is the // front one). section("Exposure"); param.choice("lens", ["gamma", "delta", "vega"], "gamma", { label: "Lens", description: "What the line and the map show, in dollars. gamma: what dealers trade per 1% move. delta: how much stock dealers must hold to hedge. vega: how much dealers gain or lose when option prices rise." }); param.choice("map_mode", ["level", "change"], "level", { label: "Map values", description: "level: each strike's exposure on the bar. change: how much it moved since the previous bar with strike data." }); param.int("nearest", 0, { min: 0, max: 7, label: "Nearest expiries", description: "How many of the soonest expiries (the days the options end) the map, flip, walls and week's numbers count. 0 counts every expiry within 7 trade days. The headline counts every expiry wherever the 10-minute statistics exist." }); param.number("window_pct", 3, { min: 0.5, max: 20, step: 0.5, label: "Map window, percent", description: "How far the map reaches above and below the price, in percent, at most 48 strike steps each way." }); input("close", ohlcv.close); // the chart's own close: the map's centre where the rows report no underlying input("strikes", option_strikes.cells, { max_cells: 4000, venue: "auto", fold: "kit", nearest: "@nearest", window_pct: 100, lens: "@lens", step_rows: 1000, levels: true, curve: true, description: "This symbol's options by strike for each bar, for expiries within 7 trade days. The server measures each bar's levels, net gamma, gamma flip and lens at every strike up to twice the price." }); // per bar a levels row, a curve row and [0, strike, value] per strike, 14 values a row input("trade_date", time.trade_date); // the bar's trade date: the change in net gamma counts from the session's first reading input("stats_gex", option_stats_10m.net_gex, { venue: "auto", missing: "nan", description: "Net gamma over every live expiry, in dollars per 1% move, from the 10-minute options statistics. It lands on the bar of each sample and stays blank between samples and where this symbol is not sampled." }); // the three statistics share one read of the chain the strike rows read input("stats_dex", option_stats_10m.net_dex, { venue: "auto", missing: "nan", description: "Net delta over every live expiry, in dollars held, each option in its own sign, from the same sample." }); input("stats_vex", option_stats_10m.net_vex, { venue: "auto", missing: "nan", description: "Net vega over every live expiry, in dollars per point of implied volatility, from the same sample." }); market.zone(); // the market's clock: the week's trade days and each chain's last trade, which the fold reads, and the trade date where the chart writes none market.option_multiplier(); // the options' multiplier: 100 on a US stock, the point value on CME, 1 on a coin; the fold's gamma curve reads it chart.interval_sec(); // the bar's length: the fold reads each bar at its close time, when its newest minute closes // Version 0.7's market fact, after the chart's facts, where 0.6's Expiry preset stood. market.kind(); // what the market trades: on New York's clock a US index (5) stops its options at their stamp, which the fold reads output("exposure", line, lower, { color: "theme.text", width: 2, split: "level", up_color: "theme.up", down_color: "theme.down", split_fill: true, format: "usd", label: "Net exposure", description: "The headline's net exposure in the lens, in dollars, over every expiry from the 10-minute statistics. Where those do not exist, it reads the week's strikes." }); output("zero_gamma", line, overlay, { color: "theme.muted", width: 1, step: true, line_style: "dashed", format: "price", label: "Gamma flip", description: "The gamma flip for the week's counted expiries: the price nearest now where dealer gamma crosses zero. Blank when none lies within 50% of the price." }); output("call_wall", line, overlay, { color: "theme.up", width: 1, step: true, format: "price", label: "Call wall", description: "The call wall: the strike holding the most call gamma, often a ceiling." }); output("put_wall", line, overlay, { color: "theme.down", width: 1, step: true, format: "price", label: "Put wall", description: "The put wall: the strike holding the most put gamma, often a floor." }); // The readings, data-only: the card's tiles read them and the Console can too. Each carries its newest reading: the // nets the newest statistics row (else the week's), the rest the newest strike rows at or before its bar. output("net_gex", none, overlay, { description: "Net gamma at open interest, in dollars per 1% move, over every expiry from the newest 10-minute sample. Without those statistics it reads the week's net gamma." }); output("net_dex", none, overlay, { description: "Net delta, in dollars held, each option in its own sign. Every expiry from the statistics, or the week's strikes." }); output("net_vex", none, overlay, { description: "Net vega, in dollars per point of implied volatility. Every expiry from the statistics, or the week's strikes." }); output("call_gex", none, overlay, { description: "The calls' gamma, in dollars per 1% move." }); output("put_gex", none, overlay, { description: "The puts' gamma, in dollars per 1% move, as a positive number." }); output("gex_change", none, overlay, { description: "Net gamma now minus net gamma at the session's first reading from the same source, in dollars per 1% move." }); output("max_pain", none, overlay, { description: "Max pain: the strike where open options would pay out the least at expiry." }); output("put_call_oi", none, overlay, { description: "Put open interest (puts still open) divided by call open interest." }); output("rows_age", none, overlay, { description: "Bars since the newest bar with strike data: 0 on such a bar, blank before the first." }); output("tone", none, overlay, { description: "The headline's regime as a code: 0 short gamma, 1 no reading or flat, 2 long gamma." }); output("map_low", none, overlay, { description: "The bottom edge of the map's lowest band on this bar." }); // the heat map reads it output("map_step", none, overlay, { description: "The height of one map band in price on this bar: the finest strike step inside the window." }); out.grid("map", { rows: 96 }); // 96 data-only outputs map_0..map_95, one per strike step, written with out_map(row, value) plot.heatmap({ name: "exposure_map", grid: "map", price_low: "map_low", price_step: "map_step", palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", auto_quantile: 0.98, opacity: 0.7, behind_candles: true, label: "Exposure by strike", tooltip: "{{value:usd}} at {{price}}" }); // the chart's down colour where puts carry the strike, its up colour where calls do // Version 0.5's readings, after the map's, so every output before them keeps its slot. output("net_gex_week", none, overlay, { description: "Net gamma of the week's counted expiries at the current price, in dollars per 1% move. It is the headline where the chart has no 10-minute statistics." }); output("stats_age", none, overlay, { description: "Bars since the newest 10-minute sample: 0 on its bar, blank before the first or where none are taken." }); // Version 0.6's reading, after 0.5's: the top node, starred in its label. output("top_node", line, overlay, { color: "theme.text", width: 1, step: true, line_style: "dotted", format: "price", label: "Top node ★", description: "The top node: the strike with the largest exposure in the lens, either way, over the week's counted expiries. A tie goes to the strike nearest the price, then the lower one." }); string("read", { max_bytes: 64 }); // the headline: the gamma regime in one plain line and its age, or why there is none string("title", { max_bytes: 96 }); // the card's title: the headline's measure, its expiries and where it reads them string("sides", { max_bytes: 48 }); // the card's by-side row: the lens's net above spot and below it, compact and signed // The card: the gamma regime leads as the headline, then the three nets, the week's net gamma, the levels of the newest // strike rows (the top node and the lens's net either side of spot among them) and the two ages. render.hud("spot", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Dealers", "read", { headline: true }), tile.value("Net gamma", "net_gex", { format: "usd" }), tile.value("Change since session start", "gex_change", { format: "usd" }), tile.value("Net delta", "net_dex", { format: "usd" }), tile.value("Net vega", "net_vex", { format: "usd" }), tile.rows([ ["Net gamma within 7 days", "net_gex_week", "usd"], ["Gamma flip", "zero_gamma", "price"], ["Call wall", "call_wall", "price"], ["Put wall", "put_wall", "price"], ["Top node ★", "top_node", "price"], ["Net above and below price", "sides"], // Above +1.2M | Below -640K: the lens's net of the strikes above spot and below it ["Max pain", "max_pain", "price"], ["Put/call open interest", "put_call_oi", "0.00"], ["Strike data age, bars", "rows_age", "int"], ["Statistics age, bars", "stats_age", "int"], ]), ], }); const ROWS = 96; // the map's rows, the grid's declared count const HALF = 48; // rows each side of the strike nearest the underlying const GAMMA = 0; const DELTA = 1; const rowValue = new StaticArray<f64>(ROWS); // this bar's map, folded from the strike table const prevStrike = new StaticArray<f64>(in_strikes_max_cells); // the previous strike rows' table: its strikes, ascending const prevValue = new StaticArray<f64>(in_strikes_max_cells); // and the lens at each, for the change map let table = new OptionStrikes(1); // one bar's week as the fold measured it: its levels, its curve's readings and the lens at each strike; sized in onStart() let lens = GAMMA; // settings, read in onStart() let changeMap = false; let nearest = 0; let windowPct = 0.03; let zone = 0; let prevCount = -1; // strikes in the previous table; -1 before the first bar with strike rows let sessionKey: f64 = NaN; // the trade date the bars are in, days since 1970-01-01 let sessionFirstGex: f64 = NaN; // the week's net gamma at the session's first strike rows let statsFirstGex: f64 = NaN; // net gamma at the session's first statistics row let age = -1; // bars since the newest bar with strike rows; -1 before the first let statsAge = -1; // bars since the bar the newest statistics row landed on; -1 before the first // The newest strike rows' readings, the week's, carried to the bars after them until the next rows arrive. let zeroGamma: f64 = NaN; let callWall: f64 = NaN; let putWall: f64 = NaN; let weekGex: f64 = NaN; let weekRegime: f64 = NaN; // the sign of the week's net gamma: 1, -1 or 0 let weekDex: f64 = NaN; let weekVex: f64 = NaN; let weekChange: f64 = NaN; let callGex: f64 = NaN; let putGex: f64 = NaN; let maxPain: f64 = NaN; let putCallOi: f64 = NaN; // The newest statistics row's readings over every expiry, held until the next row lands. let statsGex: f64 = NaN; let statsDex: f64 = NaN; let statsVex: f64 = NaN; let statsChange: f64 = NaN; let regime: f64 = NaN; // the headline's regime: the statistics' sign of net gamma once a row landed, else the week's // Version 0.6: the newest strike rows' nodes, carried like the levels. let board = new NodeBoard(1); // one bar's nodes over the lens by strike; sized in onStart() let topNode: f64 = NaN; let aboveNet: f64 = NaN; // the lens's net of the strikes above the map's spot and below it let belowNet: f64 = NaN; function onStart(): void { table = new OptionStrikes(in_strikes_max_cells); // a bar's week lists at most max_cells strikes, so a load is never refused lens = i32(p_lens()); changeMap = p_map_mode() == 1.0; nearest = i32(p_nearest()); windowPct = p_window_pct() / 100.0; zone = i32(p_market_zone()); board = new NodeBoard(in_strikes_max_cells); // a block holds at most max_cells strikes } function trackSession(t: f64): void { // the session: net gamma's change counts from its trade date's first reading const stamp = in_trade_date(); // epoch seconds of the trade date, as the chart writes it const key = isFinite(stamp) ? Math.floor(stamp / 86400.0) : optionsTradeDay(t * 1000.0, zone); if (isNaN(key)) return; if (isNaN(sessionKey) || key > sessionKey) { sessionKey = key; sessionFirstGex = NaN; // a new session: its first strike rows and its first statistics row set the bases statsFirstGex = NaN; } } // ── The lens, strike by strike, and the previous rows' value at a strike ── function lensAt(k: i32): f64 { // the lens at the table's k-th strike (ascending), as the fold measured it return table.value(k); } function previousAt(strike: f64): f64 { // the previous rows' lens at this strike; 0 where they did not list it let lo = 0; let hi = prevCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (prevStrike[mid] < strike) lo = mid + 1; else hi = mid; } return lo < prevCount && prevStrike[lo] == strike ? prevValue[lo] : 0.0; } function keepTable(): void { // this bar's table becomes the previous rows const count = table.strikeCount(); for (let k = 0; k < count; k += 1) { prevStrike[k] = table.strike(k); prevValue[k] = lensAt(k); } prevCount = count; } // ── The map: one row per strike step, centred on the strike nearest the underlying ── function clearMap(): void { // no map on this bar: every cell empty for (let r = 0; r < ROWS; r += 1) out_map(r, NaN); out_map_low(NaN); out_map_step(NaN); } function writeMap(spot: f64): void { const count = table.strikeCount(); const lo = spot * (1.0 - windowPct); const hi = spot * (1.0 + windowPct); let first = 0; // the window's strikes: [first, last) while (first < count && table.strike(first) < lo) first += 1; let last = first; while (last < count && table.strike(last) <= hi) last += 1; if (last <= first || (changeMap && prevCount < 0)) { // no strike inside the window, or no earlier rows to change from clearMap(); return; } let step = Infinity; // the finest strike step inside the window: one row per step for (let k = first + 1; k < last; k += 1) { const gap = table.strike(k) - table.strike(k - 1); if (gap > 0.0 && gap < step) step = gap; } if (step == Infinity) { // one strike in the window: its step to a neighbour, else a tenth of a percent of spot if (first > 0) step = table.strike(first) - table.strike(first - 1); else if (first + 1 < count) step = table.strike(first + 1) - table.strike(first); else step = spot * 0.001; } let centre = first; // the strike nearest the underlying, the lower one on a tie for (let k = first + 1; k < last; k += 1) { if (Math.abs(table.strike(k) - spot) < Math.abs(table.strike(centre) - spot)) centre = k; } const anchor = table.strike(centre); for (let r = 0; r < ROWS; r += 1) rowValue[r] = NaN; for (let k = first; k < last; k += 1) { const strike = table.strike(k); const row = HALF + i32(Math.round((strike - anchor) / step)); if (row < 0 || row >= ROWS) continue; // more than 48 steps from the centre const v = changeMap ? lensAt(k) - previousAt(strike) : lensAt(k); rowValue[row] = isNaN(rowValue[row]) ? v : rowValue[row] + v; // a strike off the step's grid shares the nearest row } for (let r = 0; r < ROWS; r += 1) out_map(r, rowValue[r]); out_map_low(anchor - (f64(HALF) + 0.5) * step); // each row spans its strike plus and minus half a step out_map_step(step); } // ── The card's words ── function sbCompactSigned(v: f64): void { // a net in K, M, B or T with its sign: +1.2M, -640K, 0 if (v > 0.0) sb_text("+"); sb_compact(v, 1); } function writeWords(): void { const stats = statsAge >= 0; const ago = stats ? statsAge : age; // the headline's age: its statistics row's, else its strike rows' sb_clear(); if (ago < 0) sb_text("No strike data on this chart yet"); else if (regime > 0.0) sb_text("Long gamma: dealers calm price"); else if (regime < 0.0) sb_text("Short gamma: dealers chase price"); else sb_text("Neutral gamma: no dealer hedging"); // exactly 0, or no contract to read if (ago > 0) { // the headline's newest reading is on an earlier bar sb_text(" ("); sb_int(ago); sb_text(ago == 1 ? " bar ago)" : " bars ago)"); } str_read_sb(); sb_clear(); if (stats) sb_text("Net gamma, all expiries, open interest, up to 15 minutes behind the map"); else { sb_text("Net gamma, "); if (nearest == 0) sb_text("expiries within 7 days"); else { sb_text("nearest "); sb_int(nearest); sb_text(nearest == 1 ? " expiry" : " expiries"); } sb_text(", no 10-minute statistics here"); } str_title_sb(); sb_clear(); // the newest strike rows' net either side of spot, in the lens if (age < 0) sb_text("-"); else { sb_text("Above "); sbCompactSigned(aboveNet); sb_text(" | Below "); sbCompactSigned(belowNet); } str_sides_sb(); } // onBar(): a bar with strike rows reads the data plane's measure of its week, one without keeps the newest readings; a // bar holding a statistics row takes its readings over every expiry, one without keeps the newest; the headline reads // the statistics once a row has landed, else the week's; the live bar writes the card. function onBar(): void { const close = bar.close(); const t = bar.time(); trackSession(t); const n = in_strikes_cells(); // The week's measure: the levels row, the curve row and the lens at each strike. A bar whose week keeps no strike // arrives empty, as a bar without rows; one whose minute held more than max_cells rows loads -1. const kept = n > 0 ? table.loadLevels(in_strikes_view(), n) : 0; if (kept > 0) { weekGex = table.gexAtSpot(); // the curve row: GammaCurve's net gamma at S0 over the week, its regime and its flip weekRegime = table.gammaRegime(); weekDex = table.totalNetDex(); weekVex = table.totalNetVex(); callGex = table.totalCallGex(); putGex = table.totalPutGex(); maxPain = table.maxPain(); putCallOi = table.putCallRatio(); zeroGamma = table.gammaFlip(); callWall = table.callWall(); putWall = table.putWall(); if (isNaN(sessionFirstGex)) sessionFirstGex = weekGex; weekChange = weekGex - sessionFirstGex; age = 0; const under = table.underlying(); const spot = under > 0.0 ? under : close; if (spot > 0.0) writeMap(spot); else clearMap(); keepTable(); board.load(prevStrike, prevValue, prevCount, spot); // the nodes over this bar's lens by strike, read against the map's spot topNode = board.strike(board.top()); aboveNet = board.aboveNet(); belowNet = board.belowNet(); } else { if (age >= 0) age += 1; clearMap(); } const rowGex = in_stats_gex(); // finite on the bar a statistics row landed on if (isFinite(rowGex)) { statsGex = rowGex; statsDex = in_stats_dex(); statsVex = in_stats_vex(); if (isNaN(statsFirstGex)) statsFirstGex = rowGex; statsChange = rowGex - statsFirstGex; statsAge = 0; } else if (statsAge >= 0) statsAge += 1; const stats = statsAge >= 0; const netGex = stats ? statsGex : weekGex; const netDex = stats ? statsDex : weekDex; const netVex = stats ? statsVex : weekVex; regime = stats ? dealerRegime(statsGex) : weekRegime; const headAge = stats ? statsAge : age; out_exposure(lens == GAMMA ? netGex : lens == DELTA ? netDex : netVex); out_zero_gamma(zeroGamma); out_call_wall(callWall); out_put_wall(putWall); out_net_gex(netGex); out_net_dex(netDex); out_net_vex(netVex); out_call_gex(callGex); out_put_gex(putGex); out_gex_change(stats ? statsChange : weekChange); out_max_pain(maxPain); out_put_call_oi(putCallOi); out_rows_age(age >= 0 ? f64(age) : NaN); out_tone(headAge < 0 || isNaN(regime) ? 1.0 : 1.0 + regime); out_net_gex_week(weekGex); out_stats_age(stats ? f64(statsAge) : NaN); out_top_node(topNode); if (bar.isLast()) writeWords(); } ``` ## How it works **The server measures each bar.** Each bar's strike rows are the newest minute of them inside it, one `[strike, expiry_ms, net_gex, call_gex, put_gex, net_dex, net_vex, call_oi, put_oi, call_iv, put_iv, underlying]` row per expiry and strike, and a bar holds hundreds to thousands of them. The template never downloads them. Its input asks the data plane for the strike kit fold (`fold: "kit"` with `levels: true` and `curve: true`), and the server measures each bar with the options kit's own rules and sends the result: a levels row (the totals, the call and put walls, max pain and the underlying), a curve row (the gamma curve's net gamma at S0, its flip, S0 and the as-of) and a `[0, strike, value]` row for each strike, `value` the lens. `OptionStrikes.loadLevels(cells, count)` reads them ([Chain page views](../functions/options-kit.md#chain-page-views)). A strike listed under two expiries is one row, its exposures summed; a side the strike does not list counts as 0. **Nearest expiries** (`nearest: "@nearest"`) keeps the N soonest expiries of the bar's week (0 keeps every one), and **Lens** rides the ask too (`lens: "@lens"`), so changing either fetches again. `window_pct: 100` with `step_rows: 1000` sends every strike up to twice the underlying, so the map's window, the top node and the nets by side read the whole table as they would off the raw rows. A bar whose minute held more than `max_cells` (4,000) rows arrives refused (`loadLevels()` returns -1). **The week.** The server keeps each bar's week before it measures anything: an expiry still trading at the bar's as-of, its close time (each expiry's last trade on the market's clock and kind: 15 minutes past the stamp on a US stock or ETF chain, since a PM expiry stamped 16:00 New York trades until 16:15; the stamp itself on a US index chain, on CME and on a coin), and whose trade date is 7 or fewer days after the as-of's on the market's calendar (New York on a US stock, Chicago on CME, UTC on a coin). `market.zone()` and `market.kind()` declare the two facts the fold's week reads, so an index chain's expiries leave at their stamp. It is the rule Greek Exposure's `week` counts by, so the two cards count one set of expiries on one chart. The data plane serves the expiries within 7 x 24 hours of the minute, so today the rule drops no row it serves; the totals, the walls, max pain, the strikes and the gamma curve all read the week, and a bar whose week keeps no strike arrives empty, as a bar without rows. **No Expiry preset.** Expiry preset is removed in 0.7.0: the server's fold cannot pick expiries by the calendar yet (to Friday, to the monthly opex), so the setting could no longer do what it says. **Nearest expiries** counts the soonest expiries instead: 1 keeps the front expiry, 0 every expiry within 7 days. **The convention.** The strike rows put the dealers long the calls and short the puts: a row's `net_gex` is the calls' dollar gamma minus the puts', per 1% move of the underlying, `net_vex` the calls' vega dollars minus the puts', and `net_dex` the delta dollars of both sides with each option in its own sign (puts negative). The 10-minute statistics keep the same convention, so the two sources add up the same way. The line follows the headline: `net_gex` on the gamma lens, `net_dex` or `net_vex` on the delta and vega lenses, each over every expiry from the statistics, or the week's table total (`totalNetDex()`, `totalNetVex()`) where the chart has none. **The headline: every expiry.** `input("stats_gex", option_stats_10m.net_gex, { venue: "auto", missing: "nan" })` and its twins `stats_dex` and `stats_vex` read the data plane's 10-minute options statistics of the chain the strike rows read: one read for the three, under the same venue word. Net gamma is open interest over every live expiry and strike (Black-Scholes gamma with no rate at each contract's stored mark IV, times the open interest and the multiplier, USD per 1% move), net delta each option in its own sign, and net vega per IV point. A row lands on the bar holding its stamp and reads NaN on the bars between, so the module holds the newest row itself and `stats_age` counts the bars since the bar it landed on. Once a row has landed, `net_gex`, `net_dex`, `net_vex`, the regime (the kit's `dealerRegime(net_gex)`), `gex_change` and the line read it, and the title reads `Net gamma, all expiries, open interest, up to 15 minutes behind the map`: the newest row is about 15 to 30 minutes old, up to 15 minutes behind the strike rows the map and the levels read. Before the first row, and on an underlying the data plane does not sample every ten minutes (CME roots other than ES and NQ, coins off its list), the inputs read NaN and the headline reads the week's strike rows, with the title `Net gamma, expiries within 7 days, no 10-minute statistics here` (`nearest 2 expiries` in place of the week when **Nearest expiries** counts fewer). `net_gex_week` keeps the week's net gamma beside the headline on every bar, the number the card's rows show as Net gamma within 7 days. Near a US stock's close the two sources count the same-day expiry apart: the statistics run its time to the 16:00 stamp with no 15 minutes of trading after it, so the 15:50 row carries a larger same-day book and the 16:00 and 16:10 rows none, while the week's strike rows keep it until 16:15. **The week's net gamma, its regime and the flip.** The server computes the gamma curve for each bar and sends its readings in the curve row: it loads the week's rows into the kit's `GammaCurve` (`loadStrikes`), each row a call and a put with that side's open interest and IV, priced at the bar's as-of. The block names no minute (the chart stamps it at the bar's open), and the newest minute inside a bar closes when the bar does, so the as-of is the bar's close time (`optionsAsOfMs`): the same clock Greek Exposure and the Options Dashboard read the chain at on the same bar, never a time solved back from a gamma (two solves of one minute named two times, and a same-day gamma scales with 1 / sqrt(T), so two cards on one chart read two numbers). Each contract's time to go runs to its expiry's last trade (`optionsYearsToGo`: 15 minutes past the stamp on a US stock or ETF, and never under a second while it trades, so a same-day contract keeps its gamma until 16:15; the stamp on a US index, CME or a coin). `market.option_multiplier()` and `chart.interval_sec()` declare the multiplier and the bar's length the curve reads: 100 on a US stock, the point value on CME, 1 on a coin. `gexAtSpot()` is `net_gex_week`, the curve at S0 (the nearest live expiry's median underlying), `gammaRegime()` the week's regime, its sign (the headline's where the chart has no statistics), and `gammaFlip()` is `zero_gamma`, the gamma flip, the curve's zero nearest S0 within 50%: the numbers the module's own `GammaCurve` gives over the same rows, bit for bit, and the numbers the Options Dashboard and every other options card read over the same expiries ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)). The flip and the walls stay the week's even while the headline reads every expiry, so the regime and the side of the flip spot is on can disagree. **The levels.** On every bar with strike rows the levels row carries the call wall and the put wall (`callWall()` and `putWall()`: the strikes holding the most call and put dollar gamma) and max pain (`maxPain()`: the listed strike where the open interest's payout at expiry is least), measured over every strike of the week. The three step lines draw the gamma flip and the two walls, and a fourth the top node; max pain reads in the card. **The top node.** On every bar with strike rows the kit's `NodeBoard` loads the lens by strike (the fold's `value(i)` at each strike: net gamma, delta or vega) against the map's spot, the rows' underlying or else the chart's close ([Node roles](../functions/options-kit.md#node-roles)). `top_node` is the top: the strike with the largest exposure either way, on a tie the one nearest spot, then the lower, NaN when every strike nets to zero. It draws as a dotted step line labelled `Top node ★` and reads as a row in the card. The card's "Net above and below price" row reads the `sides` slot: the lens's net of the strikes above spot and of those below it, compact and signed (`Above +1.2M | Below -640K`); a strike at spot counts in neither. Both are carried to the bars after them, like the levels. **The map.** On a bar with strike rows the module writes 96 rows from the fold's strikes (`strike(i)` and the lens at it, `value(i)`), centred on the strike nearest the underlying (the rows' own `underlying`, else the chart's close), one row per strike step: the finest gap between neighbouring strikes inside **Map window** (3% each side by default), so a ladder of $1 strikes near the money and $5 strikes further out puts each strike on its own row and leaves the rows between the $5 strikes empty. A strike off the step's grid shares the nearest row. `map_low` is the bottom edge of the lowest row and `map_step` the row height, so each strike's row spans its price plus and minus half a step; `plot.heatmap({ grid: "map", palette: ["theme.down", "theme.bg", "theme.up"], center: 0 })` paints the chart's down colour where puts carry the strike and its up colour where calls do. With **Map values** on change, each strike reads its lens minus the previous strike rows' (0 where they did not list it), and the first bar with strike rows paints nothing. **Carried readings.** The lines and the card carry their newest readings, so a minute the rows missed does not break them: the levels and the week's numbers the newest strike rows at or before each bar (`rows_age` counts the bars since, 0 on a bar that carries its own), the headline the newest statistics row (`stats_age`). The headline says "(3 bars ago)" when its newest reading is not the live bar's. Only a bar with strike rows paints the map. **The session's change.** `gex_change` is net gamma minus net gamma at the session's first reading of the same source: the first statistics row of the bar's trade date (`time.trade_date`, else the trade date on the market's clock), or its first strike rows where the chart has no statistics. It starts at 0 each session and reads how much dealer gamma the day added or removed; until the session's first reading lands it holds the previous session's. ## What the settings do - **Lens**: what the line and the map show, in dollars. gamma: what dealers trade per 1% move. delta: how much stock dealers must hold to hedge. vega: how much dealers gain or lose when option prices rise. - **Map values**: level paints each strike's exposure, and change paints how much it moved since the previous bar with strike data. - **Nearest expiries**: how many of the soonest expiries (the days the options end) the map, flip and walls count. 0 counts all within 7 trade days. - **Map window, percent**: how far the map reaches above and below the price, 3% by default. - **Dealers**: whether dealers calm price (long gamma) or chase it (short gamma). It adds the reading's age in bars when it is not from the live bar. - **Net gamma**: what dealers must trade for each 1% move over every expiry, in dollars. - **Change since session start**: how much net gamma grew or shrank since the session's first reading. - **Net delta**: the position dealers hold, in dollars, each option counted in its own direction. - **Net vega**: what dealers gain or lose, in dollars, for each point of implied volatility. - **Net gamma within 7 days**: net gamma of the expiries within 7 trade days only. - **Gamma flip**: the price where dealer gamma turns from positive to negative for those expiries. - **Call wall**: the strike with the most call gamma, often a ceiling. - **Put wall**: the strike with the most put gamma, often a floor. - **Top node ★**: the strike with the largest exposure in the lens. - **Net above and below price**: the lens's net for the strikes above the price and for those below it. - **Max pain**: the strike where open options would pay out the least at expiry. - **Put/call open interest**: put open interest (contracts still held open) divided by call open interest. - **Strike data age, bars**: how many bars ago the newest strike data arrived. - **Statistics age, bars**: how many bars ago the newest 10-minute sample arrived. ## Where it runs It runs on coins with listed options, where the chart reads the coin's own options by strike. So does a copy you run from the editor (where you write and run your own indicators). On a US stock or ETF chart with US listed options, every indicator in the browser can read them. They run 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), every indicator in the browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). They run 10 minutes behind unless you have real-time CME data. A chart whose market lists no options shows no strike data. The chart asks the server for each bar's measured strikes with the gamma curve. An older chart app without that measure shows an error that names it. The headline's 10-minute statistics cover the symbols sampled every ten minutes. On any other symbol the headline reads the strikes of the expiries within 7 trade days. ## When data is missing A bar without strike data paints no map and keeps the newest readings. That happens outside the session or on a minute the data skipped. A bar whose minute held more than 4,000 strike entries is skipped too, because it is too large to load. Net gamma, the regime and the flip stay blank on a bar whose nearest live expiry lacks the symbol's price. They never fall back to the chart's close, and stored strike data always carries a price. Before the first strike data the week's numbers stay blank. With no 10-minute sample either, the headline reads "No strike data on this chart yet". A bar without a new sample keeps the newest one. Before the first sample, or where the symbol is not sampled every ten minutes, the headline reads the week's strikes. The title then says "no 10-minute statistics here". A strike that lists one side reads that side alone. A side without implied volatility adds nothing to the implied volatility weighting. An expiry that has stopped trading, or is more than 7 trade days out, is left out of every reading. Strike data reaches back about seven days, so older bars on a longer chart draw nothing. ## Customize it - **The front expiry alone.** Set **Nearest expiries** to 1 for the exposure that settles first: the map, the flip, the walls and the week's numbers follow it, and the headline keeps every expiry where the chart has the statistics. - **Where it changed.** Set **Map values** to change: rows in the up colour are strikes where dealer gamma grew since the previous bar, rows in the down colour where it fell. - **A wider map.** Raise **Map window**; a fine ladder stops at 48 strike steps each side. - **Delta or vega.** Set **Lens** to delta or vega: the line follows the headline's net delta or vega and the map the week's, strike by strike; the walls and the regime stay gamma's. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Spot Exposures** under **HUDs**. 2. Press **Run** on a US stock or ETF chart on a 1m or 5m interval: the line, the walls and the map fill bar by bar once the strike rows arrive. 3. At the editor's Console prompt, type `net_gex` (every expiry), `net_gex_week` (the week's), `zero_gamma` (the gamma flip) and `gex_change` to read them on the live bar; `stats_age` and `rows_age` say how old each source is. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option-strikes) for the `option_strikes` celled class and its tuple, [Chain page views](../core-concepts/data-sources.md#chain-page-views) for its strike kit fold (`fold: "kit"`, `levels`, `curve`), and [US listed options, by the chart's underlying](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `option_stats_10m` statistics the headline reads - [Options kit](../functions/options-kit.md#option-strikes-bar-by-bar) for `OptionStrikes`, [Chain page views](../functions/options-kit.md#chain-page-views) for the strike kit fold's rows and `loadLevels`, and [The canonical numbers](../functions/options-kit.md#the-canonical-numbers) for `GammaCurve`, `dealerRegime`, `optionsAsOfMs`, `optionsLiveUntilMs` and `optionsYearsToGo`, the rules the server's fold reads - [Node roles](../functions/options-kit.md#node-roles) for `NodeBoard` - [Price canvases](../presentation/price-canvases.md#a-grid-the-module-computes) for `out.grid` and `plot.heatmap` - [Plotting](../presentation/plotting.md) for the split line and the step lines - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/oi-changes --> # OI changes This shows where traders opened and closed options positions since the last count, by strike (the option's price level). Open interest (contracts still held open) rising at a strike means new positions are building there. A board on the price axis colours each strike by expiry date: up colour for growth, down colour for unwinding. A table under the chart lists the five biggest increases and decreases, and the card leads with the net change. On a chart with listed options, use it to find strikes where new positions pile up. Under the hood: it reads a snapshot of this symbol's options on the live bar (`option_contract_state.cells`, [Data sources](../core-concepts/data-sources.md#us-listed-options-opra)). Each contract carries its open interest and its earlier count (`oi` and `oi_prev`), the day's volume and the quote. It checks each value's `present` bit with `hasBit()` and `isPartial()`. It spells each option's symbol from its code ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). It draws three `plot.matrix` boards, one per kind of number, of which the lens writes one ([Price canvases](../presentation/price-canvases.md#strike-matrices)). It adds a `panel.table` of styled entries ([Cards, frames and panels](../presentation/cards-frames-panels.md#table)) and a `render.hud` card in the default look. It is the `oi-changes` template: **OI Changes** under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // OI Changes: where traders opened and closed options positions since the last count. Open interest (OI: contracts // still held open) changes as positions open or close. A board on the price axis shows the change at each strike (the // option's price level). Its columns are expiries (the days the options end), nearest first. Up colour means positions // built, down colour means they unwound. A table under the chart lists the biggest increases and decreases. The card // leads with the net change for calls and puts. Use it to find strikes where new positions pile up, since they often // become magnets or walls for price. // // Under the hood: the change in open interest since its prior observation comes contract by contract from the chart's // own option chain summary (the option_contract_state source: each contract's open interest and the prior observation // of it, the day's volume and the quote, on the newest bar). A board docked on the price axis reads the change by // strike and expiry (or, by the Lens setting, the change in percent of the prior open interest, the open interest // itself, the day's volume, or the net volume, calls minus puts), a table under the chart lists the largest increases // and decreases (by contracts, or by percent of a prior open interest large enough to mean something), and a card // reads the totals: the calls' and the puts' change, the strikes that built and unwound the most, the open interest // and the day's volume. A contract without both observations of open interest counts in no change, and the card says // how many; a summary the data plane marked partial says so in the title (partial snapshot). The summary is a // snapshot of now: history bars draw nothing, and everything is measured on the last bar, at its as-of (the live // bar's close): the 0DTE column is the expiry of that trade date, and an expiry in another year names it (17 Oct, 15 // Jan '27). section("Board"); param.choice("lens", ["oi_change", "oi_change_pct", "oi", "volume", "net_volume"], "oi_change", { label: "Lens", description: "What the board shows. oi_change: contracts added since the last count. oi_change_pct: that change in percent. oi: open interest now. volume: today's trading. net_volume: calls minus puts." }); param.choice("side", ["both", "calls", "puts"], "both", { label: "Side", description: "Which contracts the board, the table and the strike totals count. Net volume always reads calls minus puts." }); param.int("columns", 6, { min: 1, max: 12, label: "Expiry columns", description: "How many expiries (the dates options end) the board shows, nearest first." }); param.number("window_pct", 5, { min: 1, max: 10, step: 0.5, label: "Strike window, percent", description: "How far the board reaches above and below the price, in percent." }); section("Biggest changes"); param.choice("rank", ["contracts", "percent"], "contracts", { label: "Rank by", description: "How the table ranks contracts: by contracts added or removed, or by percent of their earlier open interest." }); param.int("min_prior_oi", 100, { min: 1, max: 1000000, label: "Smallest prior OI for percent", when: "rank", description: "A contract ranks by percent only if it had at least this much open interest before." }); input("close", ohlcv.close); // the chart's own close: the board's centre input("state", option_contract_state.cells, { max_cells: 24000, expiries: "nearest:24", strike_window_pct: 10, description: "A snapshot of this symbol's options on the newest bar: the 24 nearest expiries, strikes within 10% of the price." }); // [root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present] per contract market.zone(); // the market's clock: each expiry's trade date chart.interval_sec(); // the bar's length: the summary's as-of is the live bar's close; a bar longer than a day names no single day, so no column reads 0DTE // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("call_change", none, overlay, { description: "The calls' open interest change since the last count, in contracts. Live bar only." }); output("put_change", none, overlay, { description: "The puts' open interest change, in contracts." }); output("net_change", none, overlay, { description: "The calls' and puts' change together, in contracts." }); output("total_oi", none, overlay, { description: "Open interest of every contract in the snapshot, in contracts." }); output("day_volume", none, overlay, { description: "Today's volume of every contract in the snapshot, in contracts." }); output("build_strike", none, overlay, { description: "The strike whose open interest grew most, all expiries together, for the Side setting." }); output("build_change", none, overlay, { description: "That strike's change, in contracts." }); output("unwind_strike", none, overlay, { description: "The strike whose open interest fell most" }); output("unwind_change", none, overlay, { description: "That strike's change, in contracts." }); output("counted", none, overlay, { description: "Contracts with both an earlier and a current open interest count." }); output("missing", none, overlay, { description: "Contracts without both counts, left out of every change." }); output("partial", none, overlay, { description: "1 when the snapshot is incomplete, else 0." }); output("tone", none, overlay, { description: "The headline's colour code: 0 net change below zero, 1 none, 2 above zero. Live bar only." }); string("read", { max_bytes: 64 }); // the headline: the net change and its two sides, or why there is none string("title", { max_bytes: 96 }); // the card's title: what the summary held // The board, one matrix per number kind; only the one the lens picks is written, so the other two stay absent. const change_board = frame("change_board", { max_bytes: 32768 }); // signed counts: the OI change, the net volume const pct_board = frame("pct_board", { max_bytes: 32768 }); // the OI change in percent const size_board = frame("size_board", { max_bytes: 32768 }); // the open interest, the day's volume const leaders = frame("leaders", { max_bytes: 8192 }); // the table: the largest increases, then the largest decreases plot.matrix({ name: "change_matrix", frame: change_board, dock: "right", column_width: 62, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "si", signed: true, decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Change by expiry", tooltip: "{{column}}: {{value:si}} at {{price}}" }); plot.matrix({ name: "pct_matrix", frame: pct_board, dock: "right", column_width: 62, row_max_px: 22, price_column: true, header: true, palette: ["theme.down", "theme.bg", "theme.up"], center: 0, scale: "sqrt", opacity: 0.95, format: "%", signed: true, decimals: 0, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Change % by expiry", tooltip: "{{column}}: {{value}}% at {{price}}" }); plot.matrix({ name: "size_matrix", frame: size_board, dock: "right", column_width: 62, row_max_px: 22, price_column: true, header: true, palette: ["theme.bg", "theme.text"], scale: "sqrt", opacity: 0.95, format: "si", decimals: 1, font_size: 10, font_weight: "medium", align: "center", text_color: "theme.text", cell_padding: 3, grid_color: "theme.bg", grid_width: 2, grid_style: "solid", grid_lines: "all", highlight_color: "theme.text", label: "Contracts by expiry", tooltip: "{{column}}: {{value:si}} at {{price}}" }); panel.table({ name: "oi_leaders", title: "Largest open interest changes", x: "category", place: "below", frame: leaders, height_frac: 0.22, header_column: true, header_text_color: "theme.muted", grid_lines: "rows", grid_color: "theme.grid", grid_width: 1, valign: "middle", cell_padding: 4, font_size: 11, series: [{ name: "Contract" }, { name: "Prior OI", align: "right", format: "int" }, { name: "OI", align: "right", format: "int" }, { name: "Change", align: "right", format: "int", signed: true }, { name: "Change %", align: "right", format: "0.0", unit: "%" }, { name: "Volume", align: "right", format: "int" }] }); // The card: the net change leads as the headline, coloured by its sign (down below zero, muted for none, up above), // then the two sides and the strikes that moved most. render.hud("oi_changes", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Open interest", "read", { headline: true, color_by: "tone", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.value("Calls", "call_change", { format: "si" }), tile.value("Puts", "put_change", { format: "si" }), tile.rows([ ["Built most at", "build_strike", "price"], ["Its change", "build_change", "si"], ["Unwound most at", "unwind_strike", "price"], ["Its change", "unwind_change", "si"], ["Total open interest", "total_oi", "si"], ["Today's volume", "day_volume", "si"], ["Without both counts", "missing", "int"], ]), ], }); const TUPLE = 13; // f64s per contract: root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present const BIT_VOLUME = 9; // present bits: volume_day, oi, oi_prev const BIT_OI = 10; const BIT_OI_PREV = 11; const MAX_ROWS = 128; // strikes on the board (a matrix's row cap) const MAX_COLS = 12; // expiries on the board (the setting's cap) const MAX_EXPIRIES = 64; // distinct expiries the summary may list const MAX_STRIKES = 4096; // distinct strikes kept for the per-strike totals, the nearest the close when more const TOP = 5; // rows each side of the leaders table const OI_CHANGE = 0; const OI_CHANGE_PCT = 1; const OI = 2; const VOLUME = 3; const NET_VOLUME = 4; const LENS_TITLES: String[] = ["OI change by expiry", "OI change % by expiry", "Open interest by expiry", "Volume by expiry", "Net volume by expiry"]; const SYMBOL_CHARS: String[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "."]; // a symbol code's characters, value 1 to 37 const expiryMs = new StaticArray<f64>(MAX_EXPIRIES); // the listed expiries, ascending const strikePrice = new StaticArray<f64>(MAX_ROWS); // the board's strikes, ascending const cellA = new StaticArray<f64>(MAX_ROWS * MAX_COLS); // per cell: the lens's sum (the change, the OI, the volume) const cellB = new StaticArray<f64>(MAX_ROWS * MAX_COLS); // per cell: the prior open interest, the percent lens's base const cellSeen = new StaticArray<i32>(MAX_ROWS * MAX_COLS); // 1 where a contract with the lens's readings landed const allStrike = new StaticArray<f64>(MAX_STRIKES); // every strike with a change, ascending const allChange = new StaticArray<f64>(MAX_STRIKES); // and its change over every expiry const upAt = new StaticArray<i32>(TOP); // the largest increases: each contract's offset in the block, and its key const upKey = new StaticArray<f64>(TOP); const downAt = new StaticArray<i32>(TOP); // the largest decreases, the most negative first const downKey = new StaticArray<f64>(TOP); const rootDigits = new StaticArray<i32>(10); // a root's characters, the last first, while it is spelled let lens = OI_CHANGE; // settings, read in onStart() let side = 0; // 0 both, 1 calls, 2 puts let columns = 6; let windowPct = 0.05; let rankPercent = false; let minPrior = 100.0; let zone = 0; let longBar = false; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let asOfMs: f64 = NaN; // the summary's as-of, the live bar's close let close: f64 = NaN; // this bar let today: f64 = NaN; // the live bar's trade date, days since 1970-01-01; NaN on a bar longer than a day let expiryCount = 0; let rowCount = 0; let strikeCount = 0; let upCount = 0; let downCount = 0; let counted = 0; // contracts with both observations let missing = 0; // contracts without them let partial = false; let callChange = 0.0; let putChange = 0.0; let totalOi = 0.0; let dayVolume = 0.0; function onStart(): void { lens = i32(p_lens()); side = i32(p_side()); columns = i32(p_columns()); if (columns > MAX_COLS) columns = MAX_COLS; windowPct = p_window_pct() / 100.0; rankPercent = p_rank() == 1.0; minPrior = p_min_prior_oi(); zone = i32(p_market_zone()); longBar = p_chart_interval_sec() > 86400.0; intervalMs = p_chart_interval_sec() * 1000.0; } // ── The tables: sorted insertion ── function noteExpiry(ms: f64): void { let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryMs[mid] < ms) lo = mid + 1; else hi = mid; } if (lo < expiryCount && expiryMs[lo] == ms) return; if (expiryCount >= MAX_EXPIRIES) { if (lo >= expiryCount) return; // later than every kept expiry expiryCount -= 1; // the latest makes room } for (let k = expiryCount; k > lo; k -= 1) expiryMs[k] = expiryMs[k - 1]; expiryMs[lo] = ms; expiryCount += 1; } function columnOf(ms: f64): i32 { // the board column of an expiry: its rank among the nearest `columns`, or -1 for (let c = 0; c < columns && c < expiryCount; c += 1) if (expiryMs[c] == ms) return c; return -1; } function clearRow(row: i32): void { for (let c = 0; c < MAX_COLS; c += 1) { cellA[row * MAX_COLS + c] = 0.0; cellB[row * MAX_COLS + c] = 0.0; cellSeen[row * MAX_COLS + c] = 0; } } function moveRow(from: i32, to: i32): void { strikePrice[to] = strikePrice[from]; for (let c = 0; c < MAX_COLS; c += 1) { cellA[to * MAX_COLS + c] = cellA[from * MAX_COLS + c]; cellB[to * MAX_COLS + c] = cellB[from * MAX_COLS + c]; cellSeen[to * MAX_COLS + c] = cellSeen[from * MAX_COLS + c]; } } function rowSlot(strike: f64): i32 { // the board row of this strike, inserted when new; -1 when the board is full and it is the farthest from the close let lo = 0; let hi = rowCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } if (lo < rowCount && strikePrice[lo] == strike) return lo; if (rowCount >= MAX_ROWS) { // full: the end farther from the close gives way, unless this strike is farther still const lowGap = Math.abs(strikePrice[0] - close); const highGap = Math.abs(strikePrice[rowCount - 1] - close); if (Math.abs(strike - close) >= Math.max(lowGap, highGap)) return -1; if (lowGap >= highGap) { // drop the lowest row: every row shifts down one for (let i = 0; i < rowCount - 1; i += 1) moveRow(i + 1, i); if (lo > 0) lo -= 1; } rowCount -= 1; if (lo > rowCount) lo = rowCount; } for (let i = rowCount; i > lo; i -= 1) moveRow(i - 1, i); strikePrice[lo] = strike; clearRow(lo); rowCount += 1; return lo; } function addStrikeChange(strike: f64, change: f64): void { // a contract's change into its strike's total over every expiry let lo = 0; let hi = strikeCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (allStrike[mid] < strike) lo = mid + 1; else hi = mid; } if (lo < strikeCount && allStrike[lo] == strike) { allChange[lo] += change; return; } if (strikeCount >= MAX_STRIKES) return; // past the cap: a strike this far down the list is left out of the totals for (let k = strikeCount; k > lo; k -= 1) { allStrike[k] = allStrike[k - 1]; allChange[k] = allChange[k - 1]; } allStrike[lo] = strike; allChange[lo] = change; strikeCount += 1; } // ── The leaders: the TOP largest increases and decreases, ties kept in the summary's order ── function offer(at: i32, key: f64): void { if (key > 0.0) { let k = upCount < TOP ? upCount : TOP; if (k == TOP && key <= upKey[TOP - 1]) return; if (k == TOP) k = TOP - 1; while (k > 0 && upKey[k - 1] < key) { upKey[k] = upKey[k - 1]; upAt[k] = upAt[k - 1]; k -= 1; } upKey[k] = key; upAt[k] = at; if (upCount < TOP) upCount += 1; } else if (key < 0.0) { let k = downCount < TOP ? downCount : TOP; if (k == TOP && key >= downKey[TOP - 1]) return; if (k == TOP) k = TOP - 1; while (k > 0 && downKey[k - 1] > key) { downKey[k] = downKey[k - 1]; downAt[k] = downAt[k - 1]; k -= 1; } downKey[k] = key; downAt[k] = at; if (downCount < TOP) downCount += 1; } } // ── The summary, measured on the live bar ── function sideKept(isCall: bool): bool { return side == 0 || (side == 1) == isCall; } function measure(n: i32): void { // n = f64 cells in the live block const cells = in_state_view(); // the live summary in place: the first n values of the build's own buffer expiryCount = 0; rowCount = 0; strikeCount = 0; upCount = 0; downCount = 0; counted = 0; missing = 0; partial = false; callChange = 0.0; putChange = 0.0; totalOi = 0.0; dayVolume = 0.0; // The first pass: the expiries, the totals, the per-strike changes and the leaders, over every contract. for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const present = cells[i + 12]; if (isPartial(present)) partial = true; const strike = cells[i + 3]; if (!(strike > 0.0) || !isFinite(cells[i + 1])) continue; noteExpiry(cells[i + 1]); if (hasBit(present, BIT_VOLUME)) dayVolume += cells[i + 9]; if (hasBit(present, BIT_OI)) totalOi += cells[i + 10]; if (!hasBit(present, BIT_OI) || !hasBit(present, BIT_OI_PREV)) { missing += 1; // an absent reading is no change continue; } const prior = cells[i + 11]; const change = cells[i + 10] - prior; const isCall = cells[i + 2] > 0.0; counted += 1; if (isCall) callChange += change; else putChange += change; if (!sideKept(isCall)) continue; addStrikeChange(strike, change); if (!rankPercent) offer(i, change); else if (prior >= minPrior) offer(i, (100.0 * change) / prior); } // The second pass: the board, the nearest `columns` expiries inside the strike window. const lo = close * (1.0 - windowPct); const hi = close * (1.0 + windowPct); for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const strike = cells[i + 3]; if (!(strike > 0.0) || strike < lo || strike > hi) continue; const col = columnOf(cells[i + 1]); if (col < 0) continue; const present = cells[i + 12]; const isCall = cells[i + 2] > 0.0; let a: f64 = NaN; // this contract's part of the cell, NaN when it carries no reading for the lens let b = 0.0; if (lens == NET_VOLUME) { if (hasBit(present, BIT_VOLUME)) a = isCall ? cells[i + 9] : -cells[i + 9]; } else if (sideKept(isCall)) { if (lens == OI) { if (hasBit(present, BIT_OI)) a = cells[i + 10]; } else if (lens == VOLUME) { if (hasBit(present, BIT_VOLUME)) a = cells[i + 9]; } else if (hasBit(present, BIT_OI) && hasBit(present, BIT_OI_PREV)) { a = cells[i + 10] - cells[i + 11]; b = cells[i + 11]; } } if (isNaN(a)) continue; const row = rowSlot(strike); if (row < 0) continue; cellA[row * MAX_COLS + col] += a; cellB[row * MAX_COLS + col] += b; cellSeen[row * MAX_COLS + col] = 1; } } // ── Text helpers, written into the frame buffer and the line buffer without allocating ── function fbRoot(code: f64): bool { // the option root a symbol code names; false (nothing written) when it names none if (!isFinite(code) || code < 1.0 || code > 6278211847988223.0 || code != Math.floor(code)) return false; let rest = u64(code); let count = 0; while (rest > 0) { const value = i32(rest % 38); if (value == 0 || count >= 10) return false; // no text encodes to a zero digit rootDigits[count] = value; count += 1; rest = rest / 38; } for (let k = count - 1; k >= 0; k -= 1) fb_text(SYMBOL_CHARS[rootDigits[k] - 1]); return true; } function fbDate(ms: f64): void { // "17 Oct", or "15 Jan '27" in another year: an expiry's trade date, the kit's label fbExpiryLabel(ms, asOfMs, zone); } function fbStrike(v: f64): void { // a strike as it is quoted: 660, 662.5, 0.25 if (v == Math.floor(v)) fb_int(i64(v)); else if (v * 10.0 == Math.floor(v * 10.0)) fb_f64(v, 1); else fb_f64(v, 2); } function fbContract(cells: StaticArray<f64>, i: i32): void { // "\"SPY 17 Oct 660C\"", a root that spells nothing as "?" fb_text("\""); if (!fbRoot(cells[i])) fb_text("?"); fb_text(" "); fbDate(cells[i + 1]); fb_text(" "); fbStrike(cells[i + 3]); fb_text(cells[i + 2] > 0.0 ? "C\"" : "P\""); } function sbCount(v: f64): void { // "+12.3K", "-850", "0" if (v > 0.0) sb_text("+"); else if (v < 0.0) sb_text("-"); const a = Math.abs(v); if (a >= 1.0e6) { sb_f64(a / 1.0e6, 1); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 1); sb_text("K"); } else sb_f64(a, 0); } // ── Frames: the board and the leaders, appended as JSON text without allocating ── function writeBoard(): void { // strikes ascending, one cell per expiry column, the row nearest the close highlighted if (rowCount == 0) return; const cols = columns < expiryCount ? columns : expiryCount; let atm = 0; // the row nearest the close for (let r = 1; r < rowCount; r += 1) if (Math.abs(strikePrice[r] - close) < Math.abs(strikePrice[atm] - close)) atm = r; fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_num(strikePrice[r]); } fb_text("],\"cells\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_text("["); for (let c = 0; c < cols; c += 1) { if (c > 0) fb_text(","); const at = r * MAX_COLS + c; if (cellSeen[at] == 0) fb_text("null"); // no contract with the lens's readings in this cell: no fill, no text else if (lens == OI_CHANGE_PCT) fb_num(cellB[at] > 0.0 ? (100.0 * cellA[at]) / cellB[at] : NaN); // a cell of new contracts only has no base: null else fb_num(cellA[at]); } fb_text("]"); } fb_text("],\"cols\":["); for (let c = 0; c < cols; c += 1) { if (c > 0) fb_text(","); fb_text("\""); if (c == 0 && !isNaN(today) && optionsTradeDay(expiryMs[c], zone) <= today) fb_text("0DTE"); else fbDate(expiryMs[c]); fb_text("\""); } fb_text("],\"title\":\""); fb_text(LENS_TITLES[lens]); fb_text("\",\"highlight\":{\"price\":"); fb_num(strikePrice[atm]); fb_text("}}"); if (lens == OI_CHANGE_PCT) writeFrameBuffer(pct_board); else if (lens == OI || lens == VOLUME) writeFrameBuffer(size_board); else writeFrameBuffer(change_board); } function fbLeader(cells: StaticArray<f64>, i: i32): void { // one table row: the contract, the prior OI, the OI, the change, the change in percent, the day's volume const prior = cells[i + 11]; const change = cells[i + 10] - prior; fb_text("["); fbContract(cells, i); fb_text(","); fb_num(prior); fb_text(","); fb_num(cells[i + 10]); fb_text(",{\"value\":"); fb_num(change); fb_text(change >= 0.0 ? ",\"text_color\":\"theme.up\"}," : ",\"text_color\":\"theme.down\"},"); if (prior > 0.0) fb_num((100.0 * change) / prior); else fb_text("\"new\""); // no prior open interest: every contract is new fb_text(","); if (hasBit(cells[i + 12], BIT_VOLUME)) fb_num(cells[i + 9]); else fb_text("null"); fb_text("]"); } function writeLeaders(): void { const cells = in_state_view(); fb_clear(); fb_text("{\"caption\":\""); if (upCount + downCount == 0) fb_text("No change in open interest to rank"); else { fb_text("Largest increases, then decreases, by "); fb_text(rankPercent ? "percent of the prior OI" : "contracts"); } fb_text("\",\"rows\":["); for (let k = 0; k < upCount; k += 1) { if (k > 0) fb_text(","); fbLeader(cells, upAt[k]); } for (let k = 0; k < downCount; k += 1) { if (upCount + k > 0) fb_text(","); fbLeader(cells, downAt[k]); } fb_text("]}"); writeFrameBuffer(leaders); } // ── The card's words ── function writeWords(): void { sb_clear(); if (counted == 0) sb_text("No contract has both open interest counts"); else { sb_text("Net "); sbCount(callChange + putChange); sb_text(": calls "); sbCount(callChange); sb_text(", puts "); sbCount(putChange); } str_read_sb(); sb_clear(); sb_text("OI change since the last count, "); sb_int(expiryCount); sb_text(expiryCount == 1 ? " expiry, " : " expiries, "); sb_int(counted); sb_text(" contracts"); if (partial) sb_text(", partial snapshot"); str_title_sb(); } // onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar measures the summary, // writes the readings (NaN on history rows), the board, the table and the card's words. function onBar(): void { close = bar.close(); const t = bar.time(); let measured = false; // the live bar carried a summary with a contract in it let stateCells = -1; if (bar.isLast() && !isNaN(close) && !isNaN(t)) { stateCells = in_state_cells(); if (stateCells >= TUPLE) { asOfMs = optionsAsOfMs(t * 1000.0, intervalMs); // the summary's as-of: the live bar's close time today = longBar ? NaN : optionsTradeDay(asOfMs, zone); measure(stateCells); measured = expiryCount > 0; } } const reading = measured && counted > 0; const net = callChange + putChange; let build = -1; // the strikes whose change, every expiry together, rose and fell most let unwind = -1; if (reading) { for (let k = 0; k < strikeCount; k += 1) { if (allChange[k] > 0.0 && (build < 0 || allChange[k] > allChange[build])) build = k; if (allChange[k] < 0.0 && (unwind < 0 || allChange[k] < allChange[unwind])) unwind = k; } } out_call_change(reading ? callChange : NaN); out_put_change(reading ? putChange : NaN); out_net_change(reading ? net : NaN); out_total_oi(measured ? totalOi : NaN); out_day_volume(measured ? dayVolume : NaN); out_build_strike(build >= 0 ? allStrike[build] : NaN); out_build_change(build >= 0 ? allChange[build] : NaN); out_unwind_strike(unwind >= 0 ? allStrike[unwind] : NaN); out_unwind_change(unwind >= 0 ? allChange[unwind] : NaN); out_counted(measured ? f64(counted) : NaN); out_missing(measured ? f64(missing) : NaN); out_partial(measured ? (partial ? 1.0 : 0.0) : NaN); out_tone(reading ? (net > 0.0 ? 2.0 : net < 0.0 ? 0.0 : 1.0) : bar.isLast() ? 1.0 : NaN); if (measured) { writeBoard(); writeLeaders(); writeWords(); } else if (bar.isLast()) { // The live bar carried nothing to measure: the headline says why, so the card is never a row of blanks. sb_clear(); sb_text(stateCells < TUPLE ? "Waiting for this symbol's options snapshot" : "No contract in the snapshot"); str_read_sb(); sb_clear(); sb_text("OI change since the last count, no snapshot yet"); str_title_sb(); } } ``` ## How it works **The summary is a snapshot of now.** `input("state", option_contract_state.cells, { max_cells: 24000, expiries: "nearest:24", strike_window_pct: 10 })` delivers one 13-value tuple per contract of the 24 nearest expiries with a strike within 10% of the underlying, on the live row; every history bar carries an empty block, so everything is measured on the last bar and the card, the board and the table are rewritten as the summary refreshes. The knobs are part of the fetch, so the sheet names them; the 24,000 cells leave room for an index's ladder of strikes. **A change needs both readings.** A contract counts in a change only when its `present` mask carries bit 10 (`oi`) and bit 11 (`oi_prev`): the change is `oi - oi_prev`, in contracts. A contract missing either reading is counted in the card's last row ("Without both counts") and left out of every change, never read as 0. A contract with a prior open interest of 0 is new: its change counts, and the table prints `new` in its percent column. When any tuple carries bit 14 the data plane cut the summary short, and the title says "partial snapshot". **The board.** The nearest **Expiry columns** expiries (6 by default) and the strikes within **Strike window** of the close (5% each side, at most 128 rows, the farthest from the close giving way first) make the board. Each cell sums its contracts on the lens: the change (`oi_change`), the change over the cell's prior open interest in percent (`oi_change_pct`; a cell of new contracts alone has no base and prints nothing), the open interest (`oi`), the day's volume (`volume`) or the call volume minus the put volume (`net_volume`). **Side** keeps the calls or the puts alone on every lens but the net volume. A cell with no contract that carries the lens's readings prints nothing and takes no tint. Each column is named by its expiry's label, the kit's `fbExpiryLabel` (`17 Oct`, or `15 Jan '27` for an expiry in another year), and the front column reads `0DTE` when its expiry's trade date is today's: the trade date of the summary's as-of, the live bar's close (`optionsAsOfMs`), on the market's clock (on a chart of a day or shorter; a longer bar names no single day). Signed counts ride a board with a diverging palette centred on zero, percents a board formatted `%`, and the open interest and the volume a board with one ramp, so each prints its own unit. **The leaders.** Every contract with both readings on the **Side** setting is offered to two lists of five: the largest increases, then the largest decreases (the most negative first), by contracts, or by percent of the prior open interest when **Rank by** says so, among the contracts holding at least **Smallest prior OI for percent** (100 by default: a change from 3 to 57,154 contracts is not a percent worth ranking). Ties keep the summary's order. Each row names the contract (`SPY 17 Oct 660C`: the root from its symbol code, `?` when the code spells nothing, the expiry's label, the strike, C or P), the prior open interest, the open interest, the change in the up or down colour, the change in percent and the day's volume. **The card.** The headline is the net change with its two sides (`Net +12.3K: calls +9.9K, puts +2.5K`), coloured by its sign (the up colour above zero, the down colour below, muted for none); then the calls' and the puts' change, the strikes whose change summed over every expiry rose and fell most, with their changes, the open interest and the day's volume of every listed contract, and the count without both readings. The title says how many expiries and contracts the summary held. ## What the settings do - **Lens**: what the board shows. oi_change: contracts added since the last count. oi_change_pct: that change in percent. oi: open interest now. volume: today's trading. net_volume: calls minus puts. - **Side**: which contracts the board, the table and the strike totals count: both, calls or puts. - **Expiry columns**: how many expiries (the dates options end) the board shows, nearest first, 6 by default. - **Strike window, percent**: how far the board reaches above and below the price, 5% by default. - **Rank by**: whether the table ranks contracts by contracts added or removed, or by percent of their earlier open interest. - **Smallest prior OI for percent**: the earlier open interest a contract needs before it can rank by percent, 100 by default. - **Open interest**: the net change since the last count, split into calls and puts, coloured by its sign. - **Calls**: how many call contracts were opened (positive) or closed (negative). - **Puts**: how many put contracts were opened or closed. - **Built most at**: the strike where open interest grew the most, all expiries together. - **Its change**: how many contracts that strike added. - **Unwound most at**: the strike where open interest fell the most. - **Its change**: how many contracts that strike lost. - **Total open interest**: the open interest of every contract in the snapshot. - **Today's volume**: the contracts traded today across the snapshot. - **Without both counts**: contracts left out because they lack an earlier or a current count. ## Where it runs It runs on coins with listed options, where the chart reads the coin's own options snapshot. So does a copy you run from the editor (where you write and run your own indicators). On a US stock or ETF chart with US listed options, every indicator in the browser can read it. It runs 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), every indicator in the browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). It runs 10 minutes behind unless you have real-time CME data. A delayed CME chart has no earlier count to compare. There every contract lands in the card's **Without both counts** line, and no change draws. ## When data is missing The card's headline says why instead of going blank. It reads "Waiting for this symbol's options snapshot" while the live bar has none. It reads "No contract in the snapshot" when the snapshot is empty. It reads "No contract has both open interest counts" when no earlier open interest was recorded. A spot on the board with no reading stays blank. When no spot has a reading, the board does not draw. ## Customize it - **Today's trading instead.** Set **Lens** to volume, or net volume for calls against puts by strike and expiry. - **The puts alone.** Set **Side** to puts: the board, the table and the strike totals count the puts. - **Rank by percent.** Set **Rank by** to percent and raise **Smallest prior OI for percent** to keep thin contracts out. - **Further out.** Change `expiries: "nearest:24"` and `strike_window_pct: 10` in the input and Run again; size `max_cells` for the contracts they keep. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **OI Changes** under **HUDs**. 2. Press **Run** on a US stock or ETF chart: the board docks at the price axis once the summary arrives, the table opens under the chart and the card at the bottom centre. 3. At the editor's Console prompt, type `net_change`, `build_strike` and `missing` to read them on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-opra) for the `option_contract_state` celled class, its tuple, its knobs and the present mask - [Price canvases](../presentation/price-canvases.md#strike-matrices) for `plot.matrix` and the matrix frame - [Cards, frames and panels](../presentation/cards-frames-panels.md#table) for `panel.table` and its styled cells - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel`, and [the chain's as-of](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsAsOfMs` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name <!-- source: https://openmarket.xyz/wrun/cookbook/top-contracts --> # Top contracts Top Contracts lists this symbol's most active option contracts right now, in a table under the chart. Rank them by today's volume, open interest (contracts still held open), premium (the money paid) or price gain. Dashed lines mark the three most traded strikes (option price levels), and dotted lines the three with most open interest. A card leads with the top contract, and put/call volume above 1 means more puts (bets on a fall) traded. Use it on a US stock, coin or CME (Chicago futures exchange) future to see where bets crowd today. Under the hood: a celled `option_contract_state.cells` input is read on the live bar naming the `top` and `totals` page views. Every setting is bound, so the data plane sends only the contracts the settings can rank and the summary's totals ([Data sources](../core-concepts/data-sources.md#us-listed-options-opra), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). The options kit's `viewTuples` and `ChainTotals` read them ([Options kit](../functions/options-kit.md#chain-page-views)). Its `present` bits are read with `hasBit()`, and its option roots are spelled from their symbol codes ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). `TextBuilder.expiry` and `fbExpiryLabel` give each contract's expiry ([A second builder](../functions/text-formatting.md#a-second-builder), [Panel frames](../presentation/cards-frames-panels.md#panel-frames)). `market.option_contract()` marks an option contract's own chart ([Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file)). A `panel.table` reads a frame of styled cells ([Cards, frames and panels](../presentation/cards-frames-panels.md#table)). Line and label handles draw the six levels named `V1` to `V3` and `OI1` to `OI3` ([Drawing objects](../presentation/drawing-objects.md#handles)). A `render.hud` card draws in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). This is also the `top-contracts` template: the **Top Contracts** card under **HUDs** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Top Contracts: this symbol's most active option contracts right now, in a table under the chart. A contract is one // option, a call (a bet on a rise) or a put (a bet on a fall). Rank them by volume today, open interest (contracts // still held open), premium (the money paid) or gain. Lines mark the strikes (option price levels) with the most volume // and open interest. A card leads with the top contract. Use it to see which bets the market crowds into today. // // Under the hood: the chart's most active option contracts on the newest bar, from its own option chain summary (the // option_contract_state source). The Rank setting orders them by the day's volume, the open interest, the premium (the // day's volume at the last price times the market's option multiplier, 100 shares on a US stock: an estimate, since the // summary carries no traded premium; none where the host does not know the multiplier), or the gain since the prior // session's close (a contract needs the Smallest volume to rank by gain), and a table under the chart lists the top // ones with the last price, the change, the volume, the open interest, volume over open interest, the premium and the // share of the day's volume. The strikes of the three most traded contracts (dashed) and of the three with the most // open interest (dotted) are drawn across the chart as muted levels, each with its contract as plain text at the axis // (on the underlying's own chart: the close inside the strikes the summary lists; never on an option contract's own // chart, market.option_contract(), whose price axis is the contract's premium: there the table keeps filling and its // caption says so), and a card leads with the top contract. A contract names its expiry as 17 Oct, or 15 Jan '27 in // another year. The summary is a snapshot of now: history bars draw nothing, and everything is measured on the last // bar. The data plane sends the contracts the table and the levels can rank on the settings, in the summary's order, // and the summary's totals. section("Ranking"); param.choice("rank", ["volume", "oi", "premium", "gain"], "volume", { label: "Rank by", description: "volume ranks by today's contracts traded. oi ranks by open interest (contracts still held open). premium ranks by the money paid today, the volume times the last price and contract size, an estimate. gain ranks by the change since the prior close." }); param.choice("side", ["both", "calls", "puts"], "both", { label: "Calls or puts", description: "Ranks calls (bets on a rise), puts (bets on a fall) or both, in the table and the levels." }); param.int("rows", 10, { min: 3, max: 25, label: "Contracts listed", description: "How many contracts the table shows." }); param.int("min_volume", 100, { min: 0, max: 1000000, label: "Smallest volume for gain", when: "rank=3", description: "Today's volume a contract needs to rank by gain. It counts contracts on US stocks and CME, coins on crypto." }); param.bool("levels", true, { label: "Strike levels", description: "Draws lines at the strikes (option price levels) of the three most traded and three most held contracts. Most held means the most open interest (contracts still held open)." }); input("close", ohlcv.close); // the chart's own close: whether the strikes belong on this chart's price axis input("state", option_contract_state.cells, { max_cells: 64, expiries: "nearest:24", strike_window_pct: 10, page_views: ["top", "totals"], rank: "@rank", side: "@side", rows: "@rows", min_volume: "@min_volume", description: "This symbol's options summary on the newest bar, for the 24 nearest expiries and strikes within 10% of the price. It holds the contracts your settings rank and the summary's totals." }); // view rows of OPTION_VIEW_ROW_STATE f64s: [0, root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present, 0, 0] per ranked contract, in the summary's order, then [1, contracts, expiries, partial, low_strike, high_strike, traded, traded_volume, call_volume, put_volume, day_volume, total_oi, missing, counted, call_change, put_change] market.zone(); // the market's clock: each expiry's trade date market.option_multiplier(); // the chain's USD per price unit and size unit: 100 on a US stock, 50 on ES, 1 on a coin; 0 unknown market.option_contract(); // 1 on an option contract's own chart: its price axis is the contract's premium, so no strike levels // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("top_strike", none, overlay, { description: "The top contract's strike (its price level). Live bar only." }); output("top_value", none, overlay, { description: "The top contract's value for Rank by, in contracts, USD or percent." }); output("total_volume", none, overlay, { description: "Today's volume of every contract listed, in contracts." }); output("call_volume", none, overlay, { description: "Today's volume of calls (bets on a rise), in contracts." }); output("put_volume", none, overlay, { description: "Today's volume of puts (bets on a fall), in contracts." }); output("put_call_volume", none, overlay, { description: "Put volume divided by call volume. Above 1 means more puts (bets on a fall) traded than calls." }); output("traded", none, overlay, { description: "Contracts that traded today." }); output("partial", none, overlay, { description: "1 when this symbol's options data arrived incomplete, else 0." }); output("top_side", none, overlay, { description: "Colour code for the top contract: 0 a put, 1 none, 2 a call. A call bets on a rise, a put on a fall." }); string("read", { max_bytes: 64 }); // the headline: the top contract and its reading, or why there is none string("title", { max_bytes: 80 }); // the card's title: the rank and what the summary held string("tag", { max_bytes: 48 }); // one bounded slot the six level texts are written through, one at a time const top = frame("top", { max_bytes: 16384 }); // the table's rows panel.table({ name: "top_contracts", title: "Most active contracts", x: "category", place: "below", frame: top, height_frac: 0.25, header_column: true, header_text_color: "theme.muted", grid_lines: "rows", grid_color: "theme.grid", grid_width: 1, valign: "middle", cell_padding: 4, font_size: 11, series: [{ name: "Contract" }, { name: "Last", align: "right", format: "0.00" }, { name: "Change", align: "right", format: "0.0", signed: true, unit: "%" }, { name: "Volume", align: "right", format: "int" }, { name: "OI", align: "right", format: "int" }, { name: "Vol/OI", align: "right", format: "0.00" }, { name: "Premium", align: "right", format: "usd" }, { name: "Share", align: "right", format: "0.0", unit: "%" }] }); handles.line({ width: 1, extend: "both" }); // the six strike levels, across the whole chart handles.label({ anchor: "right", align: "right", size: 11, color: "theme.muted", style: "plain" }); // their text: x in pixels from the right edge, y in price // The card: the top contract leads as the headline, up on a call and down on a put, then the day's volume and its // split. render.hud("top_contracts", { position: "bottom_center", title: "{{title}}", columns: 2, tiles: [ tile.pill("Top contract", "read", { headline: true, color_by: "top_side", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.value("Day volume", "total_volume", { format: "si" }), tile.value("Put/call volume", "put_call_volume", { format: "0.00" }), tile.rows([ ["Top strike", "top_strike", "price"], ["Its value", "top_value", "auto"], ["Calls traded", "call_volume", "si"], ["Puts traded", "put_volume", "si"], ["Contracts that traded", "traded", "int"], ]), ], }); const TUPLE = 13; // f64s per contract: root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present const BIT_LAST = 6; // present bits: last, prev_close, volume_day, oi const BIT_PREV_CLOSE = 7; const BIT_VOLUME = 9; const BIT_OI = 10; const MAX_ROWS = 25; // the Rows setting's cap const LEVELS = 3; // levels per list: the most traded, the most open interest const RANK_VOLUME = 0; const RANK_OI = 1; const RANK_PREMIUM = 2; const RANK_GAIN = 3; const RANK_WORDS: String[] = ["volume", "open interest", "premium", "gain"]; const SYMBOL_CHARS: String[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "."]; // a symbol code's characters, value 1 to 37 const LEVEL = theme.MUTED; // every level: a strike, never a sign const ranked = new StaticArray<f64>(in_state_max_cells * TUPLE); // the contracts the data plane ranked for the settings, in the summary's order const totals = new ChainTotals(); // the summary's counts and sums over every contract const rankAt = new StaticArray<i32>(MAX_ROWS); // the table: each contract's offset in ranked, and its key, the largest first const rankKey = new StaticArray<f64>(MAX_ROWS); const volAt = new StaticArray<i32>(LEVELS); // the most traded contracts, for the levels const volKey = new StaticArray<f64>(LEVELS); const oiAt = new StaticArray<i32>(LEVELS); // the contracts with the most open interest const oiKey = new StaticArray<f64>(LEVELS); const rootDigits = new StaticArray<i32>(10); // a root's characters, the last first, while it is spelled const lines: LineHandle[] = [draw.line(0), draw.line(1), draw.line(2), draw.line(3), draw.line(4), draw.line(5)]; // the three volume levels, then the three open interest levels const tags: LabelHandle[] = [draw.label(6), draw.label(7), draw.label(8), draw.label(9), draw.label(10), draw.label(11)]; // ids are one space across kinds const tagPrices = new StaticArray<f64>(6); // the tags placed so far on this bar, so a level near another steps inward const tagSlots = new StaticArray<i32>(6); // the step inward each placed tag took const expiryText = new TextBuilder(16); // an expiry's label, the kit's spelling, copied into the line by sbContract() let rank = RANK_VOLUME; // settings, read in onStart() let side = 0; // 0 both, 1 calls, 2 puts let rowsWanted = 10; let minVolume = 100.0; let drawLevels = true; let zone = 0; let optMult: f64 = NaN; // NaN where the host does not know the multiplier: no premium, never 0 let optionContract = false; // the chart is one option contract's own: no levels on its premium axis let close: f64 = NaN; // this bar let t: f64 = NaN; let firstT: f64 = NaN; // the first bar's open time: where the levels start let rankCount = 0; let volCount = 0; let oiCount = 0; let expiries = 0; // distinct expiries the summary lists let contracts = 0; // contracts it lists let traded = 0; // contracts with volume today let partial = false; let totalVolume = 0.0; let callVolume = 0.0; let putVolume = 0.0; let lowStrike: f64 = NaN; // the strikes the summary lists, lowest and highest let highStrike: f64 = NaN; function onStart(): void { rank = i32(p_rank()); side = i32(p_side()); rowsWanted = i32(p_rows()); if (rowsWanted > MAX_ROWS) rowsWanted = MAX_ROWS; minVolume = p_min_volume(); drawLevels = pb_levels(); zone = i32(p_market_zone()); optMult = p_market_option_multiplier() > 0.0 ? p_market_option_multiplier() : NaN; optionContract = i32(p_market_option_contract()) == 1; } // ── The rankings: insertion into a short list, the largest first, ties kept in the summary's order ── function insert(at: StaticArray<i32>, keys: StaticArray<f64>, count: i32, cap: i32, offset: i32, key: f64): i32 { // returns the new count let k = count < cap ? count : cap; if (k == cap && key <= keys[cap - 1]) return count; if (k == cap) k = cap - 1; while (k > 0 && keys[k - 1] < key) { keys[k] = keys[k - 1]; at[k] = at[k - 1]; k -= 1; } keys[k] = key; at[k] = offset; return count < cap ? count + 1 : cap; } function sideKept(isCall: bool): bool { return side == 0 || (side == 1) == isCall; } function keyOf(cells: StaticArray<f64>, i: i32): f64 { // the contract's reading on the Rank setting; NaN when it does not rank const present = cells[i + 12]; const volume = hasBit(present, BIT_VOLUME) ? cells[i + 9] : NaN; const last = hasBit(present, BIT_LAST) ? cells[i + 6] : NaN; if (rank == RANK_VOLUME) return volume > 0.0 ? volume : NaN; if (rank == RANK_OI) return hasBit(present, BIT_OI) && cells[i + 10] > 0.0 ? cells[i + 10] : NaN; if (rank == RANK_PREMIUM) return volume > 0.0 && last > 0.0 ? volume * last * optMult : NaN; const prev = hasBit(present, BIT_PREV_CLOSE) ? cells[i + 7] : NaN; if (!(volume >= minVolume) || !(volume > 0.0) || !(last > 0.0) || !(prev > 0.0)) return NaN; // gain: traded enough, both prices return (last / prev - 1.0) * 100.0; } // ── The summary, measured on the live bar: the totals the data plane summed, the rankings over what it sent ── function measure(n: i32): void { const view = in_state_view(); // the live view rows in place: the first n values of the build's own buffer rankCount = 0; volCount = 0; oiCount = 0; const loaded = totals.load(view, n); // contracts, expiries (at most 64), partial, the strikes and the volumes expiries = loaded ? i32(totals.expiries()) : 0; contracts = loaded ? i32(totals.contracts()) : 0; traded = loaded ? i32(totals.traded()) : 0; partial = loaded && totals.partial(); totalVolume = loaded ? totals.tradedVolume() : 0.0; callVolume = loaded ? totals.callVolume() : 0.0; putVolume = loaded ? totals.putVolume() : 0.0; lowStrike = totals.lowStrike(); // NaN with no contract highStrike = totals.highStrike(); const m = viewTuples(view, n, OPTION_VIEW_ROW_STATE, TUPLE, ranked); // the ranked contracts' tuples, in the summary's order for (let i = 0; i + TUPLE - 1 < m; i += TUPLE) { const present = ranked[i + 12]; const strike = ranked[i + 3]; if (!(strike > 0.0) || !isFinite(ranked[i + 1])) continue; const isCall = ranked[i + 2] > 0.0; const volume = hasBit(present, BIT_VOLUME) ? ranked[i + 9] : 0.0; if (!sideKept(isCall)) continue; const key = keyOf(ranked, i); if (!isNaN(key)) rankCount = insert(rankAt, rankKey, rankCount, rowsWanted, i, key); if (volume > 0.0) volCount = insert(volAt, volKey, volCount, LEVELS, i, volume); if (hasBit(present, BIT_OI) && ranked[i + 10] > 0.0) oiCount = insert(oiAt, oiKey, oiCount, LEVELS, i, ranked[i + 10]); } } // ── Text helpers, written into the frame buffer and the line buffer without allocating ── function rootCount(code: f64): i32 { // the characters of the root a symbol code names, the last first in rootDigits; 0 when it names none if (!isFinite(code) || code < 1.0 || code > 6278211847988223.0 || code != Math.floor(code)) return 0; let rest = u64(code); let count = 0; while (rest > 0) { const value = i32(rest % 38); if (value == 0 || count >= 10) return 0; // no text encodes to a zero digit rootDigits[count] = value; count += 1; rest = rest / 38; } return count; } function strikeDecimals(v: f64): i32 { // a strike as it is quoted: 660, 662.5, 0.25 return v == Math.floor(v) ? 0 : v * 10.0 == Math.floor(v * 10.0) ? 1 : 2; } function fbContract(cells: StaticArray<f64>, i: i32): void { // "\"SPY 17 Oct 660C\"", a root that spells nothing as "?" fb_text("\""); const count = rootCount(cells[i]); if (count == 0) fb_text("?"); for (let k = count - 1; k >= 0; k -= 1) fb_text(SYMBOL_CHARS[rootDigits[k] - 1]); fb_text(" "); fbExpiryLabel(cells[i + 1], t * 1000.0, zone); // the expiry's trade date: 17 Oct, or 15 Jan '27 in another year fb_text(" "); const decimals = strikeDecimals(cells[i + 3]); if (decimals == 0) fb_int(i64(cells[i + 3])); else fb_f64(cells[i + 3], decimals); fb_text(cells[i + 2] > 0.0 ? "C\"" : "P\""); } function sbContract(cells: StaticArray<f64>, i: i32): void { // the same words in the line buffer, unquoted const count = rootCount(cells[i]); if (count == 0) sb_text("?"); for (let k = count - 1; k >= 0; k -= 1) sb_text(SYMBOL_CHARS[rootDigits[k] - 1]); sb_text(" "); expiryText.clear().expiry(cells[i + 1], t * 1000.0, zone); for (let k = 0; k < expiryText.length(); k += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>k)); sb_text(" "); const decimals = strikeDecimals(cells[i + 3]); if (decimals == 0) sb_int(i64(cells[i + 3])); else sb_f64(cells[i + 3], decimals); sb_text(cells[i + 2] > 0.0 ? "C" : "P"); } function sbShort(v: f64): void { // "84.2K", "1.3M", "850" const a = Math.abs(v); if (v < 0.0) sb_text("-"); if (a >= 1.0e9) { sb_f64(a / 1.0e9, 2); sb_text("B"); } else if (a >= 1.0e6) { sb_f64(a / 1.0e6, 1); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 1); sb_text("K"); } else sb_f64(a, 0); } // ── The table, appended as JSON text without allocating ── function writeTable(): void { const cells = ranked; fb_clear(); fb_text("{\"caption\":\""); if (rankCount == 0) fb_text("No contract ranks on this setting"); else if (optionContract && drawLevels) fb_text("On a contract's own chart, no levels"); // the card's title names the rank else { fb_text("Ranked by "); fb_text(RANK_WORDS[rank]); if (rank == RANK_PREMIUM) fb_text(": volume at the last price, an estimate"); } fb_text("\",\"rows\":["); for (let k = 0; k < rankCount; k += 1) { const i = rankAt[k]; const present = cells[i + 12]; const last = hasBit(present, BIT_LAST) ? cells[i + 6] : NaN; const prev = hasBit(present, BIT_PREV_CLOSE) ? cells[i + 7] : NaN; const volume = hasBit(present, BIT_VOLUME) ? cells[i + 9] : NaN; const oi = hasBit(present, BIT_OI) ? cells[i + 10] : NaN; if (k > 0) fb_text(","); fb_text("["); fbContract(cells, i); fb_text(","); fb_num(last); fb_text(","); const change = last > 0.0 && prev > 0.0 ? (last / prev - 1.0) * 100.0 : NaN; if (isNaN(change)) fb_text("null"); else { fb_text("{\"value\":"); fb_num(change); fb_text(change >= 0.0 ? ",\"text_color\":\"theme.up\"}" : ",\"text_color\":\"theme.down\"}"); } fb_text(","); fb_num(volume); fb_text(","); fb_num(oi); fb_text(","); fb_num(volume >= 0.0 && oi > 0.0 ? volume / oi : NaN); fb_text(","); fb_num(volume >= 0.0 && last > 0.0 ? volume * last * optMult : NaN); fb_text(","); fb_num(volume >= 0.0 && totalVolume > 0.0 ? (100.0 * volume) / totalVolume : NaN); fb_text("]"); } fb_text("]}"); writeFrameBuffer(top); } // ── The levels: the most traded strikes and the strikes with the most open interest, named at the price axis ── function near(a: f64, b: f64): bool { // two levels within 0.3% of each other would share a text row return !isNaN(a) && !isNaN(b) && Math.abs(a - b) <= Math.abs(b) * 0.003; } function stepTaken(which: i32, price: f64, step: i32): bool { // an earlier text within 0.3% of this price already sits at this step for (let j = 0; j < which; j += 1) if (tagSlots[j] == step && near(tagPrices[j], price)) return true; return false; } function clearLevel(which: i32): void { lines[which].delete(); // no-ops when never drawn tags[which].delete(); tagPrices[which] = NaN; tagSlots[which] = -1; } function drawLevel(which: i32, cells: StaticArray<f64>, i: i32, word: String, value: f64, ink: i32, style: LineStyle): void { const strike = cells[i + 3]; lines[which].set(firstT, strike, t, strike).color(ink).width(1.0).style(style).extend(Extend.Both); let step = 0; // the first step inward that no earlier text within 0.3% holds while (stepTaken(which, strike, step)) step += 1; tagPrices[which] = strike; tagSlots[which] = step; sb_clear(); sb_text(word); sb_text(" "); sbContract(cells, i); sb_text(" "); sbShort(value); tags[which].set(56.0 + 132.0 * f64(step), strike).text(str_tag_sb).valign(VALIGN_BOTTOM); // plain muted text (the label template) whose box sits on the line, so the line never runs through it; 56 px in from the right edge clears the axis tags; each step is 132 px further in } function writeLevels(onThisChart: bool): void { const cells = ranked; for (let k = 0; k < LEVELS; k += 1) { if (drawLevels && onThisChart && k < volCount) drawLevel(k, cells, volAt[k], k == 0 ? "V1" : k == 1 ? "V2" : "V3", volKey[k], LEVEL, LineStyle.Dashed); else clearLevel(k); } for (let k = 0; k < LEVELS; k += 1) { if (drawLevels && onThisChart && k < oiCount) drawLevel(LEVELS + k, cells, oiAt[k], k == 0 ? "OI1" : k == 1 ? "OI2" : "OI3", oiKey[k], LEVEL, LineStyle.Dotted); else clearLevel(LEVELS + k); } } // ── The card's words ── function writeWords(): void { const cells = ranked; sb_clear(); if (rankCount == 0) sb_text(traded == 0 ? "No contract traded today" : "No contract ranks on this setting"); else { sbContract(cells, rankAt[0]); sb_text(": "); if (rank == RANK_PREMIUM) sb_text("$"); sbShort(rankKey[0]); if (rank == RANK_GAIN) sb_text("%"); } str_read_sb(); sb_clear(); sb_text("Top contracts by "); sb_text(RANK_WORDS[rank]); sb_text(", "); sb_int(expiries); sb_text(expiries == 1 ? " expiry, " : " expiries, "); sb_int(contracts); sb_text(" contracts"); if (partial) sb_text(", partial summary"); str_title_sb(); } // onBar() runs once per bar: history rows carry an empty block and cost one read; the live bar measures the summary, // writes the readings (NaN on history rows), the table, the levels and the card's words. function onBar(): void { close = bar.close(); t = bar.time(); if (isNaN(firstT) && !isNaN(t)) firstT = t; let measured = false; // the live bar carried a summary with a contract in it let served = false; // the live bar carried a summary: a contract, or the data plane's partial mark if (bar.isLast() && !isNaN(t)) { const n = in_state_cells(); if (n >= OPTION_VIEW_ROW_STATE) { measure(n); measured = contracts > 0; served = measured || partial; } } const cells = ranked; const topAt = measured && rankCount > 0 ? rankAt[0] : -1; out_top_strike(topAt >= 0 ? cells[topAt + 3] : NaN); out_top_value(topAt >= 0 ? rankKey[0] : NaN); out_total_volume(measured ? totalVolume : NaN); out_call_volume(measured ? callVolume : NaN); out_put_volume(measured ? putVolume : NaN); out_put_call_volume(measured && callVolume > 0.0 ? putVolume / callVolume : NaN); out_traded(measured ? f64(traded) : NaN); out_partial(measured ? (partial ? 1.0 : 0.0) : NaN); out_top_side(topAt >= 0 ? (cells[topAt + 2] > 0.0 ? 2.0 : 0.0) : bar.isLast() ? 1.0 : NaN); if (!bar.isLast()) return; if (measured) { writeTable(); // The levels belong on the underlying's own chart (its close inside the strikes the summary lists), never on an // option contract's own chart, whose price axis is the contract's premium. writeLevels(!optionContract && !isNaN(close) && close >= lowStrike && close <= highStrike); writeWords(); } else { writeLevels(false); sb_clear(); sb_text(served ? "No contract in the summary" : "Waiting for the option chain summary"); // an empty summary's totals count no contract str_read_sb(); sb_clear(); sb_text("Top contracts, no summary read"); str_title_sb(); } } ``` ## How it works **The summary is a snapshot of now.** `input("state", option_contract_state.cells, { max_cells: 64, expiries: "nearest:24", strike_window_pct: 10, page_views: ["top", "totals"], rank: "@rank", side: "@side", rows: "@rows", min_volume: "@min_volume" })` asks the data plane for two views of the summary of the 24 nearest expiries with a strike within 10% of the underlying, on the live row: `top`, the contracts the settings can rank (the top **Contracts listed** on the ranking and the three most traded and the three most held on **Calls or puts**), each the summary's own 13-value tuple in the summary's order, and `totals`, the summary's counts and sums over every contract (the contracts, the expiries, the strikes it lists, the volumes and the partial mark). `viewTuples()` copies the ranked contracts out and `ChainTotals` reads the totals; at most 32 rows arrive, so `max_cells: 64` holds them. History bars carry an empty block, so the ranking runs on the last bar. **The four rankings.** A contract ranks only on readings its `present` mask carries: - **volume**: the day's volume (bit 9), above 0; - **oi**: the open interest (bit 10), above 0; - **premium**: the day's volume times the last price (bit 6) times the market's option multiplier, the chart's market fact `market.option_multiplier()`: 100 shares on a US stock, the future's point value on CME (50 on ES), 1 on a coin. The summary carries no traded premium, so this is the day's volume valued at the last price: an estimate that reads high when the price rose through the day and low when it fell. Where the chart does not know the multiplier, no contract ranks on premium and the column prints nothing, never a guessed 100; - **gain**: the last price over the prior session's close (bit 7), minus 1, in percent, among the contracts that traded at least **Smallest volume for gain** today (100 by default: contracts on a US stock and on CME, coins on crypto), so a contract that changed hands once does not lead. **Calls or puts** keeps the calls or the puts alone. The top **Contracts listed** (10 by default, at most 25) are kept by insertion as the summary is read, the largest first, ties in the summary's order. **The table.** Each row names the contract (`SPY 17 Oct 660C`: the root from its symbol code, `?` when the code spells nothing, the expiry's label, its trade date on the market's clock, `15 Jan '27` in another year, the strike, C or P), then the last price, the change over the prior close in the up or down colour, the day's volume, the open interest, volume over open interest (above 1 when the day traded more than the open interest: positions opened or turned over), the premium as above and the contract's share of the day's volume across the summary. A reading a contract does not carry prints nothing. The caption names the ranking and, on premium, says it is an estimate; on an option contract's own chart with **Strike levels** on, it reads "On a contract's own chart, no levels" instead. **The levels.** The three most traded contracts on the **Calls or puts** setting draw their strikes as dashed muted lines across the chart (`V1 SPY 17 Oct 660C 84.2K`) and the three with the most open interest as dotted muted lines (`OI1 ...`), each named in plain muted text at the price axis, since a level marks a strike, never a sign; a name within 0.3% of an earlier one steps 132 px inward, and every name is written through the one bounded `tag` slot, 48 bytes. They draw only on the underlying's own chart: never on an option contract's own chart, which `market.option_contract()` marks (`i32(p_market_option_contract())` reads 1 there), since its price axis is the contract's premium and the strikes are not on it, and only where the close lies inside the strikes the summary lists, the rule that keeps them off a contract's chart where the host writes 0. The table fills on either chart. **Strike levels** turns them off. **The card.** The headline is the top contract and its reading (`SPY 17 Oct 660C: 84.2K`, a dollar amount on premium, a percent on gain), in the up colour on a call and the down colour on a put; then the day's volume, put volume over call volume, the top strike and its value, the calls and the puts traded, and the contracts that traded at all. The title names the ranking and how many expiries and contracts the summary held, and says "partial summary" when the data plane marked it so. ## What the settings do - **Rank by**: Ranks by today's volume, oi (open interest: contracts still held open), premium (the money paid) or price gain. - **Calls or puts**: Ranks calls (bets on a rise), puts (bets on a fall) or both. - **Contracts listed**: How many contracts the table shows, from 3 to 25. - **Smallest volume for gain**: The volume today a contract needs before it can rank by gain. - **Strike levels**: Draws lines at the strikes (option price levels) of the three most traded and three most held contracts. - **Top contract**: The top contract and its value, up colour for a call, down colour for a put. - **Day volume**: Contracts traded today across every contract listed. - **Put/call volume**: Put volume divided by call volume, where above 1 means more puts (bets on a fall) traded. - **Top strike**: The top contract's strike (its price level). - **Its value**: The top contract's value for Rank by, in contracts, USD or percent. - **Calls traded**: Call contracts traded today. - **Puts traded**: Put contracts traded today. - **Contracts that traded**: How many contracts traded at least once today. ## Where it runs On crypto, it reads each coin's options summary, each contract's price, volume and open interest (contracts still held open). A copy you run from the editor (where you write and run indicators) reads it too. On a US stock or ETF with listed options, every indicator in your browser can read it. It is real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). It is real time if you have real-time CME data, and 10 minutes behind otherwise. ## When data is missing The headline says why instead of going blank. "Waiting for the option chain summary" means the live bar has no summary yet, or an empty one. "No contract in the summary" means the summary arrived incomplete, with no contract in it. "No contract traded today" shows before the open. "No contract ranks on this setting" means no contract has what the ranking needs. Gain needs the last price, the prior close and enough volume. An empty table keeps its caption. ## Customize it - **Where the positions sit.** Set **Rank by** to oi for the contracts with the most open interest; the levels already show both. - **The day's winners.** Set **Rank by** to gain and raise **Smallest volume for gain** to keep it to contracts that really traded. - **Calls only.** Set **Calls or puts** to calls: the table and the levels rank the calls. - **A longer list.** Raise **Contracts listed** to 25. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Top Contracts** under **HUDs**. 2. Press **Run** on a BTCUSDT chart: the table opens under the chart once the summary arrives, the six levels draw across it and the card sits at the bottom centre. 3. At the editor's Console prompt, type `top_strike`, `total_volume` and `put_call_volume` to read them on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-opra) for the `option_contract_state` celled class, its tuple, its knobs and the present mask - [Chain page views](../core-concepts/data-sources.md#chain-page-views) for the `top` and `totals` views, and [Options kit](../functions/options-kit.md#chain-page-views) for `viewTuples` and `ChainTotals` - [Cards, frames and panels](../presentation/cards-frames-panels.md#table) for `panel.table` and its styled cells - [Drawing objects](../presentation/drawing-objects.md#handles) for line handles extended across the chart and right-anchored labels - [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry`, [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel` and the [Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file) for `market.option_contract()` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/options-sentiment --> # Options sentiment 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](../core-concepts/data-sources.md#us-listed-options-opra), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). It reads the `option_surface` on every bar through its `tenor_bracket` pick ([Option surface](../core-concepts/data-sources.md#option-surface), [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). It reads each wing at the maturity with `totalVarianceIv` ([The at-the-money term](../functions/options-kit.md#the-at-the-money-term)). It checks `market.option_contract()` ([Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file)). It draws a split line ([Plotting](../presentation/plotting.md)) and a line handle with a plain price label ([Drawing objects](../presentation/drawing-objects.md#handles)). It also draws a `render.hud` card with a meter ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [Blocks and tiles](../presentation/hud-and-hover-cards.md#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 ```typescript // 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](../reference/limitations.md)). 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](../core-concepts/data-sources.md#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 - [Data sources](../core-concepts/data-sources.md#us-listed-options-opra) for the `option_contract_state` celled class, its tuple and the present mask - [Option surface](../core-concepts/data-sources.md#option-surface) for the `option_surface` celled class on crypto, CME and US stock charts, and its tuple - [Options kit](../functions/options-kit.md#the-at-the-money-term) for the total-variance interpolation - [Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file) for `market.option_contract()` - [Drawing objects](../presentation/drawing-objects.md#handles) for a line handle extended across the chart and its plain price label - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the card and its meter <!-- source: https://openmarket.xyz/wrun/cookbook/volume-profile-value-area --> # Volume profile and value area ![Volume profile docked on the price axis with POC lines and heatmap](/wrun/images/volume-profile-value-area.png) The last 96 bars' volume profile docked on the price axis, the point of control row in the text colour, the value area rows muted, the rest in the grid colour. The rows never go finer than the market's own price levels, each level's volume is spread over the rows it covers, and a level the candle never touched is ignored, so the profile reads as a profile everywhere. POC, VAH and VAL are drawn as lines across the window they were measured on, through to the axis (all three thin and dashed, the POC in the text colour, VAH and VAL muted), each with its price as plain muted text at the axis, and the legend reads all three ("POC 84,798 VAH 85,987 VAL 83,288"), so a level the window measured below or above the candles in view still has a readout. Below the chart, a heatmap of volume by UTC hour for the last seven days, newest day on top, each cell the hour's percentile rank among the grid's hours, so the heavy hours jump out and the quiet ones fade. The parts are a celled `volume_profile.cells` input read as a block in `onBar()` ([Volume profile](../functions/order-flow-kit.md#volume-profile)), a frame feeding `plot.levels` docked on the price axis and a second frame feeding `panel.heatmap` below the chart ([Cards, frames and panels](../presentation/cards-frames-panels.md)), line and label handles for the three levels and their tags ([Drawing objects](../presentation/drawing-objects.md)), and a legend entry that reads them ([Legend](../presentation/legend.md)). This is also the `volume-profile-value-area` template: the **Volume Profile and Value Area** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volume Profile and Value Area: the last `window` bars' volume profile docked on the price axis with the point of // control and the value area lit (the POC row in the text ink, the value area muted, the rest in the grid ink), POC / // VAH / VAL as thin dashed lines on price (the POC in the text ink, the edges muted) with plain price tags at the axis, // and an hour-by-day volume heatmap below the chart. The trader sees where volume was accepted and where price sits // against it. section("Profile"); // the dialog's first section: the docked profile's settings param.int("window", 96, { min: 10, max: 500, label: "Window in bars", description: "Bars in the rolling profile" }); param.number("value_area", 70, { min: 50, max: 95, label: "Value area in percent", description: "Value area as a percent of the window's volume" }); param.int("rows", 64, { min: 16, max: 128, label: "Profile rows", description: "Price rows in the docked profile" }); section("Heatmap"); // the second section: the panel under the chart param.int("heat_days", 7, { min: 2, max: 14, label: "Heatmap days", description: "Days shown in the volume heatmap" }); input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("profile", volume_profile.cells, { max_cells: 8192, description: "This bar's volume by price level" }); // [low, high, buy, sell] per level; measured on Binance Futures BTCUSDT: about 280 levels per 15m bar, 860 per 1h bar output("poc", none, overlay, { description: "Point of control of the rolling profile" }); // data-only: the live level is drawn as a line across its window output("vah", none, overlay, { description: "Value area high" }); output("val", none, overlay, { description: "Value area low" }); string("tag", { max_bytes: 40 }); // one bounded slot the three price tags are written through, one at a time string("readout", { max_bytes: 64 }); // the three levels in one line of words, for the legend handles.line({ color: "theme.muted", width: 1, lineStyle: "dashed", extend: "right" }); // POC, VAH and VAL across the window they were measured on, through to the axis handles.label({ anchor: "right", align: "right", size: 11, color: "theme.muted" }); // price tags, plain text: x in pixels from the right edge, y in price const profile_rows = frame("profile_rows", { max_bytes: 8192 }); // the docked profile: one row per price bin const heat_rows = frame("heat_rows", { max_bytes: 16384 }); // the heatmap: one cell per hour and day plot.levels({ name: "profile", frame: profile_rows, dock: "right", width_frac: 0.2, labels: false, color: "theme.muted" }); panel.heatmap({ name: "volume_heat", title: "Volume by hour, percentile rank", x: "category", place: "below", frame: heat_rows }); render.legend("level_readout", { text: "readout", color: "theme.muted" }); // POC, VAH and VAL in the legend: readable when a level sits off the price pane const MAX_WINDOW = 500; const BINS = 48; const MAX_ROWS = 128; const MAX_DAYS = 14; const HOURS = 24; // ring sizes for the largest settings const barLo = new StaticArray<f64>(MAX_WINDOW); const barHi = new StaticArray<f64>(MAX_WINDOW); const barT = new StaticArray<f64>(MAX_WINDOW); // each ring bar's price span and open time const barBins = new StaticArray<f64>(MAX_WINDOW * BINS); // each ring bar's volume in BINS equal bins across its span const rowVol = new StaticArray<f64>(MAX_ROWS); // the window profile: volume per price row const heat = new StaticArray<f64>(MAX_DAYS * HOURS); const heatBars = new StaticArray<i32>(MAX_DAYS * HOURS); // volume and bar count per day and hour const jsonBytes = new StaticArray<u8>(16384); let jsonUsed = 0; // the frame JSON, appended as UTF-8 bytes const tags: LabelHandle[] = [draw.label(0), draw.label(1), draw.label(2)]; const levelLines: LineHandle[] = [draw.line(3), draw.line(4), draw.line(5)]; // POC, VAH, VAL price tags and the same three levels as lines; handle objects allocate once, ids one space across kinds let window = 96; let valueArea = 0.7; let rows = 64; let heatDays = 7; // the params, read in onStart() let head = -1; let count = 0; // the ring: head is the newest bar, count the bars in use let dayBase: i64 = -1; // the day number (days since the epoch) of the heatmap's oldest row let t: f64 = NaN; let poc: f64 = NaN; let vah: f64 = NaN; let val: f64 = NaN; // this bar's open time and the window's three levels let levelHeight: f64 = Infinity; // the market's price level height, the smallest [low, high] span seen: the row grid never goes finer let rowCount = 64; // rows in use this bar: the setting, or fewer on a market whose levels are coarser than the setting would ask let probLike = true; // every close so far sits in 0..1 on a 0.001 grid: a prediction market, whose prices read as percent let winLo: f64 = NaN; let rowHeight: f64 = NaN; let pocRow = 0; let lowRow = 0; let highRow = 0; // the window profile's geometry // ── JSON bytes: append text and numbers without allocating; one string is made per frame write ── function jbByte(b: u32): void { if (jsonUsed < jsonBytes.length) { jsonBytes[jsonUsed] = <u8>b; jsonUsed += 1; } } function jbText(s: String): void { const n = String.UTF8.byteLength(s); if (jsonUsed + n <= jsonBytes.length) jsonUsed += i32(String.UTF8.encodeUnsafe(changetype<usize>(s), s.length, changetype<usize>(jsonBytes) + jsonUsed)); } function jbUint(v: u64): void { if (v >= 10) jbUint(v / 10); jbByte(0x30 + <u32>(v % 10)); } function jbNum(v: f64, decimals: i32): void { // a fixed-point number, or null when not finite if (!isFinite(v)) { jbText("null"); return; } let x = v; if (x < 0.0) { jbByte(0x2d); x = -x; } let scale = 1.0; for (let i = 0; i < decimals; i += 1) scale *= 10.0; const scaled = Math.round(x * scale); const whole = Math.floor(scaled / scale); const frac = scaled - whole * scale; jbUint(<u64>whole); if (decimals > 0) { jbByte(0x2e); let f = <u64>frac; let digits = 1; let probe = f; while (probe >= 10) { probe /= 10; digits += 1; } for (let i = digits; i < decimals; i += 1) jbByte(0x30); jbUint(f); } } function jbFlush(slot: i32): void { writeFrame(slot, String.UTF8.decodeUnsafe(changetype<usize>(jsonBytes), jsonUsed)); jsonUsed = 0; } // ── Text helpers for the price tags ── 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: 84,210 / 2,431.55 / 12.345 / 0.13797; a prediction market's price reads as percent if (probLike) { sb_f64(v * 100.0, 1); sb_text("%"); } else if (v >= 1000.0) sbGrouped(i64(Math.round(v))); else if (v >= 100.0) sb_f64(v, 2); else if (v >= 1.0) sb_f64(v, 3); else sb_f64(v, 5); } function priceDecimals(step: f64): i32 { // enough decimals that the rounded row prices stay evenly spaced (the docked grid is contiguous only within 0.1% of its step) const d = i32(Math.ceil(Math.log(2000.0 / step) / Math.LN10)); return d < 2 ? 2 : d > 9 ? 9 : d; } // ── The heatmap: volume per UTC hour and day, the last heat_days days ── function shiftHeat(by: i32): void { // a new day arrived: drop the oldest rows if (by >= heatDays) { for (let i = 0; i < MAX_DAYS * HOURS; i += 1) { heat[i] = 0.0; heatBars[i] = 0; } return; } for (let r = 0; r < heatDays; r += 1) for (let h = 0; h < HOURS; h += 1) { const from = r + by; heat[r * HOURS + h] = from < heatDays ? heat[from * HOURS + h] : 0.0; heatBars[r * HOURS + h] = from < heatDays ? heatBars[from * HOURS + h] : 0; } } function foldHeat(t: f64, volume: f64): void { if (isNaN(t) || isNaN(volume)) return; const day = i64(Math.floor(t / 86400.0)); const hour = i32(Math.floor((t - f64(day) * 86400.0) / 3600.0)); if (dayBase < 0) dayBase = day - i64(heatDays - 1); // the first bar lands in the newest row if (day < dayBase) return; const newest = dayBase + i64(heatDays - 1); if (day > newest) { const by = i32(day - newest); shiftHeat(by); dayBase += i64(by); } const at = i32(day - dayBase) * HOURS + hour; heat[at] += volume; heatBars[at] += 1; } let civilMonth = 0; let civilDay = 0; function civilFromDays(days: i64): void { // days since 1970-01-01 -> month and day of month (proleptic Gregorian) const z = days + 719468; const era = (z >= 0 ? z : z - 146096) / 146097; const doe = z - era * 146097; const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); const mp = (5 * doy + 2) / 153; civilDay = i32(doy - (153 * mp + 2) / 5 + 1); civilMonth = i32(mp < 10 ? mp + 3 : mp - 9); } function jbTwoDigits(n: i32): void { if (n < 10) jbByte(0x30); jbUint(<u64>n); } function percentile(at: i32, filled: i32): f64 { // the share of filled hours at or below this hour's volume, 0 to 100 let below = 0; const v = heat[at]; for (let i = 0; i < heatDays * HOURS; i += 1) if (heatBars[i] > 0 && heat[i] <= v) below += 1; return Math.round((100.0 * f64(below)) / f64(filled)); } function writeHeat(): void { // [hour, day, percentile] triplets: hour on x, day on y (newest day first); the engine colours from the lowest to the highest value let filled = 0; for (let i = 0; i < heatDays * HOURS; i += 1) if (heatBars[i] > 0) filled += 1; if (filled == 0) return; let first = true; jbText("{\"rows\":["); for (let r = heatDays - 1; r >= 0; r -= 1) { civilFromDays(dayBase + i64(r)); for (let h = 0; h < HOURS; h += 1) { const at = r * HOURS + h; if (heatBars[at] == 0) continue; if (!first) jbText(","); first = false; jbText("[\""); jbTwoDigits(h); jbText("\",\""); jbTwoDigits(civilMonth); jbText("-"); jbTwoDigits(civilDay); jbText("\","); jbNum(percentile(at, filled), 0); jbText("]"); } } jbText("]}"); jbFlush(FRAME_HEAT_ROWS); } // ── The rolling profile ── function spread(a: f64, b: f64, volume: f64, gridLo: f64, width: f64, base: i32, cells: i32, into: StaticArray<f64>): void { // [a, b]'s volume over the grid cells it overlaps, in proportion if (volume <= 0.0 || !(b >= a)) return; let first = i32(Math.floor((a - gridLo) / width)); let last = i32(Math.floor((b - gridLo) / width)); if (first < 0) first = 0; if (last > cells - 1) last = cells - 1; if (first > cells - 1) first = cells - 1; if (last < 0) last = 0; if (first >= last || b - a <= 0.0) { into[base + first] += volume; return; } // one cell, or a level thinner than the grid for (let k = first; k <= last; k += 1) { const cellLo = gridLo + f64(k) * width; const cellHi = cellLo + width; const overlap = Math.min(b, cellHi) - Math.max(a, cellLo); if (overlap > 0.0) into[base + k] += (volume * overlap) / (b - a); } } function foldBar(candleLow: f64, candleHigh: f64): void { // this bar's cells into BINS bins across the bar's own price span, appended to the ring head = (head + 1) % window; if (count < window) count += 1; barT[head] = t; const n = in_profile_cells(); const base = head * BINS; for (let b = 0; b < BINS; b += 1) barBins[base + b] = 0.0; barLo[head] = NaN; barHi[head] = NaN; if (n < 4) return; // an empty block: the bar counts, its volume is unknown const cells = in_profile_view(); // this bar's cells in place: the first n values of the build's own buffer const typical = cells[(n / 8) * 4 + 1] - cells[(n / 8) * 4]; // the middle level's span: the market's level width (one stray level never sets it) if (typical > 0.0 && typical < levelHeight) levelHeight = typical; const tolerance = isFinite(levelHeight) ? levelHeight : 0.0; // a level may straddle the candle's edge by one step let lo = candleLow; let hi = candleHigh; // the candle's own span; the levels are read against it if (!(hi >= lo)) { lo = Infinity; hi = -Infinity; for (let i = 0; i + 3 < n; i += 4) { if (cells[i] < lo) lo = cells[i]; if (cells[i + 1] > hi) hi = cells[i + 1]; } } // no candle span: the cells' own if (!(hi >= lo)) return; if (hi == lo) hi = lo + Math.abs(lo) * 1e-9 + 1e-9; const binWidth = (hi - lo) / f64(BINS); for (let i = 0; i + 3 < n; i += 4) { const centre = (cells[i] + cells[i + 1]) * 0.5; if (centre < lo - tolerance || centre > hi + tolerance) continue; // a level the candle never touched: a stray print, ignored spread(cells[i], cells[i + 1], cells[i + 2] + cells[i + 3], lo, binWidth, base, BINS, barBins); // the level's volume over the bins it covers } barLo[head] = lo; barHi[head] = hi; } function buildProfile(): bool { // the ring's bars folded into `rows` price rows across the window's span; POC and value area let lo = Infinity; let hi = -Infinity; for (let k = 0; k < count; k += 1) { const i = (head + window - k) % window; if (isNaN(barLo[i])) continue; if (barLo[i] < lo) lo = barLo[i]; if (barHi[i] > hi) hi = barHi[i]; } if (!(hi > lo)) return false; rowHeight = (hi - lo) / f64(rows); // the setting's row height, or the market's level height when that is coarser (a thin-tick market) if (isFinite(levelHeight) && levelHeight > rowHeight) rowHeight = levelHeight; winLo = Math.floor(lo / rowHeight) * rowHeight; // rows sit on the level grid rowCount = i32(Math.ceil((hi - winLo) / rowHeight)); if (rowCount < 2) return false; if (rowCount > rows) rowCount = rows; lo = winLo; for (let r = 0; r < rowCount; r += 1) rowVol[r] = 0.0; let total = 0.0; for (let k = 0; k < count; k += 1) { const i = (head + window - k) % window; if (isNaN(barLo[i])) continue; const binWidth = (barHi[i] - barLo[i]) / f64(BINS); const base = i * BINS; for (let b = 0; b < BINS; b += 1) { const v = barBins[base + b]; if (v <= 0.0) continue; spread(barLo[i] + f64(b) * binWidth, barLo[i] + f64(b + 1) * binWidth, v, lo, rowHeight, 0, rowCount, rowVol); total += v; // the bin's volume over the rows it covers } } if (total <= 0.0) return false; pocRow = 0; for (let r = 1; r < rowCount; r += 1) if (rowVol[r] > rowVol[pocRow]) pocRow = r; lowRow = pocRow; highRow = pocRow; let inside = rowVol[pocRow]; // the value area grows from the POC toward the heavier neighbour while (inside < valueArea * total && (lowRow > 0 || highRow < rowCount - 1)) { const up = highRow < rowCount - 1 ? rowVol[highRow + 1] : -1.0; const down = lowRow > 0 ? rowVol[lowRow - 1] : -1.0; if (up >= down) { highRow += 1; inside += up; } else { lowRow -= 1; inside += down; } } poc = lo + (f64(pocRow) + 0.5) * rowHeight; vah = lo + f64(highRow + 1) * rowHeight; val = lo + f64(lowRow) * rowHeight; return true; } function writeProfile(): void { // prices strictly increasing (row centres), a value per row (0 where empty, so the grid stays whole), a colour per row const decimals = priceDecimals(rowHeight); jbText("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) jbText(","); jbNum(winLo + (f64(r) + 0.5) * rowHeight, decimals); } jbText("],\"values\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) jbText(","); jbNum(rowVol[r] > 0.0 ? rowVol[r] : 0.0, 2); } jbText("],\"colors\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) jbText(","); jbText(r == pocRow ? "\"theme.text\"" : r >= lowRow && r <= highRow ? "\"theme.muted\"" : "\"theme.grid\""); } jbText("]}"); jbFlush(FRAME_PROFILE_ROWS); } function drawLevel(which: i32, name: String, price: f64, ink: i32, from: f64): void { // the level as a line from the window's first bar to the live bar (extended to the axis) and its price tag levelLines[which].set(from, price, t, price).color(ink).width(1.0).style(LineStyle.Dashed).extend(Extend.Right); sb_clear(); sb_text(name); sb_text(" "); sbPrice(price); tags[which].set(which == 0 ? 6.0 : 96.0, price).text(str_tag_sb).color(theme.MUTED).valign(VALIGN_BOTTOM); // plain muted text whose box sits on the line, so the line never runs through it: the POC tag at the axis, VAH and VAL a step inward so close levels never overlap } // onStart() runs once before the first bar: read the params. function onStart(): void { window = i32(p_window()); valueArea = p_value_area() / 100.0; rows = i32(p_rows()); heatDays = i32(p_heat_days()); } // the frame strings are temporaries: the scratch the build reserves after onStart() holds them // onBar() runs once per bar: fold the bar into the heatmap and the ring, rebuild the window profile; then the three levels as // numbers on every bar, and the docked profile, the heatmap, the level lines and the tags on the live bar only. function onBar(): void { t = bar.time(); const close = bar.close(); foldHeat(t, bar.volume()); foldBar(bar.low(), bar.high()); // the bar's open time, volume and span, from the chart's own candle: a level outside the span is ignored, so one bad level never stretches the profile if (!isNaN(close) && (close < 0.0 || close > 1.0 || Math.abs(close * 1000.0 - Math.round(close * 1000.0)) > 1e-6)) probLike = false; if (count < 2 || !buildProfile()) return; // no profile yet: nothing is written on this bar out_poc(poc); out_vah(vah); out_val(val); if (bar.isLast()) { writeProfile(); writeHeat(); sb_clear(); sb_text("POC "); sbPrice(poc); sb_text(" VAH "); sbPrice(vah); sb_text(" VAL "); sbPrice(val); str_readout_sb(); // the legend's readout const from = barT[(head + window - (count - 1)) % window]; // the oldest bar in the window drawLevel(0, "POC", poc, theme.TEXT, from); drawLevel(1, "VAH", vah, theme.MUTED, from); drawLevel(2, "VAL", val, theme.MUTED, from); } } ``` ## How it works **One block per bar.** `input("profile", volume_profile.cells, { max_cells: 8192 })` delivers each bar's volume by price level as `[low, high, buy, sell]` tuples (about 280 levels per 15m bar and 860 per 1h bar on Binance Futures BTCUSDT). The rolling profile folds the last `window` (96) bars' blocks into `rows` (64) price bins between the window's low and high; a level outside the bar's own high-to-low span is ignored, so a stray print never stretches the profile, and each level's volume is spread over the bins it covers. **POC and the value area.** The bin with the most volume is the point of control; the value area grows from it, bin by bin toward the heavier neighbour, until it holds `value_area` (70) percent of the window's volume. `poc`, `vah` and `val` are data-only outputs, one value per bar; on the live bar each is drawn as a line handle across the window it was measured on, extended right to the axis, with a price tag written through the one bounded slot to a right-anchored label. The price axis scales to the candles in view, not to the window the levels are measured on, so after a run-up VAL can sit below the pane with its line and tag; the same three prices are written into a second slot, `readout`, on the live bar, and `render.legend("level_readout", { text: "readout", color: "theme.muted" })` prints that line of words in the legend beside a dot in the muted colour. On a prediction market the tags and the readout read as percent, like the axis. **Two frames, two views.** `frame("profile_rows")` carries one row per bin and feeds `plot.levels`, the docked profile (the POC row in the text colour, value-area rows muted, the rest in the grid colour); `frame("heat_rows")` carries one cell per hour and day for the last `heat_days` (7) days and feeds `panel.heatmap`, each cell the hour's percentile rank among the grid's hours (100 is the busiest). ## Where it runs Markets with a volume profile lane: crypto (Binance Futures, Binance spot, Hyperliquid) and Polymarket markets, where the profile shows the odds the crowd traded most. The heatmap reads best on charts finer than 1h; on 1h each cell is one bar. ## When data is missing Stocks and FX have no profile lane: the run stops with the toast `Volume profile data is unavailable for '<title>' (the volume_profile source lane answered empty or was declined), so the indicator cannot compute.`, where `<title>` is the tab's title. A bar without a profile block counts toward the window with no volume; the first bar draws nothing (the profile needs two bars); hours with no bars stay empty in the heatmap. ## Customize it - **A session profile.** Reset the fold at a UTC boundary (the [Session map](session-map.md) window test) instead of rolling the last `window` bars. - **Finer rows.** `rows` up to 128; the rows never go finer than the market's own price levels. - **A wider value area.** `value_area` up to 95 percent. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volume Profile and Value Area** under **Beyond the time axis**. 2. Press **Run** on a crypto chart finer than 1h, such as BTCUSDT on Binance Futures at 15m: the profile docks on the price axis, the three levels draw with their tags, and the heatmap appears below the chart. 3. At the editor's Console prompt, type `poc`, `vah` and `val` to read the three levels on the newest bar. ## Concepts used - [Volume profile](../functions/order-flow-kit.md#volume-profile) for the celled profile input and the block layout - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `plot.levels` and `panel.heatmap` - [Drawing objects](../presentation/drawing-objects.md) for line and label handles extended to the axis <!-- source: https://openmarket.xyz/wrun/cookbook/open-interest-profile --> # Open Interest Profile ![Open interest change by price docked on the right as a two-sided column, with the OI POC and the value area tagged on the axis side](/wrun/images/open-interest-profile.png) The current month's open interest change by price (or the day's, or the week's), docked on the price axis as a two-sided column: a row grows to the right in the up colour where positions were opened on balance while price traded there, and to the left in the down colour where they were closed. The OI POC, the row that added the most open interest, is dashed in the text colour from the period's first bar through to the axis, its tag plain muted text at the axis ("OI POC 83,754.2"), and the value area's high and low are dashed in the muted colour with their tags on the axis side of the column. Two dotted markers bound the period, a header line above the column reads it ("Month | Open interest | net change +12,841"), and the legend reads all four. Every chart finer than a week draws the same profile, built hour by hour, so a 1m chart and a 4h chart show the same rows. The parts are two hourly streams, `oi_candles.cells` (each closed hour's open interest) and `volume_profile_candles.cells` (each closed hour's volume by price), a month deep ([Data sources](../core-concepts/data-sources.md), [Multi-timeframe](../core-concepts/multi-timeframe.md)), the chart's own `oi.close` and `volume_profile.cells` for the forming hour, a frame feeding `plot.levels` docked right with `baseline: "center"` and `tag_place: "axis"` ([Cards, frames and panels](../presentation/cards-frames-panels.md)), line and label handles for the levels, the POC tag, the markers and the header ([Drawing objects](../presentation/drawing-objects.md)), and a legend entry that reads them ([Legend](../presentation/legend.md)). This is also the `open-interest-profile` template: the **Open Interest Profile** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Open Interest Profile: the current period's net open-interest change by price, docked on the price axis as a // two-sided column. Every closed hour of the period comes from two hourly streams: its open-interest change is spread // over that hour's volume-by-price rows in proportion to the volume traded on each row, so a row grows in the up colour // where positions were opened on balance and in the down colour where they were closed. The forming hour comes from the // chart's own bars. The OI POC is the row that added the most open interest (a period that added none draws no POC); // the value area grows from it over the net open interest added. Dotted markers bound the period and a header line // reads its net change. Every chart finer than a week reads the same hourly profile; on a weekly or coarser chart the // streams stand down and each bar is spread over its own rows. section("Profile"); param.choice("period", ["Day", "Week", "Month"], "Month"); // the calendar period the profile covers, UTC param.int("ticks", 25, { min: 1, max: 500, label: "Ticks per row", description: "Price ticks one row spans: the market's block size times this" }); param.number("value_area", 70, { min: 50, max: 95, label: "Value area in percent", description: "Value area as a percent of the period's net open interest added" }); param.choice("positive_side", ["Right", "Left"], "Right"); // which way the opened (up colour) rows grow from the column's centre input("close", ohlcv.close); // the primary input: the chart's own candles define the grid input("oi", oi.close, { currency: "Coin", missing: "nan", description: "Open interest at the bar's close, in the venue's own units" }); input("oi_open", oi.open, { currency: "Coin", missing: "nan", description: "Open interest at the bar's open: the first change on a weekly or coarser chart" }); input("profile", volume_profile.cells, { max_cells: 8192, ticks_per_bar: "@ticks", description: "This bar's volume by price row: the forming hour's rows" }); input("oi_h", oi_candles.cells, { interval: "1h", bars: 744, chart_interval_below: "1w", description: "The closed hours' open interest, a month deep" }); // [offset_ms, open, high, low, close] per hour, coins or contracts input("vp_h", volume_profile_candles.cells, { interval: "1h", bars: 744, max_cells: 32768, ticks_per_bar: "@ticks", chart_interval_below: "1w", description: "The closed hours' volume by price row, a month deep" }); // [offset_ms, low, high, buy, sell] per row of each hour: rows per hour times 744 output("poc", none, overlay, { description: "OI POC: the row that added the most open interest" }); output("vah", none, overlay, { description: "Value area high of the net open interest added" }); output("val", none, overlay, { description: "Value area low of the net open interest added" }); output("net", none, overlay, { description: "The period's net open-interest change, in the venue's own units" }); string("tag", { max_bytes: 64 }); // one bounded slot the header is written through string("poc_tag", { max_bytes: 32 }); // the OI POC tag's words string("readout", { max_bytes: 96 }); // the levels in one line of words, for the legend handles.line({ width: 1, line_style: "dashed", extend: "right" }); // POC, VAH and VAL from the period's first bar through to the axis; the two period markers handles.label({ anchor: "right", align: "left", size: 11, color: "theme.muted", style: "plain" }); // the header line and the OI POC tag: x in pixels from the right edge, y in price chart.interval_sec(); // the chart's bar interval in seconds, written by the chart: a week or more stands the streams down const oi_rows = frame("oi_rows", { max_bytes: 65536 }); // the docked column: one row per price row of the period, signed net change, a colour per row plot.levels({ name: "oi_profile", frame: oi_rows, dock: "right", baseline: "center", width_px: 220, labels: false, color: "theme.up", opacity: 0.95, thickness_px: 40, value_area_color: "theme.muted", value_area_width: 1, value_area_line_style: "dashed", value_area_labels: true, poc: false, tag_place: "axis", hover: true, format: "si" }); // the POC is a line and a tag of its own, drawn only when a row added open interest render.legend("level_readout", { text: "readout", color: "theme.muted" }); // OI POC, VAH, VAL and the net in the legend const MAX_KEYS = 16384; const HALF_KEYS = 8192; const MAX_ROWS = 512; // the row ledger (keys are row indices on the zero-based price grid) and the frame's row cap const WAIT_OI = 1024; const WAIT_VP = 64; const WAIT_VP_ROWS = 4096; // the hours one stream carried before the other: open-interest changes, and volume hours with their rows const net = new StaticArray<f64>(MAX_KEYS); // the period's net open-interest change per row key const pend = new StaticArray<f64>(MAX_KEYS); // the forming hour's volume per row key: the chart's bars since the last one that opened on the hour, less the closed hours carried since const rowNet = new StaticArray<f64>(MAX_ROWS); const rowKey = new StaticArray<i32>(MAX_ROWS); // the rows written: net per row and the first grid key each row covers const oiOpen = new StaticArray<f64>(WAIT_OI); const oiChange = new StaticArray<f64>(WAIT_OI); // waiting open-interest hours: open (epoch seconds) and change const vpOpen = new StaticArray<f64>(WAIT_VP); const vpFrom = new StaticArray<i32>(WAIT_VP); const vpTo = new StaticArray<i32>(WAIT_VP); // waiting volume hours: open and their rows' cells in vpRows const vpRows = new StaticArray<f64>(WAIT_VP_ROWS * 4); // the waiting hours' rows, [low, high, buy, sell] each const lines: LineHandle[] = [draw.line(0), draw.line(1), draw.line(2), draw.line(3), draw.line(4)]; // POC, VAH, VAL, period start marker, period end marker const header = draw.label(5); // the header line above the column const pocTag = draw.label(6); // the OI POC tag on the axis side let period = 2; let ticks = 25; let valueArea = 0.7; let positiveRight = true; // the params, read in onStart() let intervalSec: f64 = NaN; // the chart's bar interval in seconds, NaN when the chart does not say let streamed = true; // the hourly streams carry the period (a chart finer than a week) let rowH: f64 = NaN; let rowG: i64 = 0; let rowD = 0; // the row height in price (the market's block size times the ticks setting), and the gcd of every row edge seen until it is fixed, in units of 10^-rowD let rowBase = 0; let based = false; // key - rowBase indexes net and pend, centred on the first key seen let minKey = 0; let maxKey = -1; let pendMin = 0; let pendMax = -1; // the keys the period and the forming hour touched let periodStart: f64 = NaN; // the current period's first second (UTC) let prevOi: f64 = NaN; // the newest closed hour's open interest the stream carried (the previous bar's, once the streams stand down) let lastVp: f64 = NaN; // the newest closed hour the volume stream carried, its open in epoch seconds let syncT: f64 = NaN; // the open of the last chart bar that opened on the hour: pend starts there let oiWait = 0; let vpWait = 0; let vpUsed = 0; // the hours waiting in each store, and the cells vpRows holds let t: f64 = NaN; // this bar's open time let poc: f64 = NaN; let vah: f64 = NaN; let val: f64 = NaN; let netTotal: f64 = 0.0; // the period's levels and net let rowCount = 0; let merge = 1; let pocRow = 0; let lowRow = 0; let highRow = 0; // the rows written, the grid keys one row merges, the POC and value-area rows // ── Calendar math (proleptic Gregorian, UTC) ── let cy: i64 = 1970; let cm: i64 = 1; function civilFromDays(days: i64): void { // days since 1970-01-01 -> year and month const z = days + 719468; const era = (z >= 0 ? z : z - 146096) / 146097; const doe = z - era * 146097; const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; const y = yoe + era * 400; const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); const mp = (5 * doy + 2) / 153; const m = mp < 10 ? mp + 3 : mp - 9; cy = m <= 2 ? y + 1 : y; cm = m; } function daysFromCivil(y0: i64, m: i64, d: i64): i64 { // year, month, day -> days since 1970-01-01 const y = m <= 2 ? y0 - 1 : y0; const era = (y >= 0 ? y : y - 399) / 400; const yoe = y - era * 400; const doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5 + d - 1; const doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; return era * 146097 + doe - 719468; } function periodStartOf(time: f64): f64 { // the first second of the Day, Monday week or calendar month holding time const days = i64(Math.floor(time / 86400.0)); if (period == 0) return f64(days) * 86400.0; if (period == 1) return f64(days - (days + 3) % 7) * 86400.0; // 1970-01-01 was a Thursday civilFromDays(days); return f64(daysFromCivil(cy, cm, 1)) * 86400.0; } // ── 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 { // 83,754.2 / 2,431.55 / 12.345 / 0.13797 / 0.000012345: under 1, five significant digits (at most the 9 decimals text takes) if (v >= 1000.0) { const whole = Math.floor(v); sbGrouped(i64(whole)); sb_text("."); sb_int(i64(Math.round((v - whole) * 10.0)) % 10); } else if (v >= 100.0) sb_f64(v, 2); else if (v >= 1.0) sb_f64(v, 3); else if (!(v > 0.0)) sb_f64(v, 5); else { const d = i32(Math.ceil(-Math.log(v) / Math.LN10)) + 4; sb_f64(v, d < 5 ? 5 : d > 9 ? 9 : d); } } function sbSignedGrouped(v: f64): void { // +12,841 / -1,035.5 sb_text(v < 0.0 ? "-" : "+"); const a = Math.abs(v); if (a >= 10000.0) sbGrouped(i64(Math.round(a))); else { const whole = Math.floor(a); sbGrouped(i64(whole)); sb_text("."); sb_int(i64(Math.round((a - whole) * 10.0)) % 10); } } function priceDecimals(step: f64): i32 { // enough decimals that the rounded row prices stay evenly spaced (the docked grid is contiguous only within 0.1% of its step), at most the 9 the frame's text takes const d = i32(Math.ceil(Math.log(2000.0 / step) / Math.LN10)); return d < 2 ? 2 : d > 9 ? 9 : d; } // ── The period ledger ── function gcd(a: i64, b: i64): i64 { let x = a < 0 ? -a : a; let y = b < 0 ? -b : b; while (y != 0) { const r = x % y; x = y; y = r; } return x; } function decimalsOf(v: f64): i32 { // the decimals a served price needs: the least d (0..12) at which v * 10^d is a whole number, to the double's precision (0 for no price) let x = Math.abs(v); if (!(x > 0.0 && x < Infinity)) return 0; for (let d = 0; d < 12; d += 1) { const r = Math.round(x); if (r != 0.0 && Math.abs(x - r) <= 1e-12 * x) return d; x *= 10.0; } return 12; } function foldEdges(cells: StaticArray<f64>, n: i32, stride: i32, col: i32): void { // every served row edge is a multiple of the market's block size (a row is clipped to the levels that traded, so one row's height is not the grid): the gcd of many edges is the block, counted in the decimals the edges need (a fixed unit rounds a fine market's edges to nothing) and kept below 2^53 let d = rowD; let top = 0.0; for (let i = 0; i + stride <= n; i += stride) { for (let e = 0; e < 2; e += 1) { const v = Math.abs(cells[i + col + e]); const k = decimalsOf(v); if (k > d) d = k; if (v > top && v < Infinity) top = v; } } if (top > 0.0) { const cap = i32(Math.floor(Math.log(9.0e15 / top) / Math.LN10)); if (d > cap) d = cap > rowD ? cap : rowD; } while (rowD < d) { rowG *= 10; rowD += 1; } // the gcd so far, in the finer unit const unit = Math.pow(10.0, f64(rowD)); for (let i = 0; i + stride <= n; i += stride) { rowG = gcd(rowG, i64(Math.round(cells[i + col] * unit))); rowG = gcd(rowG, i64(Math.round(cells[i + col + 1] * unit))); } } function learnRow(cells: StaticArray<f64>, n: i32): void { // the row height: the block size times the ticks setting (the built-in's rule), one gcd over the month-deep stream's edges and the chart's, fixed on the first row the stream reaches (the first bar once the streams stand down; the last bar if the stream never arrives) const m = streamed ? in_vp_h_cells() : 0; if (m >= 5) foldEdges(in_vp_h_view(), m, 5, 1); foldEdges(cells, n, 4, 0); if (rowG > 0 && (m >= 5 || !streamed || bar.isLast())) rowH = (f64(rowG) / Math.pow(10.0, f64(rowD))) * f64(ticks); } function keyOf(low: f64, high: f64): i32 { return i32(Math.floor((low + high) * 0.5 / rowH + 1e-6)); } // the zero-based grid row the row's centre sits in (a clipped edge row still lands in its own; a price on a grid line, the base buckets' rows, lands in the row it opens, whatever the double's last digit) function at(key: i32): i32 { // where a key sits in the ledger, -1 outside its reach (an absurd print); the first key centres the ledger on itself if (!based) { rowBase = key - HALF_KEYS; based = true; } const i = key - rowBase; return i >= 0 && i < MAX_KEYS ? i : -1; } function addNet(key: i32, amount: f64): void { const i = at(key); if (i < 0) return; if (maxKey < minKey) { minKey = key; maxKey = key; } if (key < minKey) minKey = key; if (key > maxKey) maxKey = key; net[i] += amount; } function addPendRow(key: i32, volume: f64): void { const i = at(key); if (i < 0) return; if (pendMax < pendMin) { pendMin = key; pendMax = key; } if (key < pendMin) pendMin = key; if (key > pendMax) pendMax = key; pend[i] += volume; } function resetPeriod(start: f64): void { periodStart = start; for (let k = minKey; k <= maxKey; k += 1) { const i = at(k); if (i >= 0) net[i] = 0.0; } minKey = 0; maxKey = -1; } function clearPend(): void { for (let k = pendMin; k <= pendMax; k += 1) { const i = at(k); if (i >= 0) pend[i] = 0.0; } pendMin = 0; pendMax = -1; } function pos(v: f64): f64 { return v > 0.0 ? v : 0.0; } function startPeriodAt(time: f64): bool { // the period holding time: a later one empties the ledger; false for an earlier one const start = periodStartOf(time); if (isNaN(periodStart) || start > periodStart) { resetPeriod(start); return true; } return start == periodStart; } function spread(change: f64, cells: StaticArray<f64>, from: i32, to: i32, stride: i32, col: i32): void { // one span's change over its rows by traded volume (the built-in's rule) if (isNaN(change) || change == 0.0 || isNaN(rowH)) return; let total = 0.0; for (let i = from; i + stride <= to; i += stride) total += pos(cells[i + col + 2]) + pos(cells[i + col + 3]); if (total <= 0.0) return; for (let i = from; i + stride <= to; i += stride) { const vol = pos(cells[i + col + 2]) + pos(cells[i + col + 3]); if (vol > 0.0) addNet(keyOf(cells[i + col], cells[i + col + 1]), (change * vol) / total); } } function addPend(cells: StaticArray<f64>, from: i32, to: i32, stride: i32, col: i32, sign: f64): void { // rows into the forming hour's volume (sign -1: a closed hour's rows out of it) if (isNaN(rowH)) return; for (let i = from; i + stride <= to; i += stride) addPendRow(keyOf(cells[i + col], cells[i + col + 1]), sign * (pos(cells[i + col + 2]) + pos(cells[i + col + 3]))); } // ── The two streams, paired by the hour ── function foldHour(open: f64, change: f64, cells: StaticArray<f64>, from: i32, to: i32, stride: i32, col: i32): void { if (startPeriodAt(open)) spread(change, cells, from, to, stride, col); } function findOi(open: f64): i32 { for (let k = 0; k < oiWait; k += 1) if (oiOpen[k] == open) return k; return -1; } function dropOi(e: i32): void { for (let k = e; k + 1 < oiWait; k += 1) { oiOpen[k] = oiOpen[k + 1]; oiChange[k] = oiChange[k + 1]; } oiWait -= 1; } function waitOi(open: f64, change: f64): void { if (oiWait == WAIT_OI) dropOi(0); oiOpen[oiWait] = open; oiChange[oiWait] = change; oiWait += 1; } // the oldest drops when the store is full function findVp(open: f64): i32 { for (let k = 0; k < vpWait; k += 1) if (vpOpen[k] == open) return k; return -1; } function dropVp(e: i32): void { // one waiting volume hour out, the gap its rows leave closed const from = vpFrom[e]; const width = vpTo[e] - from; for (let i = from; i + width < vpUsed; i += 1) vpRows[i] = vpRows[i + width]; vpUsed -= width; for (let k = e; k + 1 < vpWait; k += 1) { vpOpen[k] = vpOpen[k + 1]; vpFrom[k] = vpFrom[k + 1] - width; vpTo[k] = vpTo[k + 1] - width; } vpWait -= 1; } function waitVp(open: f64, v: StaticArray<f64>, from: i32, to: i32): void { // a volume hour whose open interest has not arrived: its rows wait (the oldest drop when the store is full) const width = ((to - from) / 5) * 4; if (width > WAIT_VP_ROWS * 4) return; while (vpWait > 0 && (vpWait == WAIT_VP || vpUsed + width > WAIT_VP_ROWS * 4)) dropVp(0); vpOpen[vpWait] = open; vpFrom[vpWait] = vpUsed; for (let i = from; i + 5 <= to; i += 5) { vpRows[vpUsed] = v[i + 1]; vpRows[vpUsed + 1] = v[i + 2]; vpRows[vpUsed + 2] = v[i + 3]; vpRows[vpUsed + 3] = v[i + 4]; vpUsed += 4; } vpTo[vpWait] = vpUsed; vpWait += 1; } function readHours(): void { // this row's closed hours: the two streams are separate lanes, so an hour folds once both have carried it, on whichever rows they arrive const n = in_oi_h_cells(); if (n >= 5) { const c = in_oi_h_view(); for (let i = 0; i + 5 <= n; i += 5) { const close = c[i + 4]; let change: f64 = NaN; if (!isNaN(close)) { change = !isNaN(prevOi) ? close - prevOi : close - c[i + 1]; prevOi = close; } // the built-in's rule: against the previous hour's close, the first one within its hour const open = t + c[i] / 1000.0; const w = findVp(open); if (w >= 0) { foldHour(open, change, vpRows, vpFrom[w], vpTo[w], 4, 0); dropVp(w); } else waitOi(open, change); } } const m = in_vp_h_cells(); if (m < 5) return; const v = in_vp_h_view(); for (let i = 0; i + 5 <= m; ) { // one hour at a time: its rows share the hour's offset const off = v[i]; let j = i; while (j + 5 <= m && v[j] == off) j += 5; const open = t + off / 1000.0; if (open >= syncT) addPend(v, i, j, 5, 1, -1.0); // a closed hour the chart's bars in pend hold: out of the forming hour if (!(lastVp >= open)) lastVp = open; const w = findOi(open); if (w >= 0) { foldHour(open, oiChange[w], v, i, j, 5, 1); dropOi(w); } else waitVp(open, v, i, j); i = j; } } function foldForming(change: f64): void { // the forming hour's change over its volume rows (on the last bar only: the next tick rolls it back) if (isNaN(change) || change == 0.0) return; let total = 0.0; for (let k = pendMin; k <= pendMax; k += 1) { const i = at(k); if (i >= 0) total += pos(pend[i]); } if (total <= 0.0) return; for (let k = pendMin; k <= pendMax; k += 1) { const i = at(k); if (i >= 0 && pend[i] > 0.0) addNet(k, (change * pend[i]) / total); } } function weight(r: i32): f64 { return pos(rowNet[r]); } // the level weight: net open interest added (the built-in's 'net-positive' basis) function nearestWeightUp(from: i32): i32 { for (let i = from + 1; i < rowCount; i += 1) if (weight(i) > 0.0) return i - from; return 0x7fffffff; } function nearestWeightDown(from: i32): i32 { for (let i = from - 1; i >= 0; i -= 1) if (weight(i) > 0.0) return from - i; return 0x7fffffff; } function buildRows(): bool { // the ledger's keys as at most 512 rows (grid keys merged in groups of merge when the period spans more), then POC and the value area if (maxKey < minKey || isNaN(rowH)) return false; merge = (maxKey - minKey + MAX_ROWS) / MAX_ROWS; if (merge < 1) merge = 1; let firstKey = i32(Math.floor(f64(minKey) / f64(merge))) * merge; // merged rows stay on a grid of merge keys from zero while ((maxKey - firstKey) / merge >= MAX_ROWS) { merge += 1; firstKey = i32(Math.floor(f64(minKey) / f64(merge))) * merge; } // rounding the first key down can add a row: widen until the aligned range fits rowCount = 0; netTotal = 0.0; for (let k = firstKey; k <= maxKey && rowCount < MAX_ROWS; k += merge) { let sum = 0.0; for (let j = 0; j < merge; j += 1) { const i = at(k + j); if (i >= 0) sum += net[i]; } rowNet[rowCount] = sum; rowKey[rowCount] = k; netTotal += sum; rowCount += 1; } if (rowCount < 1) return false; pocRow = -1; let best = 0.0; for (let r = 0; r < rowCount; r += 1) { const w = weight(r); if (w > best) { best = w; pocRow = r; } } // the first largest row (the built-in's profilePocIndex) if (pocRow < 0) { poc = NaN; vah = NaN; val = NaN; return true; } // no row added open interest: rows only, and no POC let total = 0.0; for (let r = 0; r < rowCount; r += 1) total += weight(r); const target = total * valueArea; lowRow = pocRow; highRow = pocRow; let inside = weight(pocRow); while (inside < target && (highRow < rowCount - 1 || lowRow > 0)) { // the built-in's expandValueArea: toward the heavier neighbour, ties up, a zero-vs-zero tie toward the nearer weight const canUp = highRow < rowCount - 1; const canDown = lowRow > 0; const up = canUp ? weight(highRow + 1) : 0.0; const down = canDown ? weight(lowRow - 1) : 0.0; let stepUp = false; if (canUp && canDown && up == 0.0 && down == 0.0) { const du = nearestWeightUp(highRow); const dd = nearestWeightDown(lowRow); if (du == dd) { const wu = du == 0x7fffffff ? 0.0 : weight(highRow + du); const wd = dd == 0x7fffffff ? 0.0 : weight(lowRow - dd); stepUp = wu >= wd; } else stepUp = du < dd; } else stepUp = up >= down && canUp; if (stepUp && canUp) { highRow += 1; inside += up; } else if (canDown) { lowRow -= 1; inside += down; } else if (canUp) { highRow += 1; inside += up; } } poc = (f64(rowKey[pocRow]) + 0.5 * f64(merge)) * rowH; vah = (f64(rowKey[highRow]) + 0.5 * f64(merge)) * rowH; val = (f64(rowKey[lowRow]) + 0.5 * f64(merge)) * rowH; // row centres (the built-in's line convention) return true; } function writeRows(): void { // the frame: row centres ascending, each row's own band, the signed net per row, a colour per row, and the value area when it spans two rows or more const rowWidth = rowH * f64(merge); const decimals = priceDecimals(rowWidth); const sign = positiveRight ? 1.0 : -1.0; fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64((f64(rowKey[r]) + 0.5 * f64(merge)) * rowH, decimals); } fb_text("],\"lows\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(f64(rowKey[r]) * rowH, decimals); } fb_text("],\"highs\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(f64(rowKey[r] + merge) * rowH, decimals); } fb_text("],\"values\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(rowNet[r] * sign, 4); } fb_text("],\"colors\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); const v = rowNet[r]; fb_text(v > 0.0 ? "\"theme.up\"" : v < 0.0 ? "\"theme.down\"" : "\"theme.muted\""); } fb_text("]"); if (pocRow >= 0 && highRow > lowRow) { fb_text(",\"value_area\":["); fb_f64(val, decimals); fb_text(","); fb_f64(vah, decimals); fb_text("]"); } // a one-row value area is the POC's own row: no band fb_text("}"); writeFrameBuffer(oi_rows); } function drawLevels(): void { // the POC and its tag, the value area's two lines, from the period's first bar through to the axis; the two period markers, the header line const end = t + (isNaN(intervalSec) ? 0.0 : intervalSec); const rowWidth = rowH * f64(merge); const top = f64(rowKey[rowCount - 1] + merge) * rowH; const bottom = f64(rowKey[0]) * rowH; if (pocRow >= 0) { // only when a row added open interest (the dock draws no POC of its own, so a period of closes marks nothing) lines[0].set(periodStart, poc, end, poc).color(theme.TEXT).width(1.0).style(LineStyle.Dashed).extend(Extend.Right); sb_clear(); sb_text("OI POC "); sbPrice(poc); pocTag.set(4.0, poc).text(str_poc_tag_sb).color(theme.MUTED).style(LabelStyle.Plain).align(ALIGN_RIGHT).valign(VALIGN_BOTTOM); // its box sits on the POC line, so the line never runs through it } else { lines[0].delete(); pocTag.delete(); } if (pocRow >= 0 && highRow > lowRow) { // a value area of two rows or more; one row is the POC's own lines[1].set(periodStart, vah, end, vah).color(theme.MUTED).width(1.0).style(LineStyle.Dashed).extend(Extend.Right); lines[2].set(periodStart, val, end, val).color(theme.MUTED).width(1.0).style(LineStyle.Dashed).extend(Extend.Right); } else { lines[1].delete(); lines[2].delete(); } lines[3].set(periodStart, bottom, periodStart, top).color(theme.MUTED).width(1.0).style(LineStyle.Dotted).extend(Extend.None); lines[4].set(end, bottom, end, top).color(theme.MUTED).width(1.0).style(LineStyle.Dotted).extend(Extend.None); sb_clear(); sb_text(period == 0 ? "Day" : period == 1 ? "Week" : "Month"); sb_text(" | Open interest | net change "); sbSignedGrouped(netTotal); header.set(220.0, top + rowWidth * 0.6).text(str_tag_sb).color(theme.MUTED); } // onStart() runs once before the first bar: read the params; a weekly or coarser chart stands the streams down. function onStart(): void { period = i32(p_period()); ticks = i32(p_ticks()); valueArea = p_value_area() / 100.0; positiveRight = p_positive_side() == 0.0; intervalSec = p_chart_interval_sec() > 0.0 ? p_chart_interval_sec() : NaN; // 0 when the chart did not fill it streamed = isNaN(intervalSec) || intervalSec < 604800.0; } // onBar() runs once per bar, oldest first. Finer than a week: the closed hours this row carries go into the period's // ledger once both streams have them, and the forming hour's volume is the chart's own bars since the last one that // opened on the hour less the closed hours carried since; on the last bar the forming hour's change (the bar's open // interest less the newest closed hour's) is spread over it. A weekly or coarser chart spreads each bar's change over // that bar's own rows. On the last bar: the rows, the levels, the markers, the header. function onBar(): void { t = bar.time(); if (isNaN(t)) return; const n = in_profile_cells(); const cells = in_profile_view(); const oiNow = in_oi(); if (isNaN(rowH)) learnRow(cells, n); if (!streamed) { // a weekly or coarser chart: the bar's change against the previous bar's close, else within the bar let change: f64 = NaN; if (!isNaN(oiNow)) { change = !isNaN(prevOi) ? oiNow - prevOi : oiNow - in_oi_open(); prevOi = oiNow; } if (startPeriodAt(t)) spread(change, cells, 0, n, 4, 0); } else { if (t == Math.floor(t / 3600.0) * 3600.0) { clearPend(); syncT = t; } // a bar that opens on the hour: every hour before it has closed, so the forming hour's volume starts here (a 45m bar straddles hours: pend keeps the bars back to the last one on the hour) addPend(cells, 0, n, 4, 0, 1.0); readHours(); if (bar.isLast() && !isNaN(oiNow) && !isNaN(prevOi) && !isNaN(syncT) && startPeriodAt(isNaN(lastVp) ? t : Math.max(t, lastVp + 3600.0))) foldForming(oiNow - prevOi); } if (!bar.isLast()) return; if (!buildRows()) return; out_poc(poc); out_vah(vah); out_val(val); out_net(netTotal); writeRows(); drawLevels(); sb_clear(); if (pocRow >= 0) { sb_text("OI POC "); sbPrice(poc); sb_text(" VAH "); sbPrice(vah); sb_text(" VAL "); sbPrice(val); } else sb_text("No open interest added"); sb_text(" net "); sbSignedGrouped(netTotal); str_readout_sb(); } ``` ## How it works **An hour at a time.** `input("oi_h", oi_candles.cells, { interval: "1h", bars: 744 })` hands the first bar every hour that has closed in the last 744 (a month: the backlog), then each later bar the hours that closed with it, one `[offset_ms, open, high, low, close]` tuple per hour in the venue's own units (coins or contracts, the stream's default). `vp_h` hands the same hours' volume by price, one `[offset_ms, low, high, buy, sell]` tuple per price row, the rows of an hour sharing its `offset_ms` and ascending by price. An hour's change is its close less the previous hour's (the first hour's, within its own hour), spread over that hour's rows in proportion to the volume traded on each: the chart's built-in Open Interest Profile rule. The two streams are separate lanes, so an hour can reach the run on different bars for each: its change and its rows wait for each other, and the hour folds once both have arrived. **The forming hour.** The streams carry closed hours only, so the forming hour comes from the chart's own bars: their `volume_profile.cells` summed since the last bar that opened on the hour, less the closed hours the volume stream carried since. On a 15m chart that is the bars of the current hour; on a 4h chart, the live bar less the hours it already closed; on a 45m chart, whose bars straddle hours, the bars back to the last one that opened on the hour less the hours that closed since. Its change is the chart's own `oi.close`, read with `currency: "Coin"` (the stream's units), less the newest closed hour's close. It is folded on the live bar only, so every tick folds it again from the closed state. **Rows, POC and value area.** A row spans `ticks` (25) of the market's price levels: the market's block size times the setting. The block size is the greatest common divisor of the row edges served, counted in as many decimals as those prices carry (so a market priced under 0.0001 learns its grid too), learned once on the first bar the volume stream reaches, from the month of hourly rows it carries and that bar's own rows together (one sparse bar alone would read a multiple of it). The period's rows are merged into at most 512: each merged row holds the same number of grid rows, counted from the grid's zero, and the count is the least that holds the period's range once its first row is rounded down to that grid. The OI POC is the first row with the most open interest added; the value area grows from it toward the heavier neighbour until it holds `value_area` (70) percent of the open interest added. When one row alone holds that share, the value area is the POC's own row: no band, no VAH or VAL line, and `vah` and `val` read the POC's price. A period that added no open interest on any row has no POC, and nothing marks one. `poc`, `vah`, `val` and `net` are data-only outputs, written on the live bar. **The column.** `frame("oi_rows")` carries the rows (prices, each row's own low and high, the signed net, a colour per row) and the `value_area` when it spans two rows or more. It feeds `plot.levels({ dock: "right", baseline: "center", width_px: 220, poc: false, tag_place: "axis" })`: a column 220 pixels wide with zero at its centre, positives to the right (`positive_side` "Left" flips them), the VAH and VAL tags on the axis side. The level draws no POC of its own (`poc: false`): with no explicit POC a centred column would mark its largest row, an outflow in a period that added nothing. The POC line and its "OI POC" tag are a line handle and a label handle instead, drawn only when a row added open interest. The chart keeps the column's width free at the right edge, so the newest candles stop before it. ## Where it runs Perpetual futures with open interest and a volume profile: Binance Futures, Hyperliquid and the other venues that serve both. Every chart finer than a week reads the same hourly profile. On a weekly or coarser chart, `chart_interval_below: "1w"` stands the two streams down (nothing is fetched for them) and each bar's change is spread over that bar's own rows instead. `vp_h` declares `max_cells: 32768`, room for 744 hours of about 44 rows each; a market whose hours span more rows stops the run with `wrun_cell_block_too_large`, so raise `ticks` (fewer, wider rows) or `max_cells`. ## When data is missing Spot, stocks and FX carry no open interest: every change reads NaN, nothing is folded and no column is drawn. An hour the open interest stream carries without volume rows moves no row (its change is dropped, as the built-in drops it), and the next hour's change is still measured from it. Before the first closed hour reaches the run, the first change is measured within its own hour. ## Customize it - **A day or a week.** `period` Day or Week profiles the current UTC day or Monday week; the streams still read a month. - **Wider rows.** `ticks` up to 500 rows of the market's price levels. - **Flip the sides.** `positive_side` Left grows the rows that added open interest to the left. - **A wider value area.** `value_area` up to 95 percent. - **Tags at the inner end.** `tag_place: "inner"` moves the VAH and VAL tags back to the column's inner end; the POC tag is a label, placed by its own `set` call. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Open Interest Profile** under **Beyond the time axis**. 2. Press **Run** on a perpetual chart such as BTCUSDT on Binance Futures at 1m: the column docks on the right, the three levels draw from the month's first bar with their tags on the axis side, and the header reads the month's net change. Switch the chart to 1h or 4h: the same rows. 3. At the editor's Console prompt, type `poc`, `vah`, `val` and `net` to read the levels and the net change on the newest bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `oi_candles` and `volume_profile_candles` streams and `oi`'s `currency` - [Multi-timeframe](../core-concepts/multi-timeframe.md) for streams, `bars` and `chart_interval_below` - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `plot.levels` docked two-sided and `tag_place` - [Drawing objects](../presentation/drawing-objects.md) for line and label handles extended to the axis <!-- source: https://openmarket.xyz/wrun/cookbook/options-dashboard --> # Options Dashboard ![The right-hand chart of the options desk. At the top sit the BTCUSDT 1h candles, then the Options tiles. Below them, the gamma curve has a dashed Spot marker. Callouts mark the gamma flip, the peak and the trough. At the bottom, a rolling histogram of buys minus sells sits in its own pane](/wrun/images/style-anything/panes.png) Nine tiles under the chart sum up this symbol's options right now. Dealer regime says if dealers (the market makers who hedge options) calm price moves or push them. Below sit a curve of dealer hedging up to 15% away and cumulative volume delta (buys minus sells, summed). The curve crosses zero at the gamma flip, the price where dealers switch from calming price to pushing it. Use it on any chart with options to see if the next move may run or stall. Under the hood: it reads one `options_chain.cells` request naming three book folds (`numbers`, `strike_profile` and `vol_term`) ([Chain page views](../core-concepts/data-sources.md#chain-page-views)). The answer arrives as one block on the live bar, beside two sided `trades.volume` reads ([Data sources](../core-concepts/data-sources.md)). So every options number is the fold the built-in Options Dashboard draws. It writes two frames into a `panel.tiles` and a `panel.line` below the chart ([Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets)). The fold readers `BookStamp`, `OptionNumbers`, `StrikeProfile` and `VolTerm` read the block ([Book folds](../functions/options-kit.md#book-folds)). `dealerRegime` and `oneSigmaMove` give the regime and Sigma ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)). `optionsTradeDay` finds the session ([The market's own date](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). A named pane holds the histogram ([Panes](../presentation/plotting.md#panes)), and a ladder colours a legend entry ([Styling](../presentation/styling.md)). This is also the `options-dashboard` template: the **Options Dashboard** card under **Beyond the time axis** in the editor's starter list. It compiles as written. It is the right-hand chart of the options desk that [Style anything](../presentation/style-anything.md) walks through part by part, beside the [Strike Matrix](strike-matrix.md). ## The wrun indicator ```typescript // Options Dashboard: nine number tiles under the chart that sum up this symbol's options right now. Each tile reads // every expiry date (the date an option ends) unless it says otherwise. Dealers are the market makers who hedge // options. Live net GEX is the dollars dealers must trade to hedge each 1% move. The gamma flip is the price where // dealers switch from calming price to pushing it. Max pain is the strike (the option's price level) where option // holders collect the least at expiry. Dealer regime says whether dealers tend to calm moves or feed them right now. // Sigma today measures today's move against the day's expected move (how far option prices say it can move). The // put/call ratio compares open puts (bets on a fall) with open calls (bets on a rise). 25D skew shows whether traders // pay more for downside or upside protection. Net VEX is how much dealers gain or lose when option prices rise. Net DEX // is how much of the asset they must hold to hedge. Under the tiles, a curve shows dealer hedging at prices up to 15% // either side of now. Its zero crossing is the gamma flip. At the bottom, a rolling cumulative volume delta (buys minus // sells, summed) histogram tracks buying against selling. Use it for a quick read on whether dealers will dampen or // amplify the next move. // // Under the hood: nine stat tiles over the chart's own option book (net GEX, the gamma flip and the dealer regime over // every live expiry, max pain, today's move in 1σ moves, the put/call ratio, the 25-delta risk reversal, net vega // exposure, net delta exposure), the net gamma exposure curve over hypothetical spots with a signed fill and marked // spot, flip, peak and trough, and a rolling cumulative volume delta histogram in a pane of its own. Every options // number is the data plane's own fold of the chain page's whole book, the numbers the chart's built-in Options // Dashboard and GEX Curve draw, read through ONE options_chain input naming three book folds: numbers (net GEX at S0, // the flip and the next 24 hours' ATM IV, every live expiry), strike_profile with no strike rows (max pain, the // put/call ratio of open interest, net VEX and net DEX, and the curve over S0 ± 15% in 61 points) and vol_term (the // front expiry's 25-delta risk reversal, call minus put). A tile maps its fold field the way the built-in does: net GEX // the scope row's (the levels row's without one), the regime its sign, the risk reversal the front row's while the book // has a spot and the vol term's front is the nearest live expiry. Sigma is this package's own: the close's move from // the session's open (the open of the trade day's first bar on the market's clock: the UTC day on crypto, the CME trade // date, the New York date) over the day's 1σ move, the open x the next 24 hours' ATM IV x sqrt(1/252) (oneSigmaMove). // The book is live only: the tiles and the curve are rewritten on the last bar, the CVD on every bar. An empty book (no // contract) blanks every tile and the curve; a number the fold has no reading for reads n/a, never a stale value. param.int("cvd_bars", 96, { min: 2, max: 500, label: "CVD window, bars", description: "How many bars the rolling cumulative volume delta (buys minus sells, summed) covers. Buys and sells are aggressive trades, which took the other side's price." }); input("close", ohlcv.close); // the chart's close: max pain's distance from spot and Sigma's move input("buy", trades.volume, { side: "BUY", missing: "zero", description: "Aggressive buy volume" }); input("sell", trades.volume, { side: "SELL", missing: "zero", description: "Aggressive sell volume" }); // The book's block: rows of 16 f64s, [layout, ...fields] (the book stamp, the numbers rows, the levels row and the // curve's points, the term structure's rows); max_cells counts rows, the stamp's included: 400 holds the stamp, the // scope row, 264 expiry rows and the eight horizons, vol_term's 64 rows, the levels row and the 61 points. input("chain", options_chain.cells, { max_cells: 400, venue: "auto", page_views: ["numbers", "strike_profile", "vol_term"], strikes: 0, points: 61, half_pct: 15, description: "This chart's own options, summed up by OpenMarket. Venue auto reads US listed options (OPRA) on a US stock or ETF, CME on a futures chart, else Deribit." }); market.zone(); // the market's clock: Sigma's trade day chart.interval_sec(); // the bar's length: Sigma reads a daily or finer chart output("net_gex", none, overlay, { description: "Dealers' net gamma exposure in USD per 1% move, over every live expiry date. Gamma is how fast dealers must hedge as price moves. Newest bar only." }); output("gamma_flip", none, overlay, { description: "The gamma flip, where dealers switch from calming moves to feeding them, over every live expiry date. Empty when none lies within 50% of the price. Newest bar only." }); output("max_pain", none, overlay, { description: "Max pain: the strike (option price level) where option holders collect the least, over every live expiry date. Newest bar only." }); output("regime_sign", none, overlay, { description: "0 when dealers' net gamma is negative, 1 when positive or zero, empty with no reading. It picks the legend's colour." }); output("cvd_sign", none, lower, { description: "0 while the rolling CVD is negative, 1 while positive. It picks the histogram's colour." }); output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors: ["theme.down", "theme.up"], width: 0.7, label: "Agg. Rolling CVD", format: "si", description: "Rolling CVD (cumulative volume delta): aggressive buy volume minus sell volume over the window. Above zero, buyers led." }); pane("cvd", { height_frac: 0.12, format: "si" }); // the Indicator's home pane: it carries the Indicator's name, so no title here output("sigma", none, overlay, { description: "Today's move from the open, counted in 1σ moves (one standard deviation). A 1σ move is the open times the next day's implied volatility (IV) times √(1/252). Newest bar only." }); output("sigma_left", none, overlay, { description: "How much of today's 1σ move is left: 1 minus the size of sigma, never below 0. Newest bar only." }); string("regime_text", { max_bytes: 64 }); // the legend entry: "Neg Gamma (OI) | Flip · all expiries $85,722" render.legend("regime_entry", { text: "regime_text", color: "theme.muted", color_by: "regime_sign", colors: ["theme.down", "theme.up"] }); const tileRows = frame("tile_rows", { max_bytes: 4096 }); const gexCurve = frame("curve_rows", { max_bytes: 16384 }); // Nine tiles in two rows, five and four: signed dollars, unless a tile's own format word, text or colour wins. panel.tiles({ name: "tiles", title: "Options", x: "category", place: "below", frame: tileRows, columns: 5, positive_color: "theme.up", negative_color: "theme.down", format: "usd", signed: true, hover_card: true, height_frac: 0.18 }); // The gamma curve: a smooth line in the chart's text ink over hypothetical spot, filled up above zero and down below, // both axes in dollars; the spot marker and the flip, peak and trough callouts are written per run into the frame, and // the title names the one series, so it needs no legend chip. panel.line({ name: "gex_curve", title: "Net GEX (hypothetical spot)", x: "number", place: "below", frame: gexCurve, series: [{ name: "Net GEX", color: "theme.text", width: 2 }], smooth: true, fill_mode: "signed", fill_positive_color: "theme.up", fill_negative_color: "theme.down", fill_fade: true, x_format: "usd", x_decimals: 1, format: "usd", signed: true, decimals: 0, x_title: "Spot", y_zero: true, legend_style: "none", hover_card: true, height_frac: 0.25, maximize: true, stats_row: true }); const POINTS: i32 = 61; // the curve's points over S0 ± 15%: the chain input's points and half_pct const MAX_CVD = 500; // the ring the rolling CVD reads const SIGMA_YEARS: f64 = 1.0 / 252.0; // one trading day: the day's 1σ move is the open x the 1-day IV x sqrt(1/252) const NEXT_DAY_YEARS: f64 = 1.0 / 365.0; // the numbers fold's next 24 hours, the horizon Sigma's IV is read at const DAY_MS: f64 = 86400000.0; const gridSpot = new StaticArray<f64>(POINTS); // the curve's points over spot, read off the fold const gridGex = new StaticArray<f64>(POINTS); const deltas = new StaticArray<f64>(MAX_CVD); // buy minus sell per bar, the rolling window const stamp = new BookStamp(); // the book every fold read: its spot and whether it holds a contract const numbers = new OptionNumbers(1); // the scope rows, the horizons and the front expiry's row (the nearest kept) const profile = new StrikeProfile(1, POINTS); // the levels row and the curve's points (strikes 0: no strike row) const term = new VolTerm(1); // the term structure's front row (the nearest kept): its 25-delta risk reversal let cvdBars = 96; // settings, read in onStart() let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let coarse = false; // a chart coarser than a day: a bar is no session, so Sigma reads none let close: f64 = NaN; // this bar let t: f64 = NaN; let cvd: f64 = 0.0; // the rolling CVD and its ring let cvdHead = 0; let cvdCount = 0; let haveAnswer = false; // the live bar's block carried a book stamp let haveBook = false; // ... of a book holding contracts let s0: f64 = NaN; // the readings, measured on the live bar: the book's spot let netGex: f64 = NaN; let regime: f64 = NaN; // the sign of net GEX: 1, -1 or 0; NaN without a reading let flip: f64 = NaN; // the gamma flip: the curve's zero nearest S0 let pain: f64 = NaN; let pcr: f64 = NaN; let rr25: f64 = NaN; // the front expiry's 25-delta risk reversal, call minus put, vol points let vex: f64 = NaN; let dex: f64 = NaN; let points = 0; // the curve's points read let peakIdx = 0; let troughIdx = 0; let sessionDay: f64 = NaN; // the trade day the newest bar sits in, on the market's clock let sessionOpen: f64 = NaN; // the open of that trade day's first bar; NaN while the run opened inside it let sigma: f64 = NaN; // today's move in 1σ moves, the budget left and the IV it read (a decimal), live bar only let sigmaLeft: f64 = NaN; let sigmaIv: f64 = NaN; function onStart(): void { cvdBars = i32(p_cvd_bars()); if (cvdBars > MAX_CVD) cvdBars = MAX_CVD; zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; coarse = intervalMs > DAY_MS; } // A missing number reads NaN: a tile shows n/a, never a stale value. function finite(v: f64): f64 { return isFinite(v) ? v : NaN; } // ── The book on the live bar: the data plane's folds, each tile's field the built-in Dashboard's ── function measureBook(n: i32): void { // n = f64 cells in the live block const cells = in_chain_view(); // the live block in place: the first n values of the build's own buffer haveAnswer = stamp.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); // every reader at the input's row width: its widest word's, vol_term's 16 haveBook = haveAnswer && !stamp.empty(); // the empty book (no contract) answers its stamp alone s0 = NaN; netGex = NaN; regime = NaN; flip = NaN; pain = NaN; pcr = NaN; rr25 = NaN; vex = NaN; dex = NaN; points = 0; if (!haveBook) return; numbers.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); profile.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); term.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); s0 = stamp.spot(); // NaN when no expiry of the book has an anchor: its rows still read const whole = numbers.scopeIndex(0.0); // every live expiry's scope row netGex = finite(whole >= 0 ? numbers.netGex(whole) : profile.totalNetGex()); regime = dealerRegime(netGex); // the kit's one rule: the sign of net GEX, NaN without a reading flip = finite(numbers.flip(whole)); pain = finite(profile.maxPain()); pcr = finite(profile.putCallRatio()); vex = finite(profile.totalNetVex()); dex = finite(profile.totalNetDex()); // The front expiry's risk reversal: the vol term's first row while it is the nearest live expiry (numbers' first // expiry row) and the book has a spot; an expiry quoting no IV and holding no open interest has no vol term row. if (s0 > 0.0 && term.expiries() > 0) { const nearest = numbers.expiryMs(0); if (isNaN(nearest) || nearest == term.expiryMs(0)) rr25 = finite(term.rr25(0)); } points = profile.points(); for (let p = 0; p < points; p += 1) { gridSpot[p] = profile.pointX(p); gridGex[p] = profile.pointGex(p); } peakIdx = 0; troughIdx = 0; for (let p = 1; p < points; p += 1) { if (gridGex[p] > gridGex[peakIdx]) peakIdx = p; if (gridGex[p] < gridGex[troughIdx]) troughIdx = p; } } // The numbers fold's ATM IV over the next 24 hours (a decimal): its horizon row at 1/365 of a year, the nearest one. function nextDayIv(): f64 { let iv: f64 = NaN; let gap = Infinity; for (let h = 0; h < numbers.horizons(); h += 1) { const d = Math.abs(numbers.horizonYears(h) - NEXT_DAY_YEARS); if (d < gap) { gap = d; iv = numbers.horizonIv(h); } } return gap < 1.0e-9 ? iv : NaN; } // ── Sigma on the live bar: the close's move from the session's open over the day's 1σ move ── function measureSigma(): void { sigmaIv = haveBook ? finite(nextDayIv()) : NaN; sigma = finite((close - sessionOpen) / oneSigmaMove(sessionOpen, sigmaIv, SIGMA_YEARS)); // NaN without an open or an IV sigmaLeft = isNaN(sigma) ? NaN : Math.max(0.0, 1.0 - Math.abs(sigma)); } // ── Text and frames, built without allocating ── function fbUsd(v: f64): void { // "+$34.7M", "-$42.0M", "+$1.23B" if (!isFinite(v)) { fb_text("n/a"); return; } fb_text(v < 0.0 ? "-$" : "+$"); const a = Math.abs(v); if (a >= 1.0e9) { fb_f64(a / 1.0e9, 2); fb_text("B"); } else if (a >= 1.0e6) { fb_f64(a / 1.0e6, 1); fb_text("M"); } else if (a >= 1.0e3) { fb_f64(a / 1.0e3, 1); fb_text("K"); } else fb_f64(a, 0); } function fbPctFrom(price: f64, from: f64): void { // "+1.4%": how far a price sits from another const pct = (price / from - 1.0) * 100.0; if (pct >= 0.0) fb_text("+"); fb_f64(pct, 1); fb_text("%"); } function fbSigned(v: f64): void { // "+0.99", "-1.19": two decimals, a value that rounds to zero reads +0.00 if (Math.abs(v) < 0.005) { fb_text("+0.00"); return; } if (v > 0.0) fb_text("+"); fb_f64(v, 2); } function fbTone(v: f64): void { // the colour word of a signed reading fb_text(v < 0.0 ? "\"theme.down\"" : "\"theme.up\""); } function fbDollars(v: f64): void { // a dollar tile's value: its whole dollars, or "n/a" (a tile value is never null) if (isFinite(v)) fb_f64(v, 0); else fb_text("\"n/a\""); } function priceDecimals(v: f64): i32 { // decimals follow the price's size, so the tiles read on any coin: $87,526, $150.25, $0.4213 return v >= 1000.0 ? 0 : v >= 1.0 ? 2 : 4; } function fbX(v: f64): void { // a curve price, two decimals finer than a tile's, so 61 points stay apart on any price fb_f64(v, priceDecimals(v) + 2); } function fbGrouped(n: i64): void { // 85979 -> 85,979 if (n >= 1000) { fbGrouped(n / 1000); fb_text(","); const r = n % 1000; if (r < 100) fb_text("0"); if (r < 10) fb_text("0"); fb_int(r); } else fb_int(n); } function fbPrice(v: f64): void { // "$85,979", "$150.25", "$0.4213" fb_text("$"); if (v >= 1000.0) fbGrouped(i64(Math.round(v))); else fb_f64(v, priceDecimals(v)); } function writeTiles(): void { // [label, value, caption, color, spark, format], null to skip an element fb_clear(); fb_text("{\"rows\":["); fb_text("[\"Live net GEX\","); fbDollars(netGex); fb_text(",\"all expiries · open interest"); if (s0 > 0.0) { fb_text(" @ $"); if (s0 >= 1000.0) { fb_f64(s0 / 1000.0, 1); fb_text("K"); } else fb_f64(s0, priceDecimals(s0)); } fb_text("\",null,null,\"usd\"]"); if (isFinite(flip)) { fb_text(",[\"Gamma flip\",\""); fbPrice(flip); fb_text("\",\""); if (s0 > 0.0) { fbPctFrom(flip, s0); fb_text(" · "); } fb_text("all expiries\",\"theme.text\"]"); } else if (isFinite(netGex)) fb_text(",[\"Gamma flip\",\"None within 50%\",\"all expiries\",\"theme.text\"]"); // the curve has no zero within 50% of S0 else fb_text(",[\"Gamma flip\",\"n/a\",\"all expiries\",\"theme.muted\"]"); fb_text(",[\"Max pain\",\""); if (isFinite(pain)) { fbPrice(pain); fb_text("\",\""); fbPctFrom(pain, close); fb_text(" from spot · all expiries\",\"theme.text\"]"); } else fb_text("n/a\",\"all expiries\",\"theme.muted\"]"); // Version 0.4 names the measure, open-interest gamma: "(OI)" on the regime (a tile caption holds 40 characters, which // its scope fills) and in the legend entry, "open interest" in net GEX's caption. if (regime < 0.0) fb_text(",[\"Dealer regime\",\"Negative Gamma (OI)\",\"Dips sold, rallies bought · all expiries\",\"theme.down\"]"); else if (regime > 0.0) fb_text(",[\"Dealer regime\",\"Positive Gamma (OI)\",\"Dips bought, rallies sold · all expiries\",\"theme.up\"]"); else if (regime == 0.0) fb_text(",[\"Dealer regime\",\"Neutral Gamma (OI)\",\"No net gamma at S0 · all expiries\",\"theme.text\"]"); else fb_text(",[\"Dealer regime\",\"n/a\",\"all expiries\",\"theme.muted\"]"); // Sigma: the signed move in 1σ moves, the budget left and the IV under it, coloured by |sigma|'s band. fb_text(",[\"Sigma today\",\""); if (isNaN(sigma)) { fb_text("n/a\",\""); fb_text(coarse ? "Needs a daily or finer chart" : !(sessionOpen > 0.0) ? "Waiting for today's open" : "No 1-day IV in this symbol's options"); fb_text("\",\"theme.muted\"]"); } else { fbSigned(sigma); fb_text("σ\",\"1σ budget left "); fb_f64(sigmaLeft * 100.0, 0); fb_text("% · 1d IV "); fb_f64(sigmaIv * 100.0, 1); fb_text("%\","); const a = Math.abs(sigma); fb_text(a < 0.5 ? "\"theme.muted\"]" : a < 1.0 ? "\"theme.text\"]" : sigma > 0.0 ? "\"theme.up\"]" : "\"theme.down\"]"); } fb_text(",[\"P/C ratio\",\""); // a ratio of open interest, so text: two decimals and no sign if (isFinite(pcr)) { fb_f64(pcr, 2); fb_text(pcr > 1.0 ? "\",\"Puts favored\",\"theme.down\"]" : "\",\"Calls favored\",\"theme.up\"]"); } else fb_text("n/a\",\"all expiries\",\"theme.muted\"]"); fb_text(",[\"25D skew\",\""); // the risk reversal, call minus put: below zero the puts are bid if (isFinite(rr25)) { if (rr25 >= 0.0) fb_text("+"); fb_f64(rr25, 1); fb_text(rr25 < 0.0 ? "pp\",\"Puts bid (downside)\"," : "pp\",\"Calls bid (upside)\","); fbTone(rr25 < 0.0 ? -1.0 : 1.0); fb_text("]"); } else fb_text("n/a\",\"front expiry\",\"theme.muted\"]"); fb_text(",[\"Net VEX\","); fbDollars(vex); fb_text(!isFinite(vex) ? ",\"all expiries\",null,null,\"usd\"]" : vex >= 0.0 ? ",\"Dealers long vega\",null,null,\"usd\"]" : ",\"Dealers short vega\",null,null,\"usd\"]"); fb_text(",[\"Net DEX\","); // USD notional (delta x open interest x multiplier x underlying), the same quantity on a coin, a stock and a future fbDollars(dex); if (isFinite(dex)) { fb_text(dex < 0.0 ? ",\"Net short delta, USD notional\"," : ",\"Net long delta, USD notional\","); fbTone(dex); fb_text(",null,\"usd\"]"); } else fb_text(",\"all expiries\",null,null,\"usd\"]"); fb_text("]}"); writeFrameBuffer(tileRows); } function fbMarker(idx: i32, color: string): void { // a point callout pinned on the curve: "<usd> @ $<spot>" with a leader and a dot fb_text(",{\"x\":"); fbX(gridSpot[idx]); fb_text(",\"valign\":\"point\",\"series\":\"Net GEX\",\"label\":\""); fbUsd(gridGex[idx]); fb_text(" @ $"); fb_f64(gridSpot[idx], priceDecimals(gridSpot[idx])); fb_text("\",\"color\":\""); fb_text(color); fb_text("\"}"); } function writeCurve(): void { // the fold's points over S0 ± 15%; none (an empty book, no spot) clears the curve fb_clear(); fb_text("{\"rows\":["); for (let p = 0; p < points; p += 1) { fb_text(p > 0 ? ",[" : "["); fbX(gridSpot[p]); fb_text(","); fb_f64(gridGex[p], 0); fb_text("]"); } fb_text("]"); if (points > 0) { fb_text(",\"markers\":[{\"x\":\"spot\",\"label\":\"Spot\",\"wash\":true}"); if (flip >= gridSpot[0] && flip <= gridSpot[points - 1]) { // the flip as a point callout on the curve (its value is zero there) when the points reach it fb_text(",{\"x\":"); fbX(flip); fb_text(",\"valign\":\"point\",\"series\":\"Net GEX\",\"label\":\"Gamma flip\",\"color\":\"theme.text\",\"show_value\":true}"); } fbMarker(peakIdx, "theme.up"); fbMarker(troughIdx, "theme.down"); fb_text("]"); } fb_text(",\"caption\":\"live chain, all expiries\"}"); writeFrameBuffer(gexCurve); } function sbGrouped(n: i64): void { // 85979 -> 85,979 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 writeLegendText(): void { // only while net GEX has a reading (the regime is known) sb_clear(); sb_text(regime < 0.0 ? "Neg Gamma (OI) | " : regime > 0.0 ? "Pos Gamma (OI) | " : "Neutral Gamma (OI) | "); if (isNaN(flip)) sb_text("no flip within 50%"); else { sb_text("Flip · all expiries $"); if (flip >= 1000.0) sbGrouped(i64(Math.round(flip))); else sb_f64(flip, priceDecimals(flip)); } str_regime_text_sb(); } // onBar(): the session and the rolling CVD on every bar; the live bar reads the book and Sigma and writes the tiles, // the curve and the legend. function onBar(): void { t = bar.time(); close = bar.close(); // The session: the first bar of each trade day opens it; the run's first trade day opened before the run did. const day = optionsTradeDay(t * 1000.0, zone); if (isFinite(day) && day != sessionDay) { sessionOpen = isNaN(sessionDay) ? NaN : bar.open(); sessionDay = day; } // The rolling CVD: this bar's delta joins the ring, the bar that falls out of the window leaves it. const d = in_buy() - in_sell(); if (cvdCount == cvdBars) cvd -= deltas[cvdHead]; else cvdCount += 1; deltas[cvdHead] = d; cvdHead = (cvdHead + 1) % cvdBars; cvd += d; out_cvd(cvd); out_cvd_sign(cvd >= 0.0 ? 1.0 : 0.0); haveAnswer = false; haveBook = false; sigma = NaN; sigmaLeft = NaN; if (bar.isLast() && !isNaN(close) && !isNaN(t)) { measureBook(in_chain_cells()); if (!coarse) measureSigma(); } out_net_gex(haveBook ? netGex : NaN); out_gamma_flip(haveBook ? flip : NaN); out_max_pain(haveBook ? pain : NaN); out_regime_sign(haveBook && !isNaN(regime) ? (regime < 0.0 ? 0.0 : 1.0) : NaN); out_sigma(sigma); out_sigma_left(sigmaLeft); if (haveAnswer) { // a read answered: the book's numbers, or the empty book's blank tiles and curve if (haveBook && !isNaN(regime)) writeLegendText(); writeTiles(); writeCurve(); } } ``` ## How it works **The book is live only.** `input("chain", options_chain.cells, { max_cells: 400, venue: "auto", page_views: ["numbers", "strike_profile", "vol_term"], strikes: 0, points: 61, half_pct: 15 })` asks the data plane for three book folds of the chart's own option book: `numbers` (net GEX, the regime and the gamma flip over every live expiry, a row per live expiry, and the at-the-money IV at eight horizons, the next 24 hours among them), `strike_profile` with `strikes: 0` (no strike rows, only the levels row and the GEX curve: its `points`, 61, over S0 ± `half_pct`, 15%) and `vol_term` (a row per live expiry quoting an IV or holding open interest). The data plane folds them once a chain update over the chain page's whole book, priced at one instant, so the tiles read the numbers the chart's own options panes draw. The answer rides the live row as one block of rows 16 values wide, the widest word's (`vol_term`), each row `[layout, ...fields]`: the book stamp, the numbers rows, the levels row and the curve's points, the term rows. `max_cells` counts rows, the stamp's included: 400 holds the stamp, the scope row, 264 expiry rows, the eight horizons, vol_term's 64 rows, the levels row and the 61 points. History bars carry an empty block, so the tiles and the curve are read on the last bar and rewritten as the book moves. `venue: "auto"` reads the chart's own market when it lists options, else the coin's Deribit chain. **One block, four readers.** On the live bar four kit readers read the block, each at the input's row width (`OPTION_VIEW_ROW_VOL_TERM`, 16) and each its own layouts. `BookStamp` says whether an answer arrived and whether the book holds a contract (`empty()`: the empty book answers its stamp alone), and gives S0, the book's spot (`spot()`, NaN when no expiry of the book has an anchor; its rows still read). Net GEX is the `numbers` fold's scope row over every live expiry (`scopeIndex(0)`, `netGex()`; the levels row's `totalNetGex()` without one), at S0 in USD per 1% move; the dealer regime is its sign through the kit's `dealerRegime()`, NaN without a reading, and the gamma flip is that row's `flip()`, the GEX curve's zero nearest S0, NaN when none lies within 50% of it: the level the tile, the legend entry, the `gamma_flip` output and the flip callout all read. Max pain, the put/call ratio of open interest (puts over calls), net VEX and net DEX are the `strike_profile` levels row's (`maxPain()`, `putCallRatio()`, `totalNetVex()`, `totalNetDex()`), every live expiry pooled. The curve is that fold's 61 points (`points()`, `pointX()`, `pointGex()`), and the pass finds its peak and trough there. Each reader holds only what the tiles read: `OptionNumbers(1)` and `VolTerm(1)` keep the nearest expiry's row, `StrikeProfile(1, 61)` no strike row and the 61 points. A number the fold has no reading for reads NaN, so its tile prints `n/a`, never a stale value. **The other tiles.** The 25D skew tile is the front expiry's 25-delta risk reversal, the vol term's first row (`rr25()`: the 25-delta call's IV minus the 25-delta put's, in vol points, so below zero the puts are bid). It reads only while the book has a spot and that row is the nearest live expiry, the `numbers` fold's first expiry row: an expiry quoting no IV and holding no open interest has no vol term row, so the tile never prints a later expiry's skew as the front one's. Net VEX is the levels row's net vega exposure, captioned `Dealers long vega` from zero up and `Dealers short vega` below. Net DEX is its net delta exposure in USD notional (delta times open interest times the multiplier times the underlying), the one unit that reads the same on every venue (delta times open interest is coins on Deribit, where the multiplier is 1, but shares on OPRA, where it is 100, and dollars per point on CME, where it is the point value), so the tile prints through the `usd` format with a `USD notional` caption. The tiles frame is `{ rows: [[label, value, caption, color, spark, format], ...] }`, `null` skipping an element: a number prints through the panel's `format: "usd"` with `signed: true` unless the row carries its own format word, a text value prints as written (`$85,722`, `0.56` for the ratio, `-1.4pp`; prices carry thousands separators and their decimals follow the coin's price size; the flip's caption names its scope, `+1.4% · all expiries`, and with no zero within 50% of S0 the tile reads `None within 50%`; the regime's value names its measure, `Negative Gamma (OI)`, and its caption its scope, `Dips sold, rallies bought · all expiries` (a tile's caption holds at most 40 characters, which the scope fills, so the measure rides the value); net GEX's caption names both, `all expiries · open interest @ $85.7K`, and max pain's its distance from the chart's close and its scope, `-2.1% from spot · all expiries`), a dollar tile with no reading prints the text `n/a` (a tile's value is never null), and a row's own colour wins: the regime, the ratio, the skew and net DEX carry `theme.up` or `theme.down` by the side they read, the flip and max pain `theme.text`, a tile with no reading `theme.muted`, and net GEX and net VEX carry none (nor does net DEX without a reading). **Sigma.** Every bar notes its trade day on the market's clock (`optionsTradeDay()`: the UTC day on crypto, the CME trade date that opens at 17:00 Chicago, the New York date), and the first bar of each trade day opens its session at its open; the run's first trade day opened before the run did, so it has none. On the live bar the `numbers` fold's horizon row at 1/365 of a year, the next 24 hours, gives the at-the-money IV (`horizonYears()`, `horizonIv()`, a decimal). Sigma is the live close minus the session's open over `oneSigmaMove(open, iv, 1 / 252)`, the open times that IV times the square root of one trading day, and the budget left is 1 minus its size, floored at 0. The tile sits after the dealer regime: its value is the signed reading (`+0.99σ`), its caption the budget left and the IV (`1σ budget left 1% · 1d IV 16.0%`), and its colour the band: muted under 0.5, the text ink under 1, the up or down colour from 1 on. The `sigma` and `sigma_left` outputs carry the two numbers on the live bar. **The curve frame.** `{ rows: [[spot, gex], ...], markers, caption }`: the rows are the fold's 61 points, each spot written two decimals finer than a tile's price so the points stay apart on any price, and `markers` carry the Spot marker (`x: "spot"`, with a `wash`), the flip as a point callout when the points reach it (`valign: "point"` and `series: "Net GEX"` pin it on the line, `show_value` prints the spot in its label) and the peak and trough callouts with their readings. With no points (an empty book, a book with no spot) the frame carries no rows and no markers, so the curve clears. `panel.line` draws it with `x: "number"` over the spots (`x_format: "usd"`) and no `chrome`, so the pane draws horizontal value hairlines only ([The default look](../presentation/cards-frames-panels.md#the-default-look)), `smooth` on the line (its `series` colour `theme.text`, the chart's text ink), `fill_mode: "signed"` with `fill_positive_color: "theme.up"`, `fill_negative_color: "theme.down"` and `fill_fade`, `y_zero` so the zero line always shows, `legend_style: "none"` (the one series needs no legend entry: the title names it and the hover card reads it), a `stats_row`, `hover_card` and `maximize`; `height_frac: 0.25` gives it the larger share of the space below the chart, the tiles `0.18`, so with the CVD pane's `0.12` the three take 0.55 of the chart and the candles keep the rest. **The CVD pane.** Each bar's aggressive buy volume minus its sell volume joins a ring of `cvd_bars` (96) deltas and the bar that falls out of the window leaves it; the sum is the `cvd` histogram. `output("cvd", histogram, lower, { pane: "cvd", color_by: "cvd_sign", colors })` colours each bar from the `cvd_sign` ladder, `theme.down` while the sum is negative and `theme.up` while positive, and `pane("cvd", { height_frac: 0.12, format: "si" })` sizes the pane and formats its axis; the pane carries the indicator's name, so it declares no title. **The legend entry.** `render.legend("regime_entry", { text: "regime_text", color: "theme.muted", color_by: "regime_sign", colors })` reads the string slot written on the live bar while net GEX has a reading (`Neg Gamma (OI) | Flip · all expiries $85,722`, or `Pos Gamma (OI) | no flip within 50%`) and colours it from the regime ladder; without a reading `regime_sign` is NaN and the muted `color` holds the dot. ## What the settings do - **CVD window, bars**: How many bars the rolling cumulative volume delta (buys minus sells, summed) adds up. - **Live net GEX**: Net gamma exposure (GEX): the dollars dealers (options market makers) must trade per 1% move, over every expiry date. - **Gamma flip**: The price where dealers switch from calming price to pushing it, and its distance from the price. - **Max pain**: The strike (the option's price level) where option holders collect the least at expiry, and its distance from the price. - **Dealer regime**: Whether dealers calm moves (dips bought, rallies sold) or feed them (dips sold, rallies bought). - **Sigma today**: Today's move from the open in 1σ units, the day's expected move (how far option prices say it can move). Its caption shows how much of that move is left. - **P/C ratio**: Open puts (bets on a fall) per open call (bets on a rise), above 1 meaning puts favored. - **25D skew**: Call minus put implied volatility (how big a move option prices expect), below zero when puts cost more. It reads options a fair way from the price (25 delta) on the nearest expiry date. - **Net VEX**: Net vega exposure (VEX): how much dealers gain or lose in dollars when option prices rise. - **Net DEX**: Net delta exposure (DEX): how much of the asset dealers must hold to hedge, in dollars, long or short. ## Where it runs It works on any chart with listed options. On crypto, that is any coin Deribit lists options for, such as BTC, ETH and SOL, on any exchange. For example, Binance Futures BTCUSDT and Binance spot ETHUSDT both work. On a US stock or ETF chart, every indicator can read that symbol's US listed options. On a futures chart from CME, the Chicago exchange, it reads that future's own options. US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless you have real-time CME data. A copy you run from the editor (where you write and run indicators) reads crypto, US stock and CME options. On a CME chart, accept the CME market data terms first. The chart in your browser reads these numbers ready-made by OpenMarket. Run on Cloud (the choice that runs it on OpenMarket's servers instead of your browser) cannot read them yet. Protected copies (published ones that run on OpenMarket's servers) cannot read them either. Both stop with an error that names each one. A chart in local mode (`chart-local`) cannot read them, because its options data comes from your own source. The chart sends the newest numbers on the live bar only, about every 30 seconds. Older bars get no options data. The cumulative volume delta reads the chart market's own buy and sell trades. Run it beside the [Strike Matrix](strike-matrix.md) on a second chart for the whole desk. On a short timeframe, drag that chart's price axis to zoom out and see more strikes. ## When data is missing On a market with no listed options, it stops before loading anything. The error names the problem and the way out. On HYPERLIQUID_FUTURES/PURR, for example, it says PURR is not listed on Deribit. It then suggests a CME futures chart or a coin Deribit lists, such as BTC, ETH or SOL. Until the options numbers arrive, the tiles and the curve stay empty. The cumulative volume delta pane runs on its own meanwhile. A bar without buy and sell trades adds zero to it. With no open contracts at all, every tile prints `n/a` and the curve clears. A number with no reading prints `n/a` in its tile, never an old value. Without a current price for the options, the tiles still read. The Live net GEX tile's caption then drops the price, and the flip drops its distance from the price. The 25D skew reads `n/a`, and the curve has no points. With no gamma flip within 50% of the price, the curve shows no flip marker. Its tile then reads `None within 50%`. In the Console (the editor's prompt that shows a reading by its name), `gamma_flip` stays empty. A flip beyond the curve's 15% shows on its tile and in the legend, but not on the curve. The 25D skew also reads `n/a` when its first expiry date is not the nearest live one. Its caption then says `front expiry`. Sigma's tile reads `n/a` and gives the reason in its caption. `Waiting for today's open` means the chart has no first bar of today yet. `No 1-day IV in this symbol's options` means options price no implied volatility for the next 24 hours. `Needs a daily or finer chart` means each bar spans more than a day. In the Console, `sigma` and `sigma_left` then stay empty. ## Customize it - **A wider or narrower curve.** The input's `half_pct` (15, above 0 and up to 50) is the curve's reach, percent of S0 each side, and `points` (61, 2 to 1000) its points. Set `POINTS` to the same count, since `StrikeProfile(1, POINTS)` holds that many and refuses a block that carries more, and add the new points to `max_cells`, which counts rows. Past about 650 points raise the curve frame's `max_bytes` too (16384): a point takes 19 to 22 bytes on the recorded books (24 at most) and the markers and caption about 420, so the frame passes 16384 near 665 to 840 points, where the run refuses it whole (`wrun_frame_too_large`; a frame is never truncated). The curve only draws: the flip tile reads the `numbers` fold's flip at any reach, and the callout shows once the points reach the flip. - **A longer CVD window.** `cvd_bars` up to 500. - **Fewer tiles.** Delete a row in `writeTiles()` and set `columns` on `panel.tiles` to the new row length; the panel lays the rest out. - **A calendar day on crypto.** Sigma prices one trading day as 1/252 of a year on every venue; on a coin that trades every day, set `SIGMA_YEARS` to `1.0 / 365.0`. - **Pin the venue.** Change `venue: "auto"` to `"deribit"` and Run again to read the coin's Deribit chain even where the chart's market lists options of its own; `"cme"` reads a CME futures chart's chain. - **The colours.** Every colour on the desk is a theme word (`theme.up`, `theme.down`, `theme.text`) in the two `panel.*` declarations, the ladders and the frames (the callouts' colours are written in `writeCurve()`, the tiles' in `writeTiles()`), so it follows the chart's theme; a hex word in any of those places fixes a colour instead ([Style anything](../presentation/style-anything.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options Dashboard** under **Beyond the time axis**. 2. Press **Run** on a BTC or ETH chart: the tiles and the curve appear below the chart once the chain arrives, the CVD pane at the bottom from the first bar. 3. Hover a tile or the curve for its card; at the editor's Console prompt, type `net_gex` to read live net GEX, `sigma` for today's move in 1σ moves, or `last 20 cvd` for the rolling delta over the last 20 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `options_chain` celled class, the `venue` word and sided `trades.volume`, and [Chain page views](../core-concepts/data-sources.md#chain-page-views) for the book folds `numbers`, `strike_profile` and `vol_term`, their knobs and the hosted runs' refusal - [Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets) for `panel.tiles`, `panel.line`, the panel frames and markers - [Panes](../presentation/plotting.md#panes) for a named pane, its height and its format - [Styling](../presentation/styling.md) for `color_by` ladders on an output and a legend entry - [Book folds](../functions/options-kit.md#book-folds) for `BookStamp`, `OptionNumbers`, `StrikeProfile` and `VolTerm`, the rows each reads and the row width they share, [The canonical numbers](../functions/options-kit.md#the-canonical-numbers) for `dealerRegime` and `oneSigmaMove`, and [The market's own date](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay`, Sigma's session - [Style anything](../presentation/style-anything.md) for the whole desk, part by part <!-- source: https://openmarket.xyz/wrun/cookbook/odds-vs-price --> # Odds vs price ![Polymarket odds vs BTC: correlation pane, divergence bars, verdict card](/wrun/images/odds-vs-price.png) On a Polymarket chart, the market's YES odds set against a pinned asset, Binance Futures BTCUSDT by default. A pane below price holds the rolling correlation of odds changes and BTC returns (a line, -1 to 1) and a divergence histogram: the odds' z-score minus BTC's over the z-score window, muted while inside the threshold and lit in the up colour (odds stretched above BTC's move) or the down colour (below) once past it. On the odds candles, a dot marks the bar where the divergence first crossed the threshold. A window below the chart shows BTC's own close over the last two correlation windows, so the move the odds are measured against is on screen. A card at the top right reads the market's odds, BTC's price and its move over the window, the correlation, the divergence and a plain-words verdict. The parts are one candle leg pinned to another market ([Multi-source](../core-concepts/multi-source.md)), the `Correlation` and `Zscore` helpers ([TA library](../functions/ta-library.md)), a histogram with a four-rung colour ladder ([Styling](../presentation/styling.md)), a frame feeding a `panel.line` on a time axis and a `draw.card` with text slots ([Cards, frames and panels](../presentation/cards-frames-panels.md)). This is also the `odds-vs-price` template: the **Odds vs Price** card under **Prediction markets** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Odds vs Price: on a Polymarket chart, the market's YES odds against a pinned asset (Binance Futures BTCUSDT). // A pane with the rolling correlation of odds changes and asset returns, a divergence histogram (the odds' z-score // minus the asset's, lit past the threshold), the asset's own close in a window below the chart, and a card with the // live reading. The trader sees whether the odds are moving with the asset or have stretched away from it. param.int("window", 48, { min: 10, max: 500, label: "Correlation window in bars", description: "Bars in the rolling correlation" }); param.int("zscore_window", 96, { min: 10, max: 500, label: "Z-score window in bars", description: "Bars the divergence z-scores are measured over" }); param.number("threshold", 2, { min: 0.5, max: 5, step: 0.1, label: "Stretch threshold", description: "Divergence z-score that counts as stretched" }); chart.interval_sec(); // the chart's bar interval in seconds, written by the chart: the asset window breaks where a bar is missing input("close", ohlcv.close, { description: "This chart's close: the YES odds on a Polymarket market" }); // the primary input: the chart's own candles input("asset_close", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "BTCUSDT", missing: "carry", description: "The asset leg: BTCUSDT on Binance Futures" }); // pinned: change the pair here const correlationLine = output("correlation", line, lower, { color: "theme.text", width: 2, label: "Correlation", format: "0.00", description: "Rolling correlation of odds changes and asset returns, -1 to 1" }); // the handle names it for the hover card output("divergence", histogram, lower, { color_by: "div_tone", colors: ["theme.muted", "theme.muted", "theme.up", "theme.down"], label: "Divergence", format: "0.00", description: "Odds z-score minus asset z-score" }); // muted inside the threshold, up or down once stretched; two decimals in the legend hover(correlationLine, [block.value("Correlation", "correlation", { format: "0.00" }), block.rows([["Divergence", "divergence", "0.00"]])]); // the card the correlation line opens under the cursor output("div_tone", none, lower, { description: "0 mild up, 1 mild down, 2 stretched up, 3 stretched down" }); // data-only: the histogram's ladder output("stretch_up", shape, overlay, { color: "theme.up", width: 6, description: "The close of the bar where the divergence first crossed above the threshold" }); // an event dot on the odds candle output("stretch_down", shape, overlay, { color: "theme.down", width: 6, description: "The close of the bar where the divergence first crossed below minus the threshold" }); string("market_line", { max_bytes: 24 }); // "Odds 62.0%" or "Price 0.1423" string("asset_line", { max_bytes: 24 }); // "84,210" string("move_text", { max_bytes: 24 }); // "+0.4%" over the correlation window string("corr_text", { max_bytes: 16 }); // "0.29" string("div_text", { max_bytes: 16 }); // "+3.97" string("reading", { max_bytes: 24 }); // the plain-words verdict, at most 24 characters (the card clips longer values) const asset_rows = frame("asset_rows", { max_bytes: 49152 }); // the asset window: [bar open, asset close] for the last 2 x window bars and a null row per hole (at most 1000 rows of 24 bytes and 999 of 18) panel.line({ name: "asset_window", title: "Asset leg: BTCUSDT on Binance Futures", x: "time", place: "below", frame: asset_rows, legend_style: "none", series: [{ name: "BTC close", color: "theme.text" }] }); // no series chip beside the title: the one series is named once, by its value row draw.card("odds_vs_asset", { title: "Odds vs BTC", anchor: "top_right", offset: [0, 40], // below the chart's own High tag, which always sits in the pane's top-right corner rows: [ { label: "This market", value: { text: "market_line" } }, { label: "BTC", value: { text: "asset_line" } }, { label: "BTC move, window", value: { text: "move_text" } }, { label: "Correlation", value: { text: "corr_text" } }, { label: "Divergence", value: { text: "div_text" }, color: { color_by: "div_tone", colors: ["theme.text", "theme.text", "theme.up", "theme.down"] } }, { label: "Read", value: { text: "reading" } }, ], }); const RING = 1024; // the asset window ring const ringT = new StaticArray<f64>(RING); const ringAsset = new StaticArray<f64>(RING); let head = -1; let count = 0; const jsonBytes = new StaticArray<u8>(49152); let jsonUsed = 0; // the asset window JSON, appended as UTF-8 bytes (the sandbox forbids memory growth after onStart()) let window = 48; let zWindow = 96; let threshold = 2.0; // the params let corr = new Correlation(48); let zOdds = new Zscore(96); let zAsset = new Zscore(96); // rebuilt in onStart() let close: f64 = NaN; let prevClose: f64 = NaN; let asset: f64 = NaN; let prevAsset: f64 = NaN; // the two legs on this bar and the previous one let prevTone: f64 = NaN; // the divergence's tone on the previous bar: the crossing detector let barSec: f64 = NaN; // the chart's bar in seconds, NaN when the chart did not fill it (the asset window then never breaks) let unitScale = true; let centScale = true; let sameMarket = true; let bars = 0; // what this chart looks like: odds 0..1 on a 0.001 grid, odds 0..100 on a 0.1 grid, or the asset itself function round2(v: f64): f64 { return Math.round(v * 100.0) / 100.0; } function offGrid(v: f64, step: f64): bool { const k = v / step; return Math.abs(k - Math.round(k)) > 1e-6; } // ── JSON bytes: append text and numbers without allocating; one string is made per frame write ── function jbByte(b: u32): void { if (jsonUsed < jsonBytes.length) { jsonBytes[jsonUsed] = <u8>b; jsonUsed += 1; } } function jbText(text: String): void { const n = String.UTF8.byteLength(text); if (jsonUsed + n <= jsonBytes.length) jsonUsed += i32(String.UTF8.encodeUnsafe(changetype<usize>(text), text.length, changetype<usize>(jsonBytes) + jsonUsed)); } function jbUint(v: u64): void { if (v >= 10) jbUint(v / 10); jbByte(0x30 + <u32>(v % 10)); } function jbNum(v: f64, decimals: i32): void { // a fixed-point number, or null when not finite if (!isFinite(v)) { jbText("null"); return; } let x = v; if (x < 0.0) { jbByte(0x2d); x = -x; } let scale = 1.0; for (let i = 0; i < decimals; i += 1) scale *= 10.0; const scaled = Math.round(x * scale); const whole = Math.floor(scaled / scale); const frac = scaled - whole * scale; jbUint(<u64>whole); if (decimals > 0) { jbByte(0x2e); const f = <u64>frac; let digits = 1; let probe = f; while (probe >= 10) { probe /= 10; digits += 1; } for (let i = digits; i < decimals; i += 1) jbByte(0x30); jbUint(f); } } function jbFlush(slot: i32): void { writeFrame(slot, String.UTF8.decodeUnsafe(changetype<usize>(jsonBytes), jsonUsed)); jsonUsed = 0; } function sbGrouped(n: i64): void { 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 { if (v >= 1000.0) sbGrouped(i64(Math.round(v))); else if (v >= 100.0) sb_f64(v, 2); else if (v >= 1.0) sb_f64(v, 3); else sb_f64(v, 4); } function onStart(): void { window = i32(p_window()); zWindow = i32(p_zscore_window()); threshold = p_threshold(); corr = new Correlation(window); zOdds = new Zscore(zWindow); zAsset = new Zscore(zWindow); barSec = p_chart_interval_sec() > 0.0 ? p_chart_interval_sec() : NaN; // the one frame string per write is a temporary: the scratch the build reserves after onStart() holds it } // onBar() runs once per bar: the bar's odds change against the asset's log return into the correlation, both levels into their // z-scores; then the pane's two series and the card's words on every ready bar, the asset window on the live bar only. function onBar(): void { prevClose = close; prevAsset = asset; close = bar.close(); asset = in_asset_close(); const t = bar.time(); if (isNaN(close) || isNaN(asset)) return; bars += 1; if (close < 0.0 || close > 1.0 || offGrid(close, 0.001)) unitScale = false; // odds as 0..1 tick in thousandths if (close < 0.0 || close > 100.0 || offGrid(close, 0.1)) centScale = false; // odds as 0..100 tick in tenths of a cent if (Math.abs(asset - close) > 1e-9 * Math.max(1.0, Math.abs(close))) sameMarket = false; head = (head + 1) % RING; if (count < RING) count += 1; ringT[head] = t; ringAsset[head] = asset; const oddsChange = isNaN(prevClose) ? NaN : close - prevClose; const assetReturn = isNaN(prevAsset) || prevAsset <= 0.0 ? NaN : Math.log(asset / prevAsset); const correlation = isNaN(oddsChange) || isNaN(assetReturn) ? NaN : corr.update(oddsChange, assetReturn); const zo = zOdds.update(close); const za = zAsset.update(Math.log(asset)); const divergence = isNaN(zo) || isNaN(za) ? NaN : zo - za; const tone = isNaN(divergence) ? 0.0 : Math.abs(divergence) >= threshold ? (divergence > 0.0 ? 2.0 : 3.0) : divergence > 0.0 ? 0.0 : 1.0; const stretchUp = tone == 2.0 && prevTone != 2.0 && !isNaN(prevTone) ? close : NaN; // the event dots: the close on the bar the divergence crossed the threshold, NaN elsewhere const stretchDown = tone == 3.0 && prevTone != 3.0 && !isNaN(prevTone) ? close : NaN; prevTone = isNaN(divergence) ? NaN : tone; if (isNaN(correlation) || isNaN(divergence)) return; // still warming up: nothing is written on this bar out_correlation(round2(correlation)); out_divergence(Math.abs(divergence) < 0.005 ? NaN : round2(divergence)); out_div_tone(tone); out_stretch_up(stretchUp); out_stretch_down(stretchDown); // a zero-height bar is skipped sb_clear(); if (unitScale) { sb_text("Odds "); sb_f64(close * 100.0, 1); sb_text("%"); } else if (centScale) { sb_text("Odds "); sb_f64(close, 1); sb_text("%"); } else { sb_text("Price "); sbPrice(close); } str_market_line_sb(); const back = window < count ? window : count - 1; const agoAsset = ringAsset[(head + RING - back) % RING]; sb_clear(); sbPrice(asset); str_asset_line_sb(); sb_clear(); if (agoAsset > 0.0) { const move = ((asset - agoAsset) / agoAsset) * 100.0; if (move >= 0.0) sb_text("+"); sb_f64(move, 1); sb_text("% over "); sb_int(back); sb_text(" bars"); } else sb_text("n/a"); str_move_text_sb(); sb_clear(); sb_f64(correlation, 2); str_corr_text_sb(); sb_clear(); if (divergence > 0.0) sb_text("+"); sb_f64(divergence, 2); str_div_text_sb(); sb_clear(); const odds = unitScale || centScale; // the words follow the chart: odds on a prediction market, the market itself elsewhere if (sameMarket && bars > 4) sb_text("Chart is the asset leg"); else if (divergence >= threshold) sb_text(odds ? "Odds stretched above BTC" : "Stretched above BTC"); else if (divergence <= -threshold) sb_text(odds ? "Odds stretched below BTC" : "Stretched below BTC"); else if (correlation > 0.3) sb_text(odds ? "Odds moving with BTC" : "Moving with BTC"); else if (correlation < -0.3) sb_text(odds ? "Odds moving against BTC" : "Moving against BTC"); else sb_text(odds ? "Odds detached from BTC" : "Detached from BTC"); str_reading_sb(); if (bar.isLast()) { // the asset window: [bar open in seconds, asset close], oldest first const shown = count < 2 * window ? count : 2 * window; const decimals = asset >= 100.0 ? 2 : 6; jbText("{\"rows\":["); for (let k = shown - 1; k >= 0; k -= 1) { const i = (head + RING - k) % RING; if (k != shown - 1) { jbText(","); const before = ringT[(i + RING - 1) % RING]; // a whole chart bar missing (nobody traded this market then): one null row, so the line breaks instead of bridging the hole if (ringT[i] - before > 1.5 * barSec) { jbText("["); jbNum(before + barSec, 0); jbText(",null],"); } } jbText("["); jbNum(ringT[i], 0); jbText(","); jbNum(ringAsset[i], decimals); jbText("]"); } jbText("]}"); jbFlush(FRAME_ASSET_ROWS); } } ``` ## How it works **One pinned leg.** `input("asset_close", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "BTCUSDT", missing: "carry" })` reads the asset's close on the chart's own grid; to compare against another asset, change the exchange and symbol in that one line. The chart's close is the primary input: the YES odds on a Polymarket market. **Correlation and divergence.** `correlation` is the rolling correlation of odds changes and asset returns over `window` (48) bars. `divergence` is the odds' z-score minus the asset's over `zscore_window` (96) bars; `div_tone` reads 0 mild up, 1 mild down, 2 stretched up, 3 stretched down from it against `threshold` (2), and the histogram's `color_by: "div_tone"` ladder paints muted, muted, the up colour and the down colour; `format: "0.00"` prints it in the legend with two decimals ("-0.43"), never a rounded "-0". `stretch_up` and `stretch_down` carry the close on the bar the divergence first crossed the threshold, the dots on the odds candles. **The asset is on screen.** `frame("asset_rows")` carries `[bar open, asset close]` for the last two correlation windows and feeds `panel.line` on a time axis below the chart; `legend_style: "none"` leaves the one series out of the legend beside the panel's title, so its name reads once, on its value row. The card's cells (odds, the asset's price and move, the correlation, the divergence, a verdict of at most 24 characters) are text slots written on the live bar. ## Where it runs Polymarket markets on charts of one minute and coarser (the card reads odds on the 0..1 and the 0..100 scale). The chart serves the pinned leg as another market's candles at the chart's interval, joined bar by bar and live from that market's candle feed. On any other crypto chart it still runs: the first leg is then the chart's own price, so the pane reads as relative strength against BTC, the card labels the row "Price" and the verdict drops the word odds; on the BTCUSDT perp itself the two legs are one series and the card says "Chart is the asset leg". An alert on this indicator reads the pinned BTC leg as well, since alerts serve another market's candles on a secondary `ohlcv` input ([Alerts](../functions/alerts.md)); the file reads the odds as the chart's own `ohlcv` candles, never the `odds` source alerts cannot evaluate. The BTC pin is another market at the chart's interval, not a coarser timeframe, so the alert keeps 500 bars, the largest maximum among its settings, which holds the default 48 and 96-bar windows. ## When data is missing The pane needs `zscore_window` bars of both legs before it draws; a bar without an asset observation carries the last one; a divergence under 0.005 draws no bar. The asset window breaks where the chart has no bar. A Polymarket market has no candle while nobody trades it, so where the next row is more than one and a half chart bars later (`chart.interval_sec()`), the frame writes one `null` row a bar after the last one and the line stops there instead of drawing a straight line across the hole. A lone row between two holes has no neighbour to join and draws no line. ## Customize it - **Another asset.** Change the `exchange` and `symbol` words on the pinned input (declaration literals, not settings) and the panel's title. - **A stricter stretch.** Raise `threshold`; the dots and the lit bars thin out. - **A longer memory.** `window` and `zscore_window` go up to 500 bars each. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Odds vs Price** under **Prediction markets**. 2. Press **Run** on a Polymarket market's chart: the pane, the asset window below the chart and the card draw once both legs have `zscore_window` bars. 3. At the editor's Console prompt, type `last 20 divergence` to read the divergence of the last 20 bars. ## Concepts used - [Multi-source](../core-concepts/multi-source.md) for pinned symbol and exchange legs - [TA library](../functions/ta-library.md) for `Correlation` and `Zscore` - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `panel.line`, `draw.card` and text slots <!-- source: https://openmarket.xyz/wrun/cookbook/etf-flows --> # Spot ETF flow ![Daily ETF flow bars, cumulative strip and flow card on BTC](/wrun/images/etf-flows.png) The daily net flow of the chart coin's spot ETFs as one wide bar per day in a pane under the chart, the up colour for an inflow day and the down colour for an outflow day, in dollars (the legend and the axis print `$29.0M`), with a zero line between them that stays out of the legend; the flow summed since the start of the loaded window as a line in a strip along the bottom of the price pane (its own scale, so the day bars keep theirs); and a faint wash behind each day's candles in the day's colour, so the flow reads against price. A day whose flow is a multiple of the window's mean day is tagged with its size ("+$1.20B"). A card at the top right reads the latest day (value and date), the window's sum over its days, the current streak ("4 days of inflow") and the biggest day of the window; a date names its month ("Oct 2") and carries its year when it is not this year ("Oct 6, 2025"). The parts are an `etf_flow.flow_usd` input landing once per day with `missing: "nan"` ([Data sources](../core-concepts/data-sources.md)), lower-pane box handles for the day bars and label handles for the tags ([Drawing objects](../presentation/drawing-objects.md)), an `out.inset` strip along the bottom of the price pane, a `render.bgcolor` wash ([Styling](../presentation/styling.md)) and a `draw.card` with text slots ([Cards, frames and panels](../presentation/cards-frames-panels.md)). This is also the `etf-flows` template: the **Spot ETF Flow** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Spot ETF Flow: the daily net flow of the chart coin's spot ETFs, in millions of USD, as one wide bar per day in a pane // under the chart (inflow in the up colour, outflow in the down colour), the flow summed since the start of the // loaded window as a line in a strip along the bottom of the price pane, and a faint tint behind each day's candles // in the day's colour, so the flow reads against price. A day whose flow // dwarfs the window's norm is tagged with its size. A card at the top right reads the latest day, the window's sum, // the current streak and the biggest day. The flow is daily: on an intraday chart it lands on the first bar of its // day, so the pane draws the day once (a box across the day) instead of a bar per 15m; on daily and coarser charts // each bar is its own day and the histogram carries it. Weekends and holidays have no flow and draw nothing. param.number("big_day", 2.0, { min: 1.0, max: 10.0, step: 0.1, label: "Big day multiple", description: "A day is tagged with its size when its flow is this many times the window's mean day" }); input("close", ohlcv.close); // the chart's own close: the grid input("flow", etf_flow.flow_usd, { fund: "all", missing: "nan", description: "Daily net spot-ETF flow in USD, summed over every fund listed for the chart's coin; change fund to one ticker (IBIT, ETHA, ...) to follow it alone" }); // lands on the first bar of its day, NaN elsewhere output("flow_sign", none, overlay, { description: "+1 on an inflow day, -1 on an outflow day, NaN on a day without a flow; the tint's gate" }); // first output on price: the package homes on the chart output("flow_tone", none, overlay, { description: "1 on an inflow day, 0 on an outflow day: the tint's colour index" }); output("latest_tone", none, overlay, { description: "1 while the latest day is an inflow, 0 while an outflow: the card's colour index" }); output("day_flow", none, overlay, { description: "The day's net flow in millions of USD, carried through the day" }); output("inflow", histogram, lower, { color: "theme.up", label: "Inflow", format: "usd", description: "Inflow days, USD, on the bar the day lands on" }); // usd prints the legend and the axis as $29.0M output("outflow", histogram, lower, { color: "theme.down", label: "Outflow", format: "usd", description: "Outflow days, USD, on the bar the day lands on" }); output("zero", line, lower, { color: "theme.muted", width: 1, legend: false, description: "The pane's zero line: inflow above it, outflow below; it keeps zero inside the pane's scale" }); // a scale helper: kept out of the legend out.inset("cumulative", { dock: "bottom", height_px: 44, shape: "line", colors: ["theme.up", "theme.down"] }); // net flow summed since the start of the loaded window, millions of USD: a strip along the bottom of the price pane with its own scale, so the day bars keep theirs string("latest", { max_bytes: 24 }); // the card's cells, one slot each, written on the live bar string("window", { max_bytes: 24 }); string("streak", { max_bytes: 24 }); string("biggest", { max_bytes: 24 }); string("text", { max_bytes: 24 }); // the big-day tags string("note", { max_bytes: 80 }); // the one sentence while no flow day is in view render.bgcolor("flow_days", { where: "flow_sign", color_by: "flow_tone", colors: ["#ef535014", "#26a69a14"] }); // a faint wash behind each day's candles, alpha 0.08: the chart's default down and up colours (a tint takes no theme word with an alpha) handles.box({ panel: "lower", opacity: 0.55, borderWidth: 1 }); // one box per day in the pane: x in seconds, y in USD handles.label({ panel: "lower", size: 11, color: "theme.text", align: "center" }); // the big-day tags, centred over the day draw.card("flow_card", { title: "Spot ETF flow", anchor: "top_right", offset: [56, 0], // inward past the price-axis tags rows: [ { label: "Latest day", value: { text: "latest" }, color: { color_by: "latest_tone", colors: ["theme.down", "theme.up"] } }, { label: "This window", value: { text: "window" } }, { label: "Streak", value: { text: "streak" } }, { label: "Biggest day", value: { text: "biggest" } }, ], }); render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); // the sentence: top centre, clear of the card const DAY = 86400.0; const MAX_BOXES = 60; // day boxes ride a ring: the oldest is recycled const MAX_TAGS = 20; const INFLOW_INK = theme.UP; const OUTFLOW_INK = theme.DOWN; const boxes: BoxHandle[] = []; for (let i = 0; i < MAX_BOXES; i += 1) boxes.push(draw.box(i)); const tags: LabelHandle[] = []; // ids are one space across kinds for (let i = 0; i < MAX_TAGS; i += 1) tags.push(draw.label(100 + i)); let bigDay = 2.0; // setting, read in onStart() let prevT: f64 = NaN; // the previous bar's open time let barSec: f64 = NaN; // the grid spacing, the smallest gap seen between bars let dayIndex: i64 = -1; // the current day (days since the epoch) and what it carries let dayFlowM: f64 = NaN; // the day's flow in millions, NaN until it lands let dayStart: f64 = NaN; let pendingStart: f64 = NaN; // a day that landed before the grid spacing was known: its box is drawn one bar later let pendingFlowM: f64 = NaN; let cumulativeM = 0.0; // since the first landed day of the window let days = 0; // landed days in the window let sumAbsM = 0.0; // for the big-day norm let boxesDrawn = 0; let tagsDrawn = 0; let streak = 0; // consecutive landed days with the latest day's sign let latestM: f64 = NaN; let latestDay: i64 = -1; let biggestM: f64 = NaN; let biggestDay: i64 = -1; const MONTHS: StaticArray<string> = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; let civilYear: i64 = 0; let civilMonth = 0; let civilDay = 0; function civilFromDays(daysSinceEpoch: i64): void { // days since 1970-01-01 -> year, month and day of month (proleptic Gregorian) const z = daysSinceEpoch + 719468; const era = (z >= 0 ? z : z - 146096) / 146097; const doe = z - era * 146097; const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); const mp = (5 * doy + 2) / 153; civilDay = i32(doy - (153 * mp + 2) / 5 + 1); civilMonth = i32(mp < 10 ? mp + 3 : mp - 9); civilYear = yoe + era * 400 + (civilMonth <= 2 ? 1 : 0); } function sbDate(day: i64, today: i64): void { // "Sep 29", with the year when it is not this bar's year: "Oct 6, 2025" civilFromDays(today); const thisYear = civilYear; civilFromDays(day); sb_text(MONTHS[civilMonth - 1]); sb_text(" "); sb_int(civilDay); if (civilYear != thisYear) { sb_text(", "); sb_int(civilYear); } } function sbMoneyM(m: f64): void { // millions in: "+$351M", "-$1.20B", "+$5.1K" sb_text(m < 0.0 ? "-$" : "+$"); const v = Math.abs(m); if (v >= 1000.0) { sb_f64(v / 1000.0, 2); sb_text("B"); } else if (v >= 1.0) { sb_f64(v, 0); sb_text("M"); } else { sb_f64(v * 1000.0, 0); sb_text("K"); } } // A day's box in the pane: from the day's first second to its last (a 5% gap keeps neighbouring days apart), 0 to the flow. function drawDayBox(start: f64, flowM: f64): void { const k = boxesDrawn % MAX_BOXES; boxesDrawn += 1; const ink = flowM >= 0.0 ? INFLOW_INK : OUTFLOW_INK; boxes[k].set(start, flowM * 1.0e6, start + DAY * 0.95, 0.0).fill(ink).color(ink).opacity(0.55).border(1.0); } // A tag over (or under) the day's bar when the day dwarfs the window's mean day. function tagBigDay(start: f64, flowM: f64): void { const k = tagsDrawn % MAX_TAGS; tagsDrawn += 1; sb_clear(); sbMoneyM(flowM); tags[k].set(start + DAY * 0.475, flowM * 1.0e6).text(str_text_sb).color(flowM >= 0.0 ? INFLOW_INK : OUTFLOW_INK); } function onStart(): void { bigDay = p_big_day(); } // onBar() runs once per bar: the grid spacing, the day the bar belongs to, and the day's flow when it lands; then the day's // numbers on every bar, the histogram on the landing bar, the box when the chart is finer than a day, the tag on a big day, // the card on the live bar only. function onBar(): void { const close = bar.close(); const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const day = i64(Math.floor(t / DAY)); if (day != dayIndex) { dayIndex = day; dayStart = f64(day) * DAY; dayFlowM = NaN; } let landedNow = false; // this bar carried the day's value const flow = in_flow(); if (!isNaN(flow) && flow != 0.0 && isNaN(dayFlowM)) { // the day's value, once; a reported zero (a day the funds did not trade) counts as no flow dayFlowM = flow / 1.0e6; landedNow = true; cumulativeM += dayFlowM; days += 1; sumAbsM += Math.abs(dayFlowM); if (!isNaN(latestM) && (latestM >= 0.0) == (dayFlowM >= 0.0)) streak += 1; else streak = 1; latestM = dayFlowM; latestDay = day; if (isNaN(biggestM) || Math.abs(dayFlowM) > Math.abs(biggestM)) { biggestM = dayFlowM; biggestDay = day; } } if (isNaN(close)) return; const hasDay = !isNaN(dayFlowM); out_flow_sign(hasDay ? (dayFlowM >= 0.0 ? 1.0 : -1.0) : NaN); out_flow_tone(hasDay ? (dayFlowM >= 0.0 ? 1.0 : 0.0) : NaN); out_latest_tone(isNaN(latestM) ? NaN : latestM >= 0.0 ? 1.0 : 0.0); out_day_flow(dayFlowM); out_inflow(landedNow && dayFlowM >= 0.0 ? dayFlowM * 1.0e6 : NaN); // the pane is in USD: the histogram, the boxes and the tags out_outflow(landedNow && dayFlowM < 0.0 ? dayFlowM * 1.0e6 : NaN); out_zero(0.0); out_cumulative(days > 0 ? cumulativeM : NaN); const intraday = !isNaN(barSec) && barSec < DAY; if (!isNaN(pendingStart) && !isNaN(barSec)) { // the first bar's day, drawn now that the spacing is known if (intraday) drawDayBox(pendingStart, pendingFlowM); pendingStart = NaN; } if (landedNow) { if (isNaN(barSec)) { pendingStart = dayStart; pendingFlowM = dayFlowM; } else if (intraday) drawDayBox(dayStart, dayFlowM); if (days >= 3 && Math.abs(dayFlowM) >= bigDay * (sumAbsM / f64(days))) tagBigDay(dayStart, dayFlowM); // a norm needs a few days } if (bar.isLast()) str_note(days > 0 ? "" : "No ETF flow day in view: open the 1h chart or pan back a few days"); // an empty text draws no label if (bar.isLast() && days > 0) { sb_clear(); sbMoneyM(latestM); sb_text(" on "); sbDate(latestDay, day); str_latest_sb(); sb_clear(); sbMoneyM(cumulativeM); sb_text(" over "); sb_int(days); sb_text(days == 1 ? " day" : " days"); str_window_sb(); sb_clear(); sb_int(streak); sb_text(streak == 1 ? " day of " : " days of "); sb_text(latestM >= 0.0 ? "inflow" : "outflow"); str_streak_sb(); sb_clear(); sbMoneyM(biggestM); sb_text(" on "); sbDate(biggestDay, day); str_biggest_sb(); } } ``` ## How it works **A daily series on an intraday chart.** `input("flow", etf_flow.flow_usd, { fund: "all", missing: "nan" })` sums every fund listed for the chart's coin (11 for BTC, 10 for ETH, 7 for SOL); change `fund` to one ticker (IBIT, FBTC, ETHA, ...) to follow that fund alone, and the lane names the coin's tickers when one does not match. The day's value arrives on the first bar of its day and nothing else that day, so the pane draws the day once: a box handle from the day's first second to its last, with a thin histogram bar (`inflow` or `outflow`) on the landing bar that keeps the pane's scale honest, and the `zero` line between them. The pane is in dollars: `format: "usd"` on the two histograms prints the legend and the axis as `$29.0M` and `-$149.0M`, the boxes and tags sit at the same dollar heights, and `legend: false` keeps the zero line, a scale helper, out of the legend. On daily and coarser charts each bar is its own day and the histogram carries it (a weekly bar sums its days). **The flow reads against price.** `flow_sign` (+1, -1 or NaN) gates and `flow_tone` (1 inflow, 0 outflow) colours `render.bgcolor("flow_days", ...)`, the faint wash behind each day's candles; `out.inset("cumulative", { dock: "bottom", height_px: 44, shape: "line", colors: ["theme.up", "theme.down"] })` draws the flow summed since the start of the window in a strip along the bottom of the price pane with its own scale, in the up colour at or above zero and the down colour below. `day_flow` carries the day's flow in millions through the day as a data-only output. **Tags and the card.** A day whose flow is `big_day` (2.0) times the window's mean day (after three landed days) is tagged with its size through the text slot, centred over the day. The card's cells (the latest day and its date, the window's sum, the streak, the biggest day) are text slots written on the live bar, the latest day in the up colour while it is an inflow and the down colour while an outflow. `sbDate()` writes the month's short name and the day, and the year after a comma when the day falls in another year than the live bar's, so a biggest day a year back never reads as a date to come. Boxes ride a ring of 60 days; tags a ring of 20. ## Where it runs Charts of BTC, ETH and SOL on any venue (Binance Futures BTCUSDT, Binance spot ETHUSDT, ...). The flows arrive once a day, after the US session, and the chart polls for them while it is open. OpenMarket's alerts engine does not read ETF flows yet, so an alert on this indicator is refused when you save it ([Alerts](../functions/alerts.md)). ## When data is missing Other coins are refused by name before any fetch: "Input 'flow' (etf_flow) needs a chart of a coin with listed spot ETFs (BTC, ETH, SOL): this chart's coin is PURR". Gold refuses the same way. Weekends and holidays have no flow (the lane reports zero, which counts as no flow) and draw nothing; a window whose first day has no midnight bar starts on the next landed day; a day the lane has not reported yet (today, before the close) draws nothing and the card keeps the latest reported day. An intraday chart whose loaded window holds no flow day (a 1m chart on a Monday morning) reads one sentence at the top centre of the price pane, "No ETF flow day in view: open the 1h chart or pan back a few days", through a `render.label` over the `note` slot, written on the live bar and empty once a day lands. ## Customize it - **One fund.** Change `fund: "all"` to a ticker (a declaration literal, not a setting) and Run again. A ticker the coin does not list is refused by name, and the message names the coin's funds. - **More tags.** Lower `big_day`; a day is tagged once its flow passes the multiple of the window's mean day. - **No wash.** Delete the `render.bgcolor` line to keep the pane, the strip and the card without the tint. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Spot ETF Flow** under **Beyond the time axis**. 2. Press **Run** on a BTC, ETH or SOL chart, such as BTCUSDT on Binance Futures at 1h: the day bars fill the pane, the strip runs along the bottom of the price pane, and the card appears at the top right. 3. At the editor's Console prompt, type `last 5 day_flow` to read the day's flow, in millions of USD, on the last five bars (`inflow` and `outflow` carry it in dollars). ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `etf_flow` source, the `fund` word and `missing: "nan"` - [Drawing objects](../presentation/drawing-objects.md) for lower-pane box and label handles - [Styling](../presentation/styling.md) for `render.bgcolor` and [Cards, frames and panels](../presentation/cards-frames-panels.md) for `out.inset`, `draw.card` and text slots <!-- source: https://openmarket.xyz/wrun/cookbook/liquidation-map --> # Liquidation map ![A two-sided liquidation profile docked against the price axis, rows in the up colour above the price and in the down colour below, two tagged cluster lines and the card at the top left](/wrun/images/liquidation-map.png) An estimate of where the market's open positions would be liquidated, drawn on the price axis as a two-sided profile. The profile docks on the right of the pane, against the price axis, split at a centre line. Rows above the price, in the up colour, are where shorts would be liquidated (a liquidated short is a forced buy, so these rows are fuel for a move up); they grow to one side of the centre. Rows below the price, in the down colour, are where longs would be liquidated (forced sells); they grow to the other side. A longer and brighter row means more money sits at that price. Rows that price has already traded through are gone, so the profile is thin where price has recently been and thick just beyond the recent highs and lows. Resting the pointer on a row reads its price and dollars. The largest rows on each side (three by default) run across the chart as thin lines in the side's colour, each with a plain muted tag that ends just left of the profile: the price, then the money at it ("63.4K $84M"). A card at the top left, under the chart legend, reads "Estimated liquidations" in the chart's default look: the largest row in range as the big line ("$84M at 63.4K", in the colour of its side), then the money within 5% below the price (longs, in the down colour) and within 5% above it (shorts, in the up colour). Resting the pointer on a number explains it. The legend reads "Liquidation Map estimated, 672 bars". The parts are one `plot.levels` profile docked on the price axis with `baseline: "center"`, fed by one frame ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)), an `oi.close` input and side-split `trades.volume` inputs ([Data sources](../core-concepts/data-sources.md)), line and label handles for the cluster lines, their tags and the one sentence shown without open interest ([Drawing objects](../presentation/drawing-objects.md)), and a `render.hud` of three tiles in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). This is also the `liquidation-map` template: the **Liquidation Map** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Liquidation Map: where the positions opened over the lookback would be liquidated, ESTIMATED from the market's // open interest and sided volume, docked on the price axis as a two-sided profile. Rows above the price are the // shorts' liquidation prices (a liquidated short is a forced buy), drawn in the up colour to one side of the dock's // centre line; rows below the price are the longs' (a forced sell), in the down colour to the other side. The hotter a // row, the brighter it paints. A level that price already traded through is gone, so the profile reads thin where // price has been and thick where it has not. The largest rows on each side run across the chart as thin lines with a // plain tag ("63.4K $84M") on the price's side of its line, so a line at the pane's edge keeps its tag inside the // pane, and a card at the top left reads the // largest row in range as its headline and the money within 5% of the price on each side. Nothing here is a venue's // own liquidation feed: it is a model of where the open positions sit, built from the open-interest change bar by bar. // // The model, per bar: a rise in open interest opens positions at the bar's typical price, split into longs and // shorts by the bar's buy share of sided volume, and across four leverage tiers (10x, 25x, 50x, 100x) with fixed // weights; each position's liquidation price follows from its leverage and the maintenance margin. A fall in open // interest scales every live level down in proportion. A long level is swept when a later bar's low reaches it, a // short level when a later bar's high does. Levels older than the lookback drop. The profile, lines and card are // measured on the live bar only; history bars only keep the ledger. section("Positions"); param.int("lookback", 672, { min: 96, max: 2000, label: "Lookback, bars", description: "Bars of opened positions kept in the map: 672 is a week on a 15m chart, four weeks on 1h" }); param.number("maint_margin_pct", 0.5, { min: 0, max: 2, step: 0.1, label: "Maintenance margin, percent", description: "Maintenance margin as a percent of the position: the distance a liquidation sits short of the leverage's full move" }); section("Profile"); param.number("range_pct", 12, { min: 3, max: 40, label: "Profile range, percent", description: "Profile range: percent around the close, each side" }); param.int("rows", 160, { min: 40, max: 160, label: "Profile rows", description: "Price rows in the docked profile (the step snaps to a round price, so the count varies a little)" }); section("Cluster lines"); param.int("clusters", 3, { min: 0, max: 3, label: "Cluster lines per side", description: "Largest rows per side drawn as lines across the chart with a tag; 0 = none" }); param.number("cluster_gap_pct", 0.5, { min: 0, max: 5, step: 0.1, label: "Cluster gap, percent", description: "Two cluster lines on the same side sit at least this far apart, percent of price, so their tags never stack" }); param.int("tag_inset_px", 352, { min: 0, max: 1200, label: "Tag inset, pixels", description: "Pixels in from the price axis where the cluster tags end: past the docked profile, so a tag never sits on a bar" }); legend({ title: "estimated, {{lookback}} bars" }); // the words after the name in the legend input("close", ohlcv.close); // the chart's own candles: the grid, the entry price, and the sweeps input("oi", oi.close, { missing: "nan", description: "Open interest in USD; NaN on a market without it (spot, FX, prediction markets), which blanks the map" }); input("buy", trades.volume, { side: "BUY", missing: "zero", description: "Buy volume of the bar: its share of sided volume is the share of new positions read as longs" }); input("sell", trades.volume, { side: "SELL", missing: "zero", description: "Sell volume of the bar" }); output("longs_near", none, overlay, { format: "usd", description: "Estimated long liquidations within 5% below the close, USD, every bar" }); // data-only: the card and the Console read them output("shorts_near", none, overlay, { format: "usd", description: "Estimated short liquidations within 5% above the close, USD, every bar" }); output("largest_usd", none, overlay, { format: "usd", description: "The largest profile row within range, USD; live bar only" }); output("largest_price", none, overlay, { format: "price", description: "The price of the largest profile row; live bar only" }); output("largest_side", none, overlay, { description: "0 when the largest row is below the close (longs), 1 when above (shorts), 2 when the map is empty: the headline's colour index" }); string("tag", { max_bytes: 40 }); // one bounded slot the cluster tags are written through, one at a time string("largest_text", { max_bytes: 32 }); // the card's headline, "$84M at 63.4K", written on the live bar string("note", { max_bytes: 80 }); // the one sentence shown when the market has no open interest, through a label handle at the top right const liq_rows = frame("liq_rows", { max_bytes: 32768 }); // the docked profile: one row per grid price, a colour and a hint per row // The docked profile: zero mid-dock (baseline center), the shorts' rows growing one way and the longs' the other, each // row in its own colour from the frame (the up colour above the price, the down colour below, brighter the more money // sits there), bars at most 12 px tall so a zoomed-in chart reads as a ladder instead of slabs, a hover card per row // in dollars. plot.levels({ name: "liquidations", frame: liq_rows, dock: "right", width_frac: 0.22, baseline: "center", labels: false, color: "theme.muted", opacity: 1, thickness_px: 12, format: "usd", hover: true }); // The cluster lines and their tags are handles (the module picks the rows each run): width-1 lines across the whole // chart in the side's colour, and plain muted tags whose right edge sits a fixed inset left of the price axis, clear // of the profile, each hanging on the price's side of its line (a short cluster's tag under its line, a long // cluster's over it). handles.line({ width: 1, extend: "both" }); handles.label({ anchor: "right", align: "right", size: 11, style: "plain", font_weight: "medium", color: "theme.muted" }); // The card, under the chart legend at the top left: the largest row in range leads as the headline in the side's // colour, then the money within 5% of the price on each side, one tile per side. Every tile reads the newest row, the // live bar's. render.hud("liq_card", { position: "top_left", title: "Estimated liquidations", columns: 2, safe_area: true, tiles: [ tile.pill("Largest row in range", "largest_text", { headline: true, draw: "text", color_by: "largest_side", colors: ["theme.down", "theme.up", "theme.muted"] }), tile.value("Longs within 5%", "longs_near", { format: "usd", color: "theme.down", hint: "Estimated long liquidations within 5% below the price: forced sells if price falls there" }), tile.value("Shorts within 5%", "shorts_near", { format: "usd", color: "theme.up", hint: "Estimated short liquidations within 5% above the price: forced buys if price rises there" }), ], }); // Leverage tiers the opened positions are spread over, and the share of new open interest each tier takes: a // guess at the mix of a perpetual's crowd (most size at low leverage, a thin tail at 100x). Named here so the // profile's shape can be argued about in one place. const TIERS = 4; const SLOTS = TIERS * 2; // per bar: four long levels, then four short levels function tierLeverage(tier: i32): f64 { return tier == 0 ? 10.0 : tier == 1 ? 25.0 : tier == 2 ? 50.0 : 100.0; } function tierWeight(tier: i32): f64 { return tier == 0 ? 0.4 : tier == 1 ? 0.3 : tier == 2 ? 0.2 : 0.1; } const MAX_LOOKBACK = 2000; // the ring is sized for the largest lookback setting const MAX_ROWS = 240; // grid rows in the docked profile: the rows setting, up to 1.41x more when the step rounds down to the nearest round price const MAX_CLUSTERS = 3; const HEAT_STEPS = 12; // how many brightness steps a row's colour takes, from a third strength to full const levelPrice = new StaticArray<f64>(MAX_LOOKBACK * SLOTS); // the ledger: one price and one USD size per level, SLOTS per bar const levelUsd = new StaticArray<f64>(MAX_LOOKBACK * SLOTS); // 0 once swept or closed const rowUsd = new StaticArray<f64>(MAX_ROWS); // the profile grid: USD per row const rowBlocked = new StaticArray<bool>(MAX_ROWS); // rows already taken by a cluster line, and the rows within the gap around it const shortHex = new StaticArray<string>(HEAT_STEPS); // the frame's row colours, quoted, built once in onStart(): the up colour at HEAT_STEPS alphas const longHex = new StaticArray<string>(HEAT_STEPS); // the down colour at the same alphas const HEX_DIGITS = "0123456789abcdef"; const SHORT_INK = theme.UP; // shorts' liquidations, above price (forced buys): the lines' ink const LONG_INK = theme.DOWN; // longs' liquidations, below price (forced sells) const NOTE_INK = theme.MUTED; // the cluster tags, and the one sentence on a market without open interest const lines: LineHandle[] = []; // handle objects allocate once; ids are one space across kinds const tags: LabelHandle[] = []; for (let i = 0; i < MAX_CLUSTERS * 2; i += 1) { lines.push(draw.line(i)); // 0..2 the short clusters, 3..5 the long clusters tags.push(draw.label(MAX_CLUSTERS * 2 + i)); } const note = draw.label(MAX_CLUSTERS * 4); // the one line of words when the market has no open interest: a label handle pinned to the pane's top right corner, under the pane's corner buttons (a declared draw.label sits at a price, a render.label at top_right right-aligns under the price axis) let lookback = 672; // settings, read in onStart() let rangeFrac = 0.12; let rows = 160; let mm = 0.005; let clusters = 3; let gapFrac = 0.005; let tagInset = 352.0; let head = -1; // the ring: head is the newest bar, count the bars in use let count = 0; let prevOi: f64 = NaN; // the last finite open interest reading let oiSeen = false; // the market served open interest at least once let close: f64 = NaN; let t: f64 = NaN; let firstT: f64 = NaN; // the first bar's open time: where the cluster lines start let longsNear = 0.0; // live long levels within 5% below the close, USD let shortsNear = 0.0; // live short levels within 5% above the close, USD let gridLo: f64 = NaN; // the profile grid, built on the live bar let step: f64 = NaN; let rowCount = 0; let rowMax = 0.0; // the largest row in the grid: the brightness scale // ── The ledger, kept on every bar ── function sweepAndSum(high: f64, low: f64): void { // levels this bar traded through are gone; what remains near the close is summed const nearLo = close * 0.95; const nearHi = close * 1.05; longsNear = 0.0; shortsNear = 0.0; const used = count * SLOTS; for (let i = 0; i < used; i += 1) { const usd = levelUsd[i]; if (usd <= 0.0) continue; const price = levelPrice[i]; if (i % SLOTS < TIERS) { // a long level: swept once a bar's low reaches it if (low <= price) { levelUsd[i] = 0.0; continue; } if (price >= nearLo) longsNear += usd; } else { // a short level: swept once a bar's high reaches it if (high >= price) { levelUsd[i] = 0.0; continue; } if (price <= nearHi) shortsNear += usd; } } } function scaleAll(factor: f64): void { // open interest fell: every live level shrinks in proportion const used = count * SLOTS; for (let i = 0; i < used; i += 1) if (levelUsd[i] > 0.0) levelUsd[i] *= factor; longsNear *= factor; shortsNear *= factor; } function openPositions(base: i32, dOi: f64, high: f64, low: f64): void { // new open interest, placed at its liquidation prices const buy = in_buy(); const sell = in_sell(); const total = buy + sell; const longShare = total > 0.0 ? buy / total : 0.5; const entry = (high + low + close) / 3.0; const nearLo = close * 0.95; const nearHi = close * 1.05; for (let tier = 0; tier < TIERS; tier += 1) { const move = 1.0 / tierLeverage(tier) - mm; // the adverse move that liquidates this tier if (move <= 0.0) continue; // a margin wider than the tier's whole move: nobody holds that position const longPrice = entry * (1.0 - move); const shortPrice = entry * (1.0 + move); const longUsd = dOi * longShare * tierWeight(tier); const shortUsd = dOi * (1.0 - longShare) * tierWeight(tier); levelPrice[base + tier] = longPrice; levelUsd[base + tier] = longUsd; levelPrice[base + TIERS + tier] = shortPrice; levelUsd[base + TIERS + tier] = shortUsd; if (longPrice >= nearLo) longsNear += longUsd; if (shortPrice <= nearHi) shortsNear += shortUsd; } } // ── The docked profile: an evenly spaced grid of rounded prices around the close ── function niceStep(raw: f64): f64 { // the nearest of 1, 2, 2.5, 5 times a power of ten (in ratio terms), so the rows read as round prices and stay near the rows setting const mag = Math.pow(10.0, Math.floor(Math.log(raw) / Math.LN10)); const m = raw / mag; return (m < 1.414 ? 1.0 : m < 2.236 ? 2.0 : m < 3.536 ? 2.5 : m < 7.071 ? 5.0 : 10.0) * mag; // the cut points are the geometric midpoints } function priceDecimals(width: f64): i32 { // enough decimals that the rounded row prices stay evenly spaced when parsed (the docked grid is contiguous only within 0.1% of its step) const d = i32(Math.ceil(Math.log(2000.0 / width) / Math.LN10)); return d < 2 ? 2 : d > 9 ? 9 : d; } function buildGrid(): bool { const lo = close * (1.0 - rangeFrac); const hi = close * (1.0 + rangeFrac); if (!(hi > lo) || !(lo > 0.0)) return false; step = niceStep((hi - lo) / f64(rows)); gridLo = Math.floor(lo / step) * step; rowCount = i32(Math.floor((hi - gridLo) / step)) + 1; while (rowCount > MAX_ROWS) { // cannot happen with the settings' bounds; kept so the buffer is never overrun step *= 2.0; gridLo = Math.floor(lo / step) * step; rowCount = i32(Math.floor((hi - gridLo) / step)) + 1; } if (rowCount < 3) return false; // the engine needs three prices for a grid for (let r = 0; r < rowCount; r += 1) rowUsd[r] = 0.0; const used = count * SLOTS; for (let i = 0; i < used; i += 1) { // each live level adds its USD to the row it falls in const usd = levelUsd[i]; if (usd <= 0.0) continue; const r = i32(Math.round((levelPrice[i] - gridLo) / step)); if (r >= 0 && r < rowCount) rowUsd[r] += usd; } rowMax = 0.0; for (let r = 0; r < rowCount; r += 1) if (rowUsd[r] > rowMax) rowMax = rowUsd[r]; return true; } function rowPrice(r: i32): f64 { return gridLo + f64(r) * step; } function heatStep(usd: f64): i32 { // 0 (empty or faint) .. HEAT_STEPS - 1 (the largest row), on a square-root ramp so mid-sized rows still read if (!(rowMax > 0.0) || usd <= 0.0) return 0; const k = i32(Math.round(Math.sqrt(usd / rowMax) * f64(HEAT_STEPS - 1))); return k < 0 ? 0 : k >= HEAT_STEPS ? HEAT_STEPS - 1 : k; } function writeProfile(): void { // prices ascending; a signed value per row (shorts positive above the close, longs negative below, 0 where empty so the grid stays whole); a colour per row by heat; a hint per filled row const decimals = priceDecimals(step); fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); fb_f64(rowPrice(r), decimals); } fb_text("],\"values\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); const usd = rowUsd[r]; fb_f64(usd <= 0.0 ? 0.0 : rowPrice(r) > close ? usd : -usd, 0); } fb_text("],\"colors\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); const k = heatStep(rowUsd[r]); fb_text(rowPrice(r) > close ? shortHex[k] : longHex[k]); } fb_text("],\"tooltips\":["); for (let r = 0; r < rowCount; r += 1) { if (r > 0) fb_text(","); if (rowUsd[r] <= 0.0) fb_text("null"); else fb_text(rowPrice(r) > close ? "\"Short liquidations here: forced buys\"" : "\"Long liquidations here: forced sells\""); } fb_text("]}"); writeFrameBuffer(liq_rows); } // ── Text helpers ── function sbCompactPrice(v: f64): void { // 84461.8 -> "84.5K", 2431.6 -> "2431.6", 0.13797 -> "0.13797" if (v >= 10000.0) sb_compact(v, 1); else sb_auto(v); } function sbMoney(usd: f64): void { // "$1.23B", "$84M", "$8.4M", "$640K", "$12.5K" sb_text("$"); const v = Math.abs(usd); if (v >= 1.0e9) { sb_f64(v / 1.0e9, 2); sb_text("B"); } else if (v >= 1.0e6) { sb_f64(v / 1.0e6, v >= 1.0e7 ? 0 : 1); sb_text("M"); } else if (v >= 1.0e3) { sb_f64(v / 1.0e3, v >= 1.0e5 ? 0 : 1); sb_text("K"); } else sb_f64(v, 0); } function hex2(n: i32): string { // two hex digits of a byte; onStart() only (it allocates) return HEX_DIGITS.charAt((n >> 4) & 15) + HEX_DIGITS.charAt(n & 15); } // ── The cluster lines: the largest rows on each side, at least cluster_gap_pct apart so the tags stay readable ── function drawClusters(): void { for (let r = 0; r < rowCount; r += 1) rowBlocked[r] = false; const gapRows = i32(Math.ceil((close * gapFrac) / step)); // rows either side of a pick that the next pick skips for (let side = 0; side < 2; side += 1) { // 0: shorts above the close (the up colour); 1: longs below (the down colour) const ink = side == 0 ? SHORT_INK : LONG_INK; let drawn = 0; for (let j = 0; j < clusters; j += 1) { let best = -1; for (let r = 0; r < rowCount; r += 1) { if (rowBlocked[r] || rowUsd[r] <= 0.0) continue; const above = rowPrice(r) > close; if ((side == 0) != above) continue; if (best < 0 || rowUsd[r] > rowUsd[best]) best = r; } if (best < 0) break; for (let r = best - gapRows; r <= best + gapRows; r += 1) if (r >= 0 && r < rowCount) rowBlocked[r] = true; // this row and the gap around it are taken const price = rowPrice(best); const k = side * MAX_CLUSTERS + drawn; lines[k].set(firstT, price, t, price).color(ink); sb_clear(); sbCompactPrice(price); sb_text(" "); sbMoney(rowUsd[best]); tags[k].set(tagInset, price).text(str_tag_sb).color(NOTE_INK).valign(side == 0 ? VALIGN_TOP : VALIGN_BOTTOM); // toward the price: a line at the pane's edge keeps its tag inside drawn += 1; } for (let j = drawn; j < MAX_CLUSTERS; j += 1) { // fewer clusters than last time: the spare handles go lines[side * MAX_CLUSTERS + j].delete(); tags[side * MAX_CLUSTERS + j].delete(); } } } function clearDrawings(): void { for (let k = 0; k < MAX_CLUSTERS * 2; k += 1) { lines[k].delete(); // no-ops when never drawn tags[k].delete(); } } function onStart(): void { lookback = i32(p_lookback()); mm = p_maint_margin_pct() / 100.0; rangeFrac = p_range_pct() / 100.0; rows = i32(p_rows()); clusters = i32(p_clusters()); gapFrac = p_cluster_gap_pct() / 100.0; tagInset = f64(p_tag_inset_px()); for (let k = 0; k < HEAT_STEPS; k += 1) { // the row colours: the chart's up and down colours (a theme word with its alpha) at a third strength for an empty row, full for the largest const a = i32(Math.round((0.3 + 0.7 * f64(k) / f64(HEAT_STEPS - 1)) * 255.0)); shortHex[k] = "\"theme.up/" + hex2(a) + "\""; longHex[k] = "\"theme.down/" + hex2(a) + "\""; } } // onBar() runs once per bar: sweep the ledger with the bar's range, then fold the bar's open-interest change into it // (new positions at their liquidation prices, or every level scaled down); the near sums as numbers on every bar; // the profile, the cluster lines, the tags and the card on the live bar only. function onBar(): void { close = bar.close(); t = bar.time(); const high = bar.high(); const low = bar.low(); if (isNaN(firstT) && !isNaN(t)) firstT = t; if (isNaN(close)) return; sweepAndSum(high, low); head = (head + 1) % lookback; // this bar's slots: the oldest bar's levels are recycled once the ring is full if (count < lookback) count += 1; const base = head * SLOTS; for (let s = 0; s < SLOTS; s += 1) { levelUsd[base + s] = 0.0; levelPrice[base + s] = NaN; } const oiNow = in_oi(); if (!isNaN(oiNow)) { // a bar without a reading changes nothing: the last reading carries forward oiSeen = true; if (!isNaN(prevOi)) { const dOi = oiNow - prevOi; if (dOi > 0.0) openPositions(base, dOi, high, low); else if (dOi < 0.0 && prevOi > 0.0) scaleAll(oiNow / prevOi); } prevOi = oiNow; } out_longs_near(oiSeen ? longsNear : NaN); out_shorts_near(oiSeen ? shortsNear : NaN); if (!bar.isLast()) return; if (!oiSeen) { // the market served no open interest at all: the one sentence, top right, and nothing else clearDrawings(); sb_clear(); sb_text("No open interest on this market, so no liquidation estimate"); note.set(16.0, 40.0).text(str_note_sb).anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).style(LabelStyle.Plain).fontWeight(FontWeight.Normal).color(NOTE_INK); sb_clear(); sb_text("No open interest"); str_largest_text_sb(); out_largest_side(2.0); return; } note.delete(); // no-op when never drawn if (!buildGrid()) { clearDrawings(); return; } writeProfile(); drawClusters(); let best = -1; // the largest row within range, either side for (let r = 0; r < rowCount; r += 1) if (rowUsd[r] > 0.0 && (best < 0 || rowUsd[r] > rowUsd[best])) best = r; const largestUsd = best < 0 ? 0.0 : rowUsd[best]; const largestPrice = best < 0 ? NaN : rowPrice(best); out_largest_usd(largestUsd); out_largest_price(largestPrice); out_largest_side(best < 0 ? 2.0 : largestPrice > close ? 1.0 : 0.0); sb_clear(); if (best < 0) sb_text("No positions yet"); else { sbMoney(largestUsd); sb_text(" at "); sbCompactPrice(largestPrice); } str_largest_text_sb(); } ``` ## How it works **Open interest is read as positions.** On every bar `in_oi()` (the `oi.close` input, in USD) is compared with the last finite reading; a bar without a reading changes nothing. A rise is new open interest opened at the bar's typical price (high, low and close averaged), split into longs and shorts by the bar's buy share of `in_buy()` and `in_sell()` (half and half where the venue serves no sided trades), and spread over four leverage tiers, 10x, 25x, 50x and 100x, weighted 40, 30, 20 and 10 percent in `tierLeverage` and `tierWeight`. Each tier's liquidation price follows from its leverage and `maint_margin_pct`: a 10x long opened at 84,000 with the default 0.5% margin sits about 9.5% lower. A fall in open interest scales every live level down in proportion (`scaleAll`). Nothing here is a venue's own liquidation feed: read the rows as "about this much, about here". **The ledger is a ring.** `levelPrice` and `levelUsd` are two fixed arrays sized for the largest lookback, eight slots per bar (four long tiers, then four short tiers), indexed by bar; once `lookback` bars are held the oldest bar's slots are recycled, so levels older than the lookback drop. `sweepAndSum` walks the ledger first on every bar: a long level is gone once the bar's low reaches it, a short level once the bar's high does, and what remains within 5% of the close is summed into `longs_near` and `shorts_near`, data-only outputs written on every bar. The forming bar replays from the chart's snapshot, so the ring advances once per bar on live ticks too ([Repainting](../core-concepts/repainting.md)). **One frame is the profile.** On the live bar only, `buildGrid` lays an evenly spaced grid of rounded prices across `range_pct` each side of the close (`niceStep` snaps the step to 1, 2, 2.5 or 5 times a power of ten, so the row count varies a little from `rows`; on BTC near 85,000 the step is 100), and every live level adds its dollars to the row it falls in. `writeProfile` builds the `liq_rows` frame in the frame buffer with `fb_clear`, `fb_text` and `fb_f64` and sends it with `writeFrameBuffer`: `prices` ascending, a signed value per row (the shorts' rows above the close positive, the longs' below negative, 0 where empty so the grid stays whole), a colour per row and a `tooltips` hint per filled row naming its side. `baseline: "center"` puts zero mid-dock, so the two sides are the sign of one value and grow away from each other; `dock: "right"` and `width_frac: 0.22` set the profile against the price axis; `thickness_px: 12` caps a bar's height so a zoomed-in chart reads as a ladder, not slabs; `hover: true` opens the chart's hover card on a row with its price, its dollars and the hint. **Heat is the row's colour.** `heatStep` maps a row's dollars against the largest row (`rowMax`) onto twelve steps on a square-root ramp, so mid-sized rows still read, and `onStart` builds the twelve colours once: the up colour for the shorts' rows and the down colour for the longs', as theme words with a two-digit alpha after a slash (`"theme.up/" + hex2(a)`), at alphas from 30% for an empty row to 100% for the largest. `opacity: 1` paints those alphas exactly, so each row keeps its own colour. **The cluster lines are handles.** `handles.line({ width: 1, extend: "both" })` and `handles.label({ anchor: "right", align: "right", size: 11, style: "plain", font_weight: "medium", color: "theme.muted" })` declare the kinds; six `draw.line(id)` and six `draw.label(id)` handles are made once at the top, three per side. `drawClusters` picks the largest row on each side largest-first, blocks the rows within `cluster_gap_pct` of each pick so two tags never stack, then sets each line from the first bar's time to the live bar's time at the row's price, in the side's colour (the up colour for shorts, the down colour for longs), and its tag `tag_inset_px` pixels in from the price axis at that price, the text built in the `tag` slot by `sbCompactPrice` and `sbMoney` ("63.4K $84M"). Each tag hangs on the price's side of its line, `valign(VALIGN_TOP)` under a short cluster's line and `valign(VALIGN_BOTTOM)` over a long cluster's, so a cluster whose line sits on the pane's top or bottom edge keeps its tag inside the pane. Spare handles are deleted when a side has fewer clusters than last time. **The card reads slots and outputs.** `render.hud("liq_card", { position: "top_left", title: "Estimated liquidations", columns: 2, safe_area: true, tiles: [...] })` sits under the legend, in the chart's default look. The headline is a `tile.pill` with `draw: "text"` reading the `largest_text` slot ("$84M at 63.4K", written on the live bar), coloured by `largest_side`: 0 the down colour when the largest row is below the close (longs), 1 the up colour when above (shorts), 2 the muted colour when the map is empty. Two `tile.value` tiles read `longs_near` in the down colour and `shorts_near` in the up colour, in `format: "usd"`, each with a `hint` sentence on its hover card. `largest_usd` and `largest_price` are data-only outputs written on the live bar for anything that reads them, and `legend({ title: "estimated, {{lookback}} bars" })` prints the lookback after the name. ## Where it runs Perpetual futures with open interest: Binance Futures and Hyperliquid perpetuals, at any interval (BTCUSDT on Binance Futures and the PURR perpetual on Hyperliquid at 15m and 1h in the builds). The lookback is counted in bars, so 672 is a week at 15m and four weeks at 1h. The profile, the lines and the card are measured on the live bar, so they follow the forming bar; history bars only keep the ledger. The lines live in chart time and the tags in pane pixels, so on a coin whose 1h view spans a wide range the rows are thin and a tag can sit over candles; `tag_inset_px` moves the tags. No market refuses the run: the `oi` input declares `missing: "nan"`, so a market without open interest reads NaN and gets the sentence below instead of a toast. ## When data is missing On a market without open interest (spot pairs, FX, prediction markets) the indicator shows one line of words at the top right, `No open interest on this market, so no liquidation estimate`, in plain muted text: the `note` label handle pinned 40 px under the pane's top right corner and right-aligned, clear of the price axis and of the pane's corner buttons. The card's headline reads "No open interest" in the muted colour, so the card is not an empty frame, the two value tiles print a dash (`longs_near` and `shorts_near` read NaN until the market has served open interest at least once), and it draws nothing else: no profile, no lines. On a market with open interest but without sided trades, every new position is split half longs and half shorts. While no live level falls inside the profile's range the headline reads "No positions yet" and there is no row to tag. ## Customize it - **A longer or shorter memory.** `lookback` (672, 96 to 2000) is the bars of opened positions the map keeps, counted in the chart's bars: 672 is a week on a 15m chart and four weeks on 1h. `maint_margin_pct` (0.5, 0 to 2) is the maintenance margin as a percent of the position: a larger margin moves every liquidation price closer to its entry. - **A wider or finer profile.** `range_pct` (12, 3 to 40) is the percent around the price the profile covers each side; `rows` (160, 40 to 160) the price rows in it, the step snapping to a round price so the count varies a little. - **More or fewer lines.** `clusters` (3, 0 to 3) is the largest rows per side drawn across the chart, 0 for none; `cluster_gap_pct` (0.5, 0 to 5) is how far apart two lines on one side must sit, percent of price, so their tags never stack; `tag_inset_px` (352, 0 to 1200) is where the tags end, in from the price axis: raise it on a wide pane where the tags land on the longest rows. - **Another crowd.** The tier mix, 10x, 25x, 50x and 100x at 40, 30, 20 and 10 percent, is a guess at a perpetual's crowd, named in `tierLeverage` and `tierWeight` at the top of the file so the profile's shape can be argued about in one place; a venue's own leverage distribution would replace it. - **A look of its own.** The card declares no `look`, so it draws the chart's default look; when it should stand apart from the chart, add `look:` with any of the twelve shipped looks ([Looks](../presentation/hud-and-hover-cards.md#looks)), and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). A look changes the card only: the profile and the lines keep the up and down colours, and the tags the muted one. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Liquidation Map** under **Beyond the time axis**. 2. Press **Run** on a perpetual with open interest, such as BTCUSDT on Binance Futures at 15m: the two-sided profile docks against the price axis, the cluster lines cross the chart with their tags, and the card appears at the top left under the legend. Rest the pointer on a row to read its price and dollars. 3. At the editor's Console prompt, type `last 20 longs_near` to read the estimated long liquidations within 5% below the price on the last 20 bars. ## Concepts used - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels`, `baseline: "center"`, `thickness_px`, `hover`, the frame's `prices`, `values`, `colors` and `tooltips`, and the `fb_*` frame buffer on the same page - [Data sources](../core-concepts/data-sources.md) for the `oi` and `trades` sources, `side` and the `missing` policies - [Drawing objects](../presentation/drawing-objects.md) for `handles.line`, `handles.label`, the `draw.line(id)` and `draw.label(id)` handles, pane anchors and the plain style - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` with `draw: "text"` and `tile.value` with `hint` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Text formatting](../functions/text-formatting.md) for `sb_compact`, `sb_auto` and `sb_f64` behind the tags and the headline <!-- source: https://openmarket.xyz/wrun/cookbook/options-odds-cloud --> # Options odds cloud ![Options odds cloud on the price axis, with the 68% band lines, their tags and the odds card on BTC](/wrun/images/options-odds-cloud.png) This cloud on the price axis shows where traders think price ends by an expiry (the day the option ends). Each horizontal bar is the odds price ends at that level, and the longest marks the most likely price. Solid lines mark the middle 68% of outcomes (1σ, one standard deviation) and dotted lines the middle 95% (2σ). Use it to see how far price can travel by the expiry, as market odds, not a forecast. It needs this symbol's options, on a coin, a CME (Chicago futures exchange) future or a US stock. Under the hood: the odds are one curve, N(d2) with the smile's volatility at each price. It reads the expiry whose days to its end are closest to `target_days`, at least 12 hours after the chain's as-of (the live bar's close). Each strike gets one implied volatility, from its out-of-the-money contract. The grid follows the loaded bars' range plus a margin, within spot times exp(plus or minus 3σ). The card is titled "68% likely", with the expiry read and the 68% band as its headline. It reads `options_chain.cells` on the live bar ([Options kit](../functions/options-kit.md)). It docks a frame on the price axis through `plot.levels`, with per-row colours, a `gradient` alpha profile and a `poc` line ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)). It places four `draw.line` lines and five plain `draw.label` tags from the newest bar ([Run-level drawings](../presentation/drawing-objects.md#run-level-drawings)). It draws a `render.hud` card with no `look` word ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look), [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)). It is also the `options-odds-cloud` template, the **Options Odds Cloud** card under **Beyond the time axis** in the editor's starter list, which compiles as written. ## The wrun indicator ```typescript // Options Odds Cloud: where options traders think price will end by an expiry, as a cloud by the price axis. // Each horizontal bar in the cloud shows the market's odds that price ends at that level. The longest bar is the most // likely price, marked by a teal line and a Most likely tag. Solid lines mark the middle 68% of outcomes (1σ, one // standard deviation), and dotted lines the middle 95% (2σ). A card at the top left names the 68% range and the odds // of a 5% move either way. Use it to see how far price can travel by the expiry in the market's eyes. These are // market odds, not a forecast. // // Technical notes: where the options market expects price to settle at the chosen expiry, docked on the price // axis as one smooth profile. Each row is the chain's implied odds that price settles there: a ramp from slate tails // to a sky core, every bar fading from its root to its tip so it reads as a cloud, the most likely row marked by a // teal point-of-control line with a plain "Most likely 85.18K" tag beside the price axis. The rows follow the // price scale the trader sees: the loaded bars' high..low widened by a margin, never wider than spot times // exp(+-3 sigma), at least 'rows' rows across it, so the cloud is as fine on a 1m chart as on a 1h chart. The 16% and // 84% prices (the middle 68%) run across the chart as solid muted lines with plain tags "+1σ 87.9K" / "-1σ 81.2K"; // the 2.5% and 97.5% prices are dotted muted lines tagged "+2σ" / "-2σ" (every line shows whenever the pane covers // it). A card at the top left, under the legend, titled "68% likely" with the expiry read, carries the 68% band as // its headline ("83.7K to 87.0K") and the odds of a 5% move either way. The chain is live only: history bars only // widen the loaded price range; everything else is measured on the last bar at the chain's as-of (the live bar's // close, never its open), every expiry's time running to its end (15 minutes past an OPRA stamp). section("Expiry and cloud"); param.int("target_days", 2, { min: 1, max: 90, label: "Days to expiry", description: "Reads the expiry (the day the option ends) nearest this many days out, at least 12 hours away. Longer chart intervals suit more days." }); param.int("rows", 90, { min: 60, max: 160, label: "Price steps", description: "The fewest price steps the cloud splits into. They spread over the loaded candles' price range plus the margin. The cloud never reaches past 3σ (three standard deviations) from today's price." }); param.int("margin", 25, { min: 0, max: 100, label: "Margin, percent", description: "How far the cloud reaches past the loaded candles' high and low, in percent of that range." }); section("Look"); param.color("core_ink", "#38bdf8", { label: "Cloud core" }); param.color("tail_ink", "#94a3b8", { label: "Cloud tails" }); param.color("peak_ink", "#2dd4bf", { label: "Most likely price" }); input("close", ohlcv.close); // the chart's own close: the bar grid, and spot when the chain carries no underlying input("chain", options_chain.cells, { max_cells: 4000, venue: "auto", description: "This symbol's options: listed coin options on crypto, US listed options on a US stock, CME options on a future. One entry per listed contract, read on the live candle only." }); // [strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega]; side +1 call, -1 put; mark_iv in percent a year market.zone(); // the market's clock: an OPRA expiry trades 15 minutes past its stamp, and the expiry's date chart.interval_sec(); // the bar's length: the chain's as-of is the live bar's close time, the block naming none // The readings, data-only: the card and the Console read them. Each is NaN on history bars. output("p_up_move", none, overlay, { format: "%", description: "The odds price ends 5% or more above today's price at the expiry, in percent. Live candle only." }); output("p_down_move", none, overlay, { format: "%", description: "The odds price ends 5% or more below today's price at the expiry, in percent." }); output("band_low", none, overlay, { format: "price", description: "The price with 16% odds of ending below it: the bottom of the middle 68%." }); output("band_high", none, overlay, { format: "price", description: "The price with 84% odds of ending below it: the top of the middle 68%." }); output("tail_low", none, overlay, { format: "price", description: "The price with 2.5% odds of ending below it: the bottom of the middle 95%." }); output("tail_high", none, overlay, { format: "price", description: "The price with 97.5% odds of ending below it: the top of the middle 95%." }); output("most_likely", none, overlay, { format: "price", description: "The price step with the highest odds: the cloud's peak." }); output("iv_atm", none, overlay, { format: "%", description: "The implied volatility (IV) at today's price for that expiry, in percent a year." }); output("days_to_expiry", none, overlay, { format: "0.0", description: "Days from when the options were read to the end of that expiry." }); output("t_first", none, overlay, { description: "The first loaded candle's open time, in epoch seconds: where the lines start." }); output("t_last", none, overlay, { description: "The live candle's open time, in epoch seconds: where the lines and tags end." }); string("title_text", { max_bytes: 48 }); // the card's title: the odds and the expiry read, "68% likely, 10 Oct 08:00 UTC" string("band_text", { max_bytes: 32 }); // the card's headline: the 68% band, "81.2K to 87.9K" string("up_text", { max_bytes: 16 }); // the card's rows: "12%" string("down_text", { max_bytes: 16 }); string("tag_band_high", { max_bytes: 24 }); // the four price tags string("tag_band_low", { max_bytes: 24 }); string("tag_tail_high", { max_bytes: 24 }); string("tag_tail_low", { max_bytes: 24 }); string("tag_most_likely", { max_bytes: 32 }); // the cloud's peak: "Most likely 85.18K", "Most likely 85176" on rows under 10 dollars string("notice", { max_bytes: 48 }); // the one sentence on a market without a chain handles.label({ anchor: "top_right", align: "right", size: 11, color: "theme.muted", style: "plain", padding: 6, safe_area: true }); // the notice, in pane pixels from the top-right corner const cloud_rows = frame("cloud_rows", { max_bytes: 16384 }); // the docked cloud: one row per grid price // The cloud: one bar per grid price docked right, a tenth of the pane wide so the newest candles stay readable, each // row in its own colour from the frame (the slate-to-sky ramp), every bar fading from its root at the axis to its tip // (the gradient's alpha profile), the most likely row marked by the point-of-control line in teal (its tag is the // plain label below, beside the axis), a hover card per row printing the row's odds. plot.levels({ name: "odds_by_price", frame: cloud_rows, dock: "right", width_frac: 0.1, labels: false, color: "@core_ink", opacity: 0.85, gradient: ["#38bdf8ff", "#38bdf859"], format: "%", decimals: 2, hover: true, poc: true, poc_color: "@peak_ink", poc_width: 2, poc_extend: "dock", poc_label: false }); // The lines across the whole pane, placed from the newest bar: the 68% band's edges solid, the 95% band's dotted, // both in the muted ink; each shows whenever the pane covers it (an overlay never widens the price pane). draw.line("band_high_line", { x1: "t_first", y1: "band_high", x2: "t_last", y2: "band_high", color: "theme.muted", width: 1, line_style: "solid", extend: "both" }); draw.line("band_low_line", { x1: "t_first", y1: "band_low", x2: "t_last", y2: "band_low", color: "theme.muted", width: 1, line_style: "solid", extend: "both" }); draw.line("tail_high_line", { x1: "t_first", y1: "tail_high", x2: "t_last", y2: "tail_high", color: "theme.muted", width: 1, line_style: "dotted", extend: "both" }); draw.line("tail_low_line", { x1: "t_first", y1: "tail_low", x2: "t_last", y2: "tail_low", color: "theme.muted", width: 1, line_style: "dotted", extend: "both" }); // The tags: plain muted text right-aligned beside the price axis, each on its line's price side, never across it. draw.label("tag_band_high", { x: "t_last", y: "band_high", text: "tag_band_high", color: "theme.muted", style: "plain", align: "right", valign: "top", font_weight: "medium", sticky_right: true }); draw.label("tag_band_low", { x: "t_last", y: "band_low", text: "tag_band_low", color: "theme.muted", style: "plain", align: "right", valign: "bottom", font_weight: "medium", sticky_right: true }); draw.label("tag_tail_high", { x: "t_last", y: "tail_high", text: "tag_tail_high", color: "theme.muted", style: "plain", align: "right", valign: "top", font_weight: "medium", sticky_right: true }); draw.label("tag_tail_low", { x: "t_last", y: "tail_low", text: "tag_tail_low", color: "theme.muted", style: "plain", align: "right", valign: "bottom", font_weight: "medium", sticky_right: true }); // The most likely row's tag rides in the same column beside the price axis, plain, just above the POC line. draw.label("tag_most_likely", { x: "t_last", y: "most_likely", text: "tag_most_likely", color: "theme.muted", style: "plain", align: "right", valign: "bottom", font_weight: "medium", sticky_right: true }); // The card: pinned at the top left under the legend, clear of the newest candles and the cloud on the right, the title // carrying the odds and the expiry read ({{title_text}} reads the slot of that name), the 68% band alone as the // headline, then the odds of a 5% move either way as two rows; 250 px fits the longest band ("112.3K to 118.9K"). render.hud("odds", { position: "top_left", title: "{{title_text}}", columns: 1, width: 250, safe_area: true, tiles: [ tile.pill("Range at expiry", "band_text", { headline: true, font_size: 24, draw: "text" }), tile.rows([ ["Up 5% or more", "up_text"], ["Down 5% or more", "down_text"], ]), ], }); const TUPLE = 10; // f64s per contract const MAX_STRIKES = 512; // distinct strikes one expiry may list const MAX_EXPIRIES = 64; // distinct live expiries const MAX_ROWS = 512; // the levels frame's cap; the rows setting stays far under it const HALF_DAY_MS = 43200000.0; const DAY_MS = 86400000.0; const MOVE = 0.05; // the move the card prices: 5% either way const strikePrice = new StaticArray<f64>(MAX_STRIKES); // the strike table of the expiry read, sorted ascending const strikeIv = new StaticArray<f64>(MAX_STRIKES); // the out-of-the-money implied volatility at each strike, a fraction a year const expiryMs = new StaticArray<f64>(MAX_EXPIRIES); // the live expiries, sorted ascending const rowPrice = new StaticArray<f64>(MAX_ROWS); // the cloud grid: row centres const rowProb = new StaticArray<f64>(MAX_ROWS); // the probability of settling inside each row const edgeAbove = new StaticArray<f64>(MAX_ROWS + 1); // P(settle above the row's lower edge), one more than the rows const notice = draw.label(0); // the one sentence on a market without a chain; handle objects allocate once const expiryText = new TextBuilder(16); // the expiry's label, the kit's spelling, copied into the title let targetDays = 2.0; // settings, read in onStart() let rowsWanted = 90; let marginShare = 0.25; // the margin setting as a share of the loaded range let zone = 0; let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let nowMs: f64 = NaN; // the chain's as-of, the live bar's close const coreRgb = new StaticArray<i32>(3); // the ramp's inks as r, g, b: read from the colour settings in onStart() const tailRgb = new StaticArray<i32>(3); let close: f64 = NaN; // this bar let t: f64 = NaN; let firstT: f64 = NaN; // the first bar's open time: where the lines start let loadedHigh: f64 = -Infinity; // the loaded bars' price range: the cloud's rows follow it let loadedLow: f64 = Infinity; let strikeCount = 0; let expiryCount = 0; let expiry: f64 = NaN; // the expiry read, epoch ms let spot: f64 = NaN; // the chain's underlying let years: f64 = NaN; // time to the expiry's end in years, from the chain's as-of let ivAtm: f64 = NaN; // a fraction a year let sigmaT: f64 = NaN; // iv_atm times sqrt(T): one standard deviation of the log price let gridLo: f64 = NaN; let gridStep: f64 = NaN; let gridRows = 0; let peakRow = -1; let q025: f64 = NaN; // the quantile prices let q16: f64 = NaN; let q84: f64 = NaN; let q975: f64 = NaN; let pUpMove: f64 = NaN; // odds of a 5% move, percent let pDownMove: f64 = NaN; // ── The strike table: sorted insertion, one row per strike ── function strikeSlot(strike: f64): i32 { // the row of this strike, inserted when new; -1 when the table is full let lo = 0; let hi = strikeCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (strikePrice[mid] < strike) lo = mid + 1; else hi = mid; } if (lo < strikeCount && strikePrice[lo] == strike) return lo; if (strikeCount >= MAX_STRIKES) return -1; for (let i = strikeCount; i > lo; i -= 1) { strikePrice[i] = strikePrice[i - 1]; strikeIv[i] = strikeIv[i - 1]; } strikePrice[lo] = strike; strikeIv[lo] = NaN; strikeCount += 1; return lo; } function noteExpiry(ms: f64): void { // sorted insertion of a distinct live expiry let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryMs[mid] < ms) lo = mid + 1; else hi = mid; } if (lo < expiryCount && expiryMs[lo] == ms) return; if (expiryCount >= MAX_EXPIRIES) return; for (let i = expiryCount; i > lo; i -= 1) expiryMs[i] = expiryMs[i - 1]; expiryMs[lo] = ms; expiryCount += 1; } // ── The math: the smile, the normal, the odds ── function ivAt(price: f64): f64 { // implied volatility at any price: linear between neighbouring strikes, flat beyond the ends if (strikeCount == 0) return NaN; if (price <= strikePrice[0]) return strikeIv[0]; if (price >= strikePrice[strikeCount - 1]) return strikeIv[strikeCount - 1]; let lo = 0; let hi = strikeCount - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (strikePrice[mid] <= price) lo = mid; else hi = mid; } const share = (price - strikePrice[lo]) / (strikePrice[hi] - strikePrice[lo]); return strikeIv[lo] + (strikeIv[hi] - strikeIv[lo]) * share; } function normalCdf(x: f64): f64 { // the standard normal CDF through Abramowitz-Stegun 7.1.26 (error under 2e-7) const z = Math.abs(x) / Math.SQRT2; const u = 1.0 / (1.0 + 0.3275911 * z); const poly = u * (0.254829592 + u * (-0.284496736 + u * (1.421413741 + u * (-1.453152027 + u * 1.061405429)))); const erf = 1.0 - poly * Math.exp(-z * z); return x >= 0.0 ? 0.5 * (1.0 + erf) : 0.5 * (1.0 - erf); } function pAbove(price: f64): f64 { // the chain's odds that price settles above this price: N(d2) with the smile's volatility at the price if (!(price > 0.0)) return 1.0; const iv = ivAt(price); if (!(iv > 0.0)) return NaN; const d2 = (Math.log(spot / price) - 0.5 * iv * iv * years) / (iv * Math.sqrt(years)); return normalCdf(d2); } function priceWhereAbove(target: f64): f64 { // the price with P(above) = target, by bisection over eight standard deviations let lo = spot * Math.exp(-8.0 * sigmaT); let hi = spot * Math.exp(8.0 * sigmaT); for (let i = 0; i < 64; i += 1) { const mid = 0.5 * (lo + hi); if (pAbove(mid) > target) lo = mid; else hi = mid; } return 0.5 * (lo + hi); } function niceStepAtMost(raw: f64): f64 { // the largest round step at or under raw: 1, 1.5, 2, 2.5, 3, 4, 5, 6, 8 times a power of ten let mag = Math.pow(10.0, Math.floor(Math.log(raw) / Math.LN10)); if (mag > raw) mag /= 10.0; // the logarithm rounded up across a power of ten const m = raw / mag; if (m >= 8.0) return 8.0 * mag; if (m >= 6.0) return 6.0 * mag; if (m >= 5.0) return 5.0 * mag; if (m >= 4.0) return 4.0 * mag; if (m >= 3.0) return 3.0 * mag; if (m >= 2.5) return 2.5 * mag; if (m >= 2.0) return 2.0 * mag; if (m >= 1.5) return 1.5 * mag; return mag; } function priceDecimals(step: f64): i32 { // enough decimals that the grid's row prices stay evenly spaced when parsed (the docked grid is contiguous only within 0.1% of its step) const d = i32(Math.ceil(Math.log(2000.0 / step) / Math.LN10)); return d < 2 ? 2 : d > 9 ? 9 : d; } // ── The chain, measured on the live bar ── function measureChain(n: i32): bool { // n = f64 cells in the live block; false when nothing usable is listed const cells = in_chain_view(); // the live chain in place: the first n values of the build's own buffer nowMs = optionsAsOfMs(t * 1000.0, intervalMs); // the chain's as-of: the live bar's close time expiryCount = 0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) if (optionsLiveUntilMs(cells[i + 1], zone) >= nowMs + HALF_DAY_MS) noteExpiry(cells[i + 1]); // the expiries trading at least 12 h more if (expiryCount == 0) return false; let best = 0; let bestDistance = Infinity; for (let k = 0; k < expiryCount; k += 1) { // the expiry whose distance in days is closest to the setting; ties keep the earlier const distance = Math.abs((optionsLiveUntilMs(expiryMs[k], zone) - nowMs) / DAY_MS - targetDays); if (distance < bestDistance) { bestDistance = distance; best = k; } } expiry = expiryMs[best]; spot = NaN; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { // spot: the chain's own underlying at that expiry if (cells[i + 1] == expiry && cells[i + 7] > 0.0) { spot = cells[i + 7]; break; } } if (!(spot > 0.0)) spot = close; if (!(spot > 0.0)) return false; strikeCount = 0; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { // one volatility per strike, from the out-of-the-money contract: puts below spot, calls at or above if (cells[i + 1] != expiry) continue; const strike = cells[i]; if (!(strike > 0.0)) continue; const isCall = cells[i + 2] > 0.0; if (isCall != (strike >= spot)) continue; const iv = cells[i + 6] / 100.0; // mark IV rides the chain in percentage points (45.2 is 45.2%), kept as a fraction if (!(iv > 0.0)) continue; const slot = strikeSlot(strike); if (slot < 0) continue; strikeIv[slot] = iv; } if (strikeCount == 0) return false; years = optionsYearsToGo(expiry, nowMs, zone); if (!(years > 0.0)) return false; ivAtm = ivAt(spot); if (!(ivAtm > 0.0)) return false; sigmaT = ivAtm * Math.sqrt(years); q025 = priceWhereAbove(0.975); q16 = priceWhereAbove(0.84); q84 = priceWhereAbove(0.16); q975 = priceWhereAbove(0.025); pUpMove = pAbove(spot * (1.0 + MOVE)) * 100.0; pDownMove = (1.0 - pAbove(spot * (1.0 - MOVE))) * 100.0; // The grid follows the price scale the trader sees: the loaded bars' low..high widened by the margin on each side // (never thinner than a tenth of a standard deviation, for a flat or one-bar window), clamped to spot times // exp(+-3 sigma), at the largest round step that puts at least 'rows' rows across it. A 1m chart gets rows a few // dollars apart over its few hundred dollars of range, a 1h chart the whole bell; the odds are the same. const bandLo = spot * Math.exp(-3.0 * sigmaT); const bandHi = spot * Math.exp(3.0 * sigmaT); let lo = bandLo; let hi = bandHi; const range = loadedHigh - loadedLow; if (range >= 0.0) { // false when no bar carried a finite high and low: the grid keeps the whole band let seenLo = loadedLow - range * marginShare; let seenHi = loadedHigh + range * marginShare; const thinnest = 0.1 * spot * sigmaT; if (seenHi - seenLo < thinnest) { const mid = 0.5 * (seenLo + seenHi); seenLo = mid - 0.5 * thinnest; seenHi = mid + 0.5 * thinnest; } if (seenLo > lo) lo = seenLo; if (seenHi < hi) hi = seenHi; if (!(hi > lo)) { // the loaded range sits outside the band entirely (a far basis): keep the band lo = bandLo; hi = bandHi; } } // The row probability is the drop in P(above) across the row, after P(above) is forced non-increasing up the grid. gridStep = niceStepAtMost((hi - lo) / f64(rowsWanted - 1)); gridLo = Math.floor(lo / gridStep) * gridStep; gridRows = i32(Math.ceil((hi - gridLo) / gridStep)) + 1; while (gridRows > MAX_ROWS) { // never with the rows setting's range; kept so the frame can never overflow gridStep *= 2.0; gridLo = Math.floor(lo / gridStep) * gridStep; gridRows = i32(Math.ceil((hi - gridLo) / gridStep)) + 1; } if (gridRows < 3) return false; // the engine needs three prices for a grid for (let r = 0; r <= gridRows; r += 1) edgeAbove[r] = pAbove(gridLo + (f64(r) - 0.5) * gridStep); for (let r = 1; r <= gridRows; r += 1) if (!(edgeAbove[r] <= edgeAbove[r - 1])) edgeAbove[r] = edgeAbove[r - 1]; peakRow = 0; for (let r = 0; r < gridRows; r += 1) { rowPrice[r] = gridLo + f64(r) * gridStep; const p = edgeAbove[r] - edgeAbove[r + 1]; rowProb[r] = p > 0.0 ? p : 0.0; if (rowProb[r] > rowProb[peakRow]) peakRow = r; } return true; } // ── The docked cloud ── const HEX: String[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; // allocated at load, so a row colour never allocates per bar function fbHexByte(v: i32): void { // two lowercase hex digits fb_text(HEX[(v >> 4) & 0xf]); fb_text(HEX[v & 0xf]); } function fbRamp(w: f64): void { // "#rrggbb": the tail ink moved toward the core ink by w (0..1), opaque const k = w < 0.0 ? 0.0 : w > 1.0 ? 1.0 : w; fb_text("\"#"); for (let c = 0; c < 3; c += 1) fbHexByte(i32(Math.round(f64(tailRgb[c]) + (f64(coreRgb[c]) - f64(tailRgb[c])) * k))); fb_text("\""); } function readInk(packed: f64, rgb: StaticArray<i32>): void { // a colour setting arrives packed as ((r * 256 + g) * 256 + b) * 1024 + alpha thousandths const v = Math.floor(packed / 1024.0); const n = v >= 0.0 && v <= 16777215.0 ? i32(v) : 0; rgb[0] = (n >> 16) & 0xff; rgb[1] = (n >> 8) & 0xff; rgb[2] = n & 0xff; } function writeCloud(): void { const decimals = priceDecimals(gridStep); const peak = rowProb[peakRow] > 0.0 ? rowProb[peakRow] : 1.0; fb_clear(); fb_text("{\"prices\":["); for (let r = 0; r < gridRows; r += 1) { if (r > 0) fb_text(","); fb_f64(rowPrice[r], decimals); } fb_text("],\"values\":["); for (let r = 0; r < gridRows; r += 1) { if (r > 0) fb_text(","); fb_f64(rowProb[r] * 100.0, 4); // bar length: the row's odds in percent } fb_text("],\"colors\":["); for (let r = 0; r < gridRows; r += 1) { if (r > 0) fb_text(","); fbRamp(rowProb[r] / peak); // the ramp by the row's share of the peak: slate tails, a sky core } // The point of control marks the row the tag names: on a nearly flat slice (a 1m window) several rows tie at the // written precision and the engine's own pick could land a few rows away. No poc_label_text: the docked tag stays // off, the tag beside the axis names the row. fb_text("],\"poc_price\":"); fb_f64(rowPrice[peakRow], decimals); fb_text("}"); writeFrameBuffer(cloud_rows); } // ── Text helpers ── function sbK(v: f64): void { // prices as the market reads them, thousands as K: 87.9K / 2.43K / 152.33 / 0.15234 if (v >= 10000.0) { sb_f64(v / 1000.0, 1); sb_text("K"); } else if (v >= 1000.0) { sb_f64(v / 1000.0, 2); sb_text("K"); } else sb_auto(v); } function tag(name: String, price: f64): void { // "+1σ 87.9K" into the line buffer sb_clear(); sb_text(name); sb_text(" "); sbK(price); } function sbRowPrice(v: f64, step: f64): void { // a grid row's price, fine enough to tell its row from the next: 85.2K on 100-dollar rows, 85.18K on 10s, the axis's own digits below that (85176) if (v >= 1000.0 && step >= 100.0) sb_compact(v, 1); else if (v >= 1000.0 && step >= 10.0) sb_compact(v, 2); else sb_price(v, step); } function onStart(): void { targetDays = f64(p_target_days()); rowsWanted = i32(p_rows()); marginShare = f64(p_margin()) / 100.0; readInk(p_core_ink(), coreRgb); readInk(p_tail_ink(), tailRgb); zone = i32(p_market_zone()); intervalMs = p_chart_interval_sec() * 1000.0; } // onBar() runs once per bar: history rows carry an empty block and cost three reads (the first bar's time is kept // for the lines, every bar's high and low widen the loaded price range the grid follows); the live bar measures the // chain, then writes the readings as numbers, the cloud, the lines, the tags and the card's words. A live bar // without a usable chain writes the one muted sentence instead. function onBar(): void { close = bar.close(); t = bar.time(); if (isNaN(firstT) && !isNaN(t)) firstT = t; const high = bar.high(); const low = bar.low(); if (high > loadedHigh) loadedHigh = high; // NaN never widens the range if (low < loadedLow) loadedLow = low; if (!bar.isLast()) return; const n = in_chain_cells(); const chainRead = n >= TUPLE && measureChain(n); out_t_first(firstT); out_t_last(t); if (!chainRead) { sb_clear(); sb_text("No options for this market"); notice.set(16, 14).text(str_notice_sb); sb_clear(); sb_text("Options odds"); str_title_text_sb(); sb_clear(); sb_text("No expiry to read"); str_band_text_sb(); sb_clear(); sb_text("-"); str_up_text_sb(); sb_clear(); sb_text("-"); str_down_text_sb(); return; } notice.delete(); // a no-op when never drawn out_p_up_move(pUpMove); out_p_down_move(pDownMove); out_band_low(q16); out_band_high(q84); out_tail_low(q025); out_tail_high(q975); out_most_likely(rowPrice[peakRow]); out_iv_atm(ivAtm * 100.0); out_days_to_expiry(years * 365.0); writeCloud(); tag("+1σ", q84); str_tag_band_high_sb(); tag("-1σ", q16); str_tag_band_low_sb(); tag("+2σ", q975); str_tag_tail_high_sb(); tag("-2σ", q025); str_tag_tail_low_sb(); sb_clear(); sb_text("Most likely "); sbRowPrice(rowPrice[peakRow], gridStep); str_tag_most_likely_sb(); // The card's words: the odds and the expiry read for the title, the 68% band alone as the headline, the odds of // a 5% move as rows. sb_clear(); sb_text("68% likely, "); expiryText.clear().expiry(expiry, nowMs, zone); // the expiry's trade date: 10 Oct, or 15 Jan '27 in another year for (let i = 0; i < expiryText.length(); i += 1) sb_char(load<u8>(<usize>expiryText.ptr() + <usize>i)); sb_text(" "); sb_time(expiry / 1000.0, "HH:mm", 0); sb_text(" UTC"); str_title_text_sb(); sb_clear(); sbK(q16); sb_text(" to "); sbK(q84); str_band_text_sb(); sb_clear(); sb_f64(pUpMove, 0); sb_text("%"); str_up_text_sb(); sb_clear(); sb_f64(pDownMove, 0); sb_text("%"); str_down_text_sb(); } ``` ## How it works **The chain is live only.** `input("chain", options_chain.cells, { max_cells: 4000, venue: "auto" })` serves the chart's own option chain (the coin's listed options on crypto, OPRA on a US stock, CME on a futures chart) on the newest bar as one ten-value tuple per listed contract (strike, expiry, side, open interest, gamma, delta, the mark implied volatility, the underlying, the multiplier and vega), and every history bar carries an empty block. `onBar()` keeps the first bar's open time for the lines and widens the loaded price range with every bar's `bar.high()` and `bar.low()`, history included, then returns on every bar but the last, so history draws nothing; on the live bar `in_chain_cells()` counts the values and `in_chain_view()` reads the block in place. The chart's own `close` is the bar grid, and spot when the chain carries no underlying. **The chain's as-of, the live bar's close.** The odds run from the chain's as-of, `optionsAsOfMs()`: the live bar's close time, `bar.time()` plus `chart.interval_sec()`, never its open. A bar of a day or longer is read at its close, so a 1D bar's as-of is the next 00:00 UTC and a 1W bar's the next week's open. Each expiry's time runs to its end on the market's clock (`market.zone()`): `optionsLiveUntilMs()` puts an OPRA expiry's end 15 minutes past its stamp (a PM expiry stamped 16:00 New York trades until 16:15) and a CME or crypto expiry's at the stamp, and `optionsYearsToGo()` is that time in 365-day years, the time the odds are priced over. **One expiry, one smile.** `measureChain()` lists the expiries still trading at least 12 hours after the as-of and keeps the one whose days to its end are closest to `target_days` (ties keep the earlier). Spot is the chain's own underlying at that expiry, else the close. One implied volatility per strike comes from the out-of-the-money contract (puts below spot, calls at or above), the venue's percent a year turned into a fraction, and `ivAt()` reads the smile at any price: linear between neighbouring strikes, flat beyond the ends. **The odds are one curve.** `pAbove()` is the chain's odds that price settles above a price, N(d2) with the smile's volatility at that price through `normalCdf()`. `priceWhereAbove()` bisects over eight standard deviations for the prices with 97.5%, 84%, 16% and 2.5% odds of settling above them (`tail_low`, `band_low`, `band_high`, `tail_high`), and `p_up_move` and `p_down_move` are the odds of settling 5% or more above or below spot (`MOVE`). `iv_atm`, `days_to_expiry` (from the as-of to the end of the expiry read) and `most_likely` ride beside them, all data-only outputs that read NaN on history bars. **The rows follow the loaded range.** On the live bar `measureChain()` takes the loaded bars' low to high, widens it by `margin` percent of itself on each side, keeps it at least a tenth of a standard deviation wide (for a flat or one-bar window), and clamps it to spot times exp(plus or minus three standard deviations of the log price). `niceStepAtMost()` then takes the largest round step (1, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 times a power of ten) at or under the span over `rows - 1`, so `rows` is a floor: the grid holds at least that many rows. A 1m chart gets rows a few dollars apart over its few hundred dollars of range, a 1h chart the whole bell, and the odds differ only by each chart's as-of; on a fine chart the visible slice of the bell is nearly flat, which is the odds, not a fault. A row's odds are the drop in P(above) across the row, after the curve is forced non-increasing up the grid. **The grid is the cloud.** `writeCloud()` builds the frame through `fb_*` with `prices` (written to `priceDecimals()` of the step, so the rows stay evenly spaced when parsed), `values` (the odds in percent), `colors` (the tail ink moved toward the core ink by the row's share of the peak, so the tails read slate and the core sky) and `poc_price` (the most likely row), and sends it with `writeFrameBuffer(cloud_rows)`. `plot.levels` docks it right at 0.1 of the pane, narrow enough that the newest candles over it stay readable: `color: "@core_ink"` is the level's own colour, the fallback for a row without one; `gradient` is the alpha profile from each bar's root to its tip (a row with its own colour keeps its hue and takes the stops' alpha); `poc: true` draws a 2 px point-of-control line in `@peak_ink` across the dock at the price the frame names, so on a nearly flat slice, where several rows tie at the written precision, the line still marks the row the tag names; `hover: true` opens a row's odds (`format: "%"`, `decimals: 2`: a 10-dollar row holds about 0.24%). `poc_label: false` turns the engine's docked tag off, and the frame writes no `poc_label_text`, since that field alone would turn it back on. `core_ink` and `tail_ink` arrive in `onStart()` packed as one number each, and `readInk()` unpacks them to red, green and blue for the ramp. **The lines and tags are declarations.** `draw.line("band_high_line", { x1: "t_first", y1: "band_high", x2: "t_last", y2: "band_high", ... extend: "both" })` reads its coordinates from outputs by name on the newest bar; the 68% band's edges are solid and the 95% band's dotted, both in the muted colour, and each shows whenever the pane covers it. The tags are `draw.label` declarations reading string slots (`tag_band_high` holds "+1σ 87.0K", built by `sbK()` with thousands as K), plain text in the muted colour (`style: "plain"`), with `align: "right"` and `sticky_right: true`, so they ride beside the price axis as the chart scrolls. Each sits on its line's side nearer the price: `valign: "top"` on a high edge hangs the words below the line and `valign: "bottom"` on a low edge sets them above it, so no line runs through its tag and a tail at the pane's edge keeps its tag inside the pane. **The most likely row has its own tag.** `draw.label("tag_most_likely", { x: "t_last", y: "most_likely", text: "tag_most_likely", color: "theme.muted", ... sticky_right: true })` is plain text in the muted colour, right-aligned beside the price axis in the same column as the sigma tags, never on the axis. With `valign: "bottom"` its words sit just above the POC line, which crosses the dock at the same price, so the line never runs through them. `sbRowPrice()` writes the row's price at the grid's resolution: a price of 1000 or more prints compact through `sb_compact` (thousands as K), with one decimal on rows of 100 or more ("Most likely 85.2K") and two on rows of 10 or more ("Most likely 85.26K"); anything else prints through `sb_price` with the step as the tick, the axis's own digits ("Most likely 85272"). The frame's `poc_price` names the same row, so the POC line and the tag mark one price. The tag's colour is a theme word, not the peak ink, because a `draw.label` colour cannot name a setting ([The Style page](../settings/style-page.md#gotchas)): a changed peak ink moves the POC line and leaves the tag muted. **The card reads slots.** `render.hud("odds", { position: "top_left", title: "{{title_text}}", columns: 1, width: 250, safe_area: true, tiles: [...] })` names no `look`, so the card draws the chart's default look: the title is the one slot `title_text`, written on the live bar as "68% likely, ", the kit's expiry label (`TextBuilder.expiry`: the expiry's trade date on the market's clock, copied in with `sb_char`), then `sb_time(expiry / 1000.0, "HH:mm", 0)` and " UTC"; `tile.pill("Range at expiry", "band_text", { headline: true, font_size: 24, draw: "text" })` is the headline, the band alone at 24 px, where `draw: "text"` prints the words alone, with no capsule and no dot; `tile.rows` prints `up_text` and `down_text`, the odds rounded to whole percent. The 250 px width fits the longest band ("112.3K to 118.9K") at 24 px, and `safe_area` starts the card under the legend, so it covers the oldest candles on screen, never the newest ones or the cloud. ## What the settings do - **Days to expiry**: Which expiry to read: the one closest to this many days out, at least 12 hours away. - **Price steps**: The fewest price steps the cloud splits into: more steps draw a finer cloud. - **Margin, percent**: How far the cloud reaches past the loaded candles' high and low, in percent of that range. - **Cloud core**: The colour of the cloud's likely middle. - **Cloud tails**: The colour of the cloud's unlikely ends. - **Most likely price**: The colour of the line that marks the most likely price. - **Range at expiry**: The middle 68% of outcomes at the expiry, from its low price to its high price. - **Up 5% or more**: The odds price ends 5% or more above today's price at the expiry. - **Down 5% or more**: The odds price ends 5% or more below today's price at the expiry. ## Where it runs It works on coins with listed options, on any exchange and any interval. Examples are BTCUSDT on Binance Futures at 1m, 15m and 1h, and ETHUSDT on Binance spot at 15m and 1h. It reads the coin's options, from Deribit (a crypto options exchange) for the coins it lists. 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. A copy you run from the editor reads them too, once you accept the CME market data terms. The chart interval changes the odds only through the time they are read, the live candle's close. It does change how much price range the cloud covers. At 1m it is a fine, nearly flat wall over the whole pane. At 15m it is a hump, and at 1h the whole bell. The pane's own range decides what you see. On a 15m chart the +2σ and -2σ lines can sit outside the pane. Sometimes one edge of the 68% range does too, while a 1h pane shows the whole bell. A longer horizon on a fine chart needs the price axis zoomed out. The cloud never widens the price pane. The cloud shows as its own layer, so the legend lists two indicators for one file. The legend names the cloud "Odds by price". The card's title names the expiry by its date on the market's clock and its time in UTC. On a market with no options the run stops before the first candle. The legend then shows an error chip naming the market, and nothing draws. ## When data is missing When the options cannot be read, a muted note shows at the top right of the pane. It reads "No options for this market". That happens with no options at all, or no expiry still trading at least 12 hours ahead. It also happens when no strike has an implied volatility. The card's title then reads "Options odds", its headline "No expiry to read" and both odds a dash. No cloud draws, and the band lines and tags draw nothing. Older candles draw nothing: their readings are empty, and their highs and lows only set the range the cloud covers. The band lines cross the whole pane whatever history is loaded, while the cloud follows the loaded range. With no usable candle high and low, the cloud covers the whole bell out to 3σ (three standard deviations). It does the same when the range sits wholly outside the bell. A flat or one-candle window still spans a tenth of a standard deviation. ## Customize it - **A longer horizon.** `target_days` (2, from 1 to 90) picks the expiry read: the listed expiry still trading at least 12 hours after the as-of whose days to its end are closest to it. A higher timeframe wants a longer horizon, and a long horizon on a fine chart puts the band outside the pane until the price axis is zoomed out. - **A finer cloud.** `rows` (90, from 60 to 160) is the fewest rows the grid puts across the loaded range and its margin: the step is the largest round price at or under the span over `rows - 1`, so the cloud holds at least that many rows and a higher setting gives a finer step. - **A wider reach.** `margin` (25, from 0 to 100) is how far the cloud reaches past the loaded bars' high and low, percent of that range on each side: 0 keeps the rows to the loaded range, and no margin takes them past spot times exp(plus or minus three standard deviations). - **Other inks.** `core_ink` (sky), `tail_ink` (slate) and `peak_ink` (teal) under the Look section: the ramp runs from the tail ink to the core ink by each row's share of the peak, and the point-of-control line takes the peak ink. The band lines, their tags and the Most likely tag keep `theme.muted`, since a `draw.*` colour takes a literal, not a setting: change them in the source to match new inks. - **Another move.** `MOVE` (0.05) is the move the card prices; the rows' labels are literals, so change "Up 5% or more" and "Down 5% or more" with it (`p_up_move` and `p_down_move` carry the same odds for the Console and watches). - **A look of its own.** The card names no `look`, so it draws the chart's default look. When it should stand apart from the chart, add `look:` with any of the twelve shipped looks ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches the look without code ([The Style page](../settings/style-page.md#the-look-row)). Binding `look` to a `param.choice` over looks as `"@name"` makes it a setting, whose row then stands in for the Look row. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options Odds Cloud** under **Beyond the time axis**. 2. Press **Run** on a chart of a coin with listed options, such as BTCUSDT on Binance Futures at 15m: the cloud docks on the right of the price pane with its Most likely tag beside the price axis, the band lines cross the chart with their tags in the same column, and the card appears at the top left, under the legend. Rest the pointer on a cloud row to read its odds. Switch to 1m for rows a few dollars apart over the whole pane, or to 1h for the whole bell. 3. At the editor's Console prompt, type `last 20 p_up_move` to read the odds of a 5% rise on the last 20 bars: a number on the newest bar only, since the chain is live only. ## Concepts used - [Options kit](../functions/options-kit.md) for `options_chain.cells`, the ten-value tuple, `venue` and reading the chain under `bar.isLast()`, and [the chain's as-of](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsAsOfMs`, `optionsLiveUntilMs` and `optionsYearsToGo` - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels`, the frame's `colors` and `poc_price`, `gradient`, `poc` with `poc_label: false`, `decimals` and `hover` - [Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets) for `frame()`, the `fb_*` builders and `writeFrameBuffer` - [Run-level drawings](../presentation/drawing-objects.md#run-level-drawings) for declared `draw.line` and `draw.label`, their output-name coordinates, `extend`, `sticky_right` and the `style` word - [Handles](../presentation/drawing-objects.md#handles) for the `handles.label` notice - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, `width`, `offset` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name, a word beside `look` winning over it and `look` bound to a `param.choice` - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` with `draw: "text"` and `tile.rows` - [The Style page](../settings/style-page.md) for the Look row, `param.color` bound by `"@name"` and the literal a `draw.*` colour keeps - [Strings and text](../functions/text-formatting.md) for `sb_time`, `sb_compact`, `sb_price`, `sb_auto` and `sb_f64`, and [A second builder](../functions/text-formatting.md#a-second-builder) for `TextBuilder.expiry` <!-- source: https://openmarket.xyz/wrun/cookbook/whos-trading --> # Who is trading ![Whale buy share card on BTC, a donut of volume share by trade size and bought against sold columns per size under the chart](/wrun/images/whos-trading.png) Who did the volume over the last `window` bars, by the size of each trade. Under the chart, a donut shares the window's dollar volume out over seven trade-size buckets, from under 1K to 10M and up: the three sizes under 100K in the muted colour, the four whale sizes in the text colour. Every traded slice carries its name and its share ("10K-100K 51%"), the hole prints the window's total dollars, and a size that did not trade in the window has no slice. Under the donut, one pair of columns per size: bought dollars in the up colour, sold dollars in the down colour, each column printed in dollars (K, M, B) with the axis in dollars too, and the window's verdict as the panel's caption: "Whales buying", "Whales selling", "Whales balanced" or "No whale prints". On the price pane, a card in the chart's default look at the top left under the legend: "Who is trading, last 96 bars" as the title (the window in bars), the whales' buy share as the headline ("Whales 62% buy": of every dollar whales traded, the part they bought; the up colour from the `lean` setting up, the down colour from its mirror down, the muted colour between or when no whale traded), then two rows, "10M+ prints" (trades of 10M and up in the window, buys and sells together) and "Retail share" (the part of the window's dollars traded in trades under 10K, the sum of the donut's two smallest slices as printed). The legend reads the window after the name ("Who Is Trading 96 bars"). Everything is measured on the live bar over a rolling window; history bars only feed the window. The parts are a `trade_volume_by_size.cells` input with `max_cells: 7` ([Data sources](../core-concepts/data-sources.md)), two frames feeding a `panel.pie` donut and a `panel.bars` of vertical columns with a per-run caption ([Cards, frames and panels](../presentation/cards-frames-panels.md)), a `render.hud` card of a headline `tile.pill` and a `tile.rows` in the default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)), and a `handles.label` handle for the one sentence a market with no size buckets gets ([Drawing objects](../presentation/drawing-objects.md)). This is also the `whos-trading` template: the **Who Is Trading** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Who Is Trading: who did the volume over the last 'window' bars, by the size of each trade. The trader sees a donut // under the chart (the window's dollar volume shared out over seven trade-size buckets, from under 1K to 10M and up, // the trades under 100K muted and the whales' in the text ink, each slice labelled with its name and share), bars // under it (bought in the up colour against sold in the down colour, one pair per bucket, the window's verdict in the // caption), and a card on the price pane: the whales' buy share as the headline ("Whales 62% buy", in the up colour // when they bought more than they sold, the down colour when they sold more), then the count of 10M+ prints and the // retail share of the volume. Every bar feeds the rolling window; the panels and the card's numbers are measured on the // live bar only. // A trade here is one fill, bucketed by its own dollar value: an order that fills in pieces lands in smaller buckets, so // the whale share and the 10M+ count are floors. // Settings: the window in bars, and the buy share above which whales count as buying (below its mirror, selling). param.int("window", 96, { min: 12, max: 1000, label: "Window in bars", description: "Bars in the rolling window (96 bars of 15m is one day)" }); param.number("lean", 55, { min: 50, max: 90, step: 1, label: "Whale lean in percent", description: "Whale buy share, percent, from which whales count as buying; below 100 minus it they count as selling" }); legend({ title: "{{window}} bars" }); // the words after the name in the legend: the window, read by name // Inputs: the chart's own candles set the grid; the size buckets ride a celled block, one row per bucket that traded. input("close", ohlcv.close); input("sizes", trade_volume_by_size.cells, { max_cells: 7, description: "This bar's traded USD by trade-size bucket, each fill bucketed by its own value" }); // [bucket, buy_usd, sell_usd, buy_count, sell_count] per bucket that traded; seven buckets hold a full bar // Outputs: data only, written on every bar, so the card's tiles, the Console and a watch read the same numbers. output("whale_buy_share", none, overlay, { format: "0", description: "Whales' bought USD as a percent of what whales traded over the window (trades of 100K and up)" }); output("whale_share", none, overlay, { format: "0", description: "Whales' share of the window's USD volume, percent" }); output("retail_share", none, overlay, { format: "0", description: "Share of the window's USD volume in trades under 10K, percent" }); output("big_prints", none, overlay, { format: "int", description: "Prints of 10M and up over the window, buys and sells together" }); output("whale_tone", none, overlay, { description: "The verdict as a ladder rung: 0 whales selling, 1 balanced or no whale prints, 2 whales buying" }); // The card's words, written on the live bar. string("headline", { max_bytes: 24 }); // "Whales 62% buy" string("span_text", { max_bytes: 16 }); // "96 bars": the title's when string("retail_text", { max_bytes: 8 }); // "18%": the sum of the two retail slices as the donut prints them string("notice", { max_bytes: 40 }); // the one sentence when the market has no size buckets handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 }); // the notice, in pane pixels from the top-right corner // The panels under the chart: two frames, each one JSON snapshot rewritten on the live bar. const share_rows = frame("share_rows", { max_bytes: 2048 }); // the donut: [bucket, usd, color] per bucket const flow_rows = frame("flow_rows", { max_bytes: 2048 }); // the bars: [bucket, bought, sold] per bucket, plus the verdict caption // The donut: the window's dollars by trade size, labels on every traded slice, the total in the hole, a hairline gap // between slices in the chart's own background. panel.pie({ name: "size_share", title: "Share of volume by trade size", x: "category", place: "below", frame: share_rows, hole: 0.55, labels: true, chrome: "none", legend_style: "title", hole_total: true, hole_caption: "Volume", slice_gap: 2, border_color: "theme.bg", border_width: 1, format: "usd", height_frac: 0.17 }); // The bars: bought against sold per bucket, one column in the up colour and one in the down colour under each bucket // name, dollars on the axis and on every column, the window's verdict as the caption (written per run into the frame). panel.bars({ name: "size_flow", title: "Bought vs sold by trade size", x: "category", place: "below", frame: flow_rows, orientation: "vertical", labels: true, series: [{ name: "Bought", color: "theme.up" }, { name: "Sold", color: "theme.down" }], format: "usd", decimals: 0, hover_card: true, legend_style: "title", height_frac: 0.18 }); // The card: one column at the top left under the legend. The whales' buy share leads as the headline, its colour // following the verdict rung (selling, balanced, buying); two rows under it. render.hud("who", { position: "top_left", title: "Who is trading, last {{span_text}}", columns: 1, width: 300, safe_area: true, tiles: [ tile.pill("Whale buy share", "headline", { headline: true, font_size: 30, color_by: "whale_tone", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.rows("Over the window", [["10M+ prints", "big_prints", "int"], ["Retail share", "retail_text"]], { leader: "dots" }), ] }); // The seven buckets, by the USD value of one trade: 1 under 1K, 2 1K to 10K, 3 10K to 100K, 4 100K to 500K, // 5 500K to 1M, 6 1M to 10M, 7 10M and up. Whales are buckets 4 to 7; retail is buckets 1 and 2. const BUCKETS = 7; const FIRST_WHALE = 3; // bucket 4, as a 0-based slot const LAST_RETAIL = 1; // bucket 2, as a 0-based slot const BIGGEST = 6; // bucket 7, as a 0-based slot const TUPLE = 5; // f64s per block row: bucket, buy_usd, sell_usd, buy_count, sell_count const BUCKET_NAMES: String[] = ["<1K", "1K-10K", "10K-100K", "100K-500K", "500K-1M", "1M-10M", "10M+"]; const SLICE_COLORS: String[] = ["theme.muted", "theme.muted", "theme.muted", "theme.text", "theme.text", "theme.text", "theme.text"]; // the trades under 100K muted, the whales in the text ink const SELLING = 0.0; // the verdict rungs, in the ladder's order const BALANCED = 1.0; const BUYING = 2.0; // The rolling window rides rings sized for the largest window; onStart() reads the one in use. const MAX_WINDOW = 1000; const ringBuy = new StaticArray<f64>(MAX_WINDOW * BUCKETS); // each ring bar's bought USD per bucket const ringSell = new StaticArray<f64>(MAX_WINDOW * BUCKETS); // and its sold USD const ringBig = new StaticArray<f64>(MAX_WINDOW); // and its count of 10M+ prints const winBuy = new StaticArray<f64>(BUCKETS); // the window totals per bucket: the new bar added, the bar leaving subtracted const winSell = new StaticArray<f64>(BUCKETS); let winBig = 0.0; let window = 96; let lean = 55.0; let head = 0; // the ring slot the next bar takes let total = 0.0; // the window's USD volume over every bucket let whaleBuy = 0.0; // the whales' bought and sold USD let whaleSell = 0.0; let whaleBuyShare: f64 = NaN; let tone = BALANCED; const notice = draw.label(0); // handle objects allocate once, at module load // Fold this bar's block into the rings and the window totals. function foldBar(): void { const base = head * BUCKETS; for (let b = 0; b < BUCKETS; b += 1) { winBuy[b] -= ringBuy[base + b]; // the bar leaving the window winSell[b] -= ringSell[base + b]; ringBuy[base + b] = 0.0; ringSell[base + b] = 0.0; } winBig -= ringBig[head]; ringBig[head] = 0.0; const n = in_sizes_cells(); // -1 absent, 0 empty: either way this bar adds nothing if (n > 0) { const cells = in_sizes_view(); // this bar's rows in place for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { const b = i32(cells[i]) - 1; if (b < 0 || b >= BUCKETS) continue; const buy = cells[i + 1] > 0.0 ? cells[i + 1] : 0.0; const sell = cells[i + 2] > 0.0 ? cells[i + 2] : 0.0; ringBuy[base + b] += buy; ringSell[base + b] += sell; winBuy[b] += buy; winSell[b] += sell; if (b == BIGGEST) { const prints = (cells[i + 3] > 0.0 ? cells[i + 3] : 0.0) + (cells[i + 4] > 0.0 ? cells[i + 4] : 0.0); ringBig[head] += prints; winBig += prints; } } } head = (head + 1) % window; } // The window's readings. Running sums can drift a hair below zero once a bucket empties, so a negative reads as zero. function measure(): void { total = 0.0; whaleBuy = 0.0; whaleSell = 0.0; for (let b = 0; b < BUCKETS; b += 1) { if (winBuy[b] < 0.0) winBuy[b] = 0.0; if (winSell[b] < 0.0) winSell[b] = 0.0; total += winBuy[b] + winSell[b]; if (b >= FIRST_WHALE) { whaleBuy += winBuy[b]; whaleSell += winSell[b]; } } if (winBig < 0.5) winBig = 0.0; const whaleUsd = whaleBuy + whaleSell; whaleBuyShare = whaleUsd > 0.0 ? (100.0 * whaleBuy) / whaleUsd : NaN; tone = isNaN(whaleBuyShare) ? BALANCED : whaleBuyShare >= lean ? BUYING : whaleBuyShare <= 100.0 - lean ? SELLING : BALANCED; } // A bucket's share of the window's volume as the donut prints it: a whole percent. function printedShare(b: i32): i32 { return i32(Math.round((100.0 * (winBuy[b] + winSell[b])) / total)); } // The two frames, built in the kit's frame buffer without allocating: the donut's slices and the bars' rows with // the verdict caption. function writeFrames(): void { fb_clear(); fb_text("{\"rows\":["); for (let b = 0; b < BUCKETS; b += 1) { if (b > 0) fb_text(","); fb_text("["); fb_str(BUCKET_NAMES[b]); fb_text(","); fb_f64(winBuy[b] + winSell[b], 0); fb_text(","); fb_str(SLICE_COLORS[b]); fb_text("]"); } fb_text("]}"); writeFrameBuffer(share_rows); fb_clear(); fb_text("{\"caption\":"); fb_str(isNaN(whaleBuyShare) ? "No whale prints" : tone == BUYING ? "Whales buying" : tone == SELLING ? "Whales selling" : "Whales balanced"); fb_text(",\"rows\":["); for (let b = 0; b < BUCKETS; b += 1) { if (b > 0) fb_text(","); fb_text("["); fb_str(BUCKET_NAMES[b]); fb_text(","); fb_f64(winBuy[b], 0); fb_text(","); fb_f64(winSell[b], 0); fb_text("]"); } fb_text("]}"); writeFrameBuffer(flow_rows); } // The card's words: the headline, the title's when, and the retail share as the sum of the two retail slices' // printed shares, so the card and the donut never differ by a rounding point. function writeWords(): void { sb_clear(); if (isNaN(whaleBuyShare)) sb_text("No whale prints"); else { sb_text("Whales "); sb_int(i64(Math.round(whaleBuyShare))); sb_text("% buy"); } str_headline_sb(); sb_clear(); sb_int(window); sb_text(" bars"); str_span_text_sb(); sb_clear(); sb_int(printedShare(0) + printedShare(LAST_RETAIL)); sb_text("%"); str_retail_text_sb(); } // onStart() runs once before the first bar: the settings. function onStart(): void { window = i32(p_window()); lean = p_lean(); } // onBar() runs once per bar: fold the bar into the window, write the readings as numbers; the frames and the card's // words on the live bar only. A window with no size buckets at all writes the one sentence instead. function onBar(): void { foldBar(); measure(); out_whale_buy_share(whaleBuyShare); out_whale_share(total > 0.0 ? (100.0 * (whaleBuy + whaleSell)) / total : NaN); out_retail_share(total > 0.0 ? (100.0 * (winBuy[0] + winSell[0] + winBuy[LAST_RETAIL] + winSell[LAST_RETAIL])) / total : NaN); out_big_prints(total > 0.0 ? winBig : NaN); out_whale_tone(tone); if (!bar.isLast()) return; if (total <= 0.0) { sb_clear(); sb_text("No trade sizes on this market"); notice.set(16, 44).text(str_notice_sb); // under the chart's own High tag, which takes the corner when the high is at the top edge return; } notice.delete(); // a no-op when the notice was never drawn writeFrames(); writeWords(); } ``` ## How it works **Seven buckets are the input.** `input("sizes", trade_volume_by_size.cells, { max_cells: 7 })` serves this bar's traded dollars by the size of each trade, one `[bucket, buy_usd, sell_usd, buy_count, sell_count]` row per bucket that traded, bucket 1 (under 1K) to bucket 7 (10M and up); a bucket that did not trade has no row, and a bar with no trades is an empty block. `in_sizes_cells()` counts this bar's values (`-1` absent, `0` empty) and `in_sizes_view()` holds them in place; `foldBar()` walks them five at a time. Whales are buckets 4 to 7 (`FIRST_WHALE`, 100K and up) and retail is buckets 1 and 2 (`LAST_RETAIL`, under 10K); bucket 3 counts toward the donut, the bars and the total, but toward neither share on the card. **A bucket counts fills, not orders.** The lane buckets every fill, one matched trade at one price, by its own dollar value, so an order that takes liquidity from many resting orders arrives as many smaller fills: a 2M market buy that fills in forty pieces of 50K counts in the 10K-100K bucket, not the 1M-10M one. Read the whales' share and the 10M+ count as floors for what large traders did, and the retail share as a ceiling. **The window is a ring of running sums.** `foldBar()` subtracts the bar leaving the window from the per-bucket totals `winBuy` and `winSell`, writes this bar's bought and sold dollars into its slot of `ringBuy` and `ringSell` (sized at load for `MAX_WINDOW`, 1000 bars by seven buckets) and adds them to the totals; `ringBig` and `winBig` do the same for the 10M+ prints (`buy_count` plus `sell_count` of bucket 7). `measure()` then sums the window: `total` over every bucket, `whaleBuy` and `whaleSell` over buckets 4 to 7; a running sum that drifts a hair below zero once a bucket empties reads as zero. `onStart()` reads `window` (96) and `lean` (55), and `legend({ title: "{{window}} bars" })` reads the window by name, so the legend row prints "Who Is Trading 96 bars". **The verdict is a ladder.** `whaleBuyShare` is the whales' bought dollars over what whales traded, NaN when no whale traded. The rung `tone` is `BUYING` (2) from `lean` up, `SELLING` (0) from 100 minus `lean` down, `BALANCED` (1) between or when no whale traded; `whale_tone` carries it as a data-only output, and the pill's `colors` ladder reads the down, muted and up colours from it. `whale_buy_share`, `whale_share` and `retail_share` (percent) and `big_prints` (a count) are the other data-only outputs, written on every bar so the Console and a watch read the numbers the card shows. **Two frames are the panels.** On the live bar, `writeFrames()` builds `share_rows` in the frame buffer with the `fb_*` writers, one `[name, usd, color]` row per bucket from `BUCKET_NAMES` and `SLICE_COLORS` (`theme.muted` under 100K, `theme.text` for the whales), and `panel.pie` draws it as the donut: `hole: 0.55` with `hole_total` and `hole_caption: "Volume"` print the window's dollars in the hole, `labels: true` names every traded slice with its share, `legend_style: "title"` names every bucket on the title row (an untraded bucket still names itself), and `slice_gap: 2` with `border_color: "theme.bg"` cuts a hairline gap in the chart's own background. `flow_rows` carries one `[name, bought, sold]` row per bucket plus a `caption` with the verdict's words, and `panel.bars` draws it as vertical columns, `Bought` in the up colour and `Sold` in the down colour, `format: "usd"` with `decimals: 0` on the axis and on every column (`labels: true`), `hover_card: true` for a readout under the pointer. A `caption` written into the frame overrides the declared word for that run, so the verdict rides the panel's caption with none in the declaration. **The card reads slots and outputs.** `render.hud("who", { position: "top_left", title: "Who is trading, last {{span_text}}", columns: 1, width: 300, safe_area: true, ... })` is one column of 300 px that starts under the legend, its title reading the `span_text` slot ("96 bars"). `tile.pill("Whale buy share", "headline", { headline: true, font_size: 30, color_by: "whale_tone", colors: [...] })` is the headline, its words from the `headline` slot ("Whales 62% buy", or "No whale prints"), its colour from the verdict rung; `font_size: 30` sets the headline at 30 px in place of the default look's 17, and a declared word wins over any look's own, so a look picked on the Style page with a larger headline still keeps it inside the card. `tile.rows("Over the window", [["10M+ prints", "big_prints", "int"], ["Retail share", "retail_text"]], { leader: "dots" })` prints the count from the output and the retail share from a slot, with dotted leaders. `writeWords()` fills the three slots with the `sb_*` builders on the live bar; the retail text is the sum of the two retail slices' printed shares (`printedShare`, a whole percent each), so the card never disagrees with the donut by a rounding point, while the exact ratio stays the `retail_share` output. **The one sentence is a handle.** `handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 })` declares label handles placed in pane pixels from the top-right corner, and `draw.label(0)` makes the one handle at module load. On a live bar whose window holds no dollars at all, `notice.set(16, 44).text(str_notice_sb)` draws "No trade sizes on this market" under the chart's own High tag and the frames and the words are not written; on any other live bar `notice.delete()` removes it (a no-op when it was never drawn). ## Where it runs Crypto markets whose venue serves volume by trade size: Binance Futures perpetuals, Binance spot and Hyperliquid perpetuals (BTCUSDT on Binance Futures, ETHUSDT on Binance spot and PURR on Hyperliquid, at 15m and 1h). `trade_volume_by_size` is a required lane: on a market where the feed is declined (FX, CME, stocks) the run is refused by name before any bar, with a toast that begins "Trade volume by size data is unavailable" and ends "so the indicator cannot compute". The card sits at the top left of the price pane under the legend (`safe_area`), and the two panels take 0.17 and 0.18 of the chart's height under it. ## When data is missing When every bar in the window is an empty block (the feed answers but nothing traded by size), the panels are not drawn and one muted line at the top right of the price pane reads "No trade sizes on this market"; the card's tiles read a dash. Before the window is full the numbers cover the bars loaded so far. The window totals are running sums kept per bucket, so a size that stops trading leaves the donut as its bars leave the window, and a bucket that never traded keeps its name in the legend with no slice; on a window with no prints of 10M and up the 10M+ columns print $0 and the card's row reads 0. ## Customize it - **A longer window.** `window` sets the bars in the rolling window (96, 12 to 1000); 96 bars of 15m is one day, and the card's title and the legend say the window in bars. - **A stricter lean.** `lean` is the whale buy share, in percent, from which whales count as buying (55, 50 to 90); below 100 minus it they count as selling, between they are balanced. The headline's colour and the caption's verdict follow it. - **Whales from 500K.** Set `FIRST_WHALE` to 4 (bucket 5 as a 0-based slot) to count whales from 500K and up, and reword the `whale_buy_share` and `whale_share` descriptions to match. - **Bars on their side.** `orientation: "horizontal"` on `panel.bars` lays the seven buckets down the left edge; at 0.18 of the chart the pane prints only every other bucket name, so give it about 0.24 with `height_frac` and take the difference from the donut. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Who Is Trading** under **Beyond the time axis**. 2. Press **Run** on a crypto chart whose venue serves volume by trade size, such as BTCUSDT on Binance Futures at 15m: the donut and the bought-against-sold columns appear under the chart, the card at the top left of the price pane under the legend, and the legend row reads the window. 3. At the editor's Console prompt, type `last 20 whale_buy_share` to read the whales' buy share of the window on the last 20 bars. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for `trade_volume_by_size.cells`, its seven buckets and the `in_sizes_cells()` and `in_sizes_view()` readers - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, the `fb_*` writers, `panel.pie`, `panel.bars`, their words and the frame `caption` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `width` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill`, `tile.rows` and `leader: "dots"` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Drawing objects](../presentation/drawing-objects.md) for `handles.label`, `draw.label(id)` and the `set`, `text` and `delete` calls - [Strings and text](../functions/text-formatting.md) for the `sb_*` builders and `str_<slot>_sb()` <!-- source: https://openmarket.xyz/wrun/cookbook/rotation-map --> # Rotation map ![Rotation map pane under a BTC chart with eight labelled coin dots and their fading trails in four tinted quadrants, and the card at the top left](/wrun/images/rotation-map.png) Eight large coins on one map under the chart, placed by how they are doing against BTC. Left to right is strength: how far each coin's price in BTC sits above or below its own longer average. Bottom to top is momentum: whether that strength is still rising or already fading. Two dashed guides through 100 cut the map into the four quadrants a rotation moves through, clockwise: improving (top left, sky), leading (top right, teal), weakening (bottom right, amber), lagging (bottom left, orange), each quietly tinted and named in its corner. One labelled dot per coin, all one size and in its quadrant's colour, and behind each a short tail of its earlier positions on a thin line, the tail's dots smaller and fainter toward the far end. Every position is read from closed hourly candles with the same averages on every chart, so a coin sits at the same place on a 1m, a 15m and a 1h chart and the map moves once an hour; only the tail's reach follows the chart: the last day on charts up to 5m, three days up to 30m, a week on 1h and coarser. The dot farthest top right is the leader: its name carries its move against BTC over the tail ("SOL +4.1%"). A card at the top left of the price pane, in the chart's default look, answers first: the leader and its move against BTC as the headline, then how many coins are improving and how many weakening. The card's title says what the tail covers ("Rotation vs BTC, last 24h", "last 3d" or "last 7d"). The parts are nine `candles.cells` streams of closed hourly candles on Binance Futures, BTC as the reference plus eight coins, beside the chart's own close ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream), [Data sources](../core-concepts/data-sources.md#celled-sources)), the chart's bar interval from `chart.interval_sec()` for the tail step ([Sessions and units](../settings/sessions-and-units.md#the-interval-and-the-colours)), a frame feeding a `panel.scatter` with `guides`, `quadrants`, `trails` and dot `labels` ([Cards, frames and panels](../presentation/cards-frames-panels.md)), four `param.color` quadrant inks read in `onStart()` and written into the frame as hex ([The Style page](../settings/style-page.md), [Colors kit](../functions/colors-kit.md)), a `render.hud` card with no `look` word ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)), and a label handle for the one sentence ([Drawing objects](../presentation/drawing-objects.md)). This is also the `rotation-map` template: the **Rotation Map** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Rotation Map: eight large coins on a scatter below the chart, each placed by its strength against BTC (x) and the // momentum of that strength (y), both read from closed hourly candles with the same averages on every chart, so a // coin sits at the same place on a 1m, a 15m and a 1h chart. Per coin and per hourly candle: the ratio to BTC is // smoothed by an EMA (14 days); the strength is 100 plus how far that smoothed ratio sits from its own longer average // (18 days), in units of its usual distance from it; the momentum is 100 plus how far the strength sits from its own // short average (9 days), in the same units. Two dashed guides cut the pane into four quadrants at 100/100, faintly // tinted: leading (strong and still rising, teal), improving (weak but rising, sky), weakening (strong but fading, // amber), lagging (weak and falling, orange). Every coin is a labelled dot in its quadrant's colour with a short tail // of six earlier positions, one per tail step, small and faint at the far end. The tail step follows the chart, so a // tail covers the last day on a 1m chart, three days on a 15m chart and a week on a 1h chart. The dot farthest // top-right is the leader: its label carries its move against BTC over the tail, and a card at the top left answers // first: who leads, by how much, and how many coins are improving and weakening. The map and the words are written // on the live bar only. section("Map"); param.int("tail_points", 6, { min: 0, max: 12, label: "Tail points", description: "Earlier positions drawn behind each coin, one per tail step (0 = heads only)" }); param.int("smooth", 14, { min: 1, max: 21, label: "Smoothing in days", description: "Days the ratio to BTC is smoothed over (an EMA)" }); param.int("trend", 18, { min: 3, max: 28, label: "Trend average in days", description: "Days of the longer average the strength is measured from" }); param.int("momentum", 9, { min: 1, max: 14, label: "Momentum average in days", description: "Days of the short average the momentum is measured from" }); section("Quadrant colours"); param.color("leading_ink", "#2dd4bf", { label: "Leading", description: "Strong against BTC and still rising" }); param.color("improving_ink", "#38bdf8", { label: "Improving", description: "Weak against BTC but rising" }); param.color("weakening_ink", "#f8c000", { label: "Weakening", description: "Strong against BTC but fading" }); param.color("lagging_ink", "#f86800", { label: "Lagging", description: "Weak against BTC and falling" }); // The chart's bar interval in seconds, written by the chart before the first bar: it sets the tail step, 4 hours on // charts up to 5m, 12 hours up to 30m, 28 hours on 1h and coarser (0, unknown, counts as a 15m chart). chart.interval_sec(); // Inputs: the chart's own candles set the bar grid; then BTC and the eight coins as streams of closed hourly candles // on Binance Futures, the newest 1500 of them on the first bar and each later one on the bar it closes with, whatever // the chart's interval. To swap a coin: change the symbol in its input line and the name at the same position in // COIN_NAMES below (keep eight). Ten sources is the chart's cap per indicator, so nothing else may read a source. input("close", ohlcv.close); input("btc", candles.cells, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500, description: "BTC hourly candles, the reference every coin is measured against" }); input("eth", candles.cells, { symbol: "ETHUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("sol", candles.cells, { symbol: "SOLUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("xrp", candles.cells, { symbol: "XRPUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("bnb", candles.cells, { symbol: "BNBUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("doge", candles.cells, { symbol: "DOGEUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("ada", candles.cells, { symbol: "ADAUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("avax", candles.cells, { symbol: "AVAXUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); input("link", candles.cells, { symbol: "LINKUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 }); // Readings, data only: the card's rows read the counts, the Console and a watch can read them on every bar. output("leading", none, overlay, { description: "Coins in the leading quadrant: strength above 100 and momentum above 100" }); output("improving", none, overlay, { description: "Coins in the improving quadrant: strength below 100, momentum above 100" }); output("weakening", none, overlay, { description: "Coins in the weakening quadrant: strength above 100, momentum below 100" }); output("lagging", none, overlay, { description: "Coins in the lagging quadrant: strength and momentum both below 100" }); output("leader_quadrant", none, overlay, { description: "The quadrant of the dot farthest top-right: 0 leading, 1 improving, 2 weakening, 3 lagging" }); string("leader", { max_bytes: 32 }); // the headline: the leader and its move against BTC over the tail string("window_text", { max_bytes: 16 }); // the card's title reads it: "last 24h" string("notice", { max_bytes: 64 }); // the one muted line while the hourly candles load // The one muted line: a label handle pinned at the top right of the price pane, clear of the chart's own chrome. handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 12, style: "plain", safe_area: true }); // The map: one scatter frame rewritten on the live bar, rows [coin, x, y, size, colour, label]. Rows that share a coin // key form its tail (oldest first, the head last), a thin line fading toward the far end; the dashed guides cut the // four quadrants, each faintly tinted and named in its corner; the tints are rewritten per run. const rotationRows = frame("rotation_rows", { max_bytes: 16384 }); panel.scatter({ name: "rotation", title: "Rotation vs BTC", x: "number", place: "below", frame: rotationRows, height_frac: 0.45, labels: true, label_overlap: "leader", legend_style: "none", hover_card: true, format: "0.0", x_title: "Strength vs BTC", guides: [ { axis: "x", value: 100, color: "theme.muted", line_style: "dashed" }, { axis: "y", value: 100, color: "theme.muted", line_style: "dashed" }, ], quadrants: { x: 100, y: 100, colors: ["#2dd4bf0c", "#38bdf80c", "#f868000c", "#f8c0000c"], labels: ["Leading", "Improving", "Lagging", "Weakening"] }, trails: true, trail_width: 1, trail_fade: true, }); // The card: the leader and its move against BTC as the headline, then the two counts the rotation is made of. // {{window_text}} reads the slot. render.hud("rotation_card", { position: "top_left", title: "Rotation vs BTC, {{window_text}}", columns: 1, width: 210, safe_area: true, tiles: [ tile.pill("Leader", "leader", { headline: true }), tile.rows([ ["Improving", "improving", "int"], ["Weakening", "weakening", "int"], ]), ], }); // The coins, in the order of the inputs above. const COINS = 8; const COIN_NAMES: StaticArray<string> = ["ETH", "SOL", "XRP", "BNB", "DOGE", "ADA", "AVAX", "LINK"]; const HEX1: StaticArray<string> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; // hex digits, written one at a time so a colour never allocates const TUPLE = 6; // one candle in a stream block: [offset_ms, open, high, low, close, volume] // Every coin's (strength, momentum, log ratio) per hourly candle, in a ring as long as the longest tail can reach: // 12 points at the 28-hour step, plus the head. const MAX_STEP = 28; const MAX_TAIL = 12; const HIST = MAX_TAIL * MAX_STEP + 1; const histX = new StaticArray<f64>(COINS * HIST); const histY = new StaticArray<f64>(COINS * HIST); const histR = new StaticArray<f64>(COINS * HIST); // Per coin: the last close (a missing hour carries it), the smoothed log ratio, its longer average and the average // squared distance from it (with the share of weight the average has seen so far, so an early reading is not // inflated), the short average of the strength and the average squared momentum (with its weight), and the counts. const lastClose = new StaticArray<f64>(COINS); const smoothed = new StaticArray<f64>(COINS); const trendMean = new StaticArray<f64>(COINS); const trendVar = new StaticArray<f64>(COINS); const trendWeight = new StaticArray<f64>(COINS); const momMean = new StaticArray<f64>(COINS); const momVar = new StaticArray<f64>(COINS); const momWeight = new StaticArray<f64>(COINS); const seen = new StaticArray<i32>(COINS); // hourly candles folded with a ratio const zSeen = new StaticArray<i32>(COINS); // of those, candles with a strength const cursor = new StaticArray<i32>(COINS); // where this bar's merge stands in the coin's block // The live bar's map, per coin. const strength = new StaticArray<f64>(COINS); // the head's x, NaN without values const momentum = new StaticArray<f64>(COINS); // the head's y const move = new StaticArray<f64>(COINS); // the coin's move against BTC over the tail, percent const quadrant = new StaticArray<i32>(COINS); // 0 leading, 1 improving, 2 weakening, 3 lagging, -1 without values const order = new StaticArray<i32>(COINS); // coin indices by distance top-right, the leader first const tailDrawn = new StaticArray<i32>(COINS); // tail points the live bar draws behind each head const inkR = new StaticArray<i32>(4); // the four quadrant inks from the settings, one channel each const inkG = new StaticArray<i32>(4); const inkB = new StaticArray<i32>(4); const HEAD_SIZE = 5.0; // the head's radius, px, the same for every coin const TAIL_MIN = 1.5; // tail dot radii, the far end to the newest const TAIL_MAX = 2.5; const TAIL_ALPHA_MIN = 0x26; // tail dot alpha, the far end to the newest (the line between them fades on its own) const TAIL_ALPHA_MAX = 0x8c; const TINT_ALPHA = 0x0c; // the quadrant tints, quiet const REACH_MIN = 0.5; // each axis reaches at least half a usual distance past 100 on both sides: a calm hour still shows a cross const SIDE_MIN = 0.3; // the axes fit the dots, and the side of a guide with no dots still keeps 30% of the axis const PAD_X = 0.08; // room past the farthest dot, as a share of the axis, so no head sits on the pane's edge; more const PAD_Y = 0.15; // above and below, where the quadrant words sit in the corners const notice = draw.label(0); // the one muted line; a handle allocates once at module load let step = 12; // hours between two tail points, from the chart interval let tailPoints = 6; // settings, read in onStart() let smoothLen = 336; // the three averages, in hourly candles let trendLen = 432; let momLen = 216; let aSmooth = 0.0; let aTrend = 0.0; let aMom = 0.0; let histHead = 0; // the ring slot of the newest hourly candle let hours = 0; // hourly candles folded so far let rows = 0; // scatter rows written so far on this live bar let noticeShown = false; let axisLo = 0.0; // fitAxis() writes its two ends here let axisHi = 0.0; // The coin's stream by position, in the order of the inputs. function coinCells(c: i32): i32 { switch (c) { case 0: return in_eth_cells(); case 1: return in_sol_cells(); case 2: return in_xrp_cells(); case 3: return in_bnb_cells(); case 4: return in_doge_cells(); case 5: return in_ada_cells(); case 6: return in_avax_cells(); default: return in_link_cells(); } } function coinView(c: i32): StaticArray<f64> { switch (c) { case 0: return in_eth_view(); case 1: return in_sol_view(); case 2: return in_xrp_view(); case 3: return in_bnb_view(); case 4: return in_doge_view(); case 5: return in_ada_view(); case 6: return in_avax_view(); default: return in_link_view(); } } // The coin's close for the hour that opened at 'offset' (ms from this bar's open), NaN when its block has no candle // for that hour. Both blocks run oldest first, so one cursor per coin walks its block once per bar. function coinCloseAt(c: i32, offset: f64): f64 { const n = coinCells(c); if (n <= 0) return NaN; const view = coinView(c); let j = unchecked(cursor[c]); while (j + TUPLE <= n && unchecked(view[j]) < offset) j += TUPLE; unchecked((cursor[c] = j)); return j + TUPLE <= n && unchecked(view[j]) == offset ? unchecked(view[j + 4]) : NaN; } // One closed hour: every coin's ratio to BTC, smoothed; its strength and momentum; kept in the ring. function foldHour(offset: f64, btc: f64): void { histHead = (histHead + 1) % HIST; hours += 1; for (let c = 0; c < COINS; c += 1) { let px = coinCloseAt(c, offset); if (isNaN(px) || px <= 0.0) px = unchecked(lastClose[c]); else unchecked((lastClose[c] = px)); const at = c * HIST + histHead; let x: f64 = NaN; let y: f64 = NaN; let r: f64 = NaN; if (btc > 0.0 && px > 0.0) { r = Math.log(px / btc); const n = unchecked(seen[c]); if (n == 0) { unchecked((smoothed[c] = r)); unchecked((trendMean[c] = r)); } else { const s = unchecked(smoothed[c]) + aSmooth * (r - unchecked(smoothed[c])); unchecked((smoothed[c] = s)); const dev = s - unchecked(trendMean[c]); unchecked((trendMean[c] = trendMean[c] + aTrend * dev)); unchecked((trendVar[c] = (1.0 - aTrend) * (trendVar[c] + aTrend * dev * dev))); unchecked((trendWeight[c] = (1.0 - aTrend) * trendWeight[c] + aTrend)); } unchecked((seen[c] = n + 1)); const v = unchecked(trendWeight[c]) > 0.0 ? unchecked(trendVar[c]) / unchecked(trendWeight[c]) : 0.0; if (n + 1 >= trendLen && v > 0.0) { const z = (unchecked(smoothed[c]) - unchecked(trendMean[c])) / Math.sqrt(v); x = 100.0 + z; const k = unchecked(zSeen[c]); if (k == 0) { unchecked((momMean[c] = z)); } else { unchecked((momMean[c] = momMean[c] + aMom * (z - momMean[c]))); const d = z - unchecked(momMean[c]); unchecked((momVar[c] = (1.0 - aTrend) * momVar[c] + aTrend * d * d)); unchecked((momWeight[c] = (1.0 - aTrend) * momWeight[c] + aTrend)); const mv = unchecked(momVar[c]) / unchecked(momWeight[c]); if (k + 1 >= momLen && mv > 0.0) y = 100.0 + d / Math.sqrt(mv); } unchecked((zSeen[c] = k + 1)); } } unchecked((histX[at] = x)); unchecked((histY[at] = y)); unchecked((histR[at] = r)); } } // The ring slot of the candle 'back' hours before the newest, -1 when the ring does not reach it. function slotBack(back: i32): i32 { return back < hours && back < HIST ? (histHead - back + HIST) % HIST : -1; } // The quadrant of a position: strong means x above 100, rising means y above 100. function quadrantOf(x: f64, y: f64): i32 { const strong = x > 100.0; const rising = y > 100.0; return strong ? (rising ? 0 : 2) : rising ? 1 : 3; } // How far top-right a dot sits: its distance along the diagonal from the centre. function diagonal(c: i32): f64 { return strength[c] - 100.0 + (momentum[c] - 100.0); } // ── Frame writers: a colour as "#rrggbb" or "#rrggbbaa", written digit by digit (no allocation on the live bar) ── function fbHexByte(v: i32): void { fb_text(unchecked(HEX1[(v >> 4) & 15])); fb_text(unchecked(HEX1[v & 15])); } function fbInk(q: i32, alphaByte: i32): void { // the quadrant's ink from the settings; alpha 255 writes the opaque form fb_text("\"#"); fbHexByte(unchecked(inkR[q])); fbHexByte(unchecked(inkG[q])); fbHexByte(unchecked(inkB[q])); if (alphaByte < 255) fbHexByte(alphaByte); fb_text("\""); } // One scatter row: [coin, x, y, size, colour] and, on a head, the label. function writeRow(c: i32, x: f64, y: f64, size: f64, alphaByte: i32, label: i32): void { // label: 0 none, 1 the name, 2 the name and the move if (rows > 0) fb_text(","); fb_text("["); fb_int(<i64>c); fb_text(","); fb_f64(x, 3); fb_text(","); fb_f64(y, 3); fb_text(","); fb_f64(size, 1); fb_text(","); fbInk(quadrant[c], alphaByte); if (label > 0) { fb_text(",\""); fb_text(unchecked(COIN_NAMES[c])); if (label == 2 && !isNaN(move[c])) { fb_text(move[c] >= 0.05 ? " +" : " "); // a move that rounds to 0.0 carries no sign fb_f64(Math.abs(move[c]) < 0.05 ? 0.0 : move[c], 1); fb_text("%"); } fb_text("\""); } fb_text("]"); rows += 1; } // One axis fitted to the dots: from the lowest to the highest value, 100 always inside, at least REACH_MIN past 100 // on each side, the side of the guide with no dots kept at SIDE_MIN of the axis (its quadrants stay readable), then // 'pad' of room at both ends. Writes axisLo and axisHi. function fitAxis(lo: f64, hi: f64, pad: f64): void { let below = Math.max(100.0 - lo, REACH_MIN); let above = Math.max(hi - 100.0, REACH_MIN); if (below < SIDE_MIN * (below + above)) below = (SIDE_MIN / (1.0 - SIDE_MIN)) * above; if (above < SIDE_MIN * (below + above)) above = (SIDE_MIN / (1.0 - SIDE_MIN)) * below; const total = below + above; axisLo = 100.0 - below - pad * total; axisHi = 100.0 + above + pad * total; } // The map on the live bar: every coin's tail, its far end smallest and faintest, then its head with its name (the // leader's with its move); the axes fitted to the dots with the guides at 100; the four quadrant tints in the inks // the settings hold. function writeMap(lead: i32): void { let loX = 100.0; let hiX = 100.0; let loY = 100.0; let hiY = 100.0; for (let c = 0; c < COINS; c += 1) { unchecked((tailDrawn[c] = 0)); if (quadrant[c] < 0) continue; loX = Math.min(loX, strength[c]); hiX = Math.max(hiX, strength[c]); loY = Math.min(loY, momentum[c]); hiY = Math.max(hiY, momentum[c]); for (let i = 1; i <= tailPoints; i += 1) { // tail points with values, counted back from the head: a tail never jumps a gap const slot = slotBack(i * step); if (slot < 0) break; const tx = unchecked(histX[c * HIST + slot]); const ty = unchecked(histY[c * HIST + slot]); if (isNaN(tx) || isNaN(ty)) break; loX = Math.min(loX, tx); hiX = Math.max(hiX, tx); loY = Math.min(loY, ty); hiY = Math.max(hiY, ty); unchecked((tailDrawn[c] = i)); } } fb_clear(); fb_text("{\"rows\":["); rows = 0; // The leader first: where two labels would collide the pane moves the later one onto a leader line, so a crowded // cluster nudges the names of the coins farther bottom-left, never the leader's. for (let k = 0; k < COINS; k += 1) { const c = order[k]; if (quadrant[c] < 0) continue; const drawn = unchecked(tailDrawn[c]); for (let i = drawn; i >= 1; i -= 1) { // the far end first const slot = slotBack(i * step); const age = f64(drawn - i + 1) / f64(drawn + 1); // near 0 at the far end, near 1 next to the head const size = TAIL_MIN + (TAIL_MAX - TAIL_MIN) * age; const alphaByte = TAIL_ALPHA_MIN + i32(Math.round(f64(TAIL_ALPHA_MAX - TAIL_ALPHA_MIN) * age)); writeRow(c, unchecked(histX[c * HIST + slot]), unchecked(histY[c * HIST + slot]), size, alphaByte, 0); } writeRow(c, strength[c], momentum[c], HEAD_SIZE, 255, c == lead ? 2 : 1); } fitAxis(loX, hiX, PAD_X); fb_text("],\"x_min\":"); fb_f64(axisLo, 3); fb_text(",\"x_max\":"); fb_f64(axisHi, 3); fitAxis(loY, hiY, PAD_Y); fb_text(",\"y_min\":"); fb_f64(axisLo, 3); fb_text(",\"y_max\":"); fb_f64(axisHi, 3); fb_text(",\"quadrants\":{\"x\":100,\"y\":100,\"colors\":["); fbInk(0, TINT_ALPHA); fb_text(","); fbInk(1, TINT_ALPHA); fb_text(","); fbInk(3, TINT_ALPHA); fb_text(","); fbInk(2, TINT_ALPHA); fb_text("],\"labels\":[\"Leading\",\"Improving\",\"Lagging\",\"Weakening\"]}}"); writeFrameBuffer(rotationRows); } // onStart() runs once before the first bar: the tail step from the chart interval, the three averages from days to // hourly candles, the four inks unpacked, the ring emptied. function onStart(): void { const interval = p_chart_interval_sec(); step = interval > 0.0 && interval <= 300.0 ? 4 : interval <= 1800.0 ? 12 : MAX_STEP; tailPoints = i32(p_tail_points()); smoothLen = i32(p_smooth()) * 24; trendLen = i32(p_trend()) * 24; momLen = i32(p_momentum()) * 24; aSmooth = 2.0 / f64(smoothLen + 1); aTrend = 2.0 / f64(trendLen + 1); aMom = 2.0 / f64(momLen + 1); for (let q = 0; q < 4; q += 1) { const packed = fromPacked(q == 0 ? p_leading_ink() : q == 1 ? p_improving_ink() : q == 2 ? p_weakening_ink() : p_lagging_ink()); inkR[q] = red(packed); inkG[q] = green(packed); inkB[q] = blue(packed); } for (let i = 0; i < COINS * HIST; i += 1) { unchecked((histX[i] = NaN)); unchecked((histY[i] = NaN)); unchecked((histR[i] = NaN)); } } // onBar() runs once per chart bar: fold every hourly candle that closed with it (the first bar carries the backlog), // then read the newest hour's map, sort the coins, count the quadrants; on the live bar write the map and the card. function onBar(): void { const n = in_btc_cells(); if (n > 0) { const view = in_btc_view(); for (let c = 0; c < COINS; c += 1) unchecked((cursor[c] = 0)); for (let i = 0; i + TUPLE <= n; i += TUPLE) foldHour(unchecked(view[i]), unchecked(view[i + 4])); } const head = slotBack(0); const span = (tailPoints > 0 ? tailPoints : 1) * step; const back = slotBack(span); for (let c = 0; c < COINS; c += 1) { let s: f64 = NaN; let m: f64 = NaN; let mv: f64 = NaN; if (head >= 0) { s = unchecked(histX[c * HIST + head]); m = unchecked(histY[c * HIST + head]); const r = unchecked(histR[c * HIST + head]); const r0 = back >= 0 ? unchecked(histR[c * HIST + back]) : NaN; if (!isNaN(r) && !isNaN(r0)) mv = (Math.exp(r - r0) - 1.0) * 100.0; } strength[c] = s; momentum[c] = m; move[c] = mv; quadrant[c] = isNaN(s) || isNaN(m) ? -1 : quadrantOf(s, m); } // The coins by distance top-right, the leader first; coins without values last. for (let c = 0; c < COINS; c += 1) { let k = c; while (k > 0) { const prev = order[k - 1]; if (quadrant[c] < 0 || (quadrant[prev] >= 0 && diagonal(prev) >= diagonal(c))) break; order[k] = prev; k -= 1; } order[k] = c; } let leading = 0; let improving = 0; let weakening = 0; let lagging = 0; let ready = 0; for (let c = 0; c < COINS; c += 1) { const q = quadrant[c]; if (q < 0) continue; ready += 1; if (q == 0) leading += 1; else if (q == 1) improving += 1; else if (q == 2) weakening += 1; else lagging += 1; } const lead = order[0]; if (ready > 0) { out_leading(f64(leading)); out_improving(f64(improving)); out_weakening(f64(weakening)); out_lagging(f64(lagging)); out_leader_quadrant(f64(quadrant[lead])); } if (!bar.isLast()) return; // The card's title: the span the tail covers, in hours up to a day and a half, else in days. sb_clear(); sb_text("last "); if (span < 36) { sb_int(<i64>span); sb_text("h"); } else { sb_int(<i64>Math.round(f64(span) / 24.0)); sb_text("d"); } str_window_text_sb(); if (ready == 0) { // The hourly candles have not arrived yet: one line of words, no map, no headline. sb_clear(); sb_text("Loading the hourly candles for the rotation map"); notice.set(16.0, 12.0).text(str_notice_sb); noticeShown = true; return; } if (noticeShown) { notice.delete(); noticeShown = false; } writeMap(lead); // The headline: the leader and its move against BTC over the tail. sb_clear(); sb_text(unchecked(COIN_NAMES[lead])); if (!isNaN(move[lead])) { sb_text(move[lead] >= 0.05 ? " +" : " "); sb_f64(Math.abs(move[lead]) < 0.05 ? 0.0 : move[lead], 1); sb_text("%"); } str_leader_sb(); } ``` ## How it works **Hourly streams, not chart bars.** `input("close", ohlcv.close)` keeps the chart's own candles first, as the bar grid. `input("btc", candles.cells, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", interval: "1h", bars: 1500 })` streams BTC's closed hourly candles, the reference every coin is measured against, and eight more streams, `eth` to `link`, read the coins on the same venue at the same depth. Each stream starts at least 1500 hourly candles back (about two months): the first bar carries that backlog and each later bar the hours that closed with it, whatever the chart's interval. Streams, not `ohlcv` pins: a pin hands each chart bar one candle, so it reaches back only over the chart's own bars, too short on a 1m chart for averages of weeks, and a pin finer than the chart is refused, so a `1h` pin would refuse the whole run on a 4h or a 1d chart; a stream reaches back its own depth on any interval ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). An indicator counts against the plan's per-chart indicator limit once per distinct source it reads ([Limits](../reference/limits.md)), and these ten sources use the whole of a Plus chart's ten, so nothing else here reads a source: `bar.time()` would be an eleventh. The tail step reads the chart's interval from `chart.interval_sec()` instead, a hidden setting rather than a source, and the hours pair by offset, not by clock time. **Hours pair by offset, with BTC as the clock.** A block lists its hourly candles oldest first, six numbers each, `[offset_ms, open, high, low, close, volume]` (`TUPLE`), `offset_ms` being the candle's open minus this bar's open. `onBar()` walks BTC's block and folds one hour per BTC candle with `foldHour`, and `coinCloseAt` finds each coin's candle with the same `offset_ms` in that coin's block: both blocks run oldest first, so one cursor per coin walks its block once per bar. A coin hour missing from its block carries the coin's last close (`lastClose`). The first bar folds the whole backlog; after it, a bar folds the hours that closed with it: one every 60 bars on a 1m chart, one per bar on 1h, four per bar on 4h. **Strength and momentum, smoothed in days.** `onStart()` turns the three settings from days into hourly candles (`smooth` 14 is 336, `trend` 18 is 432, `momentum` 9 is 216) and each length n into an EMA weight of 2 / (n + 1). Per coin and per hour, `foldHour` takes r = ln(coin / BTC), the log of the coin's close over BTC's, and keeps s, its EMA over `smooth` days (`smoothed`). The strength is 100 plus how far s sits from its exponentially weighted mean over `trend` days, in units of its usual distance from it, the exponentially weighted standard deviation; the momentum is 100 plus how far the strength sits from its EMA over `momentum` days, in units of that gap's exponentially weighted root mean square, weighted over the same `trend` days. Both variances are divided by the share of weight their average has seen so far (`trendWeight`, `momWeight`), so the first readings are not inflated. The averages keep no list of past values: each hour updates them in a few steps, whatever the lengths. A coin has a strength once it has folded `trend` days of hours, and a momentum once it has `momentum` days of strength on top (27 days at the defaults); the largest settings with the longest tail need 1344 hours, inside the 1500 each stream brings. Every chart folds the same hours with the same averages, so a coin sits at the same place on 1m, 15m and 1h, and the map moves once an hour, when an hourly candle closes. Strength 100 is a smoothed ratio right on its longer average, so a coin crosses the vertical guide when its smoothed ratio moves above that average, and the horizontal one when the strength turns. **The tail follows the chart.** Every coin's strength, momentum and log ratio per hour sit in a ring (`histX`, `histY`, `histR`) of `HIST` slots a coin, 12 points at the 28-hour step plus the head, so the longest tail always fits; `slotBack(back)` finds the hour `back` hours before the newest, or -1 when the ring does not reach it. `onStart()` reads `p_chart_interval_sec()` and sets the tail step: 4 hours on charts up to 5m, so six points cover the last day; 12 hours up to 30m, three days; 28 hours on 1h and coarser, a week (0, an unknown interval, counts as a 15m chart). The tail is sampled back from the head, one point every step, `tail_points` points, so the spacing stays even up to the head. The move is the ratio's change over the same span, `tail_points` times the step (one step at 0 points), in percent, and the card's title names that span from the `window_text` slot, in hours under 36 and in days from 36 on: "last 24h", "last 3d" or "last 7d" at the defaults. **The leader and the counts.** On every bar `onBar()` reads the newest hour from the ring: each coin's strength, momentum and move. `quadrantOf` files each coin under 0 leading, 1 improving, 2 weakening or 3 lagging (strong is x above 100, rising is y above 100), or -1 while either number is NaN, and an insertion sort orders the coins by how far top right they sit, the largest (x - 100) + (y - 100) first (`diagonal`), coins without values last: the first is the leader. The counts `leading`, `improving`, `weakening` and `lagging` are data-only outputs (`none`), written with `leader_quadrant`, the leader's quadrant, on every bar where at least one coin has values. **One frame is the map.** On the live bar only, `writeMap` builds `frame("rotation_rows")` in the frame buffer with `fb_clear`, `fb_text`, `fb_int` and `fb_f64` and sends it with `writeFrameBuffer`: one row `[coin, x, y, size, colour, label]` per tail point and per head, and rows that share a coin form its trail, oldest first and the head last. Every head has a radius of 5 px (`HEAD_SIZE`), the same for every coin; tail dots grow from `TAIL_MIN` (1.5 px) at the far end toward `TAIL_MAX` (2.5 px) next to the head, and their alpha from `TAIL_ALPHA_MIN` (`0x26`) toward `TAIL_ALPHA_MAX` (`0x8c`). A tail stops at its first point without values, so it never jumps a gap. Labels sit on heads only: the leader's carries its move ("SOL +4.1%"), the others the name alone, and a move inside plus or minus 0.05% prints "0.0%" with no sign. `panel.scatter` draws the rows in a pane below the chart (`height_frac: 0.45`): `labels: true` with `label_overlap: "leader"` names each head, and since the leader is written first, where two names collide the pane moves the later one onto a leader line, never the leader's; `trails: true`, `trail_width: 1` and `trail_fade: true` draw a thin line between a coin's rows, fading toward the far end; two dashed `guides` at 100 cross the pane; and `quadrants` tints the four corners and names them. **The axes fit the dots.** Beside `rows`, the frame carries `x_min`, `x_max`, `y_min` and `y_max` from `fitAxis`: each axis spans the lowest to the highest head or tail point with 100 always inside and reaches at least 0.5 past 100 on both sides (`REACH_MIN`, half a usual distance), so a calm hour still shows a cross; the side of a guide with no dots still keeps 30% of the axis (`SIDE_MIN`), so its two quadrants stay readable; then 8% of room is added at both ends on x (`PAD_X`) and 15% on y (`PAD_Y`), where the quadrant words sit in the corners. The guides stay at 100 wherever the dots put them, and the frame's `quadrants` rewrites the four tints per run. **Four inks, written as hex.** `leading_ink`, `improving_ink`, `weakening_ink` and `lagging_ink` are `param.color` settings under the Quadrant colours section. A dot's colour is run data in the frame's rows, so the module writes it: `onStart()` reads the four picks with `fromPacked` and splits each into channels with `red`, `green` and `blue`, and `fbInk` writes a pick into the frame as `#rrggbb` (or `#rrggbbaa` for a tail dot or a tint), digit by digit from a 16-entry table, so a colour never allocates on the live bar. The dots, the trails and the tints follow the picks, the tints at alpha `0x0c` (`TINT_ALPHA`) in place of the declaration's literal ones. A colour word of the declaration may name a `param.color` instead, as `"@leading_ink"` ([Panel words](../presentation/cards-frames-panels.md#panel-words)); this source writes the picks into the frame, where the dots need them anyway. The picks colour the map only: the card's headline draws in the card's text colour. **The card reads slots and outputs.** `render.hud("rotation_card", { position: "top_left", title: "Rotation vs BTC, {{window_text}}", columns: 1, width: 210, safe_area: true, tiles: [...] })` is the card, drawn in the chart's default look since it names no `look` ([The default look](../presentation/hud-and-hover-cards.md#the-default-look)). `tile.pill("Leader", "leader", { headline: true })` reads the `leader` string slot, the leader and its move written with the `sb_*` builders on the live bar; `tile.rows` reads the `improving` and `weakening` outputs as integers. `{{window_text}}` in the title reads the slot the live bar writes ("last 24h", "last 3d" or "last 7d"), and `safe_area: true` starts the card under the legend stack. **One handle is the sentence.** `handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 12, style: "plain", safe_area: true })` declares the defaults and `draw.label(0)` makes the one handle at module load. While no coin has both a strength and a momentum, the live bar writes "Loading the hourly candles for the rotation map" into the `notice` slot and `notice.set(16.0, 12.0).text(str_notice_sb)` draws it in the muted colour 16 px in from the pane's top-right corner and 12 px down, past the price-axis tags, and skips the map and the headline. On the first live bar with a map, `notice.delete()` removes the line. ## Where it runs Any chart, any interval. The coins are always read from Binance Futures, so the chart's own market only changes the candles above the map, and the averages count the streams' hours, not the chart's bars, so the dots sit at the same place on every interval, and 4h and 1d charts show the 1h map with its week-long tail. On a daily chart the first draw takes longer, since a stream starts earlier when the chart has loaded more: the hourly candles reach back to the chart's first day. The map sits in its pane below the chart and the card at the top left of the price pane, under the legend stack (`safe_area: true`). ## When data is missing While no coin has both a strength and a momentum, one muted line at the top right of the price pane reads "Loading the hourly candles for the rotation map" and nothing else is drawn: no map, no headline. The card's title still names the span, since the `window_text` slot is written before the check; the `leader` slot and the five data outputs wait for a coin with both numbers, and the line goes on the first live bar that draws the map. Each stream brings at least 1500 hours, more than the 27 days a coin needs at the defaults and the 1344 hours of the largest settings with the longest tail, so the line shows while the hourly candles are still on their way. A coin hour missing from its block carries the coin's last close, so a short gap never empties the map; an hour missing from BTC's block is not folded at all, since BTC is the clock. A coin without values has no dot and is not counted, a tail stops at its first point without values, and when the hour the tail reaches back to has no ratio, the leader's label and the headline carry the name alone. ## Customize it - **Tail length.** `tail_points` (6, 0 to 12; 0 draws heads only) sets how many earlier positions each coin trails. The step between them follows the chart (4, 12 or 28 hours), and the move, the headline and the card's title follow the span the tail covers (one step at 0). - **The three averages.** `smooth` (14 days, 1 to 21) is the EMA on the ratio to BTC, `trend` (18 days, 3 to 28) the longer average the strength is measured from, and `momentum` (9 days, 1 to 14) the short average the momentum is measured from. Shorter averages stay smooth on a day-long tail but zigzag on a week-long one: a week of tail needs averages of weeks. Even the largest settings, with the longest tail, need only 1344 of the 1500 hours the streams bring. - **Quadrant colours.** The four `param.color` rows under Quadrant colours (`leading_ink` teal, `improving_ink` sky, `weakening_ink` amber, `lagging_ink` orange) recolour the dots, the trails and the tints. The card's headline stays in the card's text colour. - **Other coins.** Change the `symbol` in a coin's input line and the name at the same position in `COIN_NAMES` (keep eight); the venue ids and the spellings are in [Exchange and symbol format](../reference/symbol-format.md). - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic`; the Look row on the indicator's Style page also switches the card's look without code, As made (the default look) first ([The Style page](../settings/style-page.md#the-look-row)). Bind `look` to a `param.choice` over looks instead (`look: "@card_look"`) and the look becomes a setting, whose own row replaces the Look row ([Looks](../presentation/hud-and-hover-cards.md#looks)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Rotation Map** under **Beyond the time axis**. 2. Press **Run** on any chart, such as BTCUSDT on Binance Futures at 15m: once the hourly candles arrive, the map opens below the chart, and the card, titled "Rotation vs BTC, last 3d", appears at the top left of the price pane under the legend. Rest the pointer on a dot for its readout. 3. At the editor's Console prompt, type `last 20 leading` to read how many coins sat in the leading quadrant on each of the last 20 bars; on a 15m chart the count can change only once an hour, when an hourly candle closes. ## Concepts used - [Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream) for the `candles` stream, its `interval` and `bars`, the backlog on the first bar, and the pins a chart refuses - [Data sources](../core-concepts/data-sources.md#celled-sources) for celled sources, the `[offset_ms, open, high, low, close, volume]` tuple and the `in_<name>_cells()` / `in_<name>_view()` readers - [Sessions and units](../settings/sessions-and-units.md#the-interval-and-the-colours) for `chart.interval_sec()`, the chart's bar interval as a hidden setting - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames and the frame buffer, `panel.scatter` with `guides`, `quadrants`, `trails`, `labels` and the frame's axis ends, and the pixel offsets of an anchored handle - [Panel words](../presentation/cards-frames-panels.md#panel-words) for the colour words a `param.color` can drive as `"@name"` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `columns`, `width` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name and a look bound to a `param.choice` - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` and `tile.rows` - [Drawing objects](../presentation/drawing-objects.md) for `handles.label`, `draw.label(id)` and its `set`, `text` and `delete` - [The Style page](../settings/style-page.md#the-look-row) for the Look row and `param.color` - [Colors kit](../functions/colors-kit.md) for `fromPacked`, `red`, `green` and `blue` <!-- source: https://openmarket.xyz/wrun/cookbook/correlation-matrix --> # Correlation matrix ![An 8 by 8 correlation grid below a BTC chart, in the up colour where the markets moved together with the gold and euro rows empty, and a card at the top right reading the average, the most tied and the most free market](/wrun/images/correlation-matrix.png) How this chart's market moved with eight crypto perpetuals over the last `window` bars, as a market by market grid below the chart: the Binance Futures BTC, ETH, SOL, BNB, XRP, DOGE, ADA and AVAX perpetuals. One row and one column per market, the chart's own market first on both axes and its row label lit. A cell in the up colour is a pair that moved together over the window, a cell in the down colour a pair that moved apart, a cell in the chart's own surface colour no relation; every cell prints its correlation with two decimals and opens a hover card ("Market BTC · vs ETH"). An empty cell is a pair that shared too few bars in the window (a coin listed after the window began, or a market whose candles the chart's bars cannot join); its row and column keep their names. An Avg row under the grid gives every market its average with the others. The pane's legend reads the title and a count, "Correlation of returns, 96 bars · BTC moves with 0 of 7": how many markets moved with the chart's market at or above the `strong` setting, counted over the markets that could be measured. A card at the top right, under the chart's High tag, in the chart's default look, reads the chart market's average correlation with the others as the headline (the up colour at or above `strong`, muted between, the down colour below zero), then the market it is most tied to and the one it is most free of, each with its reading. When the chart is one of the eight markets (a Binance Futures BTC or ETH perpetual chart), that row carries the market's name and the grid is 8 by 8; on any other crypto market the first row is named "Chart" and the grid is 9 by 9. Correlation is written for crypto charts: on a chart whose candles carry no volume (forex, gold, silver) it draws no grid, the card's headline reads "Not crypto", and one sentence under the card names the way out. The parts are ten inputs over nine sources, the chart's own `ohlcv.close` first and its `ohlcv.volume` from the same candles, then eight `ohlcv.close` inputs pinned by `exchange` and `symbol` to Binance Futures perpetuals with `missing: "nan"` ([Data sources](../core-concepts/data-sources.md), [Multi-source and aggregation](../core-concepts/multi-source.md)), a frame feeding `panel.heatmap` on category axes with a palette scale, a highlight row, a caption and a summary row ([Cards, frames and panels](../presentation/cards-frames-panels.md)), a `render.hud` card of a headline `tile.pill` and a `tile.rows` in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)), and a label handle for the one sentence that stands in for the grid while the window loads or on a chart that is not crypto ([Drawing objects](../presentation/drawing-objects.md)). This is also the `correlation-matrix` template: the **Correlation Matrix** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Correlation Matrix: how this chart's market moved with eight crypto perpetuals over the last 'window' bars (the // Binance Futures BTC, ETH, SOL, BNB, XRP, DOGE, ADA and AVAX perpetuals), as a market by market heatmap below the // chart. Up-colour cells moved together, down-colour cells apart, the surface colour no relation, and an empty cell is // a pair with too few shared bars in the window (a coin listed after the window began, or one whose candles the // chart's bars cannot join); its row keeps its name. The chart's own market is the first row and column; when it is // one of the eight, that row carries the market's name and the grid is 8 by 8. The card reads the chart market's // average correlation with the others, the market it is most tied to and the one it is most free of; the panel's // legend counts how many moved with it above the 'strong' setting, and an Avg row under the grid gives every market // the same reading. The trader sees in one glance whether the market is trading on its own or as one of the crowd, // and which market to watch as a lead or a hedge. Correlation is written for crypto charts: on a chart whose candles // carry no volume (forex, gold, silver) it says so in one sentence with the way out, and draws no grid. section("Window"); param.int("window", 96, { min: 30, max: 500, label: "Window in bars", description: "Bars in the correlation window" }); param.number("strong", 0.7, { min: 0.3, max: 0.95, step: 0.05, label: "Strong correlation", description: "Correlation at or above which two markets count as moving together" }); // Inputs: the chart's own close is the grid and the first row, its volume tells a crypto chart from a quote-only // one (forex, gold and silver candles carry none; the same candles, so no extra source); the eight pins join by // timestamp and read NaN on a bar their market has no candle for, so a missing candle never fabricates a return. input("close", ohlcv.close, { description: "This chart's close: the first row and column of the grid" }); input("volume", ohlcv.volume, { description: "This chart's volume: candles that never carry any (forex, gold, silver) mark a chart that is not crypto" }); input("btc", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "BTCUSDT", missing: "nan", description: "Bitcoin, Binance Futures perpetual" }); input("eth", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "ETHUSDT", missing: "nan", description: "Ether, Binance Futures perpetual" }); input("sol", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "SOLUSDT", missing: "nan", description: "Solana, Binance Futures perpetual" }); input("bnb", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "BNBUSDT", missing: "nan", description: "BNB, Binance Futures perpetual" }); input("xrp", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "XRPUSDT", missing: "nan", description: "XRP, Binance Futures perpetual" }); input("doge", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "DOGEUSDT", missing: "nan", description: "Dogecoin, Binance Futures perpetual" }); input("ada", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "ADAUSDT", missing: "nan", description: "Cardano, Binance Futures perpetual" }); input("avax", ohlcv.close, { exchange: "BINANCE_FUTURES", symbol: "AVAXUSDT", missing: "nan", description: "Avalanche, Binance Futures perpetual" }); // Outputs are data-only, written on the live bar: the card, the Console and a watch read the same numbers. output("avg_corr", none, overlay, { format: "0.00", description: "The chart market's average correlation with the other markets in the grid" }); output("tone", none, overlay, { description: "0 moving apart, 1 loosely related, 2 moving together, NaN with no reading: the headline's colour" }); output("strong_count", none, overlay, { description: "How many of the other markets correlate with the chart's market at or above 'strong'" }); output("served_count", none, overlay, { description: "How many of the other markets had enough bars in the window to be measured" }); output("bars", none, overlay, { format: "int", description: "The window in bars, read by the card's title" }); string("avg_text", { max_bytes: 24 }); // "0.62 avg" string("tied_text", { max_bytes: 24 }); // "ETH 0.91" string("free_text", { max_bytes: 24 }); // "AVAX 0.12" string("note", { max_bytes: 80 }); // the one sentence: the window still loading, or a chart that is not crypto // The one sentence: a muted plain label at the top right of the price pane, under the card. handles.label({ text: "note", anchor: "top_right", align: "right", color: "theme.muted", size: 11, style: "plain", safe_area: true }); const note = draw.label(0); const NOTE_Y: f64 = 200.0; // pixels down from the top-right corner: under the card, which ends about 172 px down // The grid: one cell per market pair, the down colour at -1 through the chart surface at 0 to the up colour at +1, // every cell printed with two decimals, a hover card per cell, the chart's own row lit in the row labels. const grid = frame("grid", { max_bytes: 8192 }); panel.heatmap({ name: "corr_grid", title: "Correlation of returns", x: "category", place: "below", frame: grid, scale: "palette", palette: ["theme.down", "theme.bg", "theme.up"], min: -1, max: 1, row_title: "Market", col_title: "vs", format: "0.00", hover_card: true, height_frac: 0.35 }); // The card, below the chart's own High tag: the window in the title, the average correlation as the headline (the down // colour apart, muted loose, the up colour together; muted words when there is no reading), then the most tied and the // most free market with their readings. The headline is a big number: its words stay short enough to fit the card. render.hud("card", { position: "top_right", title: "Correlation, last {{bars:int}} bars", columns: 1, width: 250, offset: [0, 24], safe_area: true, tiles: [ tile.pill("Average with the others", "avg_text", { headline: true, color_by: "tone", colors: ["theme.down", "theme.muted", "theme.up"], color: "theme.muted" }), tile.rows([["Most tied", "tied_text"], ["Most free", "free_text"]]), ] }); const SERIES = 9; // the chart's market plus the eight pins const MAX_WINDOW = 500; const MAX_RING = MAX_WINDOW + 1; // 'window' returns need 'window' + 1 closes const NAMES: StaticArray<string> = ["Chart", "BTC", "ETH", "SOL", "BNB", "XRP", "DOGE", "ADA", "AVAX"]; const closes = new StaticArray<f64>(SERIES * MAX_RING); // the ring of closes, one row per series const rets = new StaticArray<f64>(SERIES * MAX_WINDOW); // the window's log returns per series, oldest first const corr = new StaticArray<f64>(SERIES * SERIES); // the live grid, NaN where a pair has too few bars const order = new StaticArray<i32>(SERIES); // the series behind each grid row: the chart first, then the pins const colAvg = new StaticArray<f64>(SERIES); // each column's average with the other markets (the Avg row) let window = 96; let strong = 0.7; let ring = 97; let minPairs = 48; // the params, read in onStart() let head = -1; let count = 0; // the ring: head is the newest slot, count the slots in use let rows = SERIES; let chartName = "Chart"; // the grid's size and the chart row's name this run let volumeSeen = false; // a bar of the chart carried volume: every crypto market trades some, quote-only candles never do function readSeries(s: i32): f64 { switch (s) { case 1: return in_btc(); case 2: return in_eth(); case 3: return in_sol(); case 4: return in_bnb(); case 5: return in_xrp(); case 6: return in_doge(); case 7: return in_ada(); case 8: return in_avax(); default: return bar.close(); } } function slotAt(k: i32, used: i32): i32 { return (head - used + 1 + k + MAX_RING) % MAX_RING; } // the k-th oldest of 'used' slots function sameClose(a: f64, b: f64): bool { return Math.abs(a - b) <= 1e-9 * Math.max(1.0, Math.abs(a)); } // At or above 'strong' as the cells print it, two decimals: a 0.6955 cell reads 0.70 and counts at 0.70. function isStrong(r: f64): bool { return Math.round(r * 100.0) >= Math.round(strong * 100.0); } // The pin that is this chart's own market, if any: its closes equal the chart's on every bar both have (the forming // bar may lag by a tick, so one mismatch is allowed). That row is dropped and the chart row takes its name. function duplicatePin(used: i32): i32 { for (let p = 1; p < SERIES; p += 1) { let present = 0; let equal = 0; for (let k = 0; k < used; k += 1) { const slot = slotAt(k, used); const a = closes[slot]; const b = closes[p * MAX_RING + slot]; if (isNaN(a) || isNaN(b)) continue; present += 1; if (sameClose(a, b)) equal += 1; } if (present >= 2 && equal >= present - 1) return p; } return 0; } // Log returns of every series over the window, NaN where either close is missing. function buildReturns(used: i32): i32 { const n = used - 1; for (let s = 0; s < SERIES; s += 1) { for (let k = 0; k < n; k += 1) { const a = closes[s * MAX_RING + slotAt(k, used)]; const b = closes[s * MAX_RING + slotAt(k + 1, used)]; rets[s * MAX_WINDOW + k] = a > 0.0 && b > 0.0 ? Math.log(b / a) : NaN; } } return n; } // Pearson correlation of two series over the bars both have; NaN under 'minPairs' bars or a flat series. function pearson(a: i32, b: i32, n: i32): f64 { let m = 0; let sx = 0.0; let sy = 0.0; let sxx = 0.0; let syy = 0.0; let sxy = 0.0; for (let k = 0; k < n; k += 1) { const x = rets[a * MAX_WINDOW + k]; const y = rets[b * MAX_WINDOW + k]; if (isNaN(x) || isNaN(y)) continue; m += 1; sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y; } if (m < minPairs) return NaN; const vx = sxx - (sx * sx) / f64(m); const vy = syy - (sy * sy) / f64(m); if (!(vx > 0.0) || !(vy > 0.0)) return NaN; const r = (sxy - (sx * sy) / f64(m)) / Math.sqrt(vx * vy); return r > 1.0 ? 1.0 : r < -1.0 ? -1.0 : r; } function buildGrid(n: i32): void { for (let i = 0; i < rows; i += 1) { for (let j = i; j < rows; j += 1) { const r = pearson(order[i], order[j], n); corr[i * SERIES + j] = r; corr[j * SERIES + i] = r; } } for (let j = 0; j < rows; j += 1) { // the Avg row: each column against the other markets let sum = 0.0; let m = 0; for (let i = 0; i < rows; i += 1) { if (i == j) continue; const r = corr[i * SERIES + j]; if (isNaN(r)) continue; sum += r; m += 1; } colAvg[j] = m > 0 ? sum / f64(m) : NaN; } } function writeGrid(strongCount: i32, served: i32): void { // [column market, row market, correlation] per cell, null where unmeasured fb_clear(); fb_text("{\"title\":\"Correlation of returns, "); fb_int(<i64>window); fb_text(" bars\",\"caption\":\""); fb_text(chartName); fb_text(" moves with "); fb_int(<i64>strongCount); fb_text(" of "); fb_int(<i64>served); fb_text("\",\"highlight\":{\"row\":"); fb_str(chartName); fb_text("},\"rows\":["); for (let i = 0; i < rows; i += 1) { for (let j = 0; j < rows; j += 1) { if (i > 0 || j > 0) fb_text(","); fb_text("["); fb_str(order[j] == 0 ? chartName : NAMES[order[j]]); fb_text(","); fb_str(order[i] == 0 ? chartName : NAMES[order[i]]); fb_text(","); fb_f64(corr[i * SERIES + j], 2); fb_text("]"); } } fb_text("],\"summary\":[{\"label\":\"Avg\",\"values\":["); for (let j = 0; j < rows; j += 1) { if (j > 0) fb_text(","); fb_f64(colAvg[j], 2); } fb_text("]}]}"); writeFrameBuffer(FRAME_GRID); } // A state with no grid: the one sentence under the card, and the card's headline for that state with a dash per row. function sayInstead(sentence: string, headline: string): void { sb_clear(); sb_text(sentence); note.set(0.0, NOTE_Y).text(str_note_sb); sb_clear(); sb_text(headline); str_avg_text_sb(); sb_clear(); sb_text("-"); str_tied_text_sb(); sb_clear(); sb_text("-"); str_free_text_sb(); } // onStart() runs once before the first bar: read the params and size the ring to the window. function onStart(): void { window = i32(p_window()); strong = p_strong(); ring = window + 1; minPairs = (window + 1) / 2; } // onBar() runs once per bar: push every close into the ring and note whether the chart's candles carry volume; on // the live bar, measure the grid and write the panel, the card's words and the outputs, or the one sentence when // the chart is not crypto or the window is not full yet. function onBar(): void { head = (head + 1) % MAX_RING; if (count < ring) count += 1; for (let s = 0; s < SERIES; s += 1) closes[s * MAX_RING + head] = readSeries(s); if (in_volume() > 0.0) volumeSeen = true; if (!bar.isLast()) return; out_bars(f64(window)); if (!volumeSeen) { // no candle carried volume: a forex, gold or silver chart, so no grid sayInstead("Correlation is written for crypto charts: switch to a BTC or ETH perp", "Not crypto"); return; } if (count < window) { // fewer bars than the window: no grid yet sayInstead("Loading more history for the correlation window", "Loading"); return; } note.delete(); const used = count < ring ? count : ring; const dup = duplicatePin(used); chartName = dup > 0 ? NAMES[dup] : "Chart"; rows = 0; order[rows] = 0; rows += 1; for (let p = 1; p < SERIES; p += 1) if (p != dup) { order[rows] = p; rows += 1; } buildGrid(buildReturns(used)); // The chart's row: its average with the others, the most tied and most free markets, the count above 'strong'. let sum = 0.0; let served = 0; let strongCount = 0; let tied = -1; let free = -1; for (let j = 1; j < rows; j += 1) { const r = corr[j]; if (isNaN(r)) continue; sum += r; served += 1; if (isStrong(r)) strongCount += 1; if (tied < 0 || r > corr[tied]) tied = j; if (free < 0 || r < corr[free]) free = j; } const avg = served > 0 ? sum / f64(served) : NaN; out_avg_corr(avg); out_strong_count(f64(strongCount)); out_served_count(f64(served)); out_tone(isNaN(avg) ? NaN : avg < 0.0 ? 0.0 : isStrong(avg) ? 2.0 : 1.0); sb_clear(); if (served > 0) { sb_f64(avg, 2); sb_text(" avg"); } else sb_text("No pairs"); str_avg_text_sb(); sb_clear(); if (tied >= 0) { sb_text(NAMES[order[tied]]); sb_text(" "); sb_f64(corr[tied], 2); } else sb_text("-"); str_tied_text_sb(); sb_clear(); if (free >= 0) { sb_text(NAMES[order[free]]); sb_text(" "); sb_f64(corr[free], 2); } else sb_text("-"); str_free_text_sb(); writeGrid(strongCount, served); } ``` ## How it works **Nine closes ride one grid.** `input("close", ohlcv.close)` is the chart's own close: the grid every other input is joined onto, and the first row and column. `input("volume", ohlcv.volume)` reads the volume of the same candles, so it adds no source; it only tells a crypto chart from a quote-only one (below). The eight pins (`btc`, `eth`, `sol`, `bnb`, `xrp`, `doge`, `ada` and `avax`, every one on `BINANCE_FUTURES`) are joined by timestamp at the chart's interval and read NaN on a bar their market has no candle for, by `missing: "nan"`, so a missing candle never fabricates a return. `ADAUSDT` and `AVAXUSDT` replaced the gold and euro pins on `FX_OTC`, so every pinned market is served wherever crypto is. Every bar pushes all nine closes into a ring sized at load for the largest window (`MAX_WINDOW` 500, plus one close: `window` returns need `window` + 1 closes). **The grid is measured on the live bar.** `onBar()` returns after the push and the volume check until `bar.isLast()`. On the live bar it writes `bars`, then stops at either state that draws no grid (below). Past them, `buildReturns()` turns the last `window` + 1 closes of every series into per-bar log returns (NaN where either close is missing), and `pearson()` measures each pair over the bars both markets have: fewer than `(window + 1) / 2` shared bars, or a flat series, reads NaN, an empty cell, and the rest is clamped to [-1, 1]. `buildGrid()` fills the pairs and the Avg row, each column's average with the other markets. The chart's row gives the card its numbers: the average over the served markets, the most tied and the most free, and the count at or above `strong`. `isStrong()` compares the correlation as the cells print it, rounded to two decimals, so a 0.6955 cell that reads 0.70 counts at a `strong` of 0.70, and the headline's up colour follows the printed average the same way. **A duplicate pin folds into the chart row.** `duplicatePin()` looks for a pin whose closes equal the chart's on every bar both have (one mismatch allowed, since the forming bar may lag by a tick). That pin's row is dropped and the chart row takes its name, so a Binance Futures BTC chart reads an 8 by 8 grid with "BTC" first, and a Binance spot ETH chart reads 9 by 9 with "Chart" first and the ETH perpetual at 1.00. **One frame is the grid.** `writeGrid()` builds `frame("grid")` through the `fb_*` builder and sends it with `writeFrameBuffer(FRAME_GRID)`: a `title` ("Correlation of returns, 96 bars"), a `caption` ("BTC moves with 0 of 7"), a `highlight` on the chart's row, one `[column market, row market, correlation]` row per cell with `null` where a pair is unmeasured, and one `summary` row, "Avg". `panel.heatmap` reads it below the chart on category axes: `scale: "palette"` with `palette: ["theme.down", "theme.bg", "theme.up"]` between `min: -1` and `max: 1` paints the down colour at -1, the chart's surface at 0 and the up colour at +1, with fixed bounds; `format: "0.00"` prints every cell; `row_title: "Market"` and `col_title: "vs"` word the hover card; `height_frac: 0.35` is the pane's share of the chart. The caption prints on the pane's legend after the title. **The card reads slots and outputs.** `avg_corr`, `tone`, `strong_count`, `served_count` and `bars` are data-only outputs (`none`) written on the live bar (`bars` in every state, the other four once the grid is measured), so the card, the Console and a watch read the same numbers. The words are string slots built with `sb_*` on the same bar ([Strings and text](../functions/text-formatting.md)): `avg_text` ("0.49 avg"), `tied_text` ("ETH 0.69") and `free_text` ("AVAX 0.31"). `render.hud("card", ...)` at `top_right` declares no `look`, so it draws the chart's default look: `title: "Correlation, last {{bars:int}} bars"` reads the `bars` output into the title, the headline `tile.pill` prints `avg_text` coloured by the `tone` ladder (0 the down colour, moving apart; 1 muted, loosely related; 2 the up colour, at or above `strong`), and `tile.rows` lists Most tied and Most free. The pill also declares `color: "theme.muted"`, the ladder's fallback where `tone` is not finite, so with no reading the words print muted while `tone` stays NaN for a watch. The headline is the card's large type (17 px bold in the default look), so the words of a state with no reading stay short enough for the 250 px card: "Not crypto", "Loading", "No pairs". `offset: [0, 24]` drops the card under the chart's High tag, `safe_area: true` keeps it clear of the price-axis tags, and `columns: 1` with `width: 250` keeps it narrow. **Volume tells a crypto chart.** Every crypto market trades some volume, while forex, gold and silver candles are quotes that carry none, so any bar whose `in_volume()` is above 0 marks the chart as crypto (`volumeSeen`). On the live bar this check comes first: a chart where no bar carried volume gets no grid. `writeGrid()` never runs, so the frame stays unwritten and the pane is absent (no empty pane), and the card and the sentence say why (below). Volume, not the bar clock: reading `bar.time()` would add a `time` source, a tenth, and the chart counts an indicator against your plan's per-chart indicator limit once per distinct source it reads, while the chart's volume rides the candles its close already reads ([How many sources you can open](../core-concepts/data-sources.md#how-many-sources-you-can-open)). **One sentence instead of a grid.** `handles.label({ text: "note", anchor: "top_right", style: "plain", color: "theme.muted", safe_area: true, ... })` declares one plain, muted label kind pinned to the top right of the price pane, and `draw.label(0)` is its one handle. `sayInstead(sentence, headline)` writes a state with no grid: the sentence into the `note` slot, placed by `note.set(0.0, NOTE_Y).text(str_note_sb)` at `NOTE_Y` (`200.0` pixels down from the top-right corner, under the card, which ends about 172 px down), the headline into `avg_text`, and a dash into `tied_text` and `free_text`. A chart that is not crypto gets "Correlation is written for crypto charts: switch to a BTC or ETH perp" with the headline "Not crypto"; while fewer bars than `window` are loaded, it gets "Loading more history for the correlation window" with "Loading". Once the grid is measured, `note.delete()` removes the sentence. ## Where it runs Crypto charts at any interval, spot and perpetual, on any venue: the eight pins are Binance Futures perpetuals, served wherever crypto is, and they join the chart's bars by timestamp at its interval. A Binance Futures BTC chart reads an 8 by 8 grid with BTC first; a Binance spot ETH chart reads 9 by 9 with "Chart" first and the ETH perpetual at 1.00. A forex, gold or silver chart carries no volume, so it gets the "Not crypto" card and the sentence instead of a grid (below). A US stock or CME chart carries volume, so the grid runs over its session bars, and a pin whose candles cannot join them stays an empty row with its name. The chart's own round button at the bottom left sits over the last row's label in the panel's gutter (the AVAX row); the hover card still names the row. ## When data is missing With fewer bars loaded than `window`, the chart draws no grid yet: the card's headline reads "Loading" in the muted colour with a dash on each row (a HUD card is never hidden per run), and one sentence sits under the card, "Loading more history for the correlation window". Once the window is full the sentence goes and the grid draws. On a chart whose candles carry no volume (forex, gold, silver) no grid is drawn at all: the frame stays unwritten, so the panel is absent (no empty pane), the headline reads "Not crypto" in the muted colour with a dash on each row, and one muted sentence sits under the card, "Correlation is written for crypto charts: switch to a BTC or ETH perp". A market the chart's bars cannot join over the window (a coin listed after the window began, or a pin whose candles miss the chart's bar times) keeps its row and column with their names and empty cells, and the legend's "N of M" counts only the markets that could be measured. A pair with fewer than half the window in shared bars, or a flat series, is an empty cell; when no market can be measured against the chart's own, the headline reads "No pairs" and the Most tied and Most free rows print a dash. `missing: "nan"` fills the bars a served market has no candle for; a pinned market the chart does not serve at all is another case. Today the chart stops the whole run when a pin is declined or answers empty, with a message that the pinned market's candle data is unavailable, whatever `missing` says. The eight pins are served wherever crypto is, so this reaches only a pin swapped to a market the chart does not serve. ## Customize it - **A longer window.** `window` (96 bars, from 30 to 500) is how many bars the returns are measured over; a pair needs at least half of it in shared bars, the grid waits until that many bars are loaded, and the card's title and the pane's legend read the new count. - **A stricter "moves with".** `strong` (0.7, from 0.3 to 0.95 in steps of 0.05) is the correlation at or above which a market counts in the legend's count and the headline turns to the up colour, compared at the two decimals the cells print. - **Other markets.** A pin is one input line and one name: edit the line's `exchange`, `symbol` and `description` to another crypto market (spellings on [Exchange and symbol format](../reference/symbol-format.md)), and its name at the same place in `NAMES`, the list the grid's rows and the card's words print ("Chart" first, then the pins in the order `readSeries()` reads them). Keep `missing: "nan"` so a missing candle never fabricates a return, and pick a market the chart serves: a pin it declines stops the run today (above). - **A taller pane.** `height_frac: 0.35` is the pane's share of the chart (0.05 to 0.9); raise it when a 9 by 9 grid crowds the row labels on a short chart. - **A look of its own.** This source writes no `look`, so the card draws the chart's default look, and the Look row on the indicator's Style page switches it between the twelve looks without code, "As made" first ([The Style page](../settings/style-page.md#the-look-row)). Write `look: "@name"` over a `param.choice` of looks and the look becomes a setting, its row the look's one control in place of the Look row ([Looks](../presentation/hud-and-hover-cards.md#looks)). The grid's colours are theme words, and every colour word of a panel declaration, a `palette` entry included, may name a `param.color` as "@name" ([Panel words](../presentation/cards-frames-panels.md#panel-words)): `palette: ["@apart", "theme.bg", "@together"]` beside two `param.color` settings puts the two ends of the scale on the Style page. The pill's ladder and the sentence's muted colour stay literals, since a tile and a `handles.*` default take no setting. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Correlation Matrix** under **Beyond the time axis**. 2. Press **Run** on BTCUSDT on Binance Futures at 15m: the grid fills the pane below the chart with BTC first, the pane's legend counts the markets that moved with it, and the card appears at the top right under the High tag. Rest the pointer on a cell to read its pair. 3. At the editor's Console prompt, type `outputs` to read the newest value of every output: the average, its tone, the strong and served counts and the window. Every output is written on the live bar, so the newest row is the whole story. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for `ohlcv.close`, `ohlcv.volume`, the `missing: "nan"` policy and how the chart counts sources - [Multi-source and aggregation](../core-concepts/multi-source.md) for pinning another market by `exchange` and `symbol` - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, the `fb_*` builder, `panel.heatmap`, its palette scale, `caption`, `highlight` and `summary`, and the panel colour words a `param.color` can drive - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, `offset` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name and a look bound to a `param.choice` - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill`, its ladder with its fallback `color`, and `tile.rows` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Drawing objects](../presentation/drawing-objects.md) for `handles.label`, the plain style and the `draw.label` handle - [Strings and text](../functions/text-formatting.md) for the `sb_*` builders and the string slots <!-- source: https://openmarket.xyz/wrun/cookbook/venue-share --> # Venue share ![Venue share donut and venue table under BTC candles, with a card at the top right naming the widest premium](/wrun/images/venue-share.png) Where BTC is trading right now. Below the candles, a donut gives each venue's share of the last 24 hours of dollar volume (this chart's venue in teal, Bybit sky, OKX violet, Coinbase rose, Binance spot slate, the total in the hole). Under it, a table lists every venue with its last price, its premium to this chart's price in basis points (signed, in the chart's up colour above and down colour below, bold and tinted once it is wide), its 24h dollar volume as an inline bar and its share. A card at the top right, in the chart's default look, leads with the widest premium ("Coinbase +4.6 bp"), in the muted colour while it is within the highlight and in the chart's up or down colour once it is wide, then the largest venue with its share and the high-low spread across the venues. The legend names the hours in use ("Venue Share 24h"). Every number is measured on the live bar; history bars only fill the volume window. The parts are the chart's own close and volume plus four pinned closes and volumes, Bybit BTCUSDT, OKX BTC-USDT-SWAP, Coinbase BTC-USD and Binance spot BTCUSDT, each with `missing: "nan"` ([Multi-source and aggregation](../core-concepts/multi-source.md), [Data sources](../core-concepts/data-sources.md)); two frames feeding a `panel.pie` donut and a `panel.table` of styled cells ([Cards, frames and panels](../presentation/cards-frames-panels.md)); five `param.color` venue inks and a `param.text` for the chart's own row name ([Setting kinds](../settings/kinds.md)); `chart.interval_sec()` turning hours into bars ([Sessions and units](../settings/sessions-and-units.md#chart-context)); a `render.hud` card in the default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)); and one `draw.label` handle for the line of words on a chart that is not a BTC market ([Drawing objects](../presentation/drawing-objects.md)). This is also the `venue-share` template: the **Venue Share** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Venue Share: where BTC is trading right now. The trader sees a donut below the candles with each venue's share of // the last 24 hours of dollar volume (this chart's venue in teal, Bybit sky, OKX violet, Coinbase rose, Binance spot // slate, the total in the hole), under it a table of venue, last price, premium to this chart's price in basis // points (signed, up colour above, down colour below, bold and tinted past the highlight), 24h dollar volume as an // inline bar and the share; and a card at the top right: the widest premium as its headline // ("Coinbase +12.3 bp"), the largest venue with its share, and the high-low spread across the venues. Every number // is measured on the live bar; history bars only fill the volume window. On a chart that is not a BTC market the // example writes one line of words at the top right and nothing else. param.int("hours", 24, { min: 1, max: 168, label: "Window in hours", description: "Hours of dollar volume behind the shares (bars = hours / the chart interval, at most 10080 bars)" }); param.number("highlight_bp", 5, { min: 1, max: 50, step: 0.5, label: "Wide premium, basis points", description: "A premium at or past this many basis points reads wide: bold and tinted in the table, the card's tone" }); param.text("chart_label", "This chart", { max_bytes: 24, label: "Chart venue name", hint: "How this chart's venue is named in the donut and the table" }); section("Venue colours"); param.color("chart_ink", "#2dd4bf", { label: "This chart" }); param.color("bybit_ink", "#38bdf8", { label: "Bybit perp" }); param.color("okx_ink", "#a78bfa", { label: "OKX perp" }); param.color("coinbase_ink", "#fb7185", { label: "Coinbase" }); param.color("binance_ink", "#94a3b8", { label: "Binance spot" }); chart.interval_sec(); // the bar interval in seconds, so hours become bars without reading the bar time legend({ title: "{{hours}}h" }); // Inputs: the chart's own candles are the grid and the reference price; four BTC venues ride beside them as pinned // closes and volumes, NaN on a bar the venue did not report (missing: "nan"), so a silent venue contributes nothing. input("close", ohlcv.close); input("volume", ohlcv.volume); input("bybit_close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BYBIT", missing: "nan", description: "Bybit BTCUSDT perpetual close" }); input("bybit_volume", ohlcv.volume, { symbol: "BTCUSDT", exchange: "BYBIT", missing: "nan", description: "Bybit BTCUSDT perpetual volume, coins" }); input("okx_close", ohlcv.close, { symbol: "BTC-USDT-SWAP", exchange: "OKEX_SWAP", missing: "nan", description: "OKX BTC-USDT perpetual swap close" }); input("okx_volume", ohlcv.volume, { symbol: "BTC-USDT-SWAP", exchange: "OKEX_SWAP", missing: "nan", description: "OKX BTC-USDT perpetual swap volume, coins" }); input("coinbase_close", ohlcv.close, { symbol: "BTC-USD", exchange: "COINBASE", missing: "nan", description: "Coinbase BTC-USD spot close" }); input("coinbase_volume", ohlcv.volume, { symbol: "BTC-USD", exchange: "COINBASE", missing: "nan", description: "Coinbase BTC-USD spot volume, coins" }); input("binance_close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE", missing: "nan", description: "Binance BTCUSDT spot close" }); input("binance_volume", ohlcv.volume, { symbol: "BTCUSDT", exchange: "BINANCE", missing: "nan", description: "Binance BTCUSDT spot volume, coins" }); // Outputs: data only, one value per bar, so the Console reads the card's numbers and they have history. output("widest_bp", none, overlay, { format: "0.0", unit: " bp", description: "The widest venue premium to this chart's price, basis points, signed" }); output("spread_bp", none, overlay, { format: "0.0", unit: " bp", description: "Highest venue price minus the lowest, as basis points of this chart's price" }); output("top_share", none, overlay, { format: "%", decimals: 1, description: "The largest venue's share of the window's dollar volume, percent" }); output("premium_tone", none, overlay, { description: "The card's tone: 0 the widest premium is within the highlight (muted), 1 above and wide (up colour), 2 below and wide (down colour)" }); // The card's words, written on the live bar only. string("headline_text", { max_bytes: 32 }); // "Coinbase +12.3 bp" string("largest_text", { max_bytes: 32 }); // "Bybit 34.1%" string("spread_text", { max_bytes: 16 }); // "23.4 bp" string("notice_text", { max_bytes: 48 }); // the one line of words on a chart that is not a BTC market string("window_text", { max_bytes: 8 }); // "24h": the card title's window, written on the live bar // The donut and the table, written on the live bar only; the frames carry the rows and the per-run words. const shareRows = frame("share_rows", { max_bytes: 2048 }); const venueRows = frame("venue_rows", { max_bytes: 4096 }); panel.pie({ name: "share", title: "Share of dollar volume", x: "category", place: "below", frame: shareRows, hole: 0.62, labels: false, legend_style: "title", hole_total: true, hole_caption: "24h volume", slice_gap: 2, format: "usd", chrome: "none", height_frac: 0.25 }); // no frame around the ring (a pie with no chrome draws the box); the venues ride the title and the table, so the ring and its hole text keep the whole pane panel.table({ name: "venues", title: "Venues", x: "category", place: "below", frame: venueRows, height_frac: 0.185, position: "top_center", font_size: 10, cell_padding: 3, valign: "middle", header_text_color: "theme.muted", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", border_width: 0, column_widths: [120, 100, 100, 150, 80], series: [ { name: "Venue" }, { name: "Last", align: "right", format: "price" }, { name: "Premium", align: "right", format: "0.0", signed: true, unit: " bp" }, { name: "24h volume", align: "right", format: "usd" }, { name: "Share", align: "right", format: "%", decimals: 1 }, ], }); // The card: the widest premium leads as the headline, lit in the chart's up or down colour once it is wide, then the // largest venue and the high-low spread as two rows. render.hud("venues_card", { position: "top_right", safe_area: true, title: "BTC across venues, {{window_text}}", columns: 1, width: 290, tiles: [ tile.pill("Widest premium", "headline_text", { headline: true, font_size: 20, color_by: "premium_tone", colors: ["theme.muted", "theme.up", "theme.down"] }), tile.rows("Across the venues", [["Largest venue", "largest_text"], ["High-low spread", "spread_text"]]), ], }); // The one line of words on a chart that is not a BTC market: a muted label in pane pixels from the top-right corner, // under the card. handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 }); const notice = draw.label(0); const VENUES = 5; // this chart, then the four pins const MAX_BARS = 10080; // 168 hours of 1-minute bars: the ring is sized for the largest window at load const NAMES: StaticArray<string> = ["This chart", "Bybit", "OKX", "Coinbase", "Binance spot"]; const HEX: StaticArray<string> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; const usdRing = new StaticArray<f64>(VENUES * MAX_BARS); // each venue's dollar volume per bar, 0 where it did not report const usdSum = new StaticArray<f64>(VENUES); // the window sums, recounted from the ring on the live bar const liveClose = new StaticArray<f64>(VENUES); // this bar's close per venue const premium = new StaticArray<f64>(VENUES); // this bar's premium to the chart, basis points const order = new StaticArray<i32>(VENUES); // the venues sorted by dollar volume, largest first const inks = new StaticArray<i32>(VENUES); // the venue colours, packed, read from the settings let chartLabel: string = "This chart"; let windowBars = 96; // bars in the window, from the hours setting and the chart interval let highlightBp = 5.0; let head = 0; // the ring's write cursor and how many slots hold a bar let filled = 0; function fbColor(c: i32): void { // a packed colour as "#rrggbb" into the frame, no allocation const r = red(c); const g = green(c); const b = blue(c); fb_text('"#'); fb_text(HEX[(r >> 4) & 15]); fb_text(HEX[r & 15]); fb_text(HEX[(g >> 4) & 15]); fb_text(HEX[g & 15]); fb_text(HEX[(b >> 4) & 15]); fb_text(HEX[b & 15]); fb_text('"'); } function fbName(v: i32): void { // a venue's name as a JSON string if (v == 0) fb_str(chartLabel); else fb_str(NAMES[v]); } function usdOf(volume: f64, close: f64): f64 { // a bar's dollar volume, 0 where the venue did not report return isNaN(volume) || isNaN(close) || volume <= 0.0 ? 0.0 : volume * close; } function onStart(): void { const interval = p_chart_interval_sec(); // 0 when the chart did not fill it: a 15-minute bar is assumed const seconds = p_hours() * 3600.0; let bars = interval > 0.0 ? i32(Math.round(seconds / interval)) : i32(Math.round(seconds / 900.0)); if (bars < 1) bars = 1; if (bars > MAX_BARS) bars = MAX_BARS; windowBars = bars; highlightBp = p_highlight_bp(); chartLabel = pt_chart_label(); if (chartLabel.length == 0) chartLabel = "This chart"; inks[0] = fromPacked(p_chart_ink()); inks[1] = fromPacked(p_bybit_ink()); inks[2] = fromPacked(p_okx_ink()); inks[3] = fromPacked(p_coinbase_ink()); inks[4] = fromPacked(p_binance_ink()); } // onBar() runs once per bar: this bar's dollar volume per venue into the ring and the premiums to the chart's close; // the window sums and the card's numbers on every bar (data only); the words, the donut and the table on the live bar. function onBar(): void { const close = bar.close(); liveClose[0] = close; liveClose[1] = in_bybit_close(); liveClose[2] = in_okx_close(); liveClose[3] = in_coinbase_close(); liveClose[4] = in_binance_close(); usdRing[head] = usdOf(bar.volume(), close); usdRing[MAX_BARS + head] = usdOf(in_bybit_volume(), liveClose[1]); usdRing[2 * MAX_BARS + head] = usdOf(in_okx_volume(), liveClose[2]); usdRing[3 * MAX_BARS + head] = usdOf(in_coinbase_volume(), liveClose[3]); usdRing[4 * MAX_BARS + head] = usdOf(in_binance_volume(), liveClose[4]); head = (head + 1) % windowBars; if (filled < windowBars) filled += 1; // The window sums, recounted from the slots (a running sum keeps a rounding crumb after a quiet stretch). let total = 0.0; for (let v = 0; v < VENUES; v += 1) { let sum = 0.0; const base = v * MAX_BARS; for (let i = 0; i < filled; i += 1) sum += usdRing[base + i]; usdSum[v] = sum; total += sum; } // Is this a BTC market: the chart's close against the mean of the venues that reported on this bar. let reference = 0.0; let reported = 0; for (let v = 1; v < VENUES; v += 1) { if (isNaN(liveClose[v]) || liveClose[v] <= 0.0) continue; reference += liveClose[v]; reported += 1; } const isBtc = reported > 0 && !isNaN(close) && close > 0.0 && Math.abs(close / (reference / f64(reported)) - 1.0) <= 0.1; // The premiums, the widest one, the high-low spread and the largest venue. let widest = 0; // the pinned venue with the widest premium, 0 while none reported let widestAbs = -1.0; let high = close; let low = close; let largest = 0; for (let v = 0; v < VENUES; v += 1) { const venueClose = liveClose[v]; const served = v == 0 || (!isNaN(venueClose) && venueClose > 0.0 && usdSum[v] > 0.0); premium[v] = v == 0 ? 0.0 : served && close > 0.0 ? (venueClose / close - 1.0) * 10000.0 : NaN; if (v > 0 && served) { if (Math.abs(premium[v]) > widestAbs) { widestAbs = Math.abs(premium[v]); widest = v; } if (venueClose > high) high = venueClose; if (venueClose < low) low = venueClose; } if (usdSum[v] > usdSum[largest]) largest = v; } const widestBp = widest > 0 ? premium[widest] : NaN; const spreadBp = close > 0.0 && high >= low ? ((high - low) / close) * 10000.0 : NaN; const topShare = total > 0.0 ? (usdSum[largest] / total) * 100.0 : NaN; const tone = isNaN(widestBp) || Math.abs(widestBp) < highlightBp ? 0.0 : widestBp > 0.0 ? 1.0 : 2.0; if (isBtc) { out_widest_bp(widestBp); out_spread_bp(spreadBp); out_top_share(topShare); out_premium_tone(tone); } if (!bar.isLast()) return; const hours = p_hours(); sb_clear(); sb_f64(hours, 0); sb_text("h"); str_window_text_sb(); // the card's title reads the window, so it follows the hours setting if (!isBtc) { // not a BTC market: the card states it in the quiet tone, the one line of words sits under it, nothing else draws out_premium_tone(0.0); sb_clear(); sb_text("Not a BTC market"); str_headline_text_sb(); sb_clear(); sb_text("n/a"); str_largest_text_sb(); sb_clear(); sb_text("n/a"); str_spread_text_sb(); sb_clear(); sb_text("Venue share is written for BTC markets"); str_notice_text_sb(); notice.set(16, 210).text(str_notice_text_sb); return; } // The card's words. sb_clear(); if (widest > 0) { sb_text(NAMES[widest]); sb_text(widestBp >= 0.0 ? " +" : " "); sb_f64(widestBp, 1); sb_text(" bp"); } else sb_text("No venue reported"); str_headline_text_sb(); sb_clear(); if (largest == 0) sb_text(chartLabel); else sb_text(NAMES[largest]); if (!isNaN(topShare)) { sb_text(" "); sb_f64(topShare, 1); sb_text("%"); } str_largest_text_sb(); sb_clear(); if (isNaN(spreadBp)) sb_text("n/a"); else { sb_f64(spreadBp, 1); sb_text(" bp"); } str_spread_text_sb(); // The venues sorted by dollar volume, largest first (insertion sort over five rows). for (let v = 0; v < VENUES; v += 1) order[v] = v; for (let i = 1; i < VENUES; i += 1) { const key = order[i]; let j = i - 1; while (j >= 0 && usdSum[order[j]] < usdSum[key]) { order[j + 1] = order[j]; j -= 1; } order[j + 1] = key; } // The donut: one slice per venue that traded in the window, in its own colour, big and small slices interleaved // (largest, smallest, second largest, ...) so two thin labels never sit side by side; the hole prints the total. let served = 0; for (let k = 0; k < VENUES; k += 1) if (usdSum[order[k]] > 0.0) served += 1; fb_clear(); fb_text('{"hole_caption":"'); fb_f64(hours, 0); fb_text('h volume","rows":['); let slices = 0; for (let k = 0; k < served; k += 1) { const v = order[(k & 1) == 0 ? k >> 1 : served - 1 - (k >> 1)]; if (slices > 0) fb_text(","); fb_text("["); fbName(v); fb_text(","); fb_f64(usdSum[v], 0); fb_text(","); fbColor(inks[v]); fb_text("]"); slices += 1; } fb_text("]}"); writeFrameBuffer(FRAME_SHARE_ROWS); // The table: venue (in its donut colour), last, premium (signed, coloured by sign, bold and tinted when wide), // dollar volume with an inline bar against the largest venue, share; a venue with no volume in the window reads // "not served" and leaves the donut. const biggest = usdSum[largest]; fb_clear(); fb_text('{"title":"Venues, last '); fb_f64(hours, 0); fb_text('h","caption":"'); fb_int(filled); fb_text("/"); fb_int(windowBars); fb_text(' bars loaded","rows":['); for (let k = 0; k < VENUES; k += 1) { const v = order[k]; if (k > 0) fb_text(","); fb_text('[{"text":'); fbName(v); fb_text(',"text_color":'); fbColor(inks[v]); fb_text(',"font_weight":"bold"}'); if (usdSum[v] <= 0.0 || isNaN(liveClose[v])) { // the lane served nothing in the window fb_text(',{"text":"not served","text_color":"theme.muted"},"","",""]'); continue; } fb_text(","); fb_num(liveClose[v]); if (v == 0) fb_text(',{"text":"reference","text_color":"theme.muted"}'); else { const bp = premium[v]; const wide = Math.abs(bp) >= highlightBp; fb_text(',{"value":'); fb_f64(bp, 1); if (Math.abs(bp) < 0.05) fb_text(',"text_color":"theme.muted"'); else { fb_text(bp > 0.0 ? ',"text_color":"theme.up"' : ',"text_color":"theme.down"'); if (wide) fb_text(bp > 0.0 ? ',"background_color":"theme.up","opacity":0.16,"font_weight":"bold"' : ',"background_color":"theme.down","opacity":0.16,"font_weight":"bold"'); } fb_text("}"); } fb_text(',{"value":'); fb_f64(usdSum[v], 0); fb_text(',"bar":'); fb_f64(biggest > 0.0 ? usdSum[v] / biggest : 0.0, 3); fb_text(',"color":'); fbColor(inks[v]); fb_text("},"); fb_f64(total > 0.0 ? (usdSum[v] / total) * 100.0 : 0.0, 1); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_VENUE_ROWS); } ``` ## How it works **Four venues ride the chart's grid.** `input("close", ohlcv.close)` and `input("volume", ohlcv.volume)` are the chart's own candles, the grid and the reference price. The four pins (`bybit_close` and `bybit_volume` on `BYBIT` `BTCUSDT`, `okx_close` and `okx_volume` on `OKEX_SWAP` `BTC-USDT-SWAP`, `coinbase_close` and `coinbase_volume` on `COINBASE` `BTC-USD`, `binance_close` and `binance_volume` on `BINANCE` `BTCUSDT`) fetch each venue's candles at the chart's interval and join them to the chart's bars by timestamp; each declares `missing: "nan"`, so a bar the venue did not report reads NaN and contributes nothing. Volumes are in coins on every venue, so a bar's dollar volume is its volume times its close (`usdOf`), 0 where the venue did not report. Ten inputs in all; `bar.time()` would take an input slot of its own, so hours become bars through the chart interval instead. **Hours become bars through the chart interval.** `chart.interval_sec()` declares a hidden setting the chart fills before `onStart()` (900 on a 15m chart), and `onStart()` divides `hours` (24) in seconds by it to size the window: 96 bars on a 15m chart, at most 10080 (168 hours of one-minute bars, the ring's size), and a 15-minute bar is assumed when the interval reads 0. `usdRing` holds every venue's dollar volume per bar; on every bar the five window sums are recounted from the slots (a running sum would keep a rounding crumb after a quiet stretch) and the total is their sum. `legend({ title: "{{hours}}h" })` prints the window after the name. **The premiums are measured on the live bar.** A pinned venue is served on a bar while it has a close on that bar and dollar volume in the window; its premium is its close over the chart's close, minus one, in basis points, and the chart's own row is the reference. `widest_bp` is the served premium of the largest size, signed; `spread_bp` the highest served close minus the lowest, as basis points of the chart's close; `top_share` the largest venue's share of the window's dollar volume; `premium_tone` 0 while the widest premium is within `highlight_bp` (5), 1 above and wide, 2 below and wide. The four are data-only outputs written on every bar, so they have history and the Console reads them. Whether this is a BTC market is decided on the bar too: the chart's close against the mean of the venue closes that reported, within 10 percent; past it nothing is written. **Two frames feed the donut and the table.** On the live bar the venues are sorted by dollar volume, largest first, and `share_rows` is built through the frame buffer (`fb_clear`, `fb_text`, `fb_str`, `fb_f64`, `writeFrameBuffer`) as one `[name, value, color]` slice per venue that traded in the window, interleaved (largest, smallest, second largest, ...) so two thin labels never sit side by side; the frame's `hole_caption` names the hours ("24h volume") and `hole_total: true` prints the total in the hole. `labels: false` keeps the slice names off the ring and `legend_style: "title"` names them on the pane's title row, one per slice in its colour, so at `height_frac: 0.25` the ring and the hole's total and caption keep the whole pane (the table carries every share). `venue_rows` carries five rows of styled cells for `panel.table`: the name bold in its venue colour; the last price in the chart's own digits (`format: "price"`); the premium as a `value` printed through the column's `format: "0.0"`, `signed: true` and `unit: " bp"`, in `theme.up` or `theme.down` by sign (`theme.muted` within 0.05 bp), with a `background_color` tint at `opacity` 0.16 and `font_weight` bold once it is at or past the highlight; the dollar volume as a `value` with a `bar` against the largest venue in the venue's colour; and the share to one decimal. The frame's `title` names the hours ("Venues, last 24h") and its `caption` the bars loaded ("96/96 bars loaded"). The two panes take 0.165 and 0.185 of the chart's height, the table placed `top_center`. **The venue colours are settings.** A panel's frame colours take no `"@name"` binding, so the five inks are `param.color` settings under the **Venue colours** section, read once in `onStart()` through `fromPacked(p_chart_ink())` and its four twins and written into both frames as `"#rrggbb"` by `fbColor` (the `red`, `green` and `blue` channel readers over a 16-entry hex table, no allocation); the Style page shows them as ordinary colour pickers. The chart's own row is "This chart" unless `chart_label`, a `param.text` read with `pt_chart_label()`, names it. **The card reads slots and a ladder.** `render.hud("venues_card", { position: "top_right", safe_area: true, title: "BTC across venues, {{window_text}}", columns: 1, width: 290, tiles: [...] })` is one card of two tiles, its title reading the `window_text` slot ("24h", written from `hours` on the live bar), so the title follows the window: a headline `tile.pill` at `font_size` 20 reading the `headline_text` slot ("Coinbase +4.6 bp", or "No venue reported" while no pin is served), coloured by the `premium_tone` ladder (`["theme.muted", "theme.up", "theme.down"]`: the muted colour within the highlight, the chart's up or down colour past it, theme words that read on a dark and a light chart alike), and a `tile.rows` of `largest_text` ("This chart 49.1%") and `spread_text` ("4.6 bp"). The slots are written on the live bar only. With no `look`, the card draws the chart's default look (near black and translucent, white paper on a light chart, the pill as its word with no capsule and no dot), and `safe_area: true` keeps the card under the pane action bar and clear of the price-axis tags. On a chart that is not a BTC market the card still draws (a HUD card has no hide): it reads "Not a BTC market" in the quiet tone with "n/a" rows, and the `draw.label` handle declared with `handles.label({ anchor: "top_right", align: "right", color: "theme.muted", size: 11 })` prints the one line of words in pane pixels under it. ## Where it runs BTC charts on any venue: BTCUSDT on Binance Futures at 15m in the picture, where the chart's own candles are half of the five-venue dollar volume, and a 1h chart of the same market reads the same total and shares (the window is 24 hours on both; the premiums move a few tenths of a basis point between the two as the venues' last prices tick). A chart that is itself one of the four pinned venues (Bybit BTCUSDT) lists that venue twice, as "This chart" and as its pin. On a chart finer than one minute the window clamps at 10080 bars: the caption counts the clamped bars while the card's title still names the hours. On any other market (ETH, a stock, FX) the run still mounts: no output is written, the card states "Not a BTC market" with "n/a" rows, and one line of words sits under it. ## When data is missing On a chart that is not a BTC market the chart prints one sentence at the top right, "Venue share is written for BTC markets", and the card reads "Not a BTC market" with "n/a" in both rows. A bar a venue did not report reads NaN (`missing: "nan"`) and adds nothing to that venue's window; a venue with no dollar volume in the window and no live close keeps its row, reads "not served" in the Last column with the rest blank, leaves the donut and is left out of the widest premium and the spread, and while no pin is served on the live bar the headline reads "No venue reported". While the loaded history is shorter than the window the shares are measured over the bars loaded and the caption says so ("48/96 bars loaded"). The four pins as written are served; a pin changed to a market the chart cannot load refuses the whole run by name before any bar, in a toast and on the overlay's **Could not load** chip ([Exchange and symbol format](../reference/symbol-format.md)). ## Customize it - **More or fewer hours.** `hours` (24; 1 to 168) sets the window behind the shares and the table; bars are hours over the chart interval, at most 10080, and the legend, the card's title, the hole's caption and the table's title follow it. - **A tighter highlight.** `highlight_bp` (5; 1 to 50 in steps of 0.5): a premium at or past it reads bold and tinted in the table, and the card's headline takes the chart's up or down colour. - **Name and colour the venues.** `chart_label` ("This chart", up to 24 bytes) names the chart's own row in the donut and the table ("Binance perp" on a Binance perp chart); the five inks under **Venue colours** are colour pickers on the Style page, and each reruns the module. - **Another venue.** Swap one pin's `exchange` and `symbol` for another BTC market the chart serves, such as `BYBIT_SPOT` and `BTCUSDT` ([Exchange and symbol format](../reference/symbol-format.md)), rename it in `NAMES`, and Run again; the premiums and the shares follow. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks, `default` to `classic` ([Looks](../presentation/hud-and-hover-cards.md#looks)); a word declared beside it still wins, and the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Venue Share** under **Beyond the time axis**. 2. Press **Run** on a BTC chart, such as BTCUSDT on Binance Futures at 15m: the donut and the table fill two panes below the candles, the card appears at the top right and the legend reads the hours ("Venue Share 24h"). 3. At the editor's Console prompt, type `last 20 widest_bp` to read the widest venue premium, in basis points, on the last 20 bars. ## Concepts used - [Multi-source and aggregation](../core-concepts/multi-source.md) for a pinned `ohlcv` input on another market, and [Data sources](../core-concepts/data-sources.md) for `missing: "nan"` - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, the `fb_*` builders, `panel.pie` and the styled cells of `panel.table` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, `safe_area` and `width`, [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name, and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` and `tile.rows` - [Setting kinds](../settings/kinds.md) for `param.color` and `param.text` and their readers, and [The Style page](../settings/style-page.md#the-look-row) for the Look row and the colour pickers - [Sessions and units](../settings/sessions-and-units.md#chart-context) for `chart.interval_sec()` - [Colors](../functions/colors-kit.md) for `fromPacked` and the `red`, `green` and `blue` channel readers - [Drawing objects](../presentation/drawing-objects.md) for `handles.label` with an `anchor` and the `draw.label` handle - [Exchange and symbol format](../reference/symbol-format.md) for the venue ids and a pin refused by name <!-- source: https://openmarket.xyz/wrun/cookbook/iv-surface --> # Volatility surface ![Volatility surface under BTC candles: implied volatility tiles by expiry, a heatmap by strike and expiry, and the card](/wrun/images/iv-surface.png) Volatility surface shows what this symbol's options cost as implied volatility (how big a move option prices expect). Tiles show it per expiry (the day the option ends) at the strike (the option's price level) nearest the price. Under them, a heatmap shows every strike and expiry, its colour stronger where options cost more. A card adds the skew (how much more puts cost than calls): pricier puts mean traders fear a drop. Use it to spot cheap or dear options before you trade, on any chart whose symbol has listed options. Under the hood: the recipe reads `options_chain.cells` with `venue: "auto"` ([Data sources](../core-concepts/data-sources.md), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). It asks for two book folds, `surface` in its IV lens and `vol_term`, the numbers the chart's built-in Options Surface and Term Structure draw. The options kit's `BookStamp`, `SurfaceMatrix` and `VolTerm` read them ([Book folds](../functions/options-kit.md#book-folds)). It feeds two frames to a `panel.tiles` and a `panel.heatmap`, with a summary row, a highlighted row and a per-run caption ([Cards, frames and panels](../presentation/cards-frames-panels.md)). It spells each strike as the built-in does, with a `TextBuilder` ([A second builder](../functions/text-formatting.md#a-second-builder)). It adds a `render.hud` card in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It also adds a corner `render.label`, and a `render.legend` entry for the term word ([Legend](../presentation/legend.md)). It is also the `iv-surface` template, the **Volatility Surface** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volatility Surface: what this symbol's options cost, as implied volatility (how big a move option prices expect). // High implied volatility means pricey options and big expected swings. A strike (the option's price level) and an // expiry (the day the option ends) place each option. Tiles under the candles show, for each expiry, the implied // volatility at the strike nearest the price. Near dates come first, so read left to right they are the term structure // (near expiries' prices against far ones). Under them, a heatmap shows every strike and expiry, its colour stronger // where options cost more. A card names the nearest expiry's implied volatility and its skew (how much more puts cost // than calls). Pricier puts mean traders fear a drop. It also says whether far dates cost more than near ones. Use it // to spot cheap or dear options before you trade them. // // Technical notes: the chart's own live option chain (OPRA on a US stock or ETF chart, the CME chain of a futures // root, Deribit on a coin) as implied volatility by strike and expiry, read from the data plane's surface fold, the // matrix the chart's built-in Options Surface draws in its IV mode: the nearest live expiries as columns, nearest // first, and the 21 strikes nearest the book's spot inside the moneyness range as rows, the highest at the top, a // heatmap below the candles with the row nearest the chart's price marked (the strike nearest the live bar's close // where it reads in the strikes' dollars, not the book's own spot, which sits off the chart's price after hours or // between chain snapshots) and each expiry's ATM implied volatility in the summary row. A cell is the strike's // out-of-the-money IV on that expiry, empty where the expiry quotes none. Under it, one tile per expiry with its ATM // implied volatility and days to expiry: the term structure read left to right. The card at the top left answers one // question first: what does the nearest expiry's ATM option cost, as implied volatility; then the 25-delta skew of // that expiry (call IV minus put IV: below 0 while puts carry the premium) and the one-week ATM against the // three-month ATM (contango while the far point sits above the near one). Those readings are the data plane's term // structure fold, the per-expiry numbers the chart's built-in Term Structure draws, read beside the surface in the same // answer: each one is a listed expiry's own (the nearest expiry at least 12 h away, and the listed expiries nearest one // week and three months away by the fold's days to expiry). Every number is the folds' own, priced once a chain update // over the whole book (the ATM IV at each expiry's forward); the package only picks and draws them. The folds are read // on the live bar: history bars draw nothing. A book with no contract, no spot or no row draws an empty surface and // says so, never the last answer's cells. section("Surface"); param.int("expiries", 6, { min: 2, max: 6, label: "Expiries", description: "How many expiry dates the surface and the tiles show, nearest first. An expiry is the day the option ends." }); param.number("range_pct", 20, { min: 5, max: 40, label: "Strike range, percent", description: "How far from the price the strikes reach, in percent each way. The surface shows the 21 strikes nearest the price inside it." }); input("close", ohlcv.close); // the chart's bars and price: the folds are read on the last bar, the bold row at its close input("chain", options_chain.cells, { max_cells: 225, venue: "auto", page_views: ["surface", "vol_term"], lens: 2, window_pct: "@range_pct", columns: "@expiries", rows: 21, description: "This symbol's live options as IV by strike and expiry, with each expiry's at-the-money IV and skew. US listed options on a stock, CME options on a future, Deribit options on a coin." }); // rows of 16 values (the widest word's, vol_term): the one book stamp row (BookStamp), the surface's [16, tag, at, value] rows (SurfaceMatrix) and one term row per live expiry (VolTerm); max_cells counts rows: the stamp, 2 x 6 + 21 + 1 + 6 x 21 surface rows and 64 term rows market.zone(); // the market's clock: each expiry's trade date, its label's year market.quote_is_usd(); // 1 when the chart's prices are in US dollars, the strikes' currency on every chain read here market.option_contract(); // 1 on an option contract's own chart: its close is the contract's premium, not a price // The readings, data-only: the card's tiles read them and the Console can too. Each is NaN on history bars. output("atm_near", none, overlay, { format: "%", description: "At-the-money IV of the nearest expiry at least 12 hours away, in percent. Live bar only." }); output("skew_25d", none, overlay, { description: "The nearest expiry's skew in IV points: the 25-delta call's IV minus the 25-delta put's. Below 0, puts cost more than calls." }); output("atm_1w", none, overlay, { description: "At-the-money IV of the expiry nearest one week away, in percent" }); output("atm_3m", none, overlay, { description: "At-the-money IV of the expiry nearest three months away, in percent" }); output("term_spread", none, overlay, { description: "The three-month at-the-money IV minus the one-week one, in IV points. Above 0 is contango (far dates cost more), below 0 backwardation (near dates cost more)." }); string("skew_text", { max_bytes: 32 }); // the card's skew row: "-4.2 pts, puts pricier" string("term_text", { max_bytes: 32 }); // the card's term row: "33.0% to 41.2%" string("term_word", { max_bytes: 16 }); // the legend entry: Contango or Backwardation string("notice", { max_bytes: 64 }); // the one sentence at the top right when the chain gives no usable expiry render.legend("term", { text: "term_word", color: "theme.muted" }); // the legend reads "term Contango" render.label("notice_tag", { position: "top_right", text: "notice", color: "theme.muted", style: "plain", offset: [12, 8] }); const heat = frame("heat", { max_bytes: 8192 }); // the surface: one cell per strike and expiry, the summary row, the highlight const termRows = frame("term_rows", { max_bytes: 2048 }); // the tiles: one per expiry // The term structure first, right under the candles: six tiles in one row, label the expiry, value its ATM IV, // caption the days to expiry (the caption shows in the tile's hover card, and on the tile itself once the panel is // maximized; the chart's own floating button sits at the bottom left of the cell, so the tiles stay above the // surface). Together the two panels take 0.35 of the chart. panel.tiles({ name: "term_tiles", title: "At-the-money IV by expiry", x: "category", place: "below", frame: termRows, columns: 6, accent: "neutral", hover_card: true, maximize: true, format: "0.0", unit: "%", height_frac: 0.12 }); // The surface: expiry on x, strike on y (the highest at the top, like the price axis), IV percent in the cell, on the // chart's one-ink ramp from faint (the cheapest options, at the money) to full (the dearest wings); the row nearest // the chart's price marked, the ATM summary row and the term word as the caption (written per run), a hover card on // every cell titled by its two labels after the built-in's axis nouns, "Strike 64,000 · Expiry 27 Dec", over its IV. panel.heatmap({ name: "surface", title: "Implied volatility", x: "category", place: "below", frame: heat, scale: "palette", row_title: "Strike", col_title: "Expiry", hover_card: true, maximize: true, format: "0.0", unit: "%", height_frac: 0.23 }); // The card, at the top left under the legend (the top right keeps the notice): the nearest ATM IV leads as the // headline, then the two rows with dotted leaders. render.hud("surface_card", { position: "top_left", title: "Volatility surface", columns: 1, width: 236, safe_area: true, tiles: [ tile.value("ATM IV, nearest expiry", "atm_near", { format: "%", headline: true, hint: "The implied volatility (IV) of the option nearest the price, on the nearest expiry at least 12 hours away. High IV means options are expensive and traders expect big swings." }), tile.rows([ ["Skew", "skew_text"], ["1 week vs 3 months", "term_text"], ], { leader: "dots" }), ], }); const MAX_COLUMNS = 6; // expiry columns the surface fold answers at most (the Expiries setting's cap) const ROWS = 21; // strike rows the surface fold answers at most, as many as the built-in Options Surface shows const MAX_TERM = 64; // term rows the vol_term fold answers at most: one per live expiry const MIN_AHEAD_DAYS = 0.5; // an expiry inside 12 h is settling, not the card's reading (the fold's days to expiry) const stamp = new BookStamp(); // the book the folds read: its priced instant and its spot const matrix = new SurfaceMatrix(MAX_COLUMNS, ROWS); // the surface: expiry columns, strike rows, the ATM summaries const term = new VolTerm(MAX_TERM); // the term structure: each live expiry's days, ATM IV and 25-delta risk reversal const strikeText = new TextBuilder(24); // a strike's label, spelled by the built-in's rule, copied into the frame const LABEL_BYTES = 24; // a strike label's bytes at most: the label builder's capacity const MAX_DECIMALS = 8; // the most decimals a strike row's label takes when two rows would read alike // Every row at up to N decimals, the trailing zeros dropped, by N: the masks of a matrix whose rows would read alike. const DECIMAL_MASKS: string[] = ["#,##0", "#,##0.#", "#,##0.##", "#,##0.###", "#,##0.####", "#,##0.#####", "#,##0.######", "#,##0.#######", "#,##0.########"]; const rowLabels = new StaticArray<u8>(ROWS * LABEL_BYTES); // each strike row's label, to find two that read alike const rowLabelBytes = new StaticArray<i32>(ROWS); const timedColumn = new StaticArray<bool>(MAX_COLUMNS); // a column whose date another column shares: its label adds the time let clock = new Clock("UTC"); // an expiry's time of day on the market's own clock, set in onStart() let zone = 0; // the market's clock, read in onStart() let quoteIsUsd = 0; // the chart's quote: 1 US dollars, 2 another currency or coin (USDT and USDC too), 0 unknown let optionContract = false; // the chart is one option contract's own: its close is a premium let strikeDecimals = -1; // the decimals every strike row's label takes; -1: the built-in's, by the strike's size let pricedAtMs: f64 = NaN; // the instant the data plane priced the book let cellsRead = 0; // the matrix cells the surface fold carried (an empty cell rides no row) let surfaceDrawn = false; // the surface fold carried a column and a row let termCount = 0; // term rows read; a book with no spot gives no reading, as the built-in Term Structure plots none let nearRow = -1; // the card's expiry: the nearest at least 12 h away with an ATM IV; -1 when none let skew25: f64 = NaN; // the readings, picked on the live bar let atm1w: f64 = NaN; let atm3m: f64 = NaN; let oneExpiry = false; // the one-week and three-month picks are the same listed expiry: no term word function onStart(): void { zone = i32(p_market_zone()); clock = new Clock(SESSION_TZ_IDS[zone]); quoteIsUsd = i32(p_market_quote_is_usd()); optionContract = i32(p_market_option_contract()) == 1; } // ── The folds, read on the live bar ── // The surface draws when the answer carries a book stamp, an expiry column and a strike row; an empty book (no // contract), no spot and an answer with no surface row carry none. The readings are the term rows' own: the nearest // expiry at least 12 h away that quotes an ATM IV (the headline, and the skew's expiry), and the listed expiries at // least 12 h away nearest one week and three months by days to expiry (the first on a tie). function read(cells: StaticArray<f64>, n: i32): void { cellsRead = 0; surfaceDrawn = false; termCount = 0; nearRow = -1; skew25 = NaN; atm1w = NaN; atm3m = NaN; oneExpiry = false; strikeDecimals = -1; for (let c = 0; c < MAX_COLUMNS; c += 1) unchecked((timedColumn[c] = false)); // Every reader reads the block at its rows' width: the widest word's, vol_term's 16. if (!stamp.load(cells, n, OPTION_VIEW_ROW_VOL_TERM)) return; pricedAtMs = stamp.pricedAtMs(); cellsRead = matrix.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); surfaceDrawn = cellsRead >= 0 && matrix.columns() > 0 && matrix.rows() > 0; if (surfaceDrawn) labelApart(); termCount = term.load(cells, n, OPTION_VIEW_ROW_VOL_TERM); if (!(stamp.spot() > 0.0)) return; // no spot: no reading, as the built-in Term Structure reads none let w = -1; let m = -1; for (let i = 0; i < termCount; i += 1) { const days = term.days(i); if (!(days > MIN_AHEAD_DAYS)) continue; // settling if (nearRow < 0 && isFinite(term.atmIv(i))) nearRow = i; if (w < 0 || Math.abs(days - 7.0) < Math.abs(term.days(w) - 7.0)) w = i; if (m < 0 || Math.abs(days - 90.0) < Math.abs(term.days(m) - 90.0)) m = i; } if (nearRow < 0) return; skew25 = term.rr25(nearRow); // call minus put atm1w = term.atmIv(w); atm3m = term.atmIv(m); oneExpiry = w == m; } // ── The labels ── // A strike as the built-in Options Surface spells it: grouped, at most four decimals under 10, two under 1,000 and none // from 1,000, the trailing zeros dropped, rounded half away from zero ("64,000", "662.5", "0.55"). The chart lays a // heatmap's rows and columns out by their labels, so two that read alike would merge into one: CME's yen options list // 0.00425 and 0.0043, both "0.0043" at four decimals. While two strike rows read alike, every row takes the fewest // decimals, from the built-in's most, that tell each row apart ("0.00425", "0.0043"), the highlighted row its row's // label. An expiry column reads its trade date, the kit's label; two columns of one date (an AM and a PM expiry) each // add the expiry's time on the market's clock ("16 Oct 09:30"), and its tile follows its column. function spellStrike(strike: f64, decimals: i32): void { // into strikeText: the built-in's mask at -1, else `decimals` at most if (decimals < 0) strikeText.clear().mask(strike, strike < 10.0 ? "#,##0.####" : strike < 1000.0 ? "#,##0.##" : "#,##0"); else strikeText.clear().mask(strike, unchecked(DECIMAL_MASKS[decimals])); } function rowsReadApart(decimals: i32): bool { // every strike row's label differs from every other row's at `decimals` for (let r = 0; r < matrix.rows(); r += 1) { spellStrike(matrix.rowStrike(r), decimals); const bytes = strikeText.length(); // at most LABEL_BYTES, the builder's capacity const at = <usize>strikeText.ptr(); for (let i = 0; i < bytes; i += 1) unchecked((rowLabels[r * LABEL_BYTES + i] = load<u8>(at + <usize>i))); unchecked((rowLabelBytes[r] = bytes)); for (let q = 0; q < r; q += 1) { if (unchecked(rowLabelBytes[q]) != bytes) continue; let same = true; for (let i = 0; i < bytes && same; i += 1) same = unchecked(rowLabels[q * LABEL_BYTES + i]) == unchecked(rowLabels[r * LABEL_BYTES + i]); if (same) return false; } } return true; } function labelApart(): void { // the strike rows' decimals and the expiry columns that add their time if (!rowsReadApart(-1)) { let decimals = 0; // from the built-in's most decimals over the rows: no row reads coarser than the built-in's for (let r = 0; r < matrix.rows(); r += 1) { const strike = matrix.rowStrike(r); const own = strike < 10.0 ? 4 : strike < 1000.0 ? 2 : 0; if (own > decimals) decimals = own; } while (decimals < MAX_DECIMALS && !rowsReadApart(decimals)) decimals += 1; strikeDecimals = decimals; } for (let c = 0; c < matrix.columns(); c += 1) { const day = optionsTradeDay(matrix.columnExpiryMs(c), zone); // the date its label names for (let d = 0; d < c; d += 1) { if (optionsTradeDay(matrix.columnExpiryMs(d), zone) != day) continue; unchecked((timedColumn[c] = true)); unchecked((timedColumn[d] = true)); } } } function fbStrike(strike: f64): void { if (!isFinite(strike)) { fb_text("NaN"); return; } spellStrike(strike, strikeDecimals); const at = <usize>strikeText.ptr(); for (let i = 0; i < strikeText.length(); i += 1) { const code = i32(load<u8>(at + <usize>i)); if (code >= 0x30 && code <= 0x39) fb_int(code - 0x30); else if (code == 0x2c) fb_text(","); else if (code == 0x2e) fb_text("."); else if (code == 0x2d) fb_text("-"); } } function fbStrikeKey(r: i32): void { fb_text("\""); fbStrike(matrix.rowStrike(r)); fb_text("\""); } function fbExpiryKey(c: i32): void { // "16 Oct", "15 Jan '27" in another year, "16 Oct 09:30" beside a column of its date fb_text("\""); fbExpiryLabel(matrix.columnExpiryMs(c), pricedAtMs, zone); if (unchecked(timedColumn[c])) fbExpiryTime(matrix.columnExpiryMs(c)); fb_text("\""); } function fbExpiryTime(ms: f64): void { // " 09:30": the expiry's time on the market's clock clock.update(Math.floor(ms / 1000.0)); fb_text(" "); fbPad(clock.hour()); fb_text(":"); fbPad(clock.minute()); } function fbPad(value: i32): void { // two digits, zero first if (value < 10) fb_text("0"); fb_int(value); } // ── The frames, written on the live bar ── // The bold row: the strike row nearest the live bar's close, the higher on a tie (the data plane's rule), where the // close reads in the strikes' US dollars (every chain read here: OPRA, CME's futures options, Deribit's coin options): // a chart priced in US dollars (unknown counts), no option contract's own (its close is the premium), the close within // half to twice the book's spot. Else (a coin quoted in KRW, BTC, EUR or a stablecoin, a premium) and while the close // is NaN, the fold's own highlight, highlightRow(): the row nearest the book's spot, which sits off the chart's price // after hours and between chain snapshots. function closeOnLadder(close: f64): f64 { if (optionContract || quoteIsUsd == 2) return NaN; // a premium axis, or another currency or coin const s0 = stamp.spot(); if (!(close >= 0.5 * s0 && close <= 2.0 * s0)) return NaN; // another unit, whatever the facts say return close; } function boldRow(price: f64): i32 { if (!isFinite(price)) return matrix.highlightRow(); // no price: the book's own pick, the row nearest its spot let best = -1; let gap = Infinity; for (let r = 0; r < matrix.rows(); r += 1) { const d = Math.abs(matrix.rowStrike(r) - price); // NaN for a row with no strike, never picked if (d < gap) { gap = d; best = r; } } return best; } function writeSurface(): void { fb_clear(); fb_text("{\"rows\":["); let first = true; for (let r = 0; r < matrix.rows() && surfaceDrawn; r += 1) { // row 0 is the highest strike: the top row, like the price axis for (let c = 0; c < matrix.columns(); c += 1) { if (!first) fb_text(","); first = false; fb_text("["); fbExpiryKey(c); fb_text(","); fbStrikeKey(r); fb_text(","); fb_num(matrix.value(r, c)); // the fold's IV, vol points; null for an empty cell fb_text("]"); } } fb_text("]"); if (surfaceDrawn && cellsRead > 0) { // the summary row rides with the cells, as on the built-in fb_text(",\"summary\":[{\"label\":\"ATM\",\"values\":["); for (let c = 0; c < matrix.columns(); c += 1) { if (c > 0) fb_text(","); fb_num(matrix.summary(c)); // each expiry's ATM IV; null where it quotes none } fb_text("]}]"); } const h = boldRow(closeOnLadder(bar.close())); // the row nearest the chart's price if (surfaceDrawn && h >= 0 && h < matrix.rows()) { fb_text(",\"highlight\":{\"row\":"); fbStrikeKey(h); fb_text("}"); } fb_text(",\"caption\":\""); if (isNaN(atm1w) || isNaN(atm3m)) fb_text("Term structure: no reading"); else if (oneExpiry) fb_text("Term structure: one expiry listed"); else { // "Contango: 1w 31.1%, 3m 36.6%" (the title row shows about 30 characters of caption) fb_text(atm3m > atm1w ? "Contango: 1w " : "Backwardation: 1w "); fb_f64(atm1w, 1); fb_text("%, 3m "); fb_f64(atm3m, 1); fb_text("%"); } fb_text("\"}"); writeFrameBuffer(FRAME_HEAT); } function writeTiles(): void { fb_clear(); fb_text("{\"rows\":["); for (let c = 0; c < matrix.columns() && surfaceDrawn; c += 1) { if (c > 0) fb_text(","); fb_text("["); fbExpiryKey(c); fb_text(","); const i = term.indexOf(matrix.columnExpiryMs(c)); // the expiry's term row: its ATM IV and days, the Term Structure's if (i >= 0 && isFinite(term.atmIv(i))) fb_num(term.atmIv(i)); else fb_text("\"no IV\""); // a tile's value is never empty: the expiry quotes no ATM IV if (i >= 0 && isFinite(term.days(i))) { fb_text(",\""); fb_f64(term.days(i), 1); fb_text(" days\"]"); } else fb_text(",null]"); } fb_text("]}"); writeFrameBuffer(FRAME_TERM_ROWS); } // onBar() runs once per bar: history rows carry an empty block and read nothing; the live bar reads the folds, writes // the readings as numbers (NaN on history rows), the two frames and the card's words. With neither a surface nor a // reading both frames are written empty, so the panels clear instead of keeping the last answer's cells. The chart // runs the live bar again as its candle moves, with the newest chain answer, so the bold row follows the price. function onBar(): void { if (bar.isLast()) read(in_chain_view(), in_chain_cells()); const measured = bar.isLast() && nearRow >= 0; out_atm_near(measured ? term.atmIv(nearRow) : NaN); out_skew_25d(measured ? skew25 : NaN); out_atm_1w(measured ? atm1w : NaN); out_atm_3m(measured ? atm3m : NaN); out_term_spread(measured ? atm3m - atm1w : NaN); if (!bar.isLast()) return; if (surfaceDrawn || measured) { writeSurface(); writeTiles(); sb_clear(); if (!measured) sb_text("no options data"); else if (isNaN(skew25)) sb_text("no 25-delta reading"); else { sb_signed(skew25, 1); sb_text(skew25 <= 0.0 ? " pts, puts pricier" : " pts, calls pricier"); } str_skew_text_sb(); sb_clear(); if (!measured) sb_text("no options data"); else if (isNaN(atm1w) || isNaN(atm3m)) sb_text("no reading"); else if (oneExpiry) sb_text("one expiry listed"); else { sb_f64(atm1w, 1); sb_text("% to "); sb_f64(atm3m, 1); sb_text("%"); } str_term_text_sb(); sb_clear(); if (measured && !isNaN(atm1w) && !isNaN(atm3m) && !oneExpiry) sb_text(atm3m > atm1w ? "Contango" : "Backwardation"); str_term_word_sb(); sb_clear(); str_notice_sb(); // no notice: the folds gave a surface or a reading } else { // No usable expiry: the one sentence at the top right, the card's rows say why, both panels cleared. writeFrame(FRAME_HEAT, "{\"rows\":[]}"); writeFrame(FRAME_TERM_ROWS, "{\"rows\":[]}"); sb_clear(); sb_text("No usable expiry in this symbol's options"); str_notice_sb(); sb_clear(); sb_text("no options data"); str_skew_text_sb(); sb_clear(); sb_text("no options data"); str_term_text_sb(); sb_clear(); str_term_word_sb(); } } ``` ## How it works **Two folds, one input.** `input("chain", options_chain.cells, { max_cells: 225, venue: "auto", page_views: ["surface", "vol_term"], lens: 2, window_pct: "@range_pct", columns: "@expiries", rows: 21 })` asks the data plane for two book folds of the chart's own live chain (OPRA on a US stock or ETF chart, the CME chain of a futures root, the coin's Deribit chain elsewhere): `surface` with `lens: 2`, implied volatility as a strike by expiry matrix, its `columns` the **Expiries** setting, its `window_pct` the **Strike range** setting (each bound with `"@<param>"`, so the chart writes the setting's value on every run) and its `rows` 21, and `vol_term`, a row per live expiry quoting an IV or holding open interest. The data plane folds both once a chain update over the chain's whole book, priced at one instant with each expiry's ATM IV at its forward, so they are the numbers the built-in Options Surface and Term Structure draw. The answer is one block of rows 16 values wide, the widest word's (`vol_term`): the one book stamp row, the surface's `[16, tag, at, value]` rows and the term rows. `max_cells` counts rows: 225 holds the stamp, the surface's 2 x 6 + 21 + 1 + 6 x 21 rows at the settings' caps (a header and a summary per column, a header per row, the highlight, a cell per strike and expiry) and 64 term rows. The block is the live row's only: history bars carry an empty block and read nothing, so everything is read under `bar.isLast()`, and the five data-only readings (`atm_near`, `skew_25d`, `atm_1w`, `atm_3m`, `term_spread`) are NaN on history bars. **The surface is the fold's matrix.** On the live bar each reader reads the block at the input's row width, `OPTION_VIEW_ROW_VOL_TERM` (16), its own layouts, and skips the rest. `BookStamp` reads the stamp (an answer with none reads nothing), the book's spot and the instant the data plane priced the book (`pricedAtMs()`, the clock each expiry's label reads its year against). `SurfaceMatrix` reads the surface: the expiry columns, nearest first (`columns()`, `columnExpiryMs(c)`), the strike rows, the highest first (`rows()`, `rowStrike(r)`), each cell's IV in vol points (`value(r, c)`, NaN for an empty cell, which rides no row), each expiry's ATM IV (`summary(c)`) and the fold's own highlight, the row nearest the book's spot (`highlightRow()`). The columns are the nearest live expiries, as the data plane counts them; the rows are the 21 strikes nearest the book's spot inside the moneyness range, so a range that holds fewer strikes shows fewer rows. The surface draws when the answer carries a column and a row: an empty book (no contract), a book with no spot and an answer with no surface row carry none. **The card reads the term structure.** `VolTerm` reads a row per live expiry: its days to expiry, its ATM IV and its 25-delta risk reversal (`days(i)`, `atmIv(i)`, `rr25(i)`). With a spot, the card's expiry is the nearest one at least 12 h away (an expiry inside 12 h is settling) that quotes an ATM IV: its ATM IV is the headline, `atm_near`, and its risk reversal the skew, `skew_25d` (`rr25()`: the 25-delta call's IV minus the 25-delta put's, in IV points, below 0 while puts carry the premium). The one-week and three-month points are the listed expiries at least 12 h away nearest 7 and 90 days by the fold's days to expiry, the first on a tie, over every term row, not only the surface's columns, so the term word holds even when the six nearest expiries all sit inside a month; `term_spread` is the three-month ATM minus the one-week ATM, above 0 contango. When the two picks are the same listed expiry there is no term word. Without a spot the vol term gives no reading, as the built-in Term Structure plots none. **Two frames feed two panels.** `frame("term_rows")` carries one `[label, value, caption]` row per surface column (the expiry's label; its ATM IV from its term row, found by `indexOf(columnExpiryMs(c))`, or the text `no IV` where it quotes none; its days to expiry, the fold's; the label is the kit's `fbExpiryLabel`, the expiry's trade date on the market's clock read against the book's priced instant, `16 Oct`, or `15 Jan '27` in another year, and the heatmap's columns read it too) and feeds `panel.tiles` with `columns: 6`, `accent: "neutral"` (IV has no sign, so the text keeps its ink) and `format: "0.0"` with `unit: "%"`, so a tile reads `27.1%`. `frame("heat")` carries one `[expiry, strike, value]` cell per strike row and expiry column, written from the highest strike down so the top row is the highest strike, like the price axis, the value `null` for an empty cell. Each strike is spelled as the built-in Options Surface spells it: grouped, at most four decimals under 10, two under 1,000 and none from 1,000, trailing zeros dropped, rounded half away from zero (`64,000`, `662.5`, `0.55`), built with a `TextBuilder` mask and copied into the frame. The chart lays the heatmap's rows and columns out by their labels, so two that read alike would merge into one: while two strike rows would read alike (CME's yen options list 0.00425 and 0.0043, both `0.0043` at four decimals), every row takes the fewest decimals, from the built-in's most, that tell the rows apart (`0.00425`, `0.0043`), and two columns of one date (an AM and a PM expiry) each add the expiry's time on the market's clock (`16 Oct 09:30`), the tiles following their columns; every other matrix keeps the built-in's spelling. Beside the cells the frame carries a `summary` row, `ATM`, each expiry's ATM IV under its column (`null` where it quotes none), a `highlight` naming the row nearest the chart's price, and the `caption` written per run (the title row shows about 30 characters of it). It feeds `panel.heatmap` with `scale: "palette"` and no `palette`, so the cells ramp from the chart's background to the text colour, `row_title: "Strike"` and `col_title: "Expiry"`, the built-in's axis nouns, which prefix each label in the hover card's title ("Strike 64,000 · Expiry 27 Dec"), and `hover_card: true` printing each cell's exact value under the pointer. Both frames are written with the `fb_*` builders and `writeFrameBuffer`, and the two panels take 0.35 of the chart together. **The bold row follows the chart's price.** `boldRow(closeOnLadder(bar.close()))` picks the strike row nearest the live bar's close, the higher strike on a tie. The fold's own highlight, `highlightRow()`, is the row nearest the book's spot, the median underlying of its nearest expiry, and that spot can sit off the chart's price: a stock trading after hours while its options are shut, or the moves between two chain snapshots. The close stands in for the price only where it reads in the strikes' units. Every chain the package reads quotes its strikes in US dollars, so `closeOnLadder()` hands the close back only on a chart priced in US dollars (`market.quote_is_usd()`, an unknown quote included) that is no option contract's own (`market.option_contract()`: its close is the contract's premium), and only within half to twice the book's spot. A coin quoted in KRW, BTC, EUR or a stablecoin, or a premium, reads NaN there, and `boldRow()` takes `highlightRow()` for NaN. The chart runs the live bar again as its candle moves, with the newest chain answer, so the bold row follows the price between chain updates while the cells keep the last answer's. **The card reads an output and two slots.** `render.hud("surface_card", { position: "top_left", columns: 1, width: 236, safe_area: true, tiles: [...] })` names the anchor and two tiles; with no `look`, the card draws the chart's default look. `tile.value("ATM IV, nearest expiry", "atm_near", { format: "%", headline: true, hint: "..." })` leads as the headline and reads the data-only output, its `hint` saying how the number is read; `tile.rows` with `leader: "dots"` reads two string slots written on the live bar under the labels `Skew` and `1 week vs 3 months`, `skew_text` ("-4.2 pts, puts pricier", from `sb_signed`; 0 reads puts pricier too) and `term_text` ("31.4% to 36.6%"). `safe_area: true` keeps the card under the legend, and the top right stays free for the notice. **The term word rides the legend, the notice the corner.** `render.legend("term", { text: "term_word", color: "theme.muted" })` prints the slot's words after the indicator's name as "term Contango", in the theme's muted ink. `render.label("notice_tag", { position: "top_right", text: "notice", color: "theme.muted", style: "plain", offset: [12, 8] })` is a label placed by a corner `position` rather than by `x` and `y`: it prints the `notice` slot in the muted colour at the top right, and the slot is empty while the folds give a surface or a reading. ## What the settings do - **Expiries**: How many expiry dates the surface and the tiles show, nearest first, from 2 to 6. - **Strike range, percent**: How far from the price the strikes reach, in percent each way, with up to 21 strikes shown. - **ATM IV, nearest expiry**: The implied volatility of the option nearest the price, on the nearest expiry at least 12 hours away. - **Skew**: The call's IV minus the put's at the same distance from the price: below 0, puts cost more. - **1 week vs 3 months**: The at-the-money IV one week out against three months out: higher far out is the calm, usual shape. ## Where it runs It works on any chart whose symbol has listed options. A coin chart reads Deribit's options for that coin (BTC, ETH and the rest of its list) on any exchange. Deribit is a crypto options exchange. A US stock or ETF chart reads its US listed options. They run 15 minutes behind unless you have real-time US options data. A CME (Chicago futures exchange) futures chart reads the options on that future, 10 minutes behind unless you have real-time CME data. A copy you run from the editor (the code panel beside the chart) reads crypto, US stock and CME options. On a CME chart, accept the CME market data terms first. Run on Cloud (the editor switch that runs a copy on OpenMarket's servers) cannot read these option prices yet. Nor can a Protected copy (published so its code stays on those servers). Each stops and says why. On a symbol with no listed options, the run stops at once and says why. The candles' exchange and timeframe change nothing on the surface. Only the bold strike follows the candles, at their last close. The surface reads the live bar only, so past bars show nothing. The tiles sit right under the candles, and the surface sits under the tiles. Its strike labels stay clear of the chart's round button. With the default settings the surface shows six expiries by 21 strikes plus the at-the-money summary, over six tiles. ## When data is missing With no usable expiry, the top right reads "No usable expiry in this symbol's options" and both panels clear. The card's skew and term lines then read "no options data", and the headline shows no number. The legend drops its term word. The five readings in the editor's Console (the panel under the code) stay empty. The same happens before the first options update arrives, and when the options carry no contract or no price. Only the live bar holds readings, so the surface has no history. With no expiry 12 hours out or more that has an at-the-money IV, the surface still draws. The card lines then read "no options data". When that expiry has no 25-delta options, the skew line reads "no 25-delta reading". When the one-week or three-month expiry has no at-the-money IV, the caption reads "Term structure: no reading". The term line then reads "no reading". When both are the same expiry, the caption reads "Term structure: one expiry listed" and the legend drops its word. A square stays blank where an expiry has no IV at that strike. A tile reads "no IV" when its expiry has no at-the-money IV. ## Customize it - **Fewer expiries.** `expiries` (6, from 2 to 6) is the surface fold's `columns`: how many of the nearest live expiries make the surface and the tiles; the one-week and three-month picks still read every term row. - **A wider or narrower smile.** `range_pct` (20, from 5 to 40) is the surface fold's `window_pct`: the moneyness range each side of the book's spot inside which the surface shows the 21 strikes nearest it, fewer where the range holds fewer. - **More strikes.** `rows` on the input (21, up to 64) sets the strike rows. Raise `ROWS` with it, since `SurfaceMatrix(MAX_COLUMNS, ROWS)` holds that many and refuses a block that carries more, raise `max_cells` by seven for each row added (its header and six cells), and raise the heat frame's `max_bytes` (8192): a cell takes 25 to 28 bytes on the recorded books (38 at most) and the summary, highlight and caption about 180, so at six columns a row adds about 160 bytes and the frame passes 8192 near 35 to 47 rows, where the run refuses it whole (`wrun_frame_too_large`; a frame is never truncated). - **Another wing.** The skew reads the vol term's 25-delta risk reversal, `term.rr25()`; `rr15()` or `rr10()` reads the 15- or 10-delta one (name the delta in the card's `Skew` row label). - **Another corner.** `position` on the card takes any of the nine anchors, `top_left` to `bottom_right`; the top right holds the notice sentence, so keep the two apart. - **A look of its own.** The card declares no `look`, so it draws the chart's default look. When it should stand apart from the chart, add `look:` with any of the twelve shipped looks ([Looks](../presentation/hud-and-hover-cards.md#looks)), or pick one on the Look row of the indicator's Style page without code, "As made" first ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volatility Surface** under **Beyond the time axis**. 2. Press **Run** on a BTC or ETH chart on any venue (BTCUSDT on Binance Futures at 15m, say): the six tiles and the surface mount below the candles, the card at the top left under the legend, and the legend reads the term word. Rest the pointer on a cell for its exact IV. 3. At the editor's Console prompt, type `last 20 atm_near` to read the nearest expiry's ATM implied volatility on the last 20 bars: only the live bar carries a number, since the folds are read on the live bar only. ## Concepts used - [Book folds](../functions/options-kit.md#book-folds) for `BookStamp`, `SurfaceMatrix` and `VolTerm`, the rows each reads and the row width they share, and [Chain page views](../core-concepts/data-sources.md#chain-page-views) for the `surface` and `vol_term` words, their knobs bound to settings with `"@<param>"` and the hosted runs' refusal - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `panel.tiles`, `panel.heatmap` with `row_title` and `col_title` ([Heatmap](../presentation/cards-frames-panels.md#heatmap)), a heatmap frame's `summary`, `highlight` and `caption` ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)), `fbExpiryLabel` and `writeFrameBuffer` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `width` and `safe_area`, and a `render.label` with a `position` as a corner readout - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.value`, its `hint` and `tile.rows` with `leader: "dots"` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Legend](../presentation/legend.md) for `render.legend` and a string slot's words in the legend - [Text formatting](../functions/text-formatting.md) for the `sb_*` and `fb_*` builders and `sb_signed`, and [A second builder](../functions/text-formatting.md#a-second-builder) for the `TextBuilder` mask that spells each strike <!-- source: https://openmarket.xyz/wrun/cookbook/vol-character --> # Volatility character How the chart market's own price has moved, read from its closed daily candles on any market and any interval, in one pane below the chart that the **View** setting picks, beside a card that names the volatility's character. **Historical volatility** draws five lines over the past year: the annualized standard deviation of daily log returns over 10, 20, 30, 60 and 90 days, the caption reading the 30-day value and where it sits in its year ("HV 30d 18.4%, 64th percentile of its year"). **Volatility cone** sets each lookback (10, 30, 60, 90 and 180 days) against its own past year: the 90th, 75th, median, 25th and 10th percentile of that window's readings as five lines across the lookbacks, today's reading as a sixth, so a "Now" line near the top of the cone is volatility high for this market and near the bottom low. **Return structure** draws the 120-day rolling lag-1 autocorrelation of daily returns with a signed fill, the up colour above 0 where a day tends to follow the day before through, the down colour below 0 where it tends to reverse it, and the Hurst exponent of the price over the year in its title ("Return structure, Hurst 0.46 random"). **Seasonality** shows the average annualized daily move by weekday, by day of the month, or on the monthly options expiry against the session after it, the hottest and the calmest buckets in the text colour and the rest muted. **Character** lists the readings behind the card in a table, each with a line on what it says. The card at the top left, in the chart's default look, names the character first (mean-reverting, moderate or persistent: how fast a volatility shock decays), then the half-life on a meter marked at 10 and 30 days, the Hurst exponent of the changes in log realized volatility, how predictable tomorrow's volatility direction is, and the 30-day volatility with its rank in the year. The parts are the chart's own close, the bar grid ([Data sources](../core-concepts/data-sources.md)); one `candles` stream of the same market at `1d`, the newest 800 closed days on the first bar and each day as it closes ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)); two `param.choice` settings labelled **View** and **Seasonality by** ([Setting kinds](../settings/kinds.md)); five frames feeding two `panel.line` panes over time, one `panel.line` over lookbacks, one `panel.bars` and one `panel.table`, of which the module writes only the picked view's frame ([Cards, frames and panels](../presentation/cards-frames-panels.md)); a `render.hud` card in the chart's default look, of a headline `tile.pill`, a `tile.meter` and a `tile.rows` with dotted leaders ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)); and a label for the one sentence while the history is short. It reads candles only, so it runs on crypto, US stocks and ETFs, CME futures, forex and gold alike; implied volatility is the [Volatility surface](iv-surface.md)'s, which reads the option chain. This is also the `vol-character` template: the **Volatility Character** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volatility Character: how this market's own price has moved, read from its closed daily candles on any market and any // chart interval (crypto, US stocks and ETFs, CME futures, forex and gold alike), in one pane below the chart that the // View setting picks, beside a card that names the volatility's character. Historical volatility: the annualized // standard deviation of daily log returns over 10, 20, 30, 60 and 90 days, one line each over the past year. Volatility // cone: for lookbacks of 10, 30, 60, 90 and 180 days, the past year of that window's realized volatility as percentile // lines (10th, 25th, median, 75th, 90th) with today's reading across them. Return structure: the 120-day rolling lag-1 // autocorrelation of daily returns (above 0 the days follow through, below 0 they reverse), the Hurst exponent of the // price in the title. Seasonality: the average annualized daily move by weekday, by day of the month, or on the monthly // options expiry against the session after it, the hottest and calmest buckets in the text ink and the rest muted. // Character: the readings behind the card in a table. The card at the top // left names the character (mean-reverting, moderate or persistent: how fast a volatility shock decays), the half-life // on a fast-to-sticky meter, the Hurst exponent of the changes in log realized volatility, how predictable tomorrow's // volatility direction is, and the 30-day volatility against its past year. A year is 252 sessions on a market that // closes for the weekend and 365 days on one that trades every day; every reading is as of the newest closed day. // Implied volatility is not read here (this file reads candles only, so it runs everywhere): the IV Term Structure // template reads the option chain and sets its implied volatility against this realized volatility. section("View"); param.choice("view", ["Historical volatility", "Volatility cone", "Return structure", "Seasonality", "Character"], "Historical volatility", { label: "View", description: "The pane below the chart: realized volatility by window, the cone, the return structure, the seasonality or the character readings" }); param.choice("season_by", ["Weekday", "Day of month", "OpEx"], "Weekday", { label: "Seasonality by", when: "view=3", description: "The Seasonality view's buckets: weekday, day of the month, or the monthly options expiry against the session after it" }); input("close", ohlcv.close); // the chart's own candles: the bar grid the daily stream rides input("days", candles.cells, { interval: "1d", bars: 800, description: "The newest 800 closed daily candles of the chart's market, then each day as it closes" }); output("hv_10", none, overlay, { format: "%", description: "Historical volatility over 10 days: the annualized standard deviation of daily log returns, percent" }); // data-only: the card, the Console and an alert read them output("hv_20", none, overlay, { format: "%", description: "Historical volatility over 20 days, percent" }); output("hv_30", none, overlay, { format: "%", description: "Historical volatility over 30 days, percent" }); output("hv_60", none, overlay, { format: "%", description: "Historical volatility over 60 days, percent" }); output("hv_90", none, overlay, { format: "%", description: "Historical volatility over 90 days, percent" }); output("hv30_rank", none, overlay, { description: "Where the 30-day historical volatility sits in its past year: the share of the year's readings below it, 0 to 100" }); output("autocorr_120", none, overlay, { description: "Lag-1 autocorrelation of daily log returns over 120 days: above 0 the days follow through, below 0 they reverse" }); output("hurst_price", none, overlay, { description: "Hurst exponent of the log price over the past year: above 0.5 trending, 0.5 a random walk, below 0.5 mean-reverting" }); output("half_life", none, overlay, { description: "Half-life of a volatility shock in trading days, from an AR(1) fit on log 5-day realized volatility; 250 when it shows no reversion" }); output("hurst_rv", none, overlay, { description: "Hurst exponent of the changes in log 5-day realized volatility, over 5 to 40 days: above 0.5 volatility moves persist" }); output("predictability", none, overlay, { description: "How well today's volatility direction foretells tomorrow's: 1 minus its conditional entropy in bits, 0 a coin flip, 1 certain" }); output("character_code", none, overlay, { description: "0 mean-reverting (half-life under 10 days), 1 moderate (10 to 30 days), 2 persistent (over 30 days)" }); string("character_word", { max_bytes: 24 }); // the card's headline: "Mean-reverting" string("hv30_text", { max_bytes: 32 }); // the card's last row: "18.4%, 64th pct" string("notice", { max_bytes: 96 }); // the one sentence while the history is too short const hvRows = frame("hv_rows", { max_bytes: 32768 }); // one frame per view: the View setting picks the one written const coneRows = frame("cone_rows", { max_bytes: 4096 }); const acRows = frame("ac_rows", { max_bytes: 16384 }); const seasonRows = frame("season_rows", { max_bytes: 4096 }); const charRows = frame("char_rows", { max_bytes: 4096 }); // The five panes. A frame never written leaves its pane off the chart, so only the view picked draws. panel.line({ name: "windows", title: "Historical volatility", x: "time", place: "below", frame: hvRows, height_frac: 0.3, hover_card: true, format: "%", decimals: 1, series: [ { name: "10d", color: "theme.muted", width: 1 }, { name: "20d", color: "theme.muted", width: 1 }, { name: "30d", color: "theme.text", width: 2 }, { name: "60d", color: "theme.muted", width: 1.5 }, { name: "90d", color: "theme.muted", width: 1.5 }, ] }); panel.line({ name: "cone", title: "Volatility cone", x: "number", place: "below", frame: coneRows, height_frac: 0.3, hover_card: true, format: "%", decimals: 1, x_title: "Lookback, days", x_format: "auto", x_decimals: 0, x_unit: "d", series: [ { name: "90th", color: "theme.muted", width: 1, line_style: "dashed" }, { name: "75th", color: "theme.muted", width: 1 }, { name: "Median", color: "theme.muted", width: 1.5 }, { name: "25th", color: "theme.muted", width: 1 }, { name: "10th", color: "theme.muted", width: 1, line_style: "dashed" }, { name: "Now", color: "theme.text", width: 2, points: true }, ] }); panel.line({ name: "returns", title: "Return structure", x: "time", place: "below", frame: acRows, height_frac: 0.3, hover_card: true, legend_style: "none", y_zero: true, fill_mode: "signed", fill_positive_color: "theme.up", fill_negative_color: "theme.down", fill_fade: true, format: "0.00", series: [{ name: "Autocorrelation, 120d", color: "theme.text", width: 1.5 }] }); panel.bars({ name: "seasonality", title: "Volatility by weekday", x: "category", place: "below", frame: seasonRows, height_frac: 0.3, hover_card: true, legend_style: "none", format: "%", decimals: 1, series: [{ name: "Average annualized move", color: "theme.muted" }] }); panel.table({ name: "character", title: "Volatility character", x: "category", place: "below", frame: charRows, height_frac: 0.3, header_column: true, grid_lines: "rows", series: [{ name: "Reading" }, { name: "Value", align: "right" }, { name: "What it says" }] }); // The card at the top left under the legend: the character first, the half-life on a meter from fast to sticky with // marks at 10 and 30 days, then three rows. render.hud("character_card", { position: "top_left", safe_area: true, title: "Volatility character", columns: 1, width: 250, tiles: [ tile.pill("Character", "character_word", { headline: true }), tile.meter("Half-life, trading days", "half_life", { min: 0, max: 60, marks: [10, 30] }), tile.rows([ ["Hurst, vol changes", "hurst_rv", "0.00"], ["Predictability", "predictability", "0.00"], ["HV 30d", "hv30_text"], ], { leader: "dots" }), ], }); render.label("notice", { position: "top_right", text: "notice", offset: [12, 8], style: "plain", color: "theme.muted", size: 12 }); const CAP = 1024; // daily candles held, newest last; a full buffer drops its oldest DROP const DROP = 256; const DAY_SEC: f64 = 86400.0; const WINDOWS: StaticArray<i32> = [10, 20, 30, 60, 90]; // the historical volatility windows, days const LOOKBACKS: StaticArray<i32> = [10, 30, 60, 90, 180]; // the cone's lookbacks, days const CONE_PCTS: StaticArray<f64> = [0.9, 0.75, 0.5, 0.25, 0.1]; // the cone's lines, in the panel's series order const AC_DAYS = 120; // the return structure's rolling window, in returns const RV_DAYS = 5; // the character's realized volatility window, days const MIN_OBS = 60; // realized volatility readings the character needs const MIN_SAMPLES = 20; // readings a percentile needs const HALF_LIFE_CAP: f64 = 250.0; // the half-life read when volatility shows no reversion const INV_LN2: f64 = 1.4426950408889634; const DAY_NAMES: StaticArray<string> = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const CHARACTER_WORDS: StaticArray<string> = ["Mean-reverting", "Moderate", "Persistent"]; const HOT = "theme.text"; // the hottest seasonality bucket const CALM = "theme.text"; // the calmest const PLAIN = "theme.muted"; const dayOpen = new StaticArray<f64>(CAP); // each held day's open, epoch seconds (00:00 UTC of its trade date) const dayClose = new StaticArray<f64>(CAP); const ret = new StaticArray<f64>(CAP); // log return into each day, NaN on the first const sum1 = new StaticArray<f64>(CAP); // prefix sums of the returns and of their squares const sum2 = new StaticArray<f64>(CAP); const lnClose = new StaticArray<f64>(CAP); const lnRv = new StaticArray<f64>(CAP); // log 5-day realized volatility, NaN where it is undefined const scratch = new StaticArray<f64>(CAP); // a lookback's year of readings, sorted for the cone const bucketSum = new StaticArray<f64>(31); // the seasonality buckets: summed moves and counts const bucketCount = new StaticArray<i32>(31); let view = 0; // settings, read in onStart() let seasonBy = 0; let days = 0; // days held let fresh = false; // a day arrived since the last measure let annual: f64 = 252.0; // sessions a year: 365 on a market that trades through the weekend let year = 252; // the past year, in held days // The newest closed day's readings, written to the outputs on every bar. let hv10: f64 = NaN; let hv20: f64 = NaN; let hv30: f64 = NaN; let hv60: f64 = NaN; let hv90: f64 = NaN; let rank30: f64 = NaN; let acNow: f64 = NaN; let hurstPrice: f64 = NaN; let halfLife: f64 = NaN; let arDay: f64 = NaN; let hurstRv: f64 = NaN; let predict: f64 = NaN; let character: f64 = NaN; let obs = 0; // realized volatility readings in the character's sample let civMonth = 0; let civDay = 0; // civil()'s answer function onStart(): void { view = i32(p_view()); seasonBy = i32(p_season_by()); } function weekday(sec: f64): i32 { return i32((i64(Math.floor(sec / DAY_SEC)) + 3) % 7); } // 1970-01-01 was a Thursday: 0 is Monday function civil(sec: f64): void { // the UTC calendar day and month of epoch seconds (days to civil, no Date) const z = i64(Math.floor(sec / DAY_SEC)) + 719468; const era = (z >= 0 ? z : z - 146096) / 146097; const doe = z - era * 146097; const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); const mp = (5 * doy + 2) / 153; civDay = i32(doy - (153 * mp + 2) / 5 + 1); civMonth = i32(mp < 10 ? mp + 3 : mp - 9); } // The monthly options expiry: the third Friday on a market that closes for the weekend (US listed options), the last // Friday on one that trades every day (Deribit's monthly). function isOpex(sec: f64): bool { if (weekday(sec) != 4) return false; civil(sec); if (annual < 300.0) return civDay >= 15 && civDay <= 21; const month = civMonth; civil(sec + 7.0 * DAY_SEC); return civMonth != month; } // The stream into the held days: each closed candle once, oldest first; a full buffer drops its oldest DROP days. function fold(t: f64): void { const block = in_days_view(); const cells = in_days_cells(); // f64 values, six 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) { const close = block[i + 4]; if (!(close > 0.0)) continue; const open = t + block[i] / 1000.0; // the day's open, epoch seconds if (days > 0 && open <= dayOpen[days - 1]) continue; if (days == CAP) { for (let k = DROP; k < CAP; k += 1) { dayOpen[k - DROP] = dayOpen[k]; dayClose[k - DROP] = dayClose[k]; } days = CAP - DROP; } dayOpen[days] = open; dayClose[days] = close; days += 1; fresh = true; } } // Realized volatility over `len` returns ending on day i: the sample standard deviation of the daily log returns, // annualized by the square root of the sessions a year, in percent; NaN until the window is full. function hv(len: i32, i: i32): f64 { if (i - len < 0 || i >= days) return NaN; const s1 = sum1[i] - sum1[i - len]; const s2 = sum2[i] - sum2[i - len]; let v = (s2 - (s1 * s1) / f64(len)) / f64(len - 1); if (v < 0.0) v = 0.0; return Math.sqrt(v * annual) * 100.0; } function yearFrom(len: i32): i32 { // the first day of the past year with a full window const from = days - year; return from < len ? len : from; } // The share of the past year's readings of a window below a value, in percent; NaN under MIN_SAMPLES readings. function rankOf(len: i32, value: f64): f64 { let n = 0; let below = 0; for (let i = yearFrom(len); i < days; i += 1) { const v = hv(len, i); if (isNaN(v)) continue; n += 1; if (v < value) below += 1; } return n >= MIN_SAMPLES && !isNaN(value) ? (100.0 * f64(below)) / f64(n) : NaN; } // Lag-1 autocorrelation of the AC_DAYS returns ending on day i, around their own mean. function autocorr(i: i32): f64 { const from = i - AC_DAYS + 1; if (from < 1 || i >= days) return NaN; let m = 0.0; for (let j = from; j <= i; j += 1) m += ret[j]; m /= f64(AC_DAYS); let num = 0.0; let den = 0.0; for (let j = from; j <= i; j += 1) { const a = ret[j] - m; den += a * a; if (j > from) num += a * (ret[j - 1] - m); } return den > 0.0 ? num / den : NaN; } // The Hurst exponent by the scaling of differences: the slope of ln(standard deviation of x[j] - x[j - k]) on ln k // over k = k0, 2 k0, 4 k0, ...; 0.5 for a random walk, above it trending, below it mean-reverting. function hurst(src: StaticArray<f64>, from: i32, to: i32, k0: i32, steps: i32): f64 { let sx = 0.0; let sy = 0.0; let sxx = 0.0; let sxy = 0.0; for (let s = 0; s < steps; s += 1) { const k = k0 << s; let n = 0; let mean = 0.0; for (let j = from + k; j <= to; j += 1) { const d = src[j] - src[j - k]; if (isNaN(d)) continue; mean += d; n += 1; } if (n < MIN_SAMPLES) return NaN; mean /= f64(n); let v = 0.0; for (let j = from + k; j <= to; j += 1) { const d = src[j] - src[j - k]; if (isNaN(d)) continue; v += (d - mean) * (d - mean); } v /= f64(n - 1); if (!(v > 0.0)) return NaN; const x = Math.log(f64(k)); const y = 0.5 * Math.log(v); sx += x; sy += y; sxx += x * x; sxy += x * y; } const m = f64(steps); const den = m * sxx - sx * sx; return den > 0.0 ? (m * sxy - sx * sy) / den : NaN; } // The AR(1) slope of log realized volatility on itself RV_DAYS days back: the two windows share no return, so the // overlap of a rolling window never reads as persistence. function arLag(from: i32, to: i32): f64 { let n = 0; let mx = 0.0; let my = 0.0; for (let j = from + RV_DAYS; j <= to; j += 1) { const x = lnRv[j - RV_DAYS]; const y = lnRv[j]; if (isNaN(x) || isNaN(y)) continue; mx += x; my += y; n += 1; } if (n < MIN_SAMPLES) return NaN; mx /= f64(n); my /= f64(n); let sxy = 0.0; let sxx = 0.0; for (let j = from + RV_DAYS; j <= to; j += 1) { const x = lnRv[j - RV_DAYS]; const y = lnRv[j]; if (isNaN(x) || isNaN(y)) continue; sxy += (x - mx) * (y - my); sxx += (x - mx) * (x - mx); } return sxx > 0.0 ? sxy / sxx : NaN; } function bits(a: i32, b: i32): f64 { // the entropy of a two-way split, in bits const n = a + b; if (n == 0) return 0.0; let h = 0.0; if (a > 0) h -= (f64(a) / f64(n)) * Math.log(f64(a) / f64(n)) * INV_LN2; if (b > 0) h -= (f64(b) / f64(n)) * Math.log(f64(b) / f64(n)) * INV_LN2; return h; } // 1 minus the entropy of tomorrow's volatility direction given today's (up or down day over day), in bits. function predictability(from: i32, to: i32): f64 { let uu = 0; let ud = 0; let du = 0; let dd = 0; let prev = -1; for (let j = from + 1; j <= to; j += 1) { const a = lnRv[j - 1]; const b = lnRv[j]; let dir = -1; if (!isNaN(a) && !isNaN(b)) dir = b > a ? 1 : b < a ? 0 : -1; if (prev == 1 && dir == 1) uu += 1; else if (prev == 1 && dir == 0) ud += 1; else if (prev == 0 && dir == 1) du += 1; else if (prev == 0 && dir == 0) dd += 1; prev = dir; } const n = uu + ud + du + dd; if (n < MIN_SAMPLES) return NaN; return 1.0 - (bits(uu, ud) * f64(uu + ud) + bits(du, dd) * f64(du + dd)) / f64(n); } // Every reading as of the newest closed day: run once each time the stream brings a day. function measure(): void { let weekend = 0; for (let i = 0; i < days; i += 1) { if (weekday(dayOpen[i]) >= 5) weekend += 1; lnClose[i] = Math.log(dayClose[i]); if (i == 0) { ret[0] = NaN; sum1[0] = 0.0; sum2[0] = 0.0; continue; } const r = Math.log(dayClose[i] / dayClose[i - 1]); ret[i] = r; sum1[i] = sum1[i - 1] + r; sum2[i] = sum2[i - 1] + r * r; } annual = weekend * 10 > days ? 365.0 : 252.0; year = i32(annual); const d = days - 1; hv10 = hv(10, d); hv20 = hv(20, d); hv30 = hv(30, d); hv60 = hv(60, d); hv90 = hv(90, d); rank30 = rankOf(30, hv30); acNow = autocorr(d); const priceFrom = d - year < 0 ? 0 : d - year; hurstPrice = d - priceFrom >= MIN_OBS ? hurst(lnClose, priceFrom, d, 1, 5) : NaN; for (let i = 0; i < days; i += 1) { // log 5-day realized volatility: the root mean square of five returns, annualized const s = i >= RV_DAYS ? sum2[i] - sum2[i - RV_DAYS] : 0.0; lnRv[i] = s > 0.0 ? Math.log(Math.sqrt((annual * s) / f64(RV_DAYS)) * 100.0) : NaN; } const from = yearFrom(RV_DAYS); obs = 0; for (let i = from; i <= d; i += 1) if (!isNaN(lnRv[i])) obs += 1; halfLife = NaN; arDay = NaN; hurstRv = NaN; predict = NaN; character = NaN; if (obs < MIN_OBS) return; const b = arLag(from, d); if (!isNaN(b)) { const kept = b > 0.001 ? b : 0.001; halfLife = b >= 1.0 ? HALF_LIFE_CAP : (f64(RV_DAYS) * Math.log(0.5)) / Math.log(kept); if (halfLife > HALF_LIFE_CAP) halfLife = HALF_LIFE_CAP; arDay = b > 0.0 ? Math.exp(Math.log(b < 1.0 ? b : 1.0) / f64(RV_DAYS)) : 0.0; character = halfLife < 10.0 ? 0.0 : halfLife <= 30.0 ? 1.0 : 2.0; } hurstRv = hurst(lnRv, from, d, RV_DAYS, 4); predict = predictability(from, d); } // ── The frames, written on the live bar for the view picked ── function fbPct(v: f64): void { fb_f64(v, 2); } // a percent, or null (JSON's gap) function fbOrdinal(n: i32): void { fb_int(n); fb_text(suffix(n)); } function writeWindows(): void { fb_clear(); fb_text("{\"caption\":\""); if (isNaN(hv30)) fb_text("Needs 31 closed days"); else { fb_text("HV 30d "); fb_f64(hv30, 1); fb_text("%"); if (!isNaN(rank30)) { fb_text(", "); fbOrdinal(i32(Math.round(rank30))); fb_text(" percentile of its year"); } } fb_text("\",\"rows\":["); const first = days - year < 1 ? 1 : days - year; for (let i = first; i < days; i += 1) { if (i > first) fb_text(","); fb_text("["); fb_int(<i64>dayOpen[i]); for (let w = 0; w < WINDOWS.length; w += 1) { fb_text(","); fbPct(hv(WINDOWS[w], i)); } fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_HV_ROWS); } function sortScratch(n: i32): void { // insertion sort: a year of readings at most for (let i = 1; i < n; i += 1) { const v = scratch[i]; let j = i - 1; while (j >= 0 && scratch[j] > v) { scratch[j + 1] = scratch[j]; j -= 1; } scratch[j + 1] = v; } } function percentile(n: i32, p: f64): f64 { // linear between the two nearest order statistics const pos = p * f64(n - 1); const lo = i32(Math.floor(pos)); const hi = lo + 1 < n ? lo + 1 : lo; return scratch[lo] + (scratch[hi] - scratch[lo]) * (pos - f64(lo)); } function writeCone(): void { fb_clear(); fb_text("{\"caption\":\""); if (isNaN(rank30)) fb_text("The cone needs a year of closed days"); else { fb_text("30-day volatility now at the "); fbOrdinal(i32(Math.round(rank30))); fb_text(" percentile of its year"); } fb_text("\",\"rows\":["); for (let l = 0; l < LOOKBACKS.length; l += 1) { const len = LOOKBACKS[l]; let n = 0; for (let i = yearFrom(len); i < days; i += 1) { const v = hv(len, i); if (isNaN(v)) continue; scratch[n] = v; n += 1; } sortScratch(n); if (l > 0) fb_text(","); fb_text("["); fb_int(len); for (let p = 0; p < CONE_PCTS.length; p += 1) { fb_text(","); fbPct(n >= MIN_SAMPLES ? percentile(n, CONE_PCTS[p]) : NaN); } fb_text(","); fbPct(n >= MIN_SAMPLES ? hv(len, days - 1) : NaN); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_CONE_ROWS); } function writeReturns(): void { const first = days - year < AC_DAYS ? AC_DAYS : days - year; let top = 0.05; // the value axis, symmetric around 0 so the zero line sits in the middle for (let i = first; i < days; i += 1) { const v = Math.abs(autocorr(i)); if (v > top) top = v; } fb_clear(); fb_text("{\"caption\":\"Above 0 the days follow through, below 0 they reverse\",\"y_min\":"); fb_f64(-top * 1.2, 3); fb_text(",\"y_max\":"); fb_f64(top * 1.2, 3); fb_text(",\"title\":\"Return structure, Hurst "); // the price's Hurst exponent as words in the run's title if (isNaN(hurstPrice)) fb_text("n/a\""); else { fb_f64(hurstPrice, 2); fb_text(hurstPrice > 0.55 ? " trending\"" : hurstPrice < 0.45 ? " reverting\"" : " random\""); } fb_text(",\"rows\":["); for (let i = first; i < days; i += 1) { if (i > first) fb_text(","); fb_text("["); fb_int(<i64>dayOpen[i]); fb_text(","); fb_f64(autocorr(i), 4); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_AC_ROWS); } function fbBucketKey(b: i32): void { // a seasonality bucket's category key: "Thu", "15", "OpEx" fb_text("\""); if (seasonBy == 0) fb_text(DAY_NAMES[b]); else if (seasonBy == 1) fb_int(b + 1); else fb_text(b == 0 ? "OpEx" : "Day after"); fb_text("\""); } function fbBucketWord(b: i32): void { // the same bucket inside the caption: "Thu", "15th" if (seasonBy == 0) fb_text(DAY_NAMES[b]); else fbOrdinal(b + 1); } function fbBucketAvg(b: i32): void { // a bucket's average move inside the caption, or n/a if (bucketCount[b] == 0) fb_text("n/a"); else { fb_f64(bucketSum[b] / f64(bucketCount[b]), 1); fb_text("%"); } } // The average annualized move (|daily log return| x the root of the sessions a year) by bucket, over the past 365 // calendar days. function writeSeasonality(): void { for (let b = 0; b < 31; b += 1) { bucketSum[b] = 0.0; bucketCount[b] = 0; } const scale = Math.sqrt(annual) * 100.0; const since = dayOpen[days - 1] - 365.0 * DAY_SEC; let all = 0.0; let allCount = 0; for (let j = 1; j < days; j += 1) { if (dayOpen[j] <= since) continue; const move = Math.abs(ret[j]) * scale; all += move; allCount += 1; let b = -1; if (seasonBy == 0) b = weekday(dayOpen[j]); else if (seasonBy == 1) { civil(dayOpen[j]); b = civDay - 1; } else if (isOpex(dayOpen[j])) b = 0; else if (isOpex(dayOpen[j - 1])) b = 1; if (b < 0) continue; bucketSum[b] += move; bucketCount[b] += 1; } const buckets = seasonBy == 0 ? 7 : seasonBy == 1 ? 31 : 2; let hot = -1; let calm = -1; for (let b = 0; b < buckets; b += 1) { if (bucketCount[b] == 0) continue; const avg = bucketSum[b] / f64(bucketCount[b]); if (hot < 0 || avg > bucketSum[hot] / f64(bucketCount[hot])) hot = b; if (calm < 0 || avg < bucketSum[calm] / f64(bucketCount[calm])) calm = b; } fb_clear(); fb_text(seasonBy == 0 ? "{\"title\":\"Volatility by weekday\"" : seasonBy == 1 ? "{\"title\":\"Volatility by day of month\"" : "{\"title\":\"Volatility at the monthly expiry\""); fb_text(",\"caption\":\""); if (hot < 0) fb_text("No closed day in the past year"); else { if (seasonBy == 2) { // "OpEx 21.2%, the day after 9.1%, all days 9.9%" fb_text("OpEx "); fbBucketAvg(0); fb_text(", the day after "); fbBucketAvg(1); } else { // "Hottest Thu 10.8%, calmest Tue 9.1%, all days 9.9%" fb_text("Hottest "); fbBucketWord(hot); fb_text(" "); fbBucketAvg(hot); fb_text(", calmest "); fbBucketWord(calm); fb_text(" "); fbBucketAvg(calm); } fb_text(", all days "); fb_f64(all / f64(allCount), 1); fb_text("%"); } fb_text("\",\"rows\":["); let written = 0; for (let b = 0; b < buckets; b += 1) { if (bucketCount[b] == 0) continue; if (written > 0) fb_text(","); fb_text("["); fbBucketKey(b); fb_text(",{\"value\":"); fb_f64(bucketSum[b] / f64(bucketCount[b]), 2); fb_text(",\"color\":\""); fb_text(b == hot ? HOT : b == calm ? CALM : PLAIN); fb_text("\"}]"); written += 1; } fb_text("]}"); writeFrameBuffer(FRAME_SEASON_ROWS); } function fbRow(label: string): void { // a table row's first cell, then the value cell opens fb_text("["); fb_str(label); fb_text(",\""); } function fbRowEnd(meaning: string): void { // the value cell closes, then the meaning fb_text("\","); fb_str(meaning); fb_text("]"); } function fbReading(v: f64, decimals: i32, unit: string): void { // inside a quoted cell: the number and its unit, or n/a if (isNaN(v)) fb_text("n/a"); else { fb_f64(v, decimals); fb_text(unit); } } function writeCharacter(): void { fb_clear(); fb_text("{\"caption\":\""); if (obs < MIN_OBS) { fb_text("Needs "); fb_int(MIN_OBS); fb_text(" days of 5-day realized volatility, "); fb_int(obs); fb_text(" so far"); } else fb_text("Log 5-day realized volatility over the past year"); fb_text("\",\"rows\":["); fbRow("Character"); fb_text(isNaN(character) ? "n/a" : CHARACTER_WORDS[i32(character)]); fbRowEnd("How fast a volatility shock decays"); fb_text(","); fbRow("Half-life"); if (halfLife >= HALF_LIFE_CAP) fb_text("no reversion"); else fbReading(halfLife, 1, " days"); fbRowEnd("Trading days for a shock to decay halfway back"); fb_text(","); fbRow("AR(1), per day"); fbReading(arDay, 2, ""); fbRowEnd("Day-to-day persistence of log realized volatility"); fb_text(","); fbRow("Hurst, vol changes"); fbReading(hurstRv, 2, ""); fbRowEnd("Above 0.5 volatility moves persist, below 0.5 they reverse"); fb_text(","); fbRow("Predictability"); fbReading(predict, 2, ""); fbRowEnd("0 is a coin flip for tomorrow's direction, 1 is certain"); fb_text(","); fbRow("Observations"); fb_int(obs); fbRowEnd("Days of 5-day realized volatility in the sample"); fb_text("]}"); writeFrameBuffer(FRAME_CHAR_ROWS); } function suffix(n: i32): string { // 1st, 2nd, 3rd, 4th, 11th, 21st const tens = n % 100; const ones = n % 10; if (tens >= 11 && tens <= 13) return "th"; return ones == 1 ? "st" : ones == 2 ? "nd" : ones == 3 ? "rd" : "th"; } function sbOrdinal(n: i32): void { sb_int(n); sb_text(suffix(n)); } // onBar() runs once per bar: fold the closed days this bar carries (the first bar carries the backlog), measure when a // day arrived, write the newest day's readings, and on the live bar the card's words and the picked view's frame. function onBar(): void { fold(bar.time()); if (fresh) { measure(); fresh = false; } out_hv_10(hv10); out_hv_20(hv20); out_hv_30(hv30); out_hv_60(hv60); out_hv_90(hv90); out_hv30_rank(rank30); out_autocorr_120(acNow); out_hurst_price(hurstPrice); out_half_life(halfLife); out_hurst_rv(hurstRv); out_predictability(predict); out_character_code(character); if (!bar.isLast()) return; sb_clear(); sb_text(isNaN(character) ? "n/a" : CHARACTER_WORDS[i32(character)]); str_character_word_sb(); sb_clear(); if (isNaN(hv30)) sb_text("n/a"); else { sb_f64(hv30, 1); sb_text("%"); if (!isNaN(rank30)) { sb_text(", "); sbOrdinal(i32(Math.round(rank30))); sb_text(" pct"); } } str_hv30_text_sb(); sb_clear(); if (days < 32) { // too short for any view: the one sentence and nothing else sb_text("Volatility Character needs 32 closed days, "); sb_int(days); sb_text(" so far"); str_notice_sb(); return; } str_notice_sb(); if (view == 0) writeWindows(); else if (view == 1) writeCone(); else if (view == 2) writeReturns(); else if (view == 3) writeSeasonality(); else writeCharacter(); } ``` ## How it works **One daily stream, any chart.** `input("days", candles.cells, { interval: "1d", bars: 800 })` hands the first bar the newest 800 closed daily candles of the chart's market and every later bar the days that closed since the bar before, so a 5m, a 1h and a 1D chart fold the same days and show the same readings ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). `fold()` keeps each day's open and close once, oldest first, in a buffer of 1,024 days that drops its oldest 256 when full. A forming day never arrives, so every reading is as of the newest closed day, on history bars and the live bar alike. **Returns, prefix sums and the calendar.** `measure()` runs once each time a day arrives: it turns the closes into daily log returns and keeps their running sums and the running sums of their squares, so any window's variance is two subtractions. A market whose days include weekends (more than one day in ten falls on a Saturday or a Sunday) is a 365-day market, every other one a 252-session market; that number annualizes every volatility and is the past year every percentile and sample is drawn from. **Historical volatility.** A window of `len` days is the sample standard deviation of its `len` daily log returns (around their own mean, divided by `len - 1`), times the square root of the sessions a year, in percent: `hv_10` through `hv_90` on every bar. `hv30_rank` is the share of the past year's 30-day readings below today's, the number the caption and the card read. **The cone.** For each lookback the module gathers that window's reading on every day of the past year, sorts them and reads the 90th, 75th, 50th, 25th and 10th percentile, linear between the two nearest readings; a lookback with fewer than 20 readings stays empty. The rows are `[lookback, p90, p75, median, p25, p10, now]` on a `number` axis of days. **Return structure.** `autocorr_120` is the lag-1 autocorrelation of the newest 120 daily returns around their own mean: above 0 a day tends to continue the day before, below 0 to reverse it. The pane draws it for each day of the past year. `hurst_price` is the Hurst exponent of the log price over the year, by the scaling of differences: the slope of the log standard deviation of `k`-day price changes on `log k` for `k` of 1, 2, 4, 8 and 16 days. A random walk reads 0.5, a trending price above it, a mean-reverting one below; the pane's title reads "trending" above 0.55 and "reverting" below 0.45. **Seasonality.** Each day of the past 365 calendar days is one sample, its move `|log return| x sqrt(sessions a year)` in percent, filed under its weekday, its day of the month, or, by OpEx, the monthly options expiry (the third Friday on a 252-session market, where US listed options settle, the last Friday on a 365-day one, Deribit's monthly) and the session after it. A bucket prints its average; the caption names the hottest and the calmest and the average of all days ("Hottest Thu 10.8%, calmest Tue 9.1%, all days 9.9%"). **Character.** The series behind the card is log 5-day realized volatility: the root mean square of five daily returns, annualized, its log. The half-life fits an AR(1) of that series on itself five days back, so the two windows share no return and a rolling window's overlap never reads as persistence: half-life = `5 x ln 0.5 / ln b`, in trading days, 250 when `b` is 1 or more (no reversion), and `AR(1), per day` is `b` to the power one fifth. `hurst_rv` is the Hurst exponent of the changes in that series over 5, 10, 20 and 40 days, the same difference scaling as the price's. `predictability` is 1 minus the entropy, in bits, of tomorrow's volatility direction (up or down day over day) given today's: 0 a coin flip, 1 certain. The character is mean-reverting under a 10-day half-life, moderate from 10 to 30 days and persistent past 30; it needs 60 readings in the year, and `character_code` carries it as 0, 1 or 2. **One frame per view.** Each pane is declared with its own frame, and `onBar()` writes only the frame of the view picked, on the live bar; a frame never written leaves its pane off the chart, so switching **View** reruns the indicator and swaps the pane. The frames carry what moves per run: the caption, a seasonality title, the return structure's value axis (symmetric around 0) and its title with the Hurst reading, the seasonality bars' colours (`{ "value", "color" }`) and the table's cells. **The card reads outputs and slots.** The headline pill reads `character_word`, the word alone (`character_code` carries the character as 0, 1 or 2); the meter reads `half_life` between 0 and 60 with marks at 10 and 30, the edges of the three characters; the rows read `hurst_rv` and `predictability` to two decimals and the `hv30_text` slot ("18.4%, 64th pct"). ## Where it runs Every market with daily candles, on any interval: crypto perpetuals and spot, US stocks and ETFs, forex and gold, and CME futures once you accept the CME market data terms (a copy run from the editor reads them too). It reads only the chart's own market, so no market refuses it. A 252-session market annualizes by 252 and a 365-day market by 365; a market that pauses for holidays simply has no candle on those days. ## When data is missing Under 32 closed days there is no pane: one sentence at the top right reads "Volatility Character needs 32 closed days, 20 so far", and the card prints n/a. Past that each view draws what the history allows: a window shorter than its own length stays empty on the oldest days, a cone lookback with fewer than 20 readings in the year stays empty, the return structure starts once 120 returns are held, and the character waits for 60 readings of 5-day realized volatility (the table's caption says how many it has). How far back the stream reaches depends on the account's history; the readings use whatever arrives. ## Customize it - **Another pane.** **View** picks historical volatility, the cone, the return structure, the seasonality or the character table; **Seasonality by** picks weekday, day of month or OpEx for the seasonality pane. - **Other windows.** `WINDOWS` and `LOOKBACKS` are the historical volatility windows and the cone's lookbacks; the panes' series follow them in order, so edit the series names with them. `bars: 800` on the stream is how many days arrive on the first bar (up to 5000). - **Other character edges.** The thresholds 10 and 30 days in `measure()` and the meter's marks set where moderate and persistent start; `RV_DAYS` is the realized volatility window and the AR(1) lag. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Volatility Character** under **Beyond the time axis**. 2. Press **Run** on BTCUSDT on Binance Futures at 1h: the historical volatility pane fills below the chart and the card names the character at the top left. Open the settings and pick **Volatility cone**, **Return structure**, **Seasonality** or **Character** for the other panes. 3. At the editor's Console prompt, type `hv_30` for the 30-day volatility on the live bar, or `outputs` for every reading together. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for `ohlcv.close`, the chart's own candles and the bar grid the stream rides - [Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream) for the `candles` stream: `interval`, `bars`, the six-number candle and the backlog on the first bar - [Setting kinds](../settings/kinds.md) for the two `param.choice` settings - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `panel.line` on `time` and `number` axes, `panel.bars`, `panel.table` and the frame buffer - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) and [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for `render.hud`, the headline `tile.pill`, `tile.meter` and `tile.rows` - [Strings and text](../functions/text-formatting.md) for the `sb_*` builders and string slots <!-- source: https://openmarket.xyz/wrun/cookbook/strike-breakdown --> # Strike breakdown Bar charts under the price chart show options at each strike (option price level), one chart per expiry date. Calls (bets on a rise) point up and puts (bets on a fall) point down. Bars show open interest (contracts still open) by default, and the Lens switches to today's trading. A tall bar marks a crowded strike, a level traders may defend or target. Use it on a coin, a CME (Chicago futures exchange) future or a US stock before an expiry arrives. Under the hood: it reads `option_contract_state.cells` on the live bar ([Data sources](../core-concepts/data-sources.md#option_contract_state)). It sums `option_contract_flow.cells` by contract over today's bars ([Data sources](../core-concepts/data-sources.md#option_contract_flow)), both through their `present` masks ([The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars)). They feed three frames for three `panel.bars` on a number axis of strikes ([Bars](../presentation/cards-frames-panels.md#bars)). Each has a title and caption written on each run ([Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets)). It uses `optionsTradeDay` for the days to go, and `optionsAsOfMs` and `optionsLiveUntilMs` for the crypto expiries still trading ([the options functions](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock)). It uses `fbExpiryLabel` for each chart's date ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)) and `market.option_contract()` for an option contract's own chart ([Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file)). This is also the `strike-breakdown` template: the **Strike Breakdown** card under **Beyond the time axis** in the editor's starter list. It compiles as written. ## The wrun indicator ```typescript // Strike Breakdown: this symbol's options by strike, in up to three bar charts under the price chart, one per expiry. A // strike is an option's price level, and an expiry is the date an option ends. Each chart shows calls (bets on a rise) // beside puts (bets on a fall) at every strike. The Lens setting picks what the bars measure. Open interest (contracts // still open) is the default. The others are its change since yesterday, contracts today, premium (money paid for // options) today, and net premium today. Net premium is money paid at the ask minus money paid at the bid. At the ask // means buyers paid the seller's price, at the bid sellers took the buyer's price. For open interest, contracts and // premium, puts draw below zero, so calls point up and puts point down. Each chart's title names its date and days to // go, and its caption totals calls and puts. A tall bar marks a strike traders crowd into, a level they may defend or // target. Use it to see where the bets sit before each expiry. // // Under the hood: the lens picks what each bar measures: open interest, its change since the prior day, contracts // traded today, premium traded today, or today's net premium (at the ask minus at the bid); the three lenses that only // grow draw the puts below zero, and the two signed ones keep each side's own sign. Up to three charts sit under the // price chart, the nearest expiries first (on crypto an expiry leaves once it expires at the live bar's close), each // titled by its date (17 Oct, or 15 Jan '27 in another year) and days to go with the calls' and puts' totals in its // caption. Open interest and today's contracts (coins on crypto) come from the chain summary on the newest bar; the // premium lenses sum each contract's flow over today's bars (VWAP times contracts times the market's option multiplier; // without the VWAP or the multiplier, the premium at the ask plus at the bid), today being the trade date on the // market's clock. A bar of today served in part makes the premium lenses a floor: the caption leads with the at-least // sign. The strikes shown sit within the window you set around the close; on an option contract's own chart // (market.option_contract(), whose price axis is the contract's premium) each chart centres on the expiry's middle // strike instead and its title says so. Net premium sides every print, cross trades and late prints too: under that // lens each chart's caption says so after the totals. param.choice("lens", ["open interest", "open interest change", "contracts today", "premium today", "net premium today"], "open interest", { label: "Lens", description: "What the bars measure: open interest (contracts still open), its daily change, contracts or premium today, or net premium. Premium is the money paid for options. Net premium today includes cross and late trades." }); param.int("charts", 2, { min: 1, max: 3, label: "Expiries", description: "How many bar charts to show, one per upcoming expiry date, nearest first" }); param.number("window_pct", 8, { min: 1, max: 15, step: 0.5, label: "Strike window, percent", description: "Shows strikes (option price levels) within this percent of the price, up to 15%" }); input("close", ohlcv.close); // the chart's own close: the strike window's centre input("state", option_contract_state.cells, { max_cells: 6000, expiries: "nearest:6", strike_window_pct: 15, description: "This symbol's options summary on the newest bar: open interest, yesterday's open interest and contracts today. It covers the six nearest expiry dates and strikes within 15% of the price." }); // [root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present] per contract input("flow", option_contract_flow.cells, { max_cells: 6000, expiries: "nearest:6", strike_window_pct: 15, description: "Each contract that traded in the bar, the six nearest expiries, strikes within 15% of the underlying" }); // [root_code, expiry_ms, side_cp, strike, vol_ask, vol_bid, vol_mid, vol_none, prem_ask, prem_bid, share_delta_net, vwap, last_price, iv_last, vol_above_ask, vol_below_bid, present] per contract market.zone(); // the market's clock: today's trade date and each expiry's market.option_multiplier(); // the chain's USD per price unit and size unit: 100 on a US stock, 50 on ES, 1 on a coin; 0 unknown market.option_contract(); // 1 on an option contract's own chart: its close is the contract's premium, never a centre for strikes chart.interval_sec(); // the bar's length: the newest bar's options data is read at its close // The readings, data-only, on the newest bar: the nearest expiry's totals under the lens. output("front_calls", none, overlay, { format: "si", description: "The nearest expiry's calls (bets on a rise) under the Lens, over the strikes shown. Newest bar only." }); output("front_puts", none, overlay, { format: "si", description: "The nearest expiry's puts (bets on a fall) under the Lens, over the strikes shown. Newest bar only." }); output("front_days", none, overlay, { description: "Days left until the nearest expiry date. Newest bar only." }); output("partial", none, overlay, { description: "1 once only part of a bar's options data arrived today. The premium totals are then a minimum." }); const expiry_1 = frame("expiry_1", { max_bytes: 16384 }); const expiry_2 = frame("expiry_2", { max_bytes: 16384 }); const expiry_3 = frame("expiry_3", { max_bytes: 16384 }); panel.bars({ name: "first_expiry", title: "Nearest expiry", x: "number", place: "below", frame: expiry_1, orientation: "vertical", series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }], format: "si", x_title: "Strike", hover_card: true, legend_style: "title", height_frac: 0.2 }); panel.bars({ name: "second_expiry", title: "Second expiry", x: "number", place: "below", frame: expiry_2, orientation: "vertical", series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }], format: "si", x_title: "Strike", hover_card: true, legend_style: "title", height_frac: 0.2 }); panel.bars({ name: "third_expiry", title: "Third expiry", x: "number", place: "below", frame: expiry_3, orientation: "vertical", series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }], format: "si", x_title: "Strike", hover_card: true, legend_style: "title", height_frac: 0.2 }); const STATE = 13; // f64s per contract: OPTION_CONTRACT_STATE_TUPLE const FLOW = 17; // OPTION_CONTRACT_FLOW_TUPLE const CAP = 4096; // contracts today's flow table holds (a power of two), an eighth of it kept free const MAX_EXPIRIES = 8; // expiries the newest bar sorts const MAX_STRIKES = 512; // strikes one chart draws: ES's 5-point ladder holds about 400 in a 15% window // Today's flow by contract: the key (root, expiry, call or put, strike), then the premium and the net premium. const keyRoot = new StaticArray<f64>(CAP); const keyExpiry = new StaticArray<f64>(CAP); const keySide = new StaticArray<f64>(CAP); const keyStrike = new StaticArray<f64>(CAP); const premiumOf = new StaticArray<f64>(CAP); const netOf = new StaticArray<f64>(CAP); const used = new StaticArray<bool>(CAP); const expiryList = new StaticArray<f64>(MAX_EXPIRIES); // the upcoming expiries, nearest first const strikeAt = new StaticArray<f64>(MAX_STRIKES); // one chart's strikes, ascending, and each side's value const callAt = new StaticArray<f64>(MAX_STRIKES); const putAt = new StaticArray<f64>(MAX_STRIKES); let lens = 0; // settings, read in onStart() let charts = 2; let windowShare = 0.08; let zone = 0; // the market facts, read in onStart() let optMult: f64 = NaN; // NaN where the host does not know the multiplier: the premium falls back to the sided floor let optionContract = false; // the chart is one option contract's own: every chart centres on the expiry's middle strike let intervalMs = 0.0; // the bar's length in milliseconds; 0 where the host writes none let asOfMs: f64 = NaN; // the newest bar's as-of: its close let day: f64 = NaN; // today's trade date on the market's clock, as a day number let stored = 0; // contracts in today's table let dropped = false; // a contract found the table full let partialToday = false; let strikes = 0; // strikes in the chart being built function onStart(): void { lens = i32(p_lens()); charts = i32(p_charts()); windowShare = p_window_pct() / 100.0; zone = i32(p_market_zone()); optMult = p_market_option_multiplier() > 0.0 ? p_market_option_multiplier() : NaN; optionContract = i32(p_market_option_contract()) == 1; intervalMs = p_chart_interval_sec() * 1000.0; } // ── Today's flow by contract ── function slotOf(root: f64, expiry: f64, side: f64, strike: f64): i32 { // the contract's slot, or -1 when the table is full let h: u64 = u64(expiry) * 0x2545f4914f6cdd1d; h ^= u64(Math.round(strike * 1000.0)) * 0x27d4eb2f165667c5; h ^= u64(root) * 0x165667b19e3779f9; h ^= u64(side > 0.0 ? 1 : 2); let at = i32(h & u64(CAP - 1)); for (let probe = 0; probe < CAP; probe += 1) { if (!used[at]) { if (stored >= CAP - CAP / 8) return -1; // keep an eighth free so a probe ends quickly used[at] = true; keyRoot[at] = root; keyExpiry[at] = expiry; keySide[at] = side; keyStrike[at] = strike; premiumOf[at] = 0.0; netOf[at] = 0.0; stored += 1; return at; } if (keyExpiry[at] == expiry && keyStrike[at] == strike && keySide[at] == side && keyRoot[at] == root) return at; at = (at + 1) & (CAP - 1); } return -1; } function startDay(today: f64): void { day = today; for (let i = 0; i < CAP; i += 1) used[i] = false; stored = 0; dropped = false; partialToday = false; } function addFlow(cells: StaticArray<f64>, n: i32): void { // one bar's contracts into today's table for (let i = 0; i + FLOW - 1 < n; i += FLOW) { if (isPartial(cells[i + 16])) partialToday = true; if (!(cells[i + 3] > 0.0)) continue; // no strike: the chart's marker for a bar served in part const at = slotOf(cells[i], cells[i + 1], cells[i + 2] > 0.0 ? 1.0 : -1.0, cells[i + 3]); if (at < 0) { dropped = true; continue; } const contracts = cells[i + 4] + cells[i + 5] + cells[i + 6] + cells[i + 7]; const sided = cells[i + 8] + cells[i + 9]; const total = hasBit(cells[i + 16], 0) ? cells[i + 11] * contracts * optMult : sided; // bit 0: the VWAP; else the two sides, a floor premiumOf[at] += total > sided ? total : sided; // an unknown multiplier (NaN) keeps the floor too netOf[at] += cells[i + 8] - cells[i + 9]; } } // ── One chart ── function addStrike(strike: f64, side: f64, value: f64): void { // a value into the chart's row for its strike let j = 0; while (j < strikes && strikeAt[j] < strike) j += 1; if (j == strikes || strikeAt[j] != strike) { if (strikes == MAX_STRIKES) return; for (let k = strikes; k > j; k -= 1) { strikeAt[k] = strikeAt[k - 1]; callAt[k] = callAt[k - 1]; putAt[k] = putAt[k - 1]; } strikeAt[j] = strike; callAt[j] = 0.0; putAt[j] = 0.0; strikes += 1; } if (side > 0.0) callAt[j] += value; else putAt[j] += value; } // The expiry's strikes under the lens, within the window around `centre`. function collect(expiry: f64, centre: f64): void { strikes = 0; if (lens <= 2) { const n = in_state_cells(); if (n <= 0) return; const cells = in_state_view(); for (let i = 0; i + STATE - 1 < n; i += STATE) { const strike = cells[i + 3]; if (cells[i + 1] != expiry || !(strike > 0.0) || Math.abs(strike / centre - 1.0) > windowShare) continue; const present = cells[i + 12]; let value: f64 = NaN; if (lens == 0 && hasBit(present, 10)) value = cells[i + 10]; // bit 10: the open interest else if (lens == 1 && hasBit(present, 10) && hasBit(present, 11)) value = cells[i + 10] - cells[i + 11]; // bit 11: the prior day's else if (lens == 2 && hasBit(present, 9)) value = cells[i + 9]; // bit 9: contracts today if (!isNaN(value)) addStrike(strike, cells[i + 2], value); } return; } for (let at = 0; at < CAP; at += 1) { const strike = keyStrike[at]; if (!used[at] || keyExpiry[at] != expiry || Math.abs(strike / centre - 1.0) > windowShare) continue; addStrike(strike, keySide[at], lens == 3 ? premiumOf[at] : netOf[at]); } } // The centre the window sits on: the close, unless the chart is an option contract's own or no strike of the expiry // lies within the window around it, then the expiry's middle strike. function centreOf(expiry: f64, close: f64): f64 { let low = Infinity; let high = -Infinity; let near = false; const n = in_state_cells(); if (n > 0) { const cells = in_state_view(); for (let i = 0; i + STATE - 1 < n; i += STATE) { const strike = cells[i + 3]; if (cells[i + 1] != expiry || !(strike > 0.0)) continue; if (strike < low) low = strike; if (strike > high) high = strike; if (close > 0.0 && Math.abs(strike / close - 1.0) <= windowShare) near = true; } } for (let at = 0; at < CAP; at += 1) { if (!used[at] || keyExpiry[at] != expiry) continue; const strike = keyStrike[at]; if (strike < low) low = strike; if (strike > high) high = strike; if (close > 0.0 && Math.abs(strike / close - 1.0) <= windowShare) near = true; } if (near && !optionContract) return close; return high >= low ? (low + high) / 2.0 : close; } // The upcoming expiries in the chain summary and today's flow, nearest first; their count. function listExpiries(today: f64, nowMs: f64): i32 { let count = 0; const n = in_state_cells(); if (n > 0) { const cells = in_state_view(); for (let i = 0; i + STATE - 1 < n; i += STATE) count = offerExpiry(cells[i + 1], today, nowMs, count); } for (let at = 0; at < CAP; at += 1) if (used[at]) count = offerExpiry(keyExpiry[at], today, nowMs, count); return count; } function offerExpiry(expiry: f64, today: f64, nowMs: f64, count: i32): i32 { // upcoming: today's or later; on crypto (zone 0) still trading at the as-of, the 08:00 UTC daily gone once it expired if (!(expiry > 0.0) || (zone == 0 ? !(optionsLiveUntilMs(expiry, zone) > nowMs) : optionsTradeDay(expiry, zone) < today)) return count; let j = 0; while (j < count && expiryList[j] < expiry) j += 1; if (j < count && expiryList[j] == expiry) return count; if (j == MAX_EXPIRIES) return count; for (let k = (count < MAX_EXPIRIES ? count : MAX_EXPIRIES - 1); k > j; k -= 1) expiryList[k] = expiryList[k - 1]; expiryList[j] = expiry; return count < MAX_EXPIRIES ? count + 1 : count; } function places(value: f64): i32 { // a coin's open interest or contracts (zone 0) to four decimals; whole values and premium bare return zone == 0 && lens <= 2 && value != Math.floor(value) ? 4 : 0; } function fbCompact(value: f64): void { // 1.2M, 340K, -12K, 12.50 (a coin amount): the number in a few characters const size = Math.abs(value); if (size >= 1e9) { fb_f64(value / 1e9, 1); fb_text("B"); } else if (size >= 1e6) { fb_f64(value / 1e6, 1); fb_text("M"); } else if (size >= 1e3) { fb_f64(value / 1e3, 1); fb_text("K"); } else fb_f64(value, places(value) > 0 ? 2 : 0); } function writeChart(slot: i32, expiry: f64, today: f64): void { let calls = 0.0; let puts = 0.0; for (let k = 0; k < strikes; k += 1) { calls += callAt[k]; puts += putAt[k]; } if (slot == 0) { out_front_calls(calls); out_front_puts(puts); out_front_days(optionsTradeDay(expiry, zone) - today); } const days = i64(optionsTradeDay(expiry, zone) - today); fb_clear(); fb_text("{\"title\":\""); fbExpiryLabel(expiry, asOfMs, zone); // the expiry's trade date: 17 Oct, or 15 Jan '27 in another year fb_text(", "); if (days == 0) fb_text("today"); else { fb_int(days); fb_text(days == 1 ? " day" : " days"); } if (optionContract) fb_text(" · middle strike"); // the window sits on the expiry's middle strike, never the contract's price fb_text("\",\"caption\":\""); if (lens >= 3 && (partialToday || dropped)) fb_text("≥ "); // at least: a bar served in part, or a full table, makes it a floor fb_text("C "); fbCompact(calls); fb_text(" / P "); fbCompact(puts); if (lens == 4) fb_text(" · Includes cross and late trades"); // net premium sides every print fb_text("\",\"rows\":["); for (let k = 0; k < strikes; k += 1) { if (k > 0) fb_text(","); fb_text("["); fb_num(strikeAt[k]); fb_text(","); fb_f64(callAt[k], places(callAt[k])); fb_text(","); fb_f64(lens == 0 || lens == 2 || lens == 3 ? -putAt[k] : putAt[k], places(putAt[k])); // a one-sided lens draws the puts below zero fb_text("]"); } fb_text("]}"); writeFrameBuffer(slot == 0 ? expiry_1 : slot == 1 ? expiry_2 : expiry_3); } // onBar() runs once per bar: a new trade date empties today's table; the bar's contracts join it; on the newest bar, // one chart per upcoming expiry from the chain summary or today's table. function onBar(): void { const close = bar.close(); const today = optionsTradeDay(bar.time() * 1000.0, zone); if (today != day) startDay(today); const n = in_flow_cells(); if (n > 0) addFlow(in_flow_view(), n); out_partial(n < 0 ? NaN : partialToday ? 1.0 : 0.0); if (!bar.isLast()) { out_front_calls(NaN); out_front_puts(NaN); out_front_days(NaN); return; } asOfMs = optionsAsOfMs(bar.time() * 1000.0, intervalMs); // the newest bar's as-of: its close time const count = listExpiries(today, asOfMs); if (count == 0) { out_front_calls(NaN); out_front_puts(NaN); out_front_days(NaN); return; // no chart: an unwritten frame leaves its chart off } for (let slot = 0; slot < charts && slot < count; slot += 1) { const expiry = expiryList[slot]; collect(expiry, centreOf(expiry, close)); writeChart(slot, expiry, today); } } ``` ## How it works **Two inputs, the six nearest expiries.** Both inputs keep the six nearest expiries (`expiries: "nearest:6"`) and the strikes within 15% of the underlying (`strike_window_pct: 15`), up to 6,000 contracts each. The chain summary arrives on the live bar with each contract's open interest (`oi`, bit 10), the prior observation (`oi_prev`, bit 11) and its contracts today (`volume_day`, bit 9). The flow arrives on every bar, one tuple per contract that traded in it. **Today's flow by contract.** Today is the trade date of the bar's open on the market's clock (`market.zone()`: the New York date on a US stock), and each expiry's date reads on the same clock; on a new trade date the table starts again. Each bar's contracts join a table keyed by the contract (root, expiry, call or put, strike): its premium (its VWAP times its contracts times the market's option multiplier, the chart's market fact `market.option_multiplier()`, 100 shares on a US stock, 50 on ES, 1 on a coin, never less than its premium at the ask plus at the bid, which stands in alone when it carries no VWAP or the chart does not know the multiplier) and its net premium (at the ask minus at the bid, where the data plane judges each print by the midpoint of the national best bid and offer just before it on a US stock, and a crypto venue or CME names the taker's side). The table holds 3,584 contracts (4,096 slots, an eighth kept free); a contract past that is left out, and the premium totals in the captions then read as a floor. **The lens.** **Lens** picks each strike's two numbers: **open interest** (the default), **open interest change** (open interest minus the prior observation, for the contracts that carry both), **contracts today**, all three from the chain summary, or **premium today** and **net premium today** from the flow table. Open interest, contracts and premium only grow, so the puts draw below zero; the change and the net premium are signed, so each side keeps its own sign. **One chart per expiry.** **Expiries** (2, up to 3) is how many charts stand under the price chart: the upcoming expiries in the chain summary and in today's flow (today's included), nearest first. On crypto, whose dailies expire at 08:00 UTC, an expiry is upcoming while it still trades at the newest bar's close (`optionsAsOfMs`, `optionsLiveUntilMs`), so once the newest bar closes at 08:00 UTC or later, tomorrow's daily leads (`17 Oct, 1 day`). Each chart keeps that expiry's strikes within **Strike window, percent** (8, up to the 15 the inputs read) of the close, up to 512 strikes (ES's 5-point ladder holds about 400 in a 15% window), calls in the up colour and puts in the down colour at each strike on a number axis, titled by the expiry's label (`fbExpiryLabel`) and days to go (`16 Oct, today` on the expiry day). A coin's open interest and contracts keep their decimals: 12.5 BTC on its bar, two decimals in the caption under 1,000 (`C 16.50 / P 7.75`). The caption sums each side over the strikes shown (`C 1.2M / P 900.0K`); under a premium lens it leads with `≥ ` when a bar of today was served in part or the table was full. A chart the setting does not ask for is never written, so it stays off the screen. **The readings.** Data-only outputs on the live bar: `front_calls` and `front_puts` (the nearest expiry's two totals under the lens, over the strikes shown) and `front_days` (its days to go), with `partial` on every bar (1 once a bar of today was served in part). **Cross and late trades.** The data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: each chart's caption under the net premium lens, after the totals, and the hint of **Lens**. ## What the settings do - **Lens**: What the bars measure: open interest (contracts still open), its daily change, contracts, premium or net premium today. - **Expiries**: How many bar charts to show, one per upcoming expiry date, nearest first. - **Strike window, percent**: Shows strikes within this percent of the price, up to 15%. ## Where it runs It runs on coins with listed options and reads the coin's own options. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read this data. On a futures chart from CME, the Chicago exchange, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read this data. They stop with an error that names it. On an option contract's own chart, it reads the options of the contract's stock or coin. That chart's price is the contract's own price, so each bar chart centres on its expiry's middle strike instead. The middle strike sits halfway between the lowest and the highest strike. The title then ends in `· middle strike`, as in `23 Oct, 6 days · middle strike`. The indicator spots an option contract's chart by itself. Elsewhere, a bar chart also centres on the middle strike when none of its strikes sits near the price. More than 6,000 contracts at once stops the run rather than cutting data. US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless your account has real-time CME access. The chart's legend says which you see. ## When data is missing - **No upcoming expiry.** With no options summary and no trades today on the newest bar, no bar chart appears. The three readings in the Console (the editor's panel that prints values) then stay empty. - **No data.** A bar older than the chart's options history adds nothing, and the Console's `partial` reading stays empty on it. - **Part of a bar.** Sometimes only part of a bar's options data arrives. On a busy symbol, an older bar may come as one empty marker instead of its contracts. This indicator never counts that marker as a contract. Once that happens today, the Console's `partial` reading shows 1. The premium captions then start with `≥ `, so today's premium is at least what they show. - **A strike without a value.** A contract without the Lens's value adds nothing to its strike. That means no open interest, no earlier reading, or no contracts today. ## Customize it - **Where the new positions are.** Set Lens to open interest change: the strikes that gained contracts since the prior day stand out above and below zero. - **Today's money.** Set Lens to premium today with three charts: the dollars spent at each strike of the three nearest expiries. - **A wider view.** Raise Strike window to 15, the widest the inputs read, on a quiet stock, or lower it to 3 on an index ETF, where strikes sit a dollar apart. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Strike Breakdown** under **Beyond the time axis**. 2. Press **Run** on a Deribit BTC chart or on a US stock chart such as SPY: the two nearest expiries stand under the chart by strike; on a US stock the legend names the tier the read was served at. 3. At the editor's Console prompt, type `front_calls` and `front_puts` to read the nearest expiry's totals under the lens. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_contract_state) for `option_contract_state` and [`option_contract_flow`](../core-concepts/data-sources.md#option_contract_flow), their tuples and [their knobs](../core-concepts/data-sources.md#the-knobs), and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for `hasBit`, `isPartial` and bit 14 - [Bars](../presentation/cards-frames-panels.md#bars) and [Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets) for `panel.bars` over frames on a number axis, a per-run title and caption, and an unwritten frame leaving its panel off - [Options kit](../functions/options-kit.md#the-markets-own-date-and-the-chains-clock) for `optionsTradeDay`, `optionsAsOfMs` and `optionsLiveUntilMs` - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel`, and the [Quick reference](../reference/quick-reference.md#declarations-top-level-statements-of-your-file) for `market.option_contract()` <!-- source: https://openmarket.xyz/wrun/cookbook/market-share --> # Market share A donut and a table under the chart split today's US options trading by exchange. The shares count calls (bets on a rise) and puts (bets on a fall), or one side alone. A bigger slice means more of the market's contracts trade on that exchange. Exchanges you do not pick show as Other, and the card names the leader with its share. Use it on US stock charts to see where options trade: crypto and CME (Chicago futures exchange) are not covered. Under the hood: the recipe reads `options_flow` call and put contracts, the whole market's under `scope: "market"`. Each exchange's comes under `scope: "venue"` named by its exchange id, behind the options of a multi setting through `when` and `when_bit` ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). The trade date comes from the `time` source ([Data sources](../core-concepts/data-sources.md#the-time-source)). It draws a `panel.pie` and a `panel.table` from frames written on the live bar ([Frames and panels](../presentation/cards-frames-panels.md)). It also draws a `render.hud` card in the chart's default look from data-only readings and `string` texts ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `market-share` template, the **Market Share** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Market Share: a donut and a table under the chart split today's US options trading by exchange. The shares count // calls (bets on a rise) and puts (bets on a fall), or one side alone. A bigger slice means more of the market's // contracts trade on that exchange. Exchanges you do not pick show as Other, and the card names the leader with its // share. Use it on US stock charts to see where options trade: crypto and CME (Chicago futures exchange) are not // covered. // // Technical notes: where the US listed options market trades its contracts, exchange by exchange. A donut under the // chart cuts the market's contracts of today, or of the newest sessions, into each exchange's share, the part no picked // exchange accounts for as Other, the total in the hole; a table beside it lists each exchange with its exchange id, // its call and put contracts, the contracts measured and its share, largest first, then Other and every venue together. // Calls or puts narrows the measure to one side. A card at the top right names the leader with its share, the next two, // how much of the market the picked exchanges account for and the bars left out. Each exchange is one read // (options_flow's venue scope, named by its exchange id), fetched only while it is picked in Exchanges; the whole is // the market scope's own total. Every exchange read is one data slot of the chart's budget on a copy run from the // editor (the market and nine exchanges are ten, a Plus chart's whole budget; OpenMarket's own package charges one), so // the nine exchanges that trade the most contracts are read by name, two fields each, the five largest picked by // default and the other four in Exchanges, and the rest (Cboe BZX, Nasdaq MRX, MIAX Sapphire and Emerald, MEMX, Nasdaq // GEMX and BX, Cboe C2, MIAX Pearl and any newer venue) read as Other. A bar counts only when the market and at least // one exchange both served a row, so the shares always divide like by like; a bar with one and not the other is left // out and counted. Venue rows are kept 7 days at 1 minute and daily for good (no 5-minute tier), the market's 7 days at // 1 minute, 30 at 5 minutes and daily for good, so on an intraday chart older bars carry no venue row. The shares are a // US stock chart's (market.zone() 1): a CME chain trades on one venue and the crypto venues are not read here, so on // those charts no read is asked (needed_by), nothing draws and the card says why. section("What it measures"); param.choice("types", ["calls and puts", "calls", "puts"], "calls and puts", { label: "Calls or puts", description: "Which contracts count: calls (bets on a rise) and puts (bets on a fall), calls only or puts only." }); param.int("sessions", 1, { min: 1, max: 30, label: "Sessions", description: "How many of the newest sessions the shares cover, today included." }); param.multi("venues", ["Cboe Options", "NYSE Arca", "NYSE American", "Nasdaq PHLX", "Nasdaq Options", "MIAX Options", "Cboe EDGX", "Nasdaq ISE", "BOX"], ["Cboe Options", "NYSE Arca", "NYSE American", "Nasdaq PHLX", "Nasdaq Options"], { label: "Exchanges", description: "The exchanges to show. Each one loads its own data, only while picked. On a copy you run from the editor, each one counts once against the chart's data budget. Trading on other exchanges shows as Other." }); input("close", ohlcv.close); // the chart's own candles: the bar grid (the shares read the whole US market on any US stock chart) input("trade_date", time.trade_date); // the bar's trade date, the New York date on a US stock: the sessions the window counts // The whole: the market scope's call and put contracts. Then each exchange's under the venue scope, named by its id // and read only while picked (when_bit is its place in Venues). input("mkt_calls", options_flow.call_contracts_total, { scope: "market", missing: "nan", needed_by: { size_unit: [2, 3] }, description: "All exchanges: call contracts in this bar." }); input("mkt_puts", options_flow.put_contracts_total, { scope: "market", missing: "nan", needed_by: { size_unit: [2, 3] }, description: "All exchanges: put contracts in this bar." }); input("xcbo_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XCBO", when: "venues", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Cboe Options: call contracts in the bar" }); input("xcbo_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XCBO", when: "venues", when_bit: 0, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Cboe Options: put contracts in the bar" }); input("arco_calls", options_flow.call_contracts_total, { scope: "venue", venue: "ARCO", when: "venues", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "NYSE Arca: call contracts in the bar" }); input("arco_puts", options_flow.put_contracts_total, { scope: "venue", venue: "ARCO", when: "venues", when_bit: 1, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "NYSE Arca: put contracts in the bar" }); input("amxo_calls", options_flow.call_contracts_total, { scope: "venue", venue: "AMXO", when: "venues", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "NYSE American: call contracts in the bar" }); input("amxo_puts", options_flow.put_contracts_total, { scope: "venue", venue: "AMXO", when: "venues", when_bit: 2, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "NYSE American: put contracts in the bar" }); input("xphl_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XPHL", when: "venues", when_bit: 3, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq PHLX: call contracts in the bar" }); input("xphl_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XPHL", when: "venues", when_bit: 3, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq PHLX: put contracts in the bar" }); input("xndq_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XNDQ", when: "venues", when_bit: 4, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq Options: call contracts in the bar" }); input("xndq_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XNDQ", when: "venues", when_bit: 4, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq Options: put contracts in the bar" }); input("xmio_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XMIO", when: "venues", when_bit: 5, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "MIAX Options: call contracts in the bar" }); input("xmio_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XMIO", when: "venues", when_bit: 5, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "MIAX Options: put contracts in the bar" }); input("edgo_calls", options_flow.call_contracts_total, { scope: "venue", venue: "EDGO", when: "venues", when_bit: 6, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Cboe EDGX: call contracts in the bar" }); input("edgo_puts", options_flow.put_contracts_total, { scope: "venue", venue: "EDGO", when: "venues", when_bit: 6, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Cboe EDGX: put contracts in the bar" }); input("xisx_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XISX", when: "venues", when_bit: 7, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq ISE: call contracts in the bar" }); input("xisx_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XISX", when: "venues", when_bit: 7, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "Nasdaq ISE: put contracts in the bar" }); input("xbox_calls", options_flow.call_contracts_total, { scope: "venue", venue: "XBOX", when: "venues", when_bit: 8, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "BOX: call contracts in the bar" }); input("xbox_puts", options_flow.put_contracts_total, { scope: "venue", venue: "XBOX", when: "venues", when_bit: 8, missing: "nan", needed_by: { size_unit: [2, 3] }, description: "BOX: put contracts in the bar" }); market.zone(); // the market's clock: the shares are a US stock chart's (zone 1) // The readings, data-only, one value per bar over the window ending at that bar: the card reads them and the Console // can too. output("market_total", none, overlay, { format: "si", description: "The whole market's contracts over the window's counted bars: calls, puts or both, as Calls or puts picks." }); output("venues_total", none, overlay, { format: "si", description: "The picked exchanges' contracts over the same bars" }); output("coverage", none, overlay, { format: "%", decimals: 1, description: "The picked exchanges' contracts as a percent of the whole market's. Below 100, the rest shows as Other." }); output("top_share", none, overlay, { format: "%", decimals: 1, description: "The leading exchange's share of the whole market's contracts, in percent." }); output("other_share", none, overlay, { format: "%", decimals: 1, description: "The share of the whole market's contracts that no picked exchange accounts for, in percent." }); output("counted_bars", none, overlay, { description: "Bars in the window with data from both the whole market and at least one exchange." }); output("skipped_bars", none, overlay, { description: "Bars in the window left out because only the whole market or only the exchanges had data." }); string("lead_text", { max_bytes: 48 }); // the card's headline: the leader and its share, or why there is none string("second_text", { max_bytes: 32 }); // the next two string("third_text", { max_bytes: 32 }); string("title", { max_bytes: 48 }); // the card's title: the side and the window // The donut and the table, written on the live bar only; the frames carry the rows and the per-run words. const share_rows = frame("share_rows", { max_bytes: 2048 }); const venue_rows = frame("venue_rows", { max_bytes: 4096 }); panel.pie({ name: "share", title: "Market share", x: "category", place: "below", frame: share_rows, hole: 0.6, labels: false, legend_style: "none", hole_total: true, hole_caption: "contracts today", slice_gap: 1, format: "si", chrome: "none", height_frac: 0.25 }); // the exchanges ride the table, in the same colours panel.table({ name: "venues", title: "By exchange", x: "category", place: "below", frame: venue_rows, height_frac: 0.25, font_size: 10, cell_padding: 3, valign: "middle", header_text_color: "theme.muted", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", border_width: 0, series: [ { name: "Exchange" }, { name: "Code" }, { name: "Calls", align: "right", format: "si" }, { name: "Puts", align: "right", format: "si" }, { name: "Contracts", align: "right", format: "si" }, { name: "Share", align: "right", format: "%", decimals: 1 }, ], }); // The card: the leader and its share, the next two, the picked exchanges' coverage of the market and the bars left // out. render.hud("share_card", { position: "top_right", safe_area: true, title: "{{title}}", columns: 1, tiles: [ tile.pill("Leader", "lead_text", { headline: true }), tile.rows([ ["Second", "second_text"], ["Third", "third_text"], ["Picked exchanges", "coverage", "%"], ["Bars left out", "skipped_bars", "int"], ]), ], }); const VENUES = 9; // the options of Venues, in its order const ENTITIES = 10; // the market, then each exchange const STORE = 3; // per entity: call contracts, put contracts, bars with a row const MAX_SESSIONS = 30; // the sessions setting's largest value const NAMES: StaticArray<string> = ["Cboe Options", "NYSE Arca", "NYSE American", "Nasdaq PHLX", "Nasdaq Options", "MIAX Options", "Cboe EDGX", "Nasdaq ISE", "BOX"]; const IDS: StaticArray<string> = ["XCBO", "ARCO", "AMXO", "XPHL", "XNDQ", "XMIO", "EDGO", "XISX", "XBOX"]; const INKS: StaticArray<string> = ["#1d4ed8", "#d97706", "#fbbf24", "#0f766e", "#14b8a6", "#6d28d9", "#60a5fa", "#2dd4bf", "#e11d48"]; const OTHER_INK = "#64748b"; const SIDES: StaticArray<string> = ["contracts", "call contracts", "put contracts"]; const HOLE_SIDES: StaticArray<string> = ["contracts", "calls", "puts"]; // the hole's caption holds 24 characters: "calls, 30 sessions" const ring = new StaticArray<f64>(MAX_SESSIONS * ENTITIES * STORE); // the finished sessions' sums, newest at head - 1 const ringBars = new StaticArray<i32>(MAX_SESSIONS); // each finished session's counted bars const ringSkipped = new StaticArray<i32>(MAX_SESSIONS); // and its bars left out const today = new StaticArray<f64>(ENTITIES * STORE); // today's sums const past = new StaticArray<f64>(ENTITIES * STORE); // the window's finished sessions, summed at each new trade date const win = new StaticArray<f64>(ENTITIES * STORE); // the window: past plus today const got = new StaticArray<f64>(2); // this bar's call and put contracts of one entity const barRows = new StaticArray<f64>(ENTITIES * STORE); // this bar's rows, entity by entity const shown = new StaticArray<f64>(VENUES); // the window's measure per picked exchange const order = new StaticArray<i32>(VENUES); // the picked exchanges sorted by the measure, largest first const itemKey = new StaticArray<i32>(VENUES); // each item's exchange index let types = 0; // settings, read in onStart() let sessions = 1; let venues = 0.0; let day: f64 = NaN; // today's trade date let head = 0; // the ring's next slot, and how many slots hold a session let stored = 0; let todayBars = 0; // today's counted bars and bars left out let todaySkipped = 0; let pastBars = 0; // the same over the window's finished sessions let pastSkipped = 0; let runBars = 0; // counted bars over the whole run let items = 0; // how many exchanges the donut and the table list: the picked ones let zone = 0; // the market's clock, read in onStart() function onStart(): void { zone = i32(p_market_zone()); types = i32(p_types()); sessions = i32(p_sessions()); if (sessions < 1) sessions = 1; if (sessions > MAX_SESSIONS) sessions = MAX_SESSIONS; venues = p_venues(); } // This bar's call and put contracts of entity e into got: the market (0), then exchange e - 1. function readEntity(e: i32): void { if (e == 0) { got[0] = in_mkt_calls(); got[1] = in_mkt_puts(); } else if (e == 1) { got[0] = in_xcbo_calls(); got[1] = in_xcbo_puts(); } else if (e == 2) { got[0] = in_arco_calls(); got[1] = in_arco_puts(); } else if (e == 3) { got[0] = in_amxo_calls(); got[1] = in_amxo_puts(); } else if (e == 4) { got[0] = in_xphl_calls(); got[1] = in_xphl_puts(); } else if (e == 5) { got[0] = in_xndq_calls(); got[1] = in_xndq_puts(); } else if (e == 6) { got[0] = in_xmio_calls(); got[1] = in_xmio_puts(); } else if (e == 7) { got[0] = in_edgo_calls(); got[1] = in_edgo_puts(); } else if (e == 8) { got[0] = in_xisx_calls(); got[1] = in_xisx_puts(); } else { got[0] = in_xbox_calls(); got[1] = in_xbox_puts(); } } // Whether exchange v is read: picked in Venues (a host that fetches its lane anyway is not read). function picked(v: i32): bool { return multiHas(venues, v); } // Entity e's contracts in sums, as the setting picks: both sides, the calls or the puts. function measureIn(sums: StaticArray<f64>, e: i32): f64 { const at = e * STORE; return types == 1 ? sums[at] : types == 2 ? sums[at + 1] : sums[at] + sums[at + 1]; } // A new trade date: today's sums join the ring as its newest session, and the window's finished sessions (the newest // sessions - 1 of them) are summed again. function closeSession(): void { const base = head * ENTITIES * STORE; for (let i = 0; i < ENTITIES * STORE; i += 1) { ring[base + i] = today[i]; today[i] = 0.0; } ringBars[head] = todayBars; ringSkipped[head] = todaySkipped; todayBars = 0; todaySkipped = 0; head = (head + 1) % MAX_SESSIONS; if (stored < MAX_SESSIONS) stored += 1; for (let i = 0; i < ENTITIES * STORE; i += 1) past[i] = 0.0; pastBars = 0; pastSkipped = 0; const take = sessions - 1 < stored ? sessions - 1 : stored; for (let k = 1; k <= take; k += 1) { const slot = (head - k + MAX_SESSIONS) % MAX_SESSIONS; const at = slot * ENTITIES * STORE; for (let i = 0; i < ENTITIES * STORE; i += 1) past[i] += ring[at + i]; pastBars += ringBars[slot]; pastSkipped += ringSkipped[slot]; } } // The picked exchanges and their measure over the window. function fillShown(): void { items = 0; for (let v = 0; v < VENUES; v += 1) { if (!picked(v)) continue; itemKey[items] = v; shown[items] = measureIn(win, v + 1); items += 1; } } // The items sorted by the measure, largest first (insertion sort, ties in Venues' order). function sortItems(): void { for (let k = 0; k < items; k += 1) order[k] = k; for (let i = 1; i < items; i += 1) { const key = order[i]; let j = i - 1; while (j >= 0 && shown[order[j]] < shown[key]) { order[j + 1] = order[j]; j -= 1; } order[j + 1] = key; } } // The picked exchanges' window calls (0) or puts (1): the part of the market they account for. function pickedSide(side: i32): f64 { let sum = 0.0; for (let v = 0; v < VENUES; v += 1) if (picked(v)) sum += win[(v + 1) * STORE + side]; return sum; } // The window in words: " today" or ", 5 sessions", into the frame or the line. function fbWindow(): void { if (sessions == 1) fb_text(" today"); else { fb_text(", "); fb_int(sessions); fb_text(" sessions"); } } function sbWindow(): void { if (sessions == 1) sb_text(" today"); else { sb_text(", "); sb_int(sessions); sb_text(" sessions"); } } // The donut and the table, on the live bar. The donut: one slice per exchange with a share, largest first, then Other; // the table: each exchange with its id, calls, puts, the measure and its share, then Other and every venue together. // An exchange that read no row in the window says so instead of a zero. function writeFrames(total: f64, venuesTotal: f64, reading: bool): void { fb_clear(); fb_text('{"hole_caption":"'); fb_text(HOLE_SIDES[types]); fbWindow(); fb_text('","rows":['); let slices = 0; for (let j = 0; j < items; j += 1) { const k = order[j]; if (!(shown[k] > 0.0)) continue; if (slices > 0) fb_text(","); fb_text("["); fb_str(NAMES[itemKey[k]]); fb_text(","); fb_f64(shown[k], 0); fb_text(","); fb_str(INKS[itemKey[k]]); fb_text("]"); slices += 1; } if (reading && total - venuesTotal > 0.0) { if (slices > 0) fb_text(","); fb_text('["Other",'); fb_f64(total - venuesTotal, 0); fb_text(","); fb_str(OTHER_INK); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_SHARE_ROWS); fb_clear(); fb_text('{"title":"By exchange'); fbWindow(); fb_text('","rows":['); for (let j = 0; j < items; j += 1) { const k = order[j]; const at = (itemKey[k] + 1) * STORE; if (j > 0) fb_text(","); fb_text('[{"text":'); fb_str(NAMES[itemKey[k]]); fb_text(',"text_color":'); fb_str(INKS[itemKey[k]]); fb_text(',"font_weight":"bold"},'); fb_str(IDS[itemKey[k]]); if (win[at + 2] == 0.0) { fb_text(',{"text":"no data","text_color":"theme.muted"},"","",""]'); continue; } fb_text(","); fb_f64(win[at], 0); fb_text(","); fb_f64(win[at + 1], 0); fb_text(","); fb_f64(shown[k], 0); fb_text(","); if (reading) fb_f64((shown[k] / total) * 100.0, 1); else fb_text('""'); fb_text("]"); } if (reading) { if (items > 0) fb_text(","); fb_text('[{"text":"Other","text_color":"theme.muted"},"",'); fb_f64(Math.max(win[0] - pickedSide(0), 0.0), 0); fb_text(","); fb_f64(Math.max(win[1] - pickedSide(1), 0.0), 0); fb_text(","); fb_f64(Math.max(total - venuesTotal, 0.0), 0); fb_text(","); fb_f64((Math.max(total - venuesTotal, 0.0) / total) * 100.0, 1); fb_text('],[{"text":"All exchanges","font_weight":"bold"},"",'); fb_f64(win[0], 0); fb_text(","); fb_f64(win[1], 0); fb_text(","); fb_f64(total, 0); fb_text(",100.0]"); } fb_text("]}"); writeFrameBuffer(FRAME_VENUE_ROWS); } // The card's words, on the live bar: the leader, the next two and the title. function writeWords(total: f64, reading: bool, counted: i32): void { sb_clear(); if (items == 0) sb_text("Pick an exchange"); else if (runBars == 0) sb_text("No exchange data on this chart yet"); else if (counted == 0) sb_text("No exchange data in this window"); else if (!reading) sb_text("Nothing traded in this window"); else { sb_text(NAMES[itemKey[order[0]]]); sb_text(" leads: "); sb_f64((shown[order[0]] / total) * 100.0, 1); sb_text("%"); } str_lead_text_sb(); for (let place = 1; place <= 2; place += 1) { sb_clear(); if (reading && items > place) { sb_text(NAMES[itemKey[order[place]]]); sb_text(" "); sb_f64((shown[order[place]] / total) * 100.0, 1); sb_text("%"); } else sb_text("n/a"); if (place == 1) str_second_text_sb(); else str_third_text_sb(); } sb_clear(); sb_text("Market share, "); sb_text(SIDES[types]); sbWindow(); str_title_sb(); } // Off a US stock chart: no frame (the donut and the table stay off) and the card's reason, on the live bar. function writeOff(): void { str_lead_text(zone == 2 ? "CME options trade on one exchange" : "Works on US stock charts only"); str_second_text("n/a"); str_third_text("n/a"); str_title("Market share"); } // onBar() runs once per bar: a new trade date closes today into the ring; this bar's rows join today when the market // and at least one picked exchange both served one (otherwise the bar is left out and counted); then the window's // readings and, on the live bar, the donut, the table and the card. Off a US stock chart every reading stays NaN. function onBar(): void { if (zone != 1) { // a CME chain trades on one venue, and the crypto venues are not read here: no share to cut if (bar.isLast()) writeOff(); return; } const date = in_trade_date(); if (!isNaN(date) && date != day) { if (!isNaN(day)) closeSession(); day = date; } let marketServed = false; let venueServed = false; for (let e = 0; e < ENTITIES; e += 1) { const at = e * STORE; barRows[at + 2] = 0.0; if (e > 0 && !picked(e - 1)) continue; readEntity(e); if (isNaN(got[0]) || isNaN(got[1])) continue; barRows[at] = got[0]; barRows[at + 1] = got[1]; barRows[at + 2] = 1.0; if (e == 0) marketServed = true; else venueServed = true; } if (marketServed && venueServed) { for (let e = 0; e < ENTITIES; e += 1) { const at = e * STORE; if (barRows[at + 2] != 1.0) continue; today[at] += barRows[at]; today[at + 1] += barRows[at + 1]; today[at + 2] += 1.0; } todayBars += 1; runBars += 1; } else if (marketServed || venueServed) todaySkipped += 1; for (let i = 0; i < ENTITIES * STORE; i += 1) win[i] = past[i] + today[i]; const counted = pastBars + todayBars; const total = measureIn(win, 0); const reading = counted > 0 && total > 0.0; fillShown(); let venuesTotal = 0.0; let top = 0.0; for (let k = 0; k < items; k += 1) { venuesTotal += shown[k]; if (shown[k] > top) top = shown[k]; } out_market_total(counted > 0 ? total : NaN); out_venues_total(counted > 0 ? venuesTotal : NaN); out_coverage(reading ? (venuesTotal / total) * 100.0 : NaN); out_top_share(reading && items > 0 ? (top / total) * 100.0 : NaN); out_other_share(reading ? (Math.max(total - venuesTotal, 0.0) / total) * 100.0 : NaN); out_counted_bars(f64(counted)); out_skipped_bars(f64(pastSkipped + todaySkipped)); if (!bar.isLast()) return; sortItems(); writeFrames(total, venuesTotal, reading); writeWords(total, reading, counted); } ``` ## How it works **The whole and its parts.** The market scope's row carries every exchange's prints together; each venue row carries one exchange's (`call_contracts_total` and `put_contracts_total`, two of the five fields the venue rows serve). A share is an exchange's contracts over the market's, so the shares of the picked exchanges and Other add up to the whole. **Nine exchanges.** Each read is one data slot of the chart's budget on a copy you run from the editor or publish yourself: one slot per distinct `options_flow` read, whether or not Exchanges picks it (OpenMarket's own package charges one). The market and nine exchanges are ten reads, a Plus chart's whole budget, so the package reads the nine that trade the most contracts by name: Cboe Options, NYSE Arca and American, Nasdaq PHLX and the Nasdaq Options Market, MIAX Options, Cboe EDGX, Nasdaq ISE and BOX, the five largest picked by default and the other four in Exchanges. The rest of the market (Cboe BZX, Nasdaq MRX, MIAX Sapphire and Emerald, MEMX, Nasdaq GEMX and BX, Cboe C2, MIAX Pearl and any newer venue) reads as Other, never as a share of the nine. **Like by like.** A bar counts only when the market and at least one picked exchange both served a row; a bar with one and not the other is left out and counted (`skipped_bars`). Venue rows are kept 7 days at one minute and daily for good, with no five-minute tier, while the market's rows reach 30 days at five minutes: on an intraday chart the bars between 7 and 30 days back carry the market's row alone, and counting them would shrink every share. An exchange that served no row on a counted bar adds 0 there. **A US stock chart's shares.** The shares are the US listed market's, so the package reads them on the New York zone only (`market.zone()` 1). Every `options_flow` input carries `needed_by: { size_unit: [2, 3] }` (the shares and contracts markets: a US stock and its option contracts' charts), so a crypto chart asks for nothing. On a CME chart, whose chain trades on one venue, and on a crypto chart, where the crypto venues are not read here, every reading stays NaN, no frame is written (the donut and the table stay off) and the card says why: "One venue: no share" on CME, "Reads US exchanges only" on crypto. **The window and Exchanges.** Sessions is the newest trade dates the shares cover, today included; each finished session's sums are kept in a ring of 30, so the window is summed again only when a new trade date starts. `venues` is a multi setting, one option per exchange: every exchange's two inputs carry `when: "venues"` and that option's `when_bit`, so the chart fetches an exchange's rows only while it is picked, and the code reads the same bits (`multiHas`), so an exchange that is not picked is neither read nor listed, even on a host that fetched its lane anyway; its part of the market lands in Other. ## What the settings do - **Calls or puts**: Counts calls and puts together, calls only or puts only. - **Sessions**: Sets how many of the newest sessions the shares cover, today included. - **Exchanges**: Picks which exchanges to show, each its own download, and trading elsewhere shows as Other. - **Leader**: The exchange with the biggest share, with its percent. - **Second**: The exchange in second place, with its share. - **Third**: The exchange in third place, with its share. - **Picked exchanges**: How much of the whole market the picked exchanges cover, in percent. - **Bars left out**: Bars in the window where only the market or only the exchanges had data. ## Where it runs It works on US stock and ETF charts, and on the charts of their option contracts. Every indicator in your browser can read it there. US options data runs 15 minutes behind unless you have real-time US options data. The chart asks for each exchange by its exchange code. If it cannot ask for an exchange, the legend names that exchange. The shares cover the whole US options market, whatever symbol the chart shows. A CME futures chart has one exchange, and crypto exchanges are not covered. On those charts nothing draws and the card says why. On a daily chart the window reaches back to the first day of stored data. On an intraday chart it reaches back 7 days. Alerts and Protected indicators (published ones that run on OpenMarket's servers) cannot read it. They say which data they lack. ## When data is missing The card says why instead of going blank. On a CME chart it reads "CME options trade on one exchange". On a crypto chart it reads "Works on US stock charts only". It reads "Pick an exchange" while Exchanges has nothing picked. It reads "No exchange data on this chart yet" until a bar has both market and exchange data. It reads "No exchange data in this window" while the window has none. **Bars left out** counts the window's bars where only one side had data. In the table, an exchange with no data in the window says "no data" instead of a zero. If the chart cannot load a data source, the legend shows a chip with the reason. ## Customize it - **A week of shares.** Set Sessions to 5: the donut and the table cover the newest five trade dates. - **Where the calls trade.** Set Calls or puts to calls: each exchange's share of the call contracts. - **Another exchange.** Change one exchange's `venue` id (`"MXOP"` for MEMX, `"C2OX"` for Cboe C2) with its name and colour in the lists: the reads stay at ten, and the exchange it replaces moves to Other. Each exchange you add is one more data slot on a copy run from the editor. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Market Share** under **Beyond the time axis**. 2. Press **Run** on a US stock chart: the donut and the table draw under the chart and the card at the top right, at your own tier, and the legend names the tier. 3. At the editor's Console prompt, type `top_share`, `coverage` and `other_share` to read the window on the live bar, or `skipped_bars` to see how many bars were left out. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` class, the venue scope and its fields - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` - [Setting kinds](../settings/kinds.md) for `param.multi` and its bitmask - [Frames and panels](../presentation/cards-frames-panels.md) for the donut, the table and their frames - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card, its pill and rows - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/premium-by-expiry --> # Premium by expiry Bars under the chart show today's options money by expiry (the day the option ends), one bar per expiry. A bar above zero means premium (money paid for options) leaned to a rise, below zero to a fall. Each bar is labelled with its date and days to go. Tall bars on near dates point to short-term bets, tall bars on far dates to longer views. Use it to see when traders expect a move, on coins, CME (Chicago futures exchange) futures or US stocks. Under the hood: it reads `option_strike_flow.cells` grouped by expiry (`group: "expiry"`). It holds one entry per expiry and option type that traded in each bar, with its present mask last ([Data sources](../core-concepts/data-sources.md#option_strike_flow)). It takes each expiry's days to go from `optionsTradeDay` ([the options functions](../functions/options-kit.md)) and its label from `fbExpiryLabel` ([Panel frames](../presentation/cards-frames-panels.md#panel-frames)). It draws a `panel.bars` below the chart with a caption written on each run ([Cards, frames and panels](../presentation/cards-frames-panels.md#panel-words)). This is also the `premium-by-expiry` template: the **Premium by Expiry** card under **Beyond the time axis** in the editor's starter list. It compiles as written. ## The wrun indicator ```typescript // Premium by Expiry: which expiry dates today's options money went into, as one bar per expiry under the chart. An // expiry is the date an option ends. Premium is the money paid for options. Calls (bets on a rise) bought at the ask // (buyers paying the seller's price) count as bullish. Puts (bets on a fall) sold at the bid (sellers taking the // buyer's price) count as bullish too. Puts bought at the ask and calls sold at the bid count as bearish. Net, the // default view, shows bullish minus bearish premium for each expiry. A bar above zero, in the up colour, means that // expiry's money leaned to a rise. A bar below zero, in the down colour, means it leaned to a fall. Sides shows the two // apart, bullish up and bearish down. Each bar is labelled with its date and its days to go. Tall bars on near dates // point to short-term bets, and tall bars on far dates to longer views. Use it to see when traders expect the move. // // Under the hood: each contract that traded adds its premium by side, calls bought at the ask and puts sold at the bid // as bullish premium, puts bought at the ask and calls sold at the bid as bearish. Net (the default) draws bullish // minus bearish per expiry, in the up colour above zero and the down colour below; Sides draws the two apart, bullish // up and bearish down. The sums run from the session's first bar (each trade date starts again), over the nearest // expiries that traded, labelled by date and days to go. Premium at the mid or with no quote has no side and counts in // neither. The cells come from option_strike_flow, the data plane's sums of each bar's flow per expiry, calls apart // from puts, added bar by bar: a bar served in part (the partial bit, 14) is a floor, and the note says so; a row that // is not whole (no expiry, a side other than call or put) is skipped and counted. 1-minute cells reach back 7 days and // 5-minute cells 30 days. Every print takes a side, cross trades and late prints too: the panel's caption says so. section("Expiries"); param.choice("view", ["net", "sides"], "net", { label: "View", description: "The net view shows bullish minus bearish premium (money paid for options) for each expiry date. The sides view shows bullish up and bearish down." }); param.int("expiries", 12, { min: 1, max: 40, label: "Expiries shown", description: "How many expiry dates to show, nearest first, among those that traded today" }); input("close", ohlcv.close); // the chart's own candles: the bar grid input("trade_date", time.trade_date); // the bar's trade date, the New York date on a US stock: the sums start again on each input("flow", option_strike_flow.cells, { max_cells: 256, group: "expiry", description: "Each bar's flow per expiry, calls apart from puts: [expiry_ms, strike, side_cp, dte_class, vol_ask, vol_bid, vol_mid, vol_none, vol_above_ask, vol_below_bid, prem_ask, prem_bid, prem_mid, prem_none, present]" }); // every expiry of the chart's underlying market.zone(); // the market's clock: each expiry's date and days to go // The readings, data-only: the Console reads them. output("session_net", none, overlay, { description: "Today's bullish minus bearish premium (money paid for options) over every expiry date, in USD. Includes cross and late trades" }); output("top_days", none, overlay, { description: "Days left until the expiry date holding today's largest net premium, up or down" }); output("top_net", none, overlay, { description: "That expiry date's net premium (money paid for options) today, in USD. Includes cross and late trades" }); output("partial_bars", none, overlay, { description: "Bars today whose options data arrived only in part. While this is above 0, the totals are a minimum." }); output("skipped", none, overlay, { description: "Entries today left out because they were incomplete" }); string("note", { max_bytes: 72 }); // the one line while there is nothing to draw, or the sums are a floor const net_rows = frame("net_rows", { max_bytes: 8192 }); const side_rows = frame("side_rows", { max_bytes: 12288 }); panel.bars({ name: "net_by_expiry", title: "Net premium by expiry", x: "category", place: "below", frame: net_rows, orientation: "vertical", color_mode: "sign", positive_color: "theme.up", negative_color: "theme.down", series: [{ name: "Net" }], format: "usd", hover_card: true, legend_style: "title", height_frac: 0.2 }); panel.bars({ name: "sides_by_expiry", title: "Bullish and bearish premium by expiry", x: "category", place: "below", frame: side_rows, orientation: "vertical", color_mode: "series", series: [{ name: "Bullish", color: "theme.up" }, { name: "Bearish", color: "theme.down" }], format: "usd", hover_card: true, legend_style: "title", height_frac: 0.2 }); render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const TUPLE = 15; // f64s per row: OPTION_STRIKE_FLOW_TUPLE const MAX_EXPIRIES = 96; // expiries kept a session, the nearest when more trade const expiryAt = new StaticArray<f64>(MAX_EXPIRIES); // the session's expiries, ascending const bullAt = new StaticArray<f64>(MAX_EXPIRIES); const bearAt = new StaticArray<f64>(MAX_EXPIRIES); let sides = false; // settings, read in onStart() let shown = 12; let zone = 0; // the market's calendar, read in onStart(): an expiry's date and days to go let day: f64 = NaN; // the trade date the sums run over let expiryCount = 0; let partialBars = 0; let skipped = 0; let runCells = 0; // rows read over the whole run function onStart(): void { sides = p_view() == 1.0; shown = i32(p_expiries()); zone = i32(p_market_zone()); } // A row counts when it names an expiry and a call or a put and its present mask is a whole number from 0 up (the // all-zero row of a bar served in part with no flow does not). function rowOk(cells: StaticArray<f64>, i: i32): bool { const present = cells[i + 14]; const side = cells[i + 2]; return cells[i] > 0.0 && (side == 1.0 || side == -1.0) && present >= 0.0 && present == Math.floor(present); } // The row of an expiry, inserted when new; -1 when the table is full and the expiry is later than every kept one. function expirySlot(ms: f64): i32 { let lo = 0; let hi = expiryCount; while (lo < hi) { const mid = (lo + hi) >> 1; if (expiryAt[mid] < ms) lo = mid + 1; else hi = mid; } if (lo < expiryCount && expiryAt[lo] == ms) return lo; if (expiryCount >= MAX_EXPIRIES) { if (lo >= expiryCount) return -1; expiryCount -= 1; // the latest makes room } for (let k = expiryCount; k > lo; k -= 1) { expiryAt[k] = expiryAt[k - 1]; bullAt[k] = bullAt[k - 1]; bearAt[k] = bearAt[k - 1]; } expiryAt[lo] = ms; bullAt[lo] = 0.0; bearAt[lo] = 0.0; expiryCount += 1; return lo; } // One bar's rows into the session's sums. function fold(n: i32): void { const cells = in_flow_view(); let partial = false; for (let i = 0; i + TUPLE - 1 < n; i += TUPLE) { if (!rowOk(cells, i)) { skipped += 1; continue; } if (isPartial(cells[i + 14])) partial = true; runCells += 1; const slot = expirySlot(cells[i]); if (slot < 0) continue; const call = cells[i + 2] > 0.0; const premAsk = cells[i + 10]; const premBid = cells[i + 11]; bullAt[slot] += call ? premAsk : premBid; // calls bought, puts sold bearAt[slot] += call ? premBid : premAsk; // puts bought, calls sold } if (partial) partialBars += 1; } function fbLabel(ms: f64, today: f64): void { // "16 Oct 0d", the expiry 15 Jan '27 in another year fb_text("\""); fbExpiryLabel(ms, today * 86400000.0, zone); fb_text(" "); fb_int(i64(optionsTradeDay(ms, zone) - today)); fb_text("d\""); } // The panel the View setting picks, on the live bar: the nearest expiries, ascending. function writePanel(today: f64): void { const last = expiryCount < shown ? expiryCount : shown; fb_clear(); fb_text("{\"caption\":\"Includes cross and late trades\","); // every print takes a side fb_text("\"rows\":["); for (let e = 0; e < last; e += 1) { if (e > 0) fb_text(","); fb_text("["); fbLabel(expiryAt[e], today); fb_text(","); if (sides) { fb_f64(bullAt[e], 0); fb_text(","); fb_f64(-bearAt[e], 0); } else fb_f64(bullAt[e] - bearAt[e], 0); fb_text("]"); } fb_text("]}"); if (sides) writeFrameBuffer(side_rows); else writeFrameBuffer(net_rows); } // onBar() runs once per bar: a new trade date starts the sums again; the bar's block adds each contract's bullish // and bearish premium to its expiry; then the readings and, on the live bar, the panel and the note. function onBar(): void { const date = in_trade_date(); if (!isNaN(date) && date != day) { day = date; expiryCount = 0; partialBars = 0; skipped = 0; } const n = in_flow_cells(); if (n >= TUPLE) fold(n); let net = 0.0; let topDays: f64 = NaN; let topNet: f64 = NaN; const today = Math.floor(day / 86400.0); // the bar's own date as a day number (the chart fills trade_date on every bar) for (let e = 0; e < expiryCount; e += 1) { const row = bullAt[e] - bearAt[e]; net += row; if (isNaN(topNet) || Math.abs(row) > Math.abs(topNet)) { topNet = row; topDays = optionsTradeDay(expiryAt[e], zone) - today; } } const reading = expiryCount > 0; out_session_net(reading ? net : NaN); out_top_days(topDays); out_top_net(topNet); out_partial_bars(f64(partialBars)); out_skipped(f64(skipped)); if (!bar.isLast()) return; if (reading && !isNaN(today)) writePanel(today); sb_clear(); if (runCells == 0) sb_text("No contract flow on this chart yet"); else if (!reading) sb_text("No contract flow yet this session"); else if (partialBars > 0) { sb_text("Totals are a minimum: "); sb_int(partialBars); sb_text(partialBars == 1 ? " bar arrived in part" : " bars arrived in part"); } str_note_sb(); // an empty text draws no label } ``` ## How it works **An expiry's premium by side.** The data plane sums each bar's prints per expiry, calls apart from puts: each tuple carries `prem_ask` and `prem_bid`, the premium of those prints at the ask and at the bid in the bar. A call row adds its ask premium to bullish and its bid premium to bearish; a put row the other way round. Premium at the mid or with no quote has no side, so neither sum holds it. On crypto and CME every print carries the taker's side: bought by the taker at the ask, sold at the bid. **By expiry, through the session.** The expiries live in a small table kept in date order; a new trade date (`time.trade_date`) empties it. On the live bar the panel reads the nearest Expiries shown that traded this session, each labelled `16 Oct 1d` (the kit's `fbExpiryLabel`; an expiry in another year reads its year, `15 Jan '27`): the expiry's trade date on the market's clock (`market.zone()`: the New York date on a US stock, the UTC date on crypto, the CME trade date on a future) and its days to go from the bar's trade date, 0 on expiration day. `session_net` is the session's bullish minus bearish premium over every expiry, and `top_days` and `top_net` name the expiry holding the most either way. **Whole rows only.** A tuple counts when it is whole: an expiry, a side of `+1` or `-1` and a present mask that is a whole number. Anything else is skipped and counted in `skipped`, never summed under a guess. **Cross and late trades.** On US listed options the data plane sides every print by the quote, cross trades and late or out-of-sequence prints included, because the feed carries no sale conditions, so a source that leaves those prints unsided shows a different net premium. The package says so where its net premium shows: the panel's caption and the descriptions of `session_net` and `top_net`. ## What the settings do - **View**: Net shows bullish minus bearish premium (money paid for options) per expiry date, and sides shows both apart. - **Expiries shown**: How many expiry dates to show, nearest first, among those that traded today. ## Where it runs It runs on coins with listed options and reads the coin's own options on its exchange. A copy you run from the editor (where you write and run your own indicators) reads them too. On a US stock or ETF chart with US listed options, every indicator in your browser can read this data. The charts of that stock's option contracts work the same way. On a futures chart from CME, the Chicago exchange, every indicator in your browser can read it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). US options data is 15 minutes behind unless you have real-time US options data. CME data is 10 minutes behind unless you have real-time CME data. The chart's legend says which you see. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. ## When data is missing When only part of a bar's options data arrives, today's totals become a minimum. A muted label at the top counts such bars, as in "Totals are a minimum: 2 bars arrived in part". A bar with no options data adds nothing. A label at the top says "No contract flow on this chart yet" until a bar has an options trade. It says "No contract flow yet this session" while today has none. The bars under the chart stay hidden until then. ## Customize it - **The sides apart.** Switch View to `sides` to see both bets on an expiry, not only their difference. - **More expiries.** Raise Expiries shown to follow the longer-dated money; the table keeps every expiry that traded. - **Calls and puts.** Keep one sum per side and per type to split each expiry's bar into the four flows. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Premium by Expiry** under **Beyond the time axis**. 2. Press **Run** on a BTC chart or a US stock chart: the bars draw under the chart. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `session_net`, `top_days` and `top_net` to read the session on the live bar. ## Concepts used - [Data sources](../core-concepts/data-sources.md#option_strike_flow) for the `option_strike_flow` tuple and its `group` knob - [Data sources](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for the present mask and the partial bit - [Options kit](../functions/options-kit.md) for `optionsTradeDay` - [Panel frames](../presentation/cards-frames-panels.md#panel-frames) for `fbExpiryLabel` - [Cards, frames and panels](../presentation/cards-frames-panels.md#panel-words) for `panel.bars` and its caption - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/options-at-price --> # Options at price Options at Price stacks option trades at the chart's price when they traded, like a volume profile. It covers the last 1 to 30 sessions, and the busiest price level is marked. Bullish trades are calls (bets on a rise) bought and puts (bets on a fall) sold, and bearish the reverse. A print (one option trade) bought at the ask (the seller's price) means someone paid up for that bet. Use it on a US stock, coin or CME (Chicago futures exchange) future to find where traders bet hardest. Under the hood: sixteen scalar `options_flow` inputs carry the contracts and the premium by side for calls and puts ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). They land each bar's flow on the row holding its typical price, the high plus the low plus the close over three. That price comes from the chart's own candles, with the trade date and session from the `time` source ([Data sources](../core-concepts/data-sources.md#the-time-source)). The rows feed a `plot.levels` profile docked on the price axis, with a `poc_price` in its frame ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)). Its stacked `series` read bullish, neutral at the mid or with no quote, and bearish, or calls and puts. This is also the `options-at-price` template: the **Options at Price** card under **Beyond the time axis** in the editor's starter list. It compiles as written. ## The wrun indicator ```typescript // Options at Price: this symbol's option trades over the last 1 to 30 sessions, stacked by price. The profile sits // on the price axis, like a volume profile. Bullish trades are calls (bets on a rise) bought and puts (bets on a fall) // sold, and bearish the reverse. Neutral trades hit the middle of the quote or had no quote. The busiest price level // is marked. Use it to find the prices where options traders bet hardest. // // Under the hood: the options traded on the chart's underlying over the last 1 to 30 sessions, by the price the stock // stood at when they traded, docked on the price axis as a profile. Each bar's option flow lands on the row holding the // bar's typical price, (high + low + close) / 3, so a finer chart places it more exactly. Sentiment (the default) // splits each row into bullish (calls bought at the ask and puts sold at the bid), neutral (the prints at the mid or // with no quote) and bearish (puts bought at the ask and calls sold at the bid); Calls and puts splits it into the two. // Contracts or premium, by the Measure setting. The rows span the window's lowest to highest typical price, and the // busiest row is marked. The rows come from options_flow, one per bar: 1-minute rows reach back 7 days and 5-minute // rows 30 days, so a window longer than the tier's reach is a floor; a bar without a row adds nothing, and the // regular-session bars that had none are counted. section("Profile"); param.int("sessions", 5, { min: 1, max: 30, label: "Sessions", description: "How many recent trading days the profile adds up, newest first." }); param.int("rows", 48, { min: 8, max: 128, label: "Price levels", description: "How many price levels split the window, from its lowest to its highest typical price. The typical price is the bar's high, low and close averaged." }); param.choice("measure", ["contracts", "premium"], "contracts", { label: "Measure", description: "Counts contracts, or premium (the money paid) in USD." }); param.choice("split", ["sentiment", "calls_puts"], "sentiment", { label: "Split", description: "sentiment splits each level into bullish, neutral and bearish. calls_puts splits it into calls (bets on a rise) and puts (bets on a fall)." }); input("close", ohlcv.close); // the chart's own candles: the bar grid and the typical price input("high", ohlcv.high); input("low", ohlcv.low); input("trade_date", time.trade_date); // the bar's trade date: the window counts them input("session", time.session); // 1 in the regular session: the bars a missing row is counted on input("call_ask", options_flow.call_contracts_ask, { missing: "nan", description: "Call contracts bought at the ask in the bar, on this symbol" }); // NaN on a bar the class serves no row for input("call_bid", options_flow.call_contracts_bid, { missing: "nan", description: "Call contracts sold at the bid" }); input("call_mid", options_flow.call_contracts_mid, { missing: "nan", description: "Call contracts printed at the mid" }); input("call_none", options_flow.call_contracts_none, { missing: "nan", description: "Call contracts printed with no quote" }); input("put_ask", options_flow.put_contracts_ask, { missing: "nan", description: "Put contracts bought at the ask" }); input("put_bid", options_flow.put_contracts_bid, { missing: "nan", description: "Put contracts sold at the bid" }); input("put_mid", options_flow.put_contracts_mid, { missing: "nan", description: "Put contracts printed at the mid" }); input("put_none", options_flow.put_contracts_none, { missing: "nan", description: "Put contracts printed with no quote" }); input("call_prem_ask", options_flow.call_prem_ask, { missing: "nan", description: "Call premium bought at the ask, USD" }); input("call_prem_bid", options_flow.call_prem_bid, { missing: "nan", description: "Call premium sold at the bid, USD" }); input("call_prem_mid", options_flow.call_prem_mid, { missing: "nan", description: "Call premium at the mid, USD" }); input("call_prem_none", options_flow.call_prem_none, { missing: "nan", description: "Call premium with no quote, USD" }); input("put_prem_ask", options_flow.put_prem_ask, { missing: "nan", description: "Put premium bought at the ask, USD" }); input("put_prem_bid", options_flow.put_prem_bid, { missing: "nan", description: "Put premium sold at the bid, USD" }); input("put_prem_mid", options_flow.put_prem_mid, { missing: "nan", description: "Put premium at the mid, USD" }); input("put_prem_none", options_flow.put_prem_none, { missing: "nan", description: "Put premium with no quote, USD" }); // The readings, data-only, on the live bar: the Console reads them. output("poc_price", none, overlay, { description: "The price where the window's options traded most, the middle of the busiest level. Live bar only." }); output("window_total", none, overlay, { description: "Everything the profile holds, in the unit Measure picks. Live bar only." }); output("bull_share", none, overlay, { description: "Bullish as a percent of bullish plus bearish, from trades with a known side only. Live bar only." }); output("sessions_read", none, overlay, { description: "Trading days the profile holds, at most the Sessions setting. Live bar only." }); output("missing_bars", none, overlay, { description: "Regular-hours bars in the window that had no options data. Live bar only." }); string("note", { max_bytes: 72 }); // the one line while the profile is a floor or empty // The two profiles, one per split; only the one the setting picks is written, so the other stays absent. const sentiment_rows = frame("sentiment_rows", { max_bytes: 32768 }); const side_rows = frame("side_rows", { max_bytes: 24576 }); plot.levels({ name: "by_sentiment", frame: sentiment_rows, dock: "right", width_frac: 0.18, labels: false, hover: true, format: "si", poc: true, poc_label: true, series: [{ name: "Bullish", color: "theme.up" }, { name: "Neutral", color: "theme.muted" }, { name: "Bearish", color: "theme.down" }] }); plot.levels({ name: "by_side", frame: side_rows, dock: "right", width_frac: 0.18, labels: false, hover: true, format: "si", poc: true, poc_label: true, series: [{ name: "Calls", color: "theme.up" }, { name: "Puts", color: "theme.down" }] }); render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const MAX_BARS = 16384; // flow bars kept, the newest: 30 sessions of 1-minute regular-session bars fit const MAX_ROWS = 128; const barPrice = new StaticArray<f64>(MAX_BARS); // each kept bar's typical price, trade date and flow, a ring const barDate = new StaticArray<f64>(MAX_BARS); const barBull = new StaticArray<f64>(MAX_BARS); const barNeutral = new StaticArray<f64>(MAX_BARS); const barBear = new StaticArray<f64>(MAX_BARS); const barCalls = new StaticArray<f64>(MAX_BARS); const barPuts = new StaticArray<f64>(MAX_BARS); const rowBull = new StaticArray<f64>(MAX_ROWS); // the profile, folded on the live bar const rowNeutral = new StaticArray<f64>(MAX_ROWS); const rowBear = new StaticArray<f64>(MAX_ROWS); const rowCalls = new StaticArray<f64>(MAX_ROWS); const rowPuts = new StaticArray<f64>(MAX_ROWS); const DAYS = 32; // the newest regular-session trade dates, each with its bars that carried no flow row const dayDate = new StaticArray<f64>(DAYS); const dayMissing = new StaticArray<i32>(DAYS); let sessions = 5; // settings, read in onStart() let rowCount = 48; let premium = false; let bySide = false; let head = 0; // the ring's next slot let kept = 0; // bars in the ring let dayHead = 0; // the dates' ring let days = 0; function onStart(): void { sessions = i32(p_sessions()); rowCount = i32(p_rows()); premium = p_measure() == 1.0; bySide = p_split() == 1.0; } function noteSession(date: f64, missed: bool): void { // a regular-session bar of this trade date, with or without a row const last = (dayHead + DAYS - 1) % DAYS; if (days == 0 || dayDate[last] != date) { dayDate[dayHead] = date; dayMissing[dayHead] = 0; dayHead = (dayHead + 1) % DAYS; if (days < DAYS) days += 1; } if (missed) dayMissing[(dayHead + DAYS - 1) % DAYS] += 1; } function writeProfile(lo: f64, step: f64, first: i32, last: i32, pocPrice: f64): void { fb_clear(); fb_text("{\"poc_price\":"); fb_num(pocPrice); fb_text(",\"prices\":["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(lo + step * (f64(r) + 0.5)); } fb_text("],\"values\":["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(bySide ? rowCalls[r] + rowPuts[r] : rowBull[r] + rowNeutral[r] + rowBear[r]); } fb_text("],\"series\":["); if (bySide) { fb_text("["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(rowCalls[r]); } fb_text("],["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(rowPuts[r]); } fb_text("]]}"); writeFrameBuffer(side_rows); return; } fb_text("["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(rowBull[r]); } fb_text("],["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(rowNeutral[r]); } fb_text("],["); for (let r = first; r <= last; r += 1) { if (r > first) fb_text(","); fb_num(rowBear[r]); } fb_text("]]}"); writeFrameBuffer(sentiment_rows); } // The live bar: the window is the newest Sessions regular-session trade dates; walk back through the ring over the // bars inside it, span the rows over their typical prices, fold every bar onto its row, write the profile and the // readings. function measure(): void { const inWindow = days < sessions ? days : sessions; // trade dates in the window let oldest: f64 = Infinity; // the window's first trade date let missingInWindow = 0; for (let k = 0; k < inWindow; k += 1) { const at = (dayHead - 1 - k + DAYS) % DAYS; oldest = dayDate[at]; missingInWindow += dayMissing[at]; } let count = 0; // ring entries inside the window, newest first let flowDates = 0; // trade dates inside the window that carried a flow row let lastDate: f64 = NaN; for (let k = 0; k < kept; k += 1) { const at = (head - 1 - k + MAX_BARS) % MAX_BARS; if (!(barDate[at] >= oldest)) break; if (barDate[at] != lastDate) { flowDates += 1; lastDate = barDate[at]; } count += 1; } out_sessions_read(f64(flowDates)); out_missing_bars(f64(missingInWindow)); if (count == 0) { out_poc_price(NaN); out_window_total(NaN); out_bull_share(NaN); str_note(kept == 0 ? "No options flow on this chart yet" : "No options flow in the window"); return; } let lo: f64 = Infinity; let hi: f64 = -Infinity; for (let k = 0; k < count; k += 1) { const at = (head - 1 - k + MAX_BARS) % MAX_BARS; if (barPrice[at] < lo) lo = barPrice[at]; if (barPrice[at] > hi) hi = barPrice[at]; } const rowsUsed = hi > lo ? rowCount : 1; const step = hi > lo ? (hi - lo) / f64(rowCount) : Math.max(Math.abs(lo) * 0.001, 0.01); // one row around a single price const base = hi > lo ? lo : lo - step * 0.5; for (let r = 0; r < rowsUsed; r += 1) { rowBull[r] = 0.0; rowNeutral[r] = 0.0; rowBear[r] = 0.0; rowCalls[r] = 0.0; rowPuts[r] = 0.0; } let bull = 0.0; let bear = 0.0; let total = 0.0; for (let k = 0; k < count; k += 1) { const at = (head - 1 - k + MAX_BARS) % MAX_BARS; let r = i32(Math.floor((barPrice[at] - base) / step)); if (r >= rowsUsed) r = rowsUsed - 1; // the highest price sits on the top row's upper edge if (r < 0) r = 0; rowBull[r] += barBull[at]; rowNeutral[r] += barNeutral[at]; rowBear[r] += barBear[at]; rowCalls[r] += barCalls[at]; rowPuts[r] += barPuts[at]; bull += barBull[at]; bear += barBear[at]; total += barCalls[at] + barPuts[at]; } let poc = 0; let best: f64 = -1.0; for (let r = 0; r < rowsUsed; r += 1) { const row = rowCalls[r] + rowPuts[r]; if (row > best) { best = row; poc = r; } } const pocPrice = base + step * (f64(poc) + 0.5); writeProfile(base, step, 0, rowsUsed - 1, pocPrice); // the frame names the busiest row, so the chart marks the same one out_poc_price(pocPrice); out_window_total(total); out_bull_share(bull + bear > 0.0 ? (100.0 * bull) / (bull + bear) : NaN); sb_clear(); if (inWindow < sessions) { sb_text("The chart holds "); sb_int(inWindow); sb_text(" of "); sb_int(sessions); sb_text(" sessions"); } else if (flowDates < inWindow) { sb_text("Options flow on "); sb_int(flowDates); sb_text(" of "); sb_int(inWindow); sb_text(" sessions"); } else if (missingInWindow > 0) { sb_text("Partial: "); sb_int(missingInWindow); sb_text(missingInWindow == 1 ? " regular-hours bar had no options data" : " regular-hours bars had no options data"); } str_note_sb(); // an empty text draws no label } // onBar() runs once per bar: a bar with a flow row joins the ring at its typical price, in the Measure setting's // unit; a regular-session bar without one is counted on its trade date; the live bar measures the window. function onBar(): void { const close = in_close(); const high = in_high(); const low = in_low(); const date = in_trade_date(); const callAsk = premium ? in_call_prem_ask() : in_call_ask(); const callBid = premium ? in_call_prem_bid() : in_call_bid(); const callOther = premium ? in_call_prem_mid() + in_call_prem_none() : in_call_mid() + in_call_none(); const putAsk = premium ? in_put_prem_ask() : in_put_ask(); const putBid = premium ? in_put_prem_bid() : in_put_bid(); const putOther = premium ? in_put_prem_mid() + in_put_prem_none() : in_put_mid() + in_put_none(); const served = !isNaN(callAsk) && !isNaN(callBid) && !isNaN(callOther) && !isNaN(putAsk) && !isNaN(putBid) && !isNaN(putOther); const price = (high + low + close) / 3.0; if (in_session() == 1.0 && !isNaN(date)) noteSession(date, !served); if (served && !isNaN(price) && !isNaN(date)) { barPrice[head] = price; barDate[head] = date; barBull[head] = callAsk + putBid; barNeutral[head] = callOther + putOther; barBear[head] = putAsk + callBid; barCalls[head] = callAsk + callBid + callOther; barPuts[head] = putAsk + putBid + putOther; head = (head + 1) % MAX_BARS; if (kept < MAX_BARS) kept += 1; } if (bar.isLast()) measure(); else { out_poc_price(NaN); out_window_total(NaN); out_bull_share(NaN); out_sessions_read(NaN); out_missing_bars(NaN); } } ``` ## How it works **A bar's flow at a price.** The flow rows carry no underlying price, so each bar's options land on the row holding the bar's typical price, the high plus the low plus the close over three: the average price the underlying traded at while those prints went through. A finer chart places the flow more exactly; on a five-minute chart a row is never off by more than the bar's own range. Every bar with a flow row joins a ring, kept with its typical price, its trade date and its five sums in the Measure setting's unit. **The window.** On the live bar the window is the newest Sessions regular-session trade dates (`time.session` names them, so a pre-market bar never opens one; on crypto every bar is in session and a trade date is a UTC day). The rows are Price levels equal steps from the window's lowest to its highest typical price, and each kept bar adds to the one row holding its price. `poc_price` is the middle of the busiest row, and the frame names it so the chart marks the same row. **The split.** Bullish is the calls bought at the ask plus the puts sold at the bid, bearish the puts bought at the ask plus the calls sold at the bid, and neutral the prints at the mid or with no quote, whose side is unknown. Calls and puts drops the sides and splits each row into the two. On crypto and CME every print carries the taker's side, so neutral reads 0 there. Only the profile the Split setting picks is written, so the other stays absent. ## What the settings do - **Sessions**: How many recent trading days the profile adds up, from 1 to 30. - **Price levels**: How many price levels split the range from the lowest to the highest price, from 8 to 128. - **Measure**: Counts contracts, or premium (the money paid) in USD. - **Split**: sentiment shows bullish, neutral and bearish, and calls_puts shows calls (bets on a rise) beside puts (bets on a fall). ## Where it runs On crypto, it reads the coin's options on one exchange, usually Deribit. An exchange can list a coin's options in two sets, such as Deribit's BTC and BTC_USDC. It reads one set, the one named like the coin. A copy you run from the editor (where you write and run indicators) reads them too. On a US stock or ETF with US listed options, every indicator in your browser can read them. They are real time if you have real-time US options data, and 15 minutes behind otherwise. On a CME futures chart, every indicator in your browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data, and the legend shows which delay applies. It shows the last 7 days on 1-minute charts and the last 30 days on 5-minute charts. So 30 sessions need a 5-minute or longer timeframe. On crypto a session is a UTC day, and the profile holds about 11 days of 1-minute bars (16,384 bars). ## When data is missing A label at the top of the chart says what the profile lacks. "The chart holds 3 of 5 sessions" means the loaded bars hold fewer sessions than you asked for. "Options flow on 4 of 5 sessions" means a session in the window had no options data. A 1-minute chart past 7 days does that. "Partial: 2 regular-hours bars had no options data" means single bars had none. With any of these, the profile counts only what arrived, never a guess at the rest. "No options flow on this chart yet" means no bar on the chart had options data. ## Customize it - **A longer memory.** Raise Sessions to 30 on a fifteen-minute chart to see the month's options positioned by price. - **Finer rows.** Raise Price levels when the window spans a wide range; lower it on a quiet stock so each row holds enough flow to read. - **Premium.** Switch Measure to `premium` to weigh each row by the money spent rather than the contracts. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Options at Price** under **Beyond the time axis**. 2. Press **Run** on a BTC chart or a US stock chart: the profile docks on the price axis. On a US stock or a CME future the copy reads the flow at your own tier, and the legend names the tier. On a CME future, accept the CME market data terms first. 3. At the editor's Console prompt, type `poc_price` for the busiest price and `bull_share` for the window's bullish share of the sided flow. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `options_flow` side fields - [Data sources](../core-concepts/data-sources.md#the-time-source) for `time.trade_date` and `time.session` - [Docked profiles](../presentation/cards-frames-panels.md#docked-profiles) for `plot.levels`, its `series` and `poc_price` - [Limitations](../reference/limitations.md) for the US options rule <!-- source: https://openmarket.xyz/wrun/cookbook/iv-rank --> # IV rank This rank sets today's option prices between the past year's cheapest and priciest. It ranks implied volatility (how big a move option prices expect): high means traders expect big swings. A pane draws the rank, where 0 is the year's lowest implied volatility and 100 its highest. A high rank means expensive options and nervous traders, a low rank cheap options and a calm market. Check it before you buy or sell options, once there are 60 trading days of daily options data. Under the hood: the recipe reads the 30-day at-the-money IV from `option_daily` with `missing: "nan"`, so each session lands on one bar ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It ranks that IV over the window in the options kit's `DayHistory` ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws two step lines and two guides ([Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks)). A `render.hud` card in the chart's default look sits beside them ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). It is also the `iv-rank` template, the **IV Rank** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // IV Rank: where today's option prices sit between the past year's cheapest and priciest. It ranks implied volatility // (how big a move option prices expect): high means traders expect big swings. A pane under the chart draws the rank: 0 // is the year's lowest implied volatility, 100 its highest. A dotted line beside it draws the percentile, the share of // past days with a lower reading. A card at the bottom right names the verdict. A high rank means expensive options and // nervous traders, a low rank cheap options and a calm market. Check it before you buy or sell options. // // Technical notes: the 30-day IV is the at-the-money IV at a constant 30-day maturity from the daily options // statistics (option_daily). The IV rank is where the session's 30-day IV sits between the window's low (0) and high // (100); the IV percentile is the share of the window's earlier sessions whose IV was lower. Both are step lines in a // pane under the chart, with guides at the two bands, and the card reads the verdict, the IV, both readings, the // window's low and high and the sessions behind them. Each session's reading is the statistics job's close of that // session: it lands on its own bar on a daily chart and on the first bar of its day on an intraday chart, and the // lines hold it until the next session's lands (the live session's row arrives after its close). The window is 252 // sessions, about a year, and the history is short until the data plane has kept the statistics that long: below // Minimum history (60 sessions) the card says how many sessions there are and the lines stay empty, so a few days are // never ranked as a year. Between the minimum and a full window the card names the sessions it read. A chart coarser // than a day reads one line saying so. param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "How many past trading days (sessions) today is ranked against. 252 is about a year." }); param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "Trading days of data needed before a rank shows. Until then the card counts the days so far." }); param.number("high_band", 80, { min: 50, max: 100, step: 1, label: "High band", description: "A rank at or above this reads as high IV: options are expensive." }); param.number("low_band", 20, { min: 0, max: 50, step: 1, label: "Low band", description: "A rank at or below this reads as low IV: options are cheap." }); input("close", ohlcv.close); // the chart's own close: the grid input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of this symbol's options, in percent, one reading per trading day" }); // lands on the first bar of its day, NaN elsewhere output("iv_rank", line, lower, { color: "theme.text", width: 2, step: true, label: "IV rank", format: "0.0", description: "Where today's 30-day IV sits between the window's lowest (0) and highest (100). Empty until Minimum history is met." }); output("iv_pct", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, step: true, line_style: "dotted", label: "IV percentile", format: "0.0", description: "The share of past days in the window with a lower 30-day IV, in percent. Empty until Minimum history is met." }); output("high_guide", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "High band", align: "right", description: "The line where the rank turns high" }); output("low_guide", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "Low band", align: "right", description: "The line where the rank turns low" }); output("band", none, lower, { description: "0 low (rank at or below Low band), 1 between, 2 high (at or above High band). It reads 1 while there is no rank." }); output("iv", none, lower, { description: "The newest 30-day IV, in percent" }); output("iv_low", none, lower, { description: "The lowest 30-day IV in the window, in percent" }); output("iv_high", none, lower, { description: "The highest 30-day IV in the window, in percent" }); output("sessions", none, lower, { description: "How many trading days of data the window holds" }); output("status", none, lower, { description: "0 not enough history yet, 1 the rank shows, 2 bars longer than a day. Empty before the first trading day." }); string("read", { max_bytes: 64 }); // the headline: the verdict, or why there is none string("title", { max_bytes: 64 }); // the card's title: the session the readings are as of // The card: the headline, then the IV and the two readings, and the window as rows. render.hud("iv_rank_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("IV rank", "read", { headline: true }), tile.value("30-day IV", "iv", { format: "0.00" }), tile.value("Rank, 0 to 100", "iv_rank", { format: "0.0" }), tile.rows([ ["IV percentile", "iv_pct", "0.0"], ["Lowest IV", "iv_low", "0.00"], ["Highest IV", "iv_high", "0.00"], ["Trading days read", "sessions", "int"], ]), ], }); const DAY = 86400.0; const CAPACITY = 520; // the most sessions the history keeps: the window's largest setting const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const history = new DayHistory(CAPACITY); // one 30-day IV per session const dateClock = new Clock("UTC"); // reads a date from its day number let lookback = 252; // settings, read in onStart() let need = 60; let highBand = 80.0; let lowBand = 20.0; let prevT: f64 = NaN; // the bar spacing: the smallest gap seen between two bars let barSec: f64 = NaN; let held = 0; // the readings, measured when a session lands and held until the next one let ivNow: f64 = NaN; let ivLow: f64 = NaN; let ivHigh: f64 = NaN; let rank: f64 = NaN; let pct: f64 = NaN; function onStart(): void { lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; // the window can never hold more than itself highBand = p_high_band(); lowBand = p_low_band(); } // ── The readings, measured on the bar a session lands ── function measure(): void { held = history.span(lookback); ivNow = history.value(0); ivLow = history.min(lookback); ivHigh = history.max(lookback); const ready = held >= need; rank = ready ? history.rank(lookback) : NaN; pct = ready ? history.percentile(lookback) : NaN; } function bandOf(r: f64): f64 { // 0 low, 1 between, 2 high; 1 with no rank if (isNaN(r)) return 1.0; return r >= highBand ? 2.0 : r <= lowBand ? 0.0 : 1.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } // ── The card's words, on the live bar ── function writeWords(coarse: bool): void { sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (history.count() == 0) sb_text("Waiting for the daily options statistics"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else if (isNaN(rank)) sb_text("No range: the IV has not moved in the window"); else { const b = bandOf(rank); sb_text(b == 2.0 ? "High IV, options expensive: rank " : b == 0.0 ? "Low IV, options cheap: rank " : "Mid-range IV: rank "); sb_f64(rank, 0); sb_text(", percentile "); sb_f64(pct, 0); } str_read_sb(); sb_clear(); sb_text("IV rank, 30-day IV"); if (!coarse && history.count() > 0) { sb_text(", as of "); sbDay(history.day(0)); if (held >= need && held < lookback) { sb_text(", "); sb_int(held); sb_text(" sessions"); } } str_title_sb(); } // onBar() runs once per bar: the bar spacing, then the session's IV when it lands (measured once, held after); every // bar writes the held readings, so an intraday chart draws each session as a step. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; // a weekly bar would read one session a week as a day const iv = in_iv30(); if (!coarse && !isNaN(iv) && iv > 0.0 && history.push(Math.floor(t / DAY), iv)) measure(); out_high_guide(highBand); out_low_guide(lowBand); const ready = !coarse && held >= need; out_iv_rank(ready ? rank : NaN); out_iv_pct(ready ? pct : NaN); out_band(ready ? bandOf(rank) : 1.0); out_iv(coarse ? NaN : ivNow); out_iv_low(coarse ? NaN : ivLow); out_iv_high(coarse ? NaN : ivHigh); out_sessions(coarse ? NaN : f64(held)); out_status(coarse ? 2.0 : history.count() == 0 ? NaN : ready ? 1.0 : 0.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **One reading per session.** The daily options statistics carry one row per session, the statistics job's reading at that session's close. The chart lands it on the session's own bar on a daily chart and on the first bar of its day on an intraday chart; every other bar reads `NaN` under `missing: "nan"`. `DayHistory.push(day, iv)` keeps it under the bar's UTC day, so an intraday chart and a daily chart hold the same sessions, and a revised row for the same day replaces the reading instead of adding one. **The rank and the percentile.** Over the newest `lookback` sessions (252 by default, about a year), `rank()` is `(IV - low) / (high - low) x 100` and `percentile()` is the share of the earlier sessions strictly below today's, times 100. A window whose IV never moved has no range: the rank reads `NaN` and the card says so. **The lines hold.** The readings are measured once, on the bar a session lands, and every later bar writes them again, so an intraday chart draws each session as a step until the next one lands. The live session's own row arrives after its close, so during the session the lines read the previous session. ## What the settings do - **Window, sessions**: The number of past trading days today is ranked against: 252 is about a year. - **Minimum history, sessions**: A rank shows only after this many trading days of data, so a few days never pass for a year. - **High band**: A rank at or above this reads as high IV, which means options are expensive. - **Low band**: A rank at or below this reads as low IV, which means options are cheap. - **IV rank**: The verdict in words: high, mid-range or low IV, with the rank and the percentile. - **30-day IV**: Today's implied volatility for the next 30 days, as a yearly percent. - **Rank, 0 to 100**: Where today's IV sits between the window's lowest IV (0) and its highest (100). - **IV percentile**: The share of past days with a lower IV, which reads truer than the rank after one big spike. - **Lowest IV**: The lowest 30-day IV in the window. - **Highest IV**: The highest 30-day IV in the window. - **Trading days read**: How many trading days of data the window holds. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, 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 CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. A weekly chart would count one trading day a week as a day, so it shows a note instead. Crypto trades every day, so the default **Window, sessions** of 252 covers about eight months there. Set it to 365 for a calendar year. ## When data is missing The history starts the day OpenMarket switched on these daily readings, so it stays short for a year. Below **Minimum history** (60 trading days), the lines stay empty. The card reads "Not enough history yet: 12 of 60 sessions", so a few days never pass for a year. Between the minimum and a full window, the rank uses the days there are and the title counts them. Before the first trading day, the card reads "Waiting for the daily options statistics". The recipe skips a day with no IV reading and never counts it. A chart with bars longer than a day reads "Needs a daily or finer chart". ## Customize it - **A shorter or longer year.** Set `lookback` to 126 for half a year or 504 for two. - **Rank sooner or later.** Lower **Minimum history** to read a rank over fewer sessions, knowing what it is; raise it to wait for a full window. - **Other bands.** Move **High band** and **Low band** to set where the guides sit and where the verdict reads high or low IV. ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **IV Rank** under **Beyond the time axis**. 2. Press **Run** on a US stock's daily chart: the pane fills from the first session the statistics hold, and the card says how many there are. 3. At the editor's Console prompt, type `iv_rank`, `iv_pct` and `sessions` to read the newest readings. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for the `option_daily` class and its fields - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks) for step lines and guides - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card and its tiles <!-- source: https://openmarket.xyz/wrun/cookbook/vrp --> # Variance risk premium Variance risk premium is for option sellers: do options price in bigger moves than the market then makes? The pane draws implied volatility (how big a move option prices expect) beside realized volatility (how much price actually moved). Its premium is the implied volatility of a month ago minus the moves that followed: above zero, sellers got paid. A card names the zone: sell options, neutral or stand down. Use it to judge whether selling options pays now, once 60 premiums exist, about 81 trading days. Under the hood: the recipe reads the 30-day at-the-money IV from `option_daily`. It reads a `candles` stream of the chart's own daily candles, kept in a `CandleList` ([Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists)). Two `DayHistory` rings from the options kit keep the IV and the completed premiums ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws the spread as columns coloured per bar by a sign value, beside a `render.hud` card in the chart's default look. It is also the `vrp` template, the **Variance Risk Premium** card under **Beyond the time axis** in the editor's starter list. It compiles as written. ## The wrun indicator ```typescript // Variance Risk Premium: for option sellers, do options price in bigger moves than the market then makes? A pane under // the chart draws implied volatility (how big a move option prices expect). It also draws realized volatility (how much // price actually moved), and the gap between the two as columns. Then it draws the premium: the implied volatility of a // month ago minus the moves that followed. Above zero, option sellers got paid for the risk they took. A card says sell // options when the premium ranks high, and stand down when it ranks low or negative. Use it to judge whether selling // options has paid lately. // // Technical notes: the chart's underlying's implied volatility against the volatility its price then delivered, from // the daily options statistics (option_daily, the 30-day at-the-money IV per session) and the chart's own daily // candles. Two readings, both in volatility points. The spread is today's 30-day IV minus the realized volatility of // the last 21 daily returns (30 on crypto, which trades every day, so its month holds 30): known at once, but it // compares the forecast with the past. The premium is the IV of that many sessions ago minus the realized volatility of // the returns that followed it: the honest comparison, known only that many sessions later, so it is drawn on the // session it completes, never on the session it starts. Realized volatility annualizes over 252 days a year, 365 on // crypto. The premium's rank is its percentile among the window's earlier completed premiums; at or over the sell rank // with a positive premium the options have paid their sellers (the sell zone), at or under the stand-down rank or with // a negative premium they have not (the stand-down zone). A pane under the chart draws the IV and the realized // volatility as step lines, the spread as columns and the premium as a line; a card at the bottom right reads the zone, // the ratio and the numbers behind them. The statistics are short today (they start when the data plane switches the // daily job on): the spread needs one session, the premium 22 sessions (31 on crypto), and its rank Minimum history // (60) completed premiums; until then the card says how many there are. Daily or finer charts. param.int("rv_days", 0, { min: 0, max: 63, label: "Realized window, days", description: "How many daily price changes each realized volatility measures. 0 is auto: 30 on crypto, which trades every day, and 21 elsewhere. Either way, that is the month the 30-day IV covers." }); param.int("lookback", 252, { min: 20, max: 520, label: "Rank window, sessions", description: "How many past premiums the rank compares against. 252 is about a year, or 8 months on crypto." }); param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "Completed premiums needed before a rank shows. Until then the card counts them." }); param.number("sell_rank", 50, { min: 0, max: 100, step: 1, label: "Sell zone rank", description: "A premium ranked at or above this, and above zero, marks the sell zone." }); param.number("stand_rank", 20, { min: 0, max: 100, step: 1, label: "Stand-down rank", description: "A premium ranked at or below this, or below zero, marks the stand-down zone." }); input("close", ohlcv.close); // the chart's own close: the grid input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of this symbol's options, in percent, one reading per trading day" }); // lands on the first bar of its day, NaN elsewhere input("daily", candles.cells, { interval: "1d", bars: 400, description: "This symbol's closed daily candles, the newest 400 and each new one as it closes, for the realized volatility" }); // [offset_ms, open, high, low, close, volume] per candle, oldest first market.zone(); // the market's clock: 0 UTC on crypto, which trades every day (the realized window and year) output("iv", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, step: true, label: "30-day IV", format: "0.00", unit: "%", description: "The newest 30-day IV, in percent" }); output("rv", line, lower, { color: "theme.text", opacity: 0.32, width: 1, step: true, label: "Realized vol", format: "0.00", unit: "%", description: "How much the price actually moved over the realized window, as a yearly percent. It counts 252 days a year, 365 on crypto." }); output("spread", histogram, lower, { color_by: "spread_sign", colors: ["theme.down", "theme.up"], opacity: 0.6, label: "IV minus realized", format: "0.00", description: "Today's 30-day IV minus the realized volatility up to today's close, in IV points" }); output("premium", line, lower, { color: "theme.text", width: 2, step: true, label: "Premium", format: "0.00", description: "The IV from one realized window ago minus the realized volatility that followed it, in IV points. It draws on the day it completes." }); output("zero", line, lower, { role: "guide", color: "theme.muted", width: 1, line_style: "dashed", label: "0", description: "The zero line" }); output("spread_sign", none, lower, { description: "1 when the IV is above the realized volatility, 0 below. It sets the columns' colour." }); output("zone", none, lower, { description: "0 stand down, 1 neutral, 2 sell zone. Empty until the premium has a rank." }); output("prem_rank", none, lower, { description: "Where the newest premium ranks among the window's earlier ones, 0 to 100" }); output("ratio", none, lower, { description: "The 30-day IV divided by the realized volatility" }); output("completed", none, lower, { description: "How many completed premiums the rank window holds" }); output("status", none, lower, { description: "0 waiting for history or candles, 1 the premium has a rank, 2 bars longer than a day" }); string("read", { max_bytes: 64 }); // the headline: the zone, or why there is none string("title", { max_bytes: 64 }); // the card's title: the session the readings are as of string("spread_text", { max_bytes: 48 }); // "IV over realized by 3.20 pts, 1.21x" render.hud("vrp_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Premium", "read", { headline: true }), tile.pill("Spread", "spread_text", { color_by: "spread_sign", colors: ["theme.down", "theme.up"] }), tile.value("Premium rank", "prem_rank", { format: "0" }), tile.rows([ ["IV, 30 days", "iv", "0.00"], ["Realized vol", "rv", "0.00"], ["IV minus realized", "spread", "0.00"], ["Premium, completed", "premium", "0.00"], ["Premiums ranked", "completed", "int"], ]), ], }); const DAY = 86400.0; const CAPACITY = 520; // the most sessions each history keeps const MAX_CANDLES = 420; // the daily candles kept: the stream's backlog and the window's days const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const ivs = new DayHistory(CAPACITY); // one 30-day IV per session const premiums = new DayHistory(CAPACITY); // one completed premium per session, keyed by the session it starts const days = new CandleList(MAX_CANDLES); // the chart's closed daily candles const dateClock = new Clock("UTC"); let rvDays = 21; // settings, read in onStart() let lookback = 252; let need = 60; let sellRank = 50.0; let standRank = 20.0; let yearDays = 252.0; // the year realized volatility annualizes over: 365 on crypto let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let pairedDay: f64 = NaN; // the newest session the spread has paired with its close let doneDay: f64 = NaN; // the newest session whose premium completed (or can never complete) let lastCandleT: f64 = NaN; // the newest candle seen: new work only when it moves let rvNow: f64 = NaN; // the readings, held until the next session moves them let spreadNow: f64 = NaN; let ratioNow: f64 = NaN; let premiumNow: f64 = NaN; let rankNow: f64 = NaN; function onStart(): void { const crypto = i32(p_market_zone()) == 0; // zone 0, UTC: a market that trades every day of the year rvDays = i32(p_rv_days()) > 0 ? i32(p_rv_days()) : crypto ? 30 : 21; // 0 is auto: a month of the market's sessions yearDays = crypto ? 365.0 : 252.0; lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; sellRank = p_sell_rank(); standRank = p_stand_rank(); } function candleDay(i: i32): f64 { return Math.floor(days.openSec(i) / DAY); } /** The candle of day d, newest first; -1 when the list holds none. */ function candleOf(d: f64): i32 { for (let i = days.count() - 1; i >= 0; i -= 1) { const cd = candleDay(i); if (cd == d) return i; if (cd < d) return -1; } return -1; } /** The realized volatility of the daily log returns from candle first's close to candle last's, annualized, percent: * the sample standard deviation, NaN under two returns or on a close that is not above 0. */ function realized(first: i32, last: i32): f64 { const n = last - first; if (n < 2 || first < 0) return NaN; let sum = 0.0; for (let k = first + 1; k <= last; k += 1) { const before = days.close(k - 1); const after = days.close(k); if (!(before > 0.0) || !(after > 0.0)) return NaN; sum += Math.log(after / before); } const mean = sum / f64(n); let squares = 0.0; for (let k = first + 1; k <= last; k += 1) { const r = Math.log(days.close(k) / days.close(k - 1)) - mean; squares += r * r; } return Math.sqrt((squares / f64(n - 1)) * yearDays) * 100.0; } // ── The spread: the newest session's IV against the realized volatility through its close ── function pairSpread(): void { if (ivs.count() == 0) return; const d = ivs.day(0); if (d == pairedDay) return; const at = candleOf(d); if (at < 0) return; // its candle has not closed yet: the previous pairing holds const rv = realized(at - rvDays, at); pairedDay = d; rvNow = rv; const iv = ivs.value(0); spreadNow = isNaN(rv) ? NaN : iv - rv; ratioNow = rv > 0.0 ? iv / rv : NaN; } // ── The premium: each session's IV against the realized volatility of the rvDays returns after it ── function completePremiums(): void { const newest = days.count() - 1; if (newest < 0) return; const oldestDay = candleDay(0); let moved = false; for (let ago = ivs.count() - 1; ago >= 0; ago -= 1) { // oldest session first const d = ivs.day(ago); if (!isNaN(doneDay) && d <= doneDay) continue; const at = candleOf(d); if (at < 0) { if (d < oldestDay) { doneDay = d; // older than every kept candle: it can never complete continue; } if (d < candleDay(newest)) { doneDay = d; // no candle that day (a holiday on the chart's own calendar): skipped continue; } break; // its candle has not closed yet, nor any later one } if (at + rvDays > newest) break; // not enough returns after it yet, nor after any later session const rv = realized(at, at + rvDays); doneDay = d; if (!isNaN(rv) && premiums.push(d, ivs.value(ago) - rv)) moved = true; } if (!moved) return; premiumNow = premiums.value(0); rankNow = premiums.span(lookback) >= need ? premiums.percentile(lookback) : NaN; } function zoneOf(): f64 { // 0 stand down, 1 neutral, 2 sell; NaN with no rank if (isNaN(rankNow)) return NaN; if (premiumNow < 0.0 || rankNow <= standRank) return 0.0; return rankNow >= sellRank ? 2.0 : 1.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function writeWords(coarse: bool): void { const held = premiums.span(lookback); sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (ivs.count() == 0) sb_text("Waiting for the daily options statistics"); else if (isNaN(rankNow)) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" premiums"); } else { const z = zoneOf(); if (z == 2.0) sb_text("Sell zone: options overpriced, rank "); else if (z == 0.0) sb_text(premiumNow < 0.0 ? "Stand down: options underpriced, rank " : "Stand down: thin premium, rank "); else sb_text("Neutral: premium rank "); sb_f64(rankNow, 0); } str_read_sb(); sb_clear(); if (coarse || ivs.count() == 0) sb_text("No spread"); else if (isNaN(spreadNow)) { sb_text("Needs "); sb_int(rvDays + 1); sb_text(" daily closes"); } else { sb_text(spreadNow >= 0.0 ? "IV over realized by " : "IV under realized by "); sb_f64(Math.abs(spreadNow), 2); sb_text(" pts"); if (!isNaN(ratioNow)) { sb_text(", "); sb_f64(ratioNow, 2); sb_text("x"); } } str_spread_text_sb(); sb_clear(); sb_text("Variance risk premium"); if (!coarse && ivs.count() > 0) { sb_text(", as of "); sbDay(ivs.day(0)); } str_title_sb(); } // onBar() runs once per bar: the bar spacing; every closed daily candle the bar carries; the session's IV when it lands; // then the spread when its close is in and every premium that completed. Each bar writes the held readings. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; days.load(in_daily_view(), in_daily_cells(), t); const iv = in_iv30(); let landed = false; if (!coarse && !isNaN(iv) && iv > 0.0) landed = ivs.push(Math.floor(t / DAY), iv); const newestT = days.count() > 0 ? days.openSec(days.count() - 1) : NaN; if (!coarse && (landed || newestT != lastCandleT)) { lastCandleT = newestT; pairSpread(); completePremiums(); } out_zero(0.0); out_iv(coarse || ivs.count() == 0 ? NaN : ivs.value(0)); out_rv(coarse ? NaN : rvNow); out_spread(coarse ? NaN : spreadNow); out_spread_sign(coarse || isNaN(spreadNow) ? NaN : spreadNow >= 0.0 ? 1.0 : 0.0); out_premium(coarse ? NaN : premiumNow); out_zone(coarse ? NaN : zoneOf()); out_prem_rank(coarse ? NaN : rankNow); out_ratio(coarse ? NaN : ratioNow); out_completed(coarse ? NaN : f64(premiums.span(lookback))); out_status(coarse ? 2.0 : isNaN(rankNow) ? 0.0 : 1.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **Realized volatility.** The sample standard deviation of `rv_days` daily log returns of the chart's own closes, annualized over 252 days a year, in percent: the same unit as the IV. The defaults follow the market's clock (`market.zone()`): `rv_days` 0 is auto, 21 returns on a US stock or a CME future and 30 on crypto, a month of the market's sessions either way, and crypto annualizes over 365 days, since it trades every day. **The spread pairs each session with its own close.** The IV row of a session is its closing reading, so the spread waits for that session's daily candle: on a daily chart they arrive on the same bar; on an intraday chart the candle closes later, and until it does the previous pairing holds. **The premium completes a window later.** Each session's IV is paired with the `rv_days` returns after its close (21, or 30 on crypto). On the bar the last of those candles closes, the premium of that session joins its own `DayHistory` (keyed by the session it starts on) and the line moves. A session with no candle of its own on the chart's calendar is skipped and never blocks the later ones. **The rank and the zone.** `percentile()` over the newest `lookback` completed premiums. The zone is stand down when the premium is negative or the rank is at or under **Stand-down rank** (20), sell when the rank is at or over **Sell zone rank** (50), neutral between. ## What the settings do - **Realized window, days**: How many daily price changes realized volatility measures, where 0 picks 30 on crypto and 21 elsewhere. - **Rank window, sessions**: How many past premiums the rank compares against: 252 is about a year, 8 months on crypto. - **Minimum history, sessions**: A rank shows only after this many completed premiums, so a short history never passes for a year. - **Sell zone rank**: A positive premium ranked at or above this marks the sell zone, where selling options has paid. - **Stand-down rank**: A premium ranked at or below this, or below zero, marks the stand-down zone, where selling has not paid. - **Premium**: The zone in words, sell, neutral or stand down, with the premium's rank. - **Spread**: Today's IV against the realized volatility so far: known at once, but it compares a forecast with the past. - **Premium rank**: Where the newest premium ranks among the window's earlier ones, 0 to 100. - **IV, 30 days**: Today's 30-day implied volatility, as a yearly percent. - **Realized vol**: How much the price actually moved over the realized window, as a yearly percent. - **IV minus realized**: Today's 30-day IV minus the realized volatility, in IV points. - **Premium, completed**: The IV of one window ago minus the moves that followed: the honest comparison, known only later. - **Premiums ranked**: How many completed premiums the rank window holds. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, 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 CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. The daily candles come from this chart's own market. ## When data is missing The history starts the day OpenMarket switched on these daily readings, so it is short. The spread shows from the first trading day, since the candles reach back 400 days. The premium needs 22 trading days, or 31 on crypto. Its rank needs **Minimum history** (60) completed premiums, about 81 trading days in all, or 90 on crypto. Until then the card reads "Not enough history yet: 12 of 60 premiums" and names no zone. With too few daily closes, the card's Spread line reads "Needs 22 daily closes", or 31 on crypto. Before the first trading day, the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". ## Customize it - **Another horizon.** Set `rv_days` to 10 for two weeks of returns, or 63 for a quarter (the premium then completes that many sessions later); 0 goes back to the market's month. - **Another year.** `lookback` sets how many completed premiums the rank reads. - **Other zones.** Move **Sell zone rank** and **Stand-down rank** to the bands you act on. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Variance Risk Premium** under **Beyond the time axis**. 2. Press **Run** on BTCUSDT's daily chart: the lines fill from the first session the statistics hold. 3. At the editor's Console prompt, type `spread`, `premium` and `prem_rank`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) for the `candles` stream and `CandleList` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/skew-history --> # Skew history Skew history tracks how much more puts, which pay when price falls, cost than calls over time. A pane draws calls' implied volatility (how big a move option prices expect) minus puts', daily and per bar. Below zero, puts cost more and traders fear a drop, and the card says how unusual today's reading is. Panels add the term structure (near expiries' prices against far ones) against its past and daily moves in standard deviations. Use it to see fear build or fade, once 60 trading days of daily options data exist. Under the hood: the recipe reads `option_daily` fields and `option_surface` through `hasBit` and `isPartial`. On each bar it asks for the `nearest_days` pick ([Option surface](../core-concepts/data-sources.md#option-surface), [Chain page views](../core-concepts/data-sources.md#chain-page-views)). That is the one expiry nearest **Expiry, days out** with both wings at **Expiry line, delta**. The options kit's `DayHistory` keeps the percentiles, the z-score, the quantiles and each session's 1-day IV ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws the year's percentile in a named pane ([Panes](../presentation/plotting.md#panes)). The Sigma strip comes from a `candles` stream kept in a `CandleList`, with `oneSigmaMove`, as a `panel.bars` coloured per bar ([Bars](../presentation/cards-frames-panels.md#bars)). The term structure draws as a `panel.line` over category maturities ([Line panels](../presentation/cards-frames-panels.md#line-panels)), beside a `render.hud` card. It is also the `skew-history` template, the **Skew History** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Skew History: how this symbol's options skew moves over time. Skew is how much more puts cost than calls. A put pays // when price falls, and a call pays when it rises. Here it is the risk reversal: the call's implied volatility (how big // a move option prices expect) minus the put's. Below zero, puts cost more and traders fear a drop. A pane under the // chart draws the daily 30-day skew and one expiry's skew on every bar. A card rates the skew against its own history. // It also says how pricey puts far below the price are, and flags skew that moves against the price. A panel compares // today's term structure (near expiries' prices against far ones) with its past. A strip shows each day's move in 1σ // moves (one standard deviation). Use it to see fear build or fade. // // Technical notes: how the chart's underlying's options skew has moved, and where today's term structure sits in its // own past. Four reads. The 30-day 25 delta risk reversal, one per session from the daily options statistics // (option_daily: the call's IV minus the put's at the expiry nearest 30 days), drawn as a step line with its percentile // and z-score against the window's earlier sessions. The risk reversal of one expiry, the one nearest the Expiry // setting's days out, at 25 or 10 delta, read on every bar from the option surface (option_surface: one tuple per // expiry with present bits per value; a bar the data plane marks partial, bit 14, draws on a dotted line of its own and // is counted, never mixed into the solid line). The put tail of that same expiry: the 10 delta put's IV minus the 25 // delta put's, drawn on every solid bar, with its z-score against its last Put tail window solid readings in five steps // (low at -1.5 or under, easing at -0.5 or under, normal, elevated at +0.5 or over, high at +1.5 or over); the window // holds one expiry's readings and restarts when the picked expiry rolls. And the term structure now against its window: // the at-the-money IV at seven constant maturities (7 days to a year) beside each one's median and 25th and 75th // percentile over the window's sessions, in a panel below the chart. The surface line is also read against spot: over // the Skew vs spot window, the close up by Spot move or more while the risk reversal falls by Skew move or more is puts // bid into a rally, the close down while it rises is calls bid into a dip, and either tints the candles; both ends of // the window must be solid bars on one expiry. A card at the bottom right names the skew (puts rich over 0.06 of the // 30-day IV, calls rich below 0, flat between) with the numbers behind it. The statistics are short today (they start // when the data plane switches the daily job on): the percentile, the z-score and the distribution need Minimum history // (60 sessions), and until then the card says how many sessions there are. The surface's five-minute history is kept 30 // days, so older intraday bars arrive partial. Crypto, CME and US stock charts, daily or finer. Beside the window's // percentile, the 30-day risk reversal's percentile over a fixed year, its last 252 sessions (the newest against the // 251 before it), is drawn as a step line in a pane of its own and read on the card; it needs Minimum history too. And // Sigma by session, a strip under the chart: each of the chart's newest closed daily candles (a session, keyed by the // UTC day it opens on) has its close against its open over its 1σ move, the open x the prior session's 1-day ATM IV // from the daily statistics x sqrt(1/252) (oneSigmaMove), the newest 60 sessions drawn. param.int("days", 30, { min: 1, max: 365, label: "Expiry, days out", description: "The expiry line draws the skew of one expiry (the day the option ends) on every bar. It reads the expiry nearest this many days out, never one that ends today." }); param.choice("delta", ["25 delta", "10 delta"], "25 delta", { label: "Expiry line, delta", description: "Which options the expiry line compares: 25 delta sits a moderate distance from the price, 10 delta far out." }); param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "The past trading days the percentile, the z-score and the term panel compare against. 252 is about a year." }); param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "The percentile, the z-score and the term panel show only after this many trading days of data." }); param.int("tail_bars", 72, { min: 10, max: 2000, label: "Put tail window, bars", description: "The put tail is how much more puts far below the price cost than nearer puts. Its z-score (standard deviations from average) uses this many recent bars with full options data. 72 is three days of hourly bars." }); param.int("vs_bars", 24, { min: 2, max: 500, label: "Skew vs spot window, bars", description: "The price move and the skew move run over this many bars. 24 is a day of hourly bars." }); param.number("vs_spot_pct", 1, { min: 0.1, max: 20, step: 0.1, label: "Spot move, percent", description: "How far the price must rise or fall over that window to count as a rally or a dip" }); param.number("vs_rr_points", 0.5, { min: 0.05, max: 10, step: 0.05, label: "Skew move, IV points", description: "How far the skew must fall or rise over that window to count as puts or calls getting pricier" }); param.bool("vs_tint", true, { label: "Tint candles on a divergence", description: "Colours candles where skew fights price: down for puts pricier in a rally, up for calls pricier in a dip." }); input("close", ohlcv.close); // the chart's own close: the grid input("rr25", option_daily.rr25_30d, { missing: "nan", description: "The 30-day skew: the 25 delta call's IV minus the put's, in IV points, one reading per trading day" }); input("iv7", option_daily.atm_iv_7d, { missing: "nan", description: "The 7-day at-the-money IV, in percent" }); input("iv14", option_daily.atm_iv_14d, { missing: "nan", description: "The 14-day at-the-money IV, in percent" }); input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day at-the-money IV, in percent" }); input("iv60", option_daily.atm_iv_60d, { missing: "nan", description: "The 60-day at-the-money IV, in percent" }); input("iv90", option_daily.atm_iv_90d, { missing: "nan", description: "The 90-day at-the-money IV, in percent" }); input("iv180", option_daily.atm_iv_180d, { missing: "nan", description: "The 180-day at-the-money IV, in percent" }); input("iv365", option_daily.atm_iv_365d, { missing: "nan", description: "The 365-day at-the-money IV, in percent" }); input("surface", option_surface.cells, { max_cells: 1800, pick: "nearest_days", days: "@days", delta: "@delta", description: "This symbol's options on each bar: only the expiry nearest the days set, with both sides at the chosen delta" }); // [expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present] per expiry, in the surface's order input("iv1d", option_daily.atm_iv_1d, { missing: "nan", description: "The 1-day at-the-money IV, in percent, one reading per trading day. The day before's reading sets each day's 1σ move (one standard deviation)." }); input("daily", candles.cells, { interval: "1d", bars: 64, description: "The newest 64 closed daily candles: each day's open and close for the Sigma strip" }); // [offset_ms, open, high, low, close, volume] per candle, oldest first output("rr30", line, lower, { color: "theme.text", width: 2, step: true, label: "Skew 30d", format: "0.00", description: "The 30-day skew: the 25 delta call's IV minus the put's, in IV points, one per trading day" }); output("rr_expiry", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Skew, expiry", format: "0.00", description: "The chosen expiry's skew at the chosen delta: call IV minus put IV, in IV points, per bar" }); output("rr_partial", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, line_style: "dotted", label: "Skew, partial", format: "0.00", description: "The same reading on a bar with partial options data, drawn dotted and kept off the solid line" }); output("zero", line, lower, { role: "guide", color: "theme.muted", width: 1, line_style: "dashed", label: "0", description: "The zero line: below it, puts cost more than calls" }); output("rr_pct", none, lower, { description: "Where today's 30-day skew ranks among the window's earlier days, 0 to 100" }); output("rr_z", none, lower, { description: "Today's 30-day skew in standard deviations from the window's average" }); output("scaled", none, lower, { description: "Put IV minus call IV, divided by the 30-day IV: the number behind the skew verdict" }); output("skew_code", none, lower, { description: "0 calls rich (under 0), 1 flat, 2 puts rich (over 0.06). It reads 1 with no reading." }); output("expiry_days", none, lower, { description: "Days until the expiry the expiry line reads" }); output("partial_bars", none, lower, { description: "Bars so far with partial options data" }); output("sessions", none, lower, { description: "How many trading days of data the window holds" }); output("status", none, lower, { description: "0 not enough history yet, 1 the window reads, 2 bars longer than a day" }); output("tail", line, lower, { color: "theme.text", opacity: 0.32, width: 1, label: "Put tail", format: "0.00", description: "The put tail: the 10 delta put's IV minus the 25 delta put's, in IV points, per bar. High means crash cover is dear." }); output("tail_z", none, lower, { description: "The put tail in standard deviations from its average over the Put tail window. The window starts over when the expiry rolls. Empty on a bar without a reading." }); output("tail_code", none, lower, { description: "The put tail's z-score in five steps. 0 low (-1.5 or under), 1 easing (-0.5 or under), 2 normal, 3 elevated (+0.5 up), 4 high (+1.5 up). It reads 2 until the window holds enough bars, and again after the expiry rolls." }); output("spot_chg", none, lower, { description: "The price change over the Skew vs spot window, in percent" }); output("rr_chg", none, lower, { description: "The expiry line's skew change over the Skew vs spot window, in IV points. Empty unless both bars have full data on one expiry." }); output("vs_code", none, lower, { description: "0 puts pricier in a rally, 1 in line or no reading, 2 calls pricier in a dip" }); output("vs_on", none, lower, { description: "1 on a bar where skew moves against price and the candle takes the tint" }); output("rr_pct_1y", line, lower, { pane: "skew_pct", color: "theme.text", width: 1.5, step: true, label: "Skew percentile, 252 sessions", format: "0", description: "Where today's 30-day skew ranks among the 251 trading days before it, about a year, 0 to 100. Empty until Minimum history is met." }); pane("skew_pct", { title: "Skew percentile, 252 sessions", height_frac: 0.1, min: 0, max: 100, format: "0" }); string("read", { max_bytes: 64 }); // the headline string("title", { max_bytes: 64 }); // the card's title string("history_text", { max_bytes: 48 }); // "Percentile 18, z-score -1.42" or the wait string("tail_text", { max_bytes: 48 }); // "Put tail elevated, z-score +1.07" or the wait string("vs_text", { max_bytes: 56 }); // "Puts pricier in a rally, spot +2.00%, skew -1.00" or the wait const termRows = frame("term_rows", { max_bytes: 4096 }); // one row per maturity: [label, now, median, 25th, 75th] // The term structure now against its window: the maturities across, IV up; the frame carries the caption per run. panel.line({ name: "term", title: "Term structure now against its past", x: "category", place: "below", frame: termRows, height_frac: 0.24, hover_card: true, format: "0.0", unit: "%", series: [ { name: "Now", color: "theme.text", width: 2, points: true }, { name: "Median", color: "theme.muted", width: 1.5 }, { name: "25th", color: "theme.muted", width: 1, line_style: "dashed" }, { name: "75th", color: "theme.muted", width: 1, line_style: "dashed" }, ] }); render.barcolor("divergence_tint", { where: "vs_on", color_by: "vs_code", colors: ["theme.down", "theme.muted", "theme.up"] }); // the candles where skew moves against spot const sigmaRows = frame("sigma_rows", { max_bytes: 6144 }); // the strip: one bar per session, oldest first // Sigma by session under the chart: each bar a session's close against its open in 1σ moves, its colour the band // (muted under 0.5, the text ink under 1, up or down from 1 on). panel.bars({ name: "sigma_strip", title: "Sigma by session", x: "category", place: "below", frame: sigmaRows, orientation: "vertical", series: [{ name: "Sigma", color: "theme.text" }], format: "0.00", hover_card: true, legend_style: "title", height_frac: 0.12 }); render.hud("skew_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Skew", "read", { headline: true }), tile.pill("Against its history", "history_text"), tile.pill("Put tail", "tail_text"), tile.pill("Skew vs spot", "vs_text"), tile.value("Skew, 30 days", "rr30", { format: "0.00" }), tile.rows([ ["Skew, chosen expiry", "rr_expiry", "0.00"], ["Expiry, days out", "expiry_days", "int"], ["Skew over IV", "scaled", "0.000"], ["Percentile", "rr_pct", "0"], ["Percentile, 252 sessions", "rr_pct_1y", "0"], ["Z-score", "rr_z", "0.00"], ["Partial bars", "partial_bars", "int"], ]), ], }); const DAY = 86400.0; const TUPLE = 9; // option_surface: expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present const BIT_DTE = 1; // present bits: each value after expiry_ms, then the partial bar const BIT_P25 = 4; const BIT_C25 = 5; const BIT_P10 = 6; const BIT_C10 = 7; const PUT_RICH = 0.06; // the scaled skew past which puts are rich (under 0, calls are) const CAPACITY = 520; const YEAR = 252; // the fixed window of the year's percentile, in sessions const SIGMA_YEARS: f64 = 1.0 / 252.0; // one trading day: a session's 1σ move is its open x the 1-day IV x sqrt(1/252) const DAY_MS: f64 = 86400000.0; const STRIP = 60; // sessions the Sigma strip draws const dailyCandles = new CandleList(64); // the chart's newest closed daily candles: the strip's sessions const ivDays = new DayHistory(128); // the 1-day at-the-money IV per session, keyed by the UTC day its row lands on const stripDay = new StaticArray<f64>(STRIP); // the strip's sessions, newest first: the day and the sigma const stripSigma = new StaticArray<f64>(STRIP); const TENORS = 7; const TENOR_LABELS: String[] = ["7d", "14d", "30d", "60d", "90d", "180d", "1y"]; const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const rrs = new DayHistory(CAPACITY); // one 30-day risk reversal per session const terms: DayHistory[] = []; // one history per maturity for (let k = 0; k < TENORS; k += 1) terms.push(new DayHistory(CAPACITY)); const termNow = new StaticArray<f64>(TENORS); // the newest session's IV per maturity const dateClock = new Clock("UTC"); const TAIL_HIGH = 1.5; // the put tail's z-score steps const TAIL_ELEVATED = 0.5; const TAIL_WORDS: String[] = ["Put tail low", "Put tail easing", "Put tail normal", "Put tail elevated", "Put tail high"]; const VS_CAP = 501; // the window's buffer: the most bars back plus the bar itself const vsClose = new StaticArray<f64>(VS_CAP); // each bar's close, solid risk reversal and expiry const vsRr = new StaticArray<f64>(VS_CAP); const vsExpiry = new StaticArray<f64>(VS_CAP); let targetDays = 30.0; // settings, read in onStart() let tenDelta = false; let lookback = 252; let need = 60; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let rrNow: f64 = NaN; // the session readings, held let pctNow: f64 = NaN; let pctYearNow: f64 = NaN; // the newest session's percentile over the last YEAR sessions let needYear = 60; // Minimum history, at most YEAR: the year's percentile shows from there let zNow: f64 = NaN; let scaledNow: f64 = NaN; let iv30Now: f64 = NaN; let partialBars = 0; let lastDays: f64 = NaN; // the surface line's expiry, held for the card let tailWindow = 72; // the put tail's window, read in onStart() let tailZs = new Zscore(72); // rebuilt in onStart() let tailCount = 0; // solid put tail readings so far let tailZNow: f64 = NaN; // the newest solid reading's z-score, held for the card let tailExpiry: f64 = NaN; // the expiry the window's readings come from: a roll restarts the window let vsBars = 24; // the skew against spot settings, read in onStart() let vsSpot = 1.0; let vsMove = 0.5; let vsTint = true; let vsAt = 0; // bars so far: the next bar's slot in the window's buffer let vsSpotNow: f64 = NaN; // the bar's spot move and skew move over the window let vsRrNow: f64 = NaN; function onStart(): void { targetDays = p_days(); tenDelta = i32(p_delta()) == 1; lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; needYear = i32(p_min_sessions()); if (needYear > YEAR) needYear = YEAR; for (let k = 0; k < TENORS; k += 1) termNow[k] = NaN; tailWindow = i32(p_tail_bars()); tailZs = new Zscore(tailWindow); vsBars = i32(p_vs_bars()); vsSpot = p_vs_spot_pct(); vsMove = p_vs_rr_points(); vsTint = p_vs_tint() > 0.5; } function tenorInput(k: i32): f64 { if (k == 0) return in_iv7(); if (k == 1) return in_iv14(); if (k == 2) return in_iv30(); if (k == 3) return in_iv60(); if (k == 4) return in_iv90(); if (k == 5) return in_iv180(); return in_iv365(); } // ── The surface on this bar: the expiry nearest targetDays with both wings served, and whether the bar is partial ── let surfaceRr: f64 = NaN; let surfaceDays: f64 = NaN; let surfacePartial = false; let surfaceTail: f64 = NaN; let surfaceExpiry: f64 = NaN; function readSurface(): void { surfaceRr = NaN; surfaceDays = NaN; surfacePartial = false; surfaceTail = NaN; surfaceExpiry = NaN; const n = in_surface_cells(); if (n < TUPLE) return; // an empty bar: no surface, a gap in the line const cells = in_surface_view(); const putBit = tenDelta ? BIT_P10 : BIT_P25; const callBit = tenDelta ? BIT_C10 : BIT_C25; const putAt = tenDelta ? 6 : 4; const callAt = tenDelta ? 7 : 5; let bestGap: f64 = Infinity; let bestExpiry: f64 = Infinity; for (let i = 0; i + TUPLE <= n; i += TUPLE) { const present = cells[i + 8]; if (isPartial(present)) surfacePartial = true; if (!hasBit(present, BIT_DTE) || !hasBit(present, putBit) || !hasBit(present, callBit)) continue; const dte = cells[i + 1]; if (!(dte >= 1.0)) continue; // an expiry that settles today never stands for a tenor const gap = Math.abs(dte - targetDays); const expiry = cells[i]; if (gap < bestGap || (gap == bestGap && expiry < bestExpiry)) { bestGap = gap; bestExpiry = expiry; surfaceDays = dte; surfaceRr = cells[i + callAt] - cells[i + putAt]; surfaceTail = hasBit(present, BIT_P10) && hasBit(present, BIT_P25) ? cells[i + 6] - cells[i + 4] : NaN; surfaceExpiry = expiry; } } } // ── The session readings, when a session lands ── function measure(): void { rrNow = rrs.value(0); const ready = rrs.span(lookback) >= need; pctNow = ready ? rrs.percentile(lookback) : NaN; zNow = ready ? rrs.zscore(lookback) : NaN; pctYearNow = rrs.span(YEAR) >= needYear ? rrs.percentile(YEAR) : NaN; scaledNow = iv30Now > 0.0 ? -rrNow / iv30Now : NaN; } function skewCode(): f64 { if (isNaN(scaledNow)) return 1.0; return scaledNow > PUT_RICH ? 2.0 : scaledNow < 0.0 ? 0.0 : 1.0; } function tailCode(z: f64): f64 { // the five steps; 2 with no reading if (isNaN(z)) return 2.0; return z >= TAIL_HIGH ? 4.0 : z >= TAIL_ELEVATED ? 3.0 : z > -TAIL_ELEVATED ? 2.0 : z > -TAIL_HIGH ? 1.0 : 0.0; } function vsCode(spot: f64, rr: f64): f64 { // 0 puts bid into a rally, 2 calls bid into a dip, 1 in line or no reading if (isNaN(spot) || isNaN(rr)) return 1.0; if (spot >= vsSpot && rr <= -vsMove) return 0.0; return spot <= -vsSpot && rr >= vsMove ? 2.0 : 1.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function sbSigned(v: f64): void { // "+1.20", "-4.05" if (v >= 0.0) sb_text("+"); sb_f64(v, 2); } // ── The term panel: each maturity now, its median and quartiles over the window ── function writeTerm(): void { fb_clear(); fb_text("{\"rows\":["); for (let k = 0; k < TENORS; k += 1) { if (k > 0) fb_text(","); fb_text("["); fb_str(TENOR_LABELS[k]); const h = terms[k]; const ready = h.span(lookback) >= need; const now = termNow[k]; fb_text(","); if (isNaN(now)) fb_text("null"); else fb_f64(now, 2); for (let q = 0; q < 3; q += 1) { fb_text(","); const v = ready ? h.quantile(lookback, q == 0 ? 0.5 : q == 1 ? 0.25 : 0.75) : NaN; if (isNaN(v)) fb_text("null"); else fb_f64(v, 2); } fb_text("]"); } fb_text("],\"caption\":\""); const held = terms[2].span(lookback); if (held < need) { fb_text("Not enough history yet: "); fb_int(held); fb_text(" of "); fb_int(need); fb_text(" sessions"); } else { fb_text("Now against "); fb_int(held); fb_text(" sessions"); } fb_text("\"}"); writeFrameBuffer(FRAME_TERM_ROWS); } // ── The Sigma strip: each closed daily candle's close against its open over its 1σ move ── function priorIv(day: f64): f64 { // the newest daily 1-day IV of a day before day, a decimal; NaN with none for (let ago = 0; ago < ivDays.count(); ago += 1) { if (ivDays.day(ago) < day) return ivDays.value(ago) / 100.0; } return NaN; } function fbBand(s: f64): void { // the band's colour word const a = Math.abs(s); fb_text(a < 0.5 ? "theme.muted" : a < 1.0 ? "theme.text" : s < 0.0 ? "theme.down" : "theme.up"); } function writeStrip(nowMs: f64): void { // the newest STRIP sessions with a reading, written oldest first; none, no strip let held = 0; for (let i = dailyCandles.count() - 1; i >= 0 && held < STRIP; i -= 1) { const day = Math.floor(dailyCandles.openSec(i) / DAY); // the session's day, the one its own statistics row lands on const open = dailyCandles.open(i); const s = (dailyCandles.close(i) - open) / oneSigmaMove(open, priorIv(day), SIGMA_YEARS); // the prior session's IV if (!isFinite(s)) continue; stripDay[held] = day; stripSigma[held] = s; held += 1; } if (held == 0) return; fb_clear(); fb_text("{\"rows\":["); for (let k = held - 1; k >= 0; k -= 1) { if (k < held - 1) fb_text(","); fb_text("[\""); fbExpiryLabel(stripDay[k] * DAY_MS, nowMs, 0); // the session's date: a 00:00 UTC stamp reads as the date it names fb_text("\",{\"value\":"); fb_f64(stripSigma[k], 3); fb_text(",\"color\":\""); fbBand(stripSigma[k]); fb_text("\"}]"); } fb_text("],\"caption\":\"Each session's close against its open, in 1σ moves\"}"); writeFrameBuffer(sigmaRows); } function writeWords(coarse: bool): void { const held = rrs.span(lookback); sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (rrs.count() == 0) sb_text("Waiting for the daily options statistics"); else { const code = skewCode(); sb_text(code == 2.0 ? "Puts rich: skew " : code == 0.0 ? "Calls rich: skew " : "Flat: skew "); sbSigned(rrNow); } str_read_sb(); sb_clear(); if (coarse || rrs.count() == 0) sb_text("No history"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else { sb_text("Percentile "); sb_f64(pctNow, 0); if (!isNaN(zNow)) { sb_text(", z-score "); sbSigned(zNow); } } str_history_text_sb(); sb_clear(); if (coarse) sb_text("No reading"); else if (tailCount < tailWindow) { sb_text("Put tail: "); sb_int(tailCount); sb_text(" of "); sb_int(tailWindow); sb_text(" bars"); } else { sb_text(TAIL_WORDS[i32(tailCode(tailZNow))]); sb_text(", z-score "); sbSigned(tailZNow); } str_tail_text_sb(); sb_clear(); if (coarse) sb_text("No reading"); else if (isNaN(vsSpotNow) || isNaN(vsRrNow)) { sb_text("Needs "); sb_int(vsBars); sb_text(" bars on one expiry"); } else { const vs = vsCode(vsSpotNow, vsRrNow); sb_text(vs == 0.0 ? "Puts pricier in a rally" : vs == 2.0 ? "Calls pricier in a dip" : "In line with spot"); sb_text(", spot "); sbSigned(vsSpotNow); sb_text("%, skew "); sbSigned(vsRrNow); } str_vs_text_sb(); sb_clear(); sb_text("Skew history, 25 delta"); if (!coarse && rrs.count() > 0) { sb_text(", as of "); sbDay(rrs.day(0)); } str_title_sb(); } // onBar() runs once per bar: the spacing; the surface's expiry and its put tail on every bar, and the bar against the // window's first bar for skew against spot; the session's statistics when they land (the risk reversal and each // maturity's IV). Each bar writes the held session readings beside its own surface line. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; dailyCandles.load(in_daily_view(), in_daily_cells(), t); readSurface(); if (surfacePartial) partialBars += 1; const tailSolid = !coarse && !surfacePartial && !isNaN(surfaceTail); let tailZ: f64 = NaN; if (tailSolid) { if (surfaceExpiry != tailExpiry) { // the picked expiry rolled: its tails start a window of their own tailZs = new Zscore(tailWindow); tailCount = 0; tailExpiry = surfaceExpiry; } tailZ = tailZs.update(surfaceTail); tailCount += 1; tailZNow = tailZ; } const at = vsAt % VS_CAP; const close = in_close(); vsClose[at] = close; vsRr[at] = coarse || surfacePartial ? NaN : surfaceRr; vsExpiry[at] = surfaceExpiry; vsSpotNow = NaN; vsRrNow = NaN; if (!coarse && vsAt >= vsBars) { const back = (vsAt - vsBars) % VS_CAP; if (vsClose[back] > 0.0) vsSpotNow = (close / vsClose[back] - 1.0) * 100.0; if (vsExpiry[back] == vsExpiry[at]) vsRrNow = vsRr[at] - vsRr[back]; } vsAt += 1; const vs = vsCode(vsSpotNow, vsRrNow); if (!isNaN(surfaceDays)) lastDays = surfaceDays; const day = Math.floor(t / DAY); if (!coarse) { const iv30 = in_iv30(); if (!isNaN(iv30) && iv30 > 0.0) iv30Now = iv30; for (let k = 0; k < TENORS; k += 1) { const v = tenorInput(k); if (!isNaN(v) && v > 0.0 && terms[k].push(day, v)) termNow[k] = v; } const rr = in_rr25(); if (!isNaN(rr) && rrs.push(day, rr)) measure(); ivDays.push(day, in_iv1d()); // a bar with no row reads NaN, which push() skips } out_zero(0.0); out_rr30(coarse ? NaN : rrNow); out_rr_expiry(coarse || surfacePartial ? NaN : surfaceRr); out_rr_partial(!coarse && surfacePartial ? surfaceRr : NaN); out_rr_pct(coarse ? NaN : pctNow); out_rr_z(coarse ? NaN : zNow); out_scaled(coarse ? NaN : scaledNow); out_skew_code(coarse ? 1.0 : skewCode()); out_expiry_days(coarse ? NaN : lastDays); out_partial_bars(f64(partialBars)); out_sessions(coarse ? NaN : f64(rrs.span(lookback))); out_status(coarse ? 2.0 : rrs.span(lookback) >= need ? 1.0 : 0.0); out_tail(tailSolid ? surfaceTail : NaN); out_tail_z(tailZ); out_tail_code(coarse ? 2.0 : tailCode(tailZNow)); out_spot_chg(vsSpotNow); out_rr_chg(vsRrNow); out_vs_code(vs); out_vs_on(vsTint && vs != 1.0 ? 1.0 : 0.0); out_rr_pct_1y(coarse ? NaN : pctYearNow); if (bar.isLast()) { writeWords(coarse); if (!coarse) { writeTerm(); writeStrip(t * 1000.0); } } } ``` ## How it works **The session line.** `rr25_30d` is the statistics' 30-day risk reversal, call IV minus put IV in volatility points: below zero the puts are dearer, the usual shape on a stock. Each session's reading joins a `DayHistory`; `percentile()` and `zscore()` read it against the window's earlier sessions. **The year's percentile.** `percentile(252)` reads the same history over its last 252 sessions, about a year of trading days, whatever **Window, sessions** holds: the share of the 251 sessions before the newest that sit strictly below it, times 100. `rr_pct_1y` draws it as a step line in the `skew_pct` pane (0 to 100) and the card reads it as **Percentile, 252 sessions**. At the default window the two percentiles read the same; a window of 520 reads two years beside the fixed one. **The surface line.** Every bar's `option_surface` block holds one tuple per expiry, `[expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present]`. The module keeps the expiry whose `dte_days` is nearest the setting among those whose days and both wings are present (bits 1, 4 and 5 at 25 delta, bits 1, 6 and 7 at 10 delta), never an expiry that settles that day, and draws its call wing minus its put wing. When the nearest expiry lacks a wing the next nearest stands in. A bar with bit 14 set on any tuple is partial (older than the five-minute history the data plane keeps, or cut short): its reading goes to the dotted **Skew, partial** line, a floor of the data rather than a value. **The put tail.** From the tuple the surface line keeps, the module reads `iv_p10` minus `iv_p25` when both are present (bits 6 and 4): how much dearer the 10 delta put is than the 25 delta put, in volatility points. A partial bar draws no put tail and is never counted. Each solid reading feeds a `Zscore` over the last **Put tail window** readings (the population deviation, the newest included). The window holds one expiry's readings and restarts when the picked expiry rolls, so a further expiry's wider tail never reads as a tail move. The newest z-score sets the step: high at +1.5 or over, elevated at +0.5 or over, easing at -0.5 or under, low at -1.5 or under, normal between. A high step says protection against a sharp fall is being bid harder than usual. **Skew against spot.** Each bar keeps its close, the surface line's risk reversal on a solid bar and the expiry it read, in a buffer of the last 501 bars. Over the last **Skew vs spot window** bars, the spot move is the close against the close that many bars back, in percent, and the skew move is the risk reversal against its reading that many bars back, in volatility points. The skew move reads only when both bars are solid and read the same expiry, so a roll, a partial bar or an empty bar reads none. The close up by **Spot move, percent** or more while the risk reversal falls by **Skew move, IV points** or more is puts bid into a rally: the rally is being hedged, a warning. The close down by as much while the risk reversal rises by as much is calls bid into a dip: the dip may be bought. Either one tints the candles through the `vs_on` gate while **Tint candles on a divergence** is on, the down colour for puts bid and the up colour for calls bid. **The term panel.** Each maturity's IV joins its own `DayHistory`; on the live bar `quantile()` reads the median and the quartiles over the window, and the panel draws them beside the newest session's curve. **The Sigma strip.** The `daily` input is the chart's own daily candles, the newest 64 closed ones, kept in a `CandleList` that every bar feeds, and each daily row's 1-day at-the-money IV joins a `DayHistory` by the UTC day its row lands on. On the live bar each candle is a session, keyed by the UTC day it opens on (the day its own statistics row lands on): its close minus its open over `oneSigmaMove(open, iv, 1 / 252)`, the IV the newest row of a day before it, so a session is priced on the IV it opened with and never on its own day's row. The newest 60 sessions with a reading draw as bars labelled by date, each in its band's colour: muted under 0.5, the text ink under 1, the up or down colour from 1 on. ## What the settings do - **Expiry, days out**: The expiry line draws the skew of one expiry (the day the option ends) on every bar. It reads the expiry nearest this many days out, never one that ends today. - **Expiry line, delta**: Which options the expiry line compares: 25 delta sits a moderate distance from the price, 10 delta far out. - **Window, sessions**: The past trading days the percentile, the z-score and the term panel compare against: 252 is about a year. - **Minimum history, sessions**: The percentile, the z-score and the term panel show only after this many trading days of data. - **Put tail window, bars**: The put tail is how much more puts far below the price cost than nearer puts. Its z-score (standard deviations from average) uses this many recent bars with full options data. 72 is three days of hourly bars. - **Skew vs spot window, bars**: The price move and the skew move run over this many bars: 24 is a day of hourly bars. - **Spot move, percent**: How far the price must rise or fall over that window to count as a rally or a dip. - **Skew move, IV points**: How far the skew must fall or rise over that window to count as puts or calls getting pricier. - **Tint candles on a divergence**: Colours candles where skew fights price: down for puts pricier in a rally, up for calls pricier in a dip. - **Skew**: The verdict, puts rich, calls rich or flat, with today's 30-day skew in IV points. - **Against its history**: Where today's skew ranks in the window, as a percentile and a z-score (standard deviations from average). - **Put tail**: How much more puts far below the price cost than nearer puts, against the recent past. It reads low, easing, normal, elevated or high. - **Skew vs spot**: Whether skew moves against the price over the window: puts pricier in a rally or calls pricier in a dip. - **Skew, 30 days**: Today's 30-day skew: the 25 delta call's IV minus the put's, in IV points. - **Skew, chosen expiry**: The same gap on the expiry line's expiry, at the chosen delta. - **Expiry, days out**: Days until the expiry the expiry line reads. - **Skew over IV**: Put IV minus call IV over the 30-day IV: over 0.06 is puts rich, under 0 calls rich. - **Percentile**: Where today's 30-day skew ranks among the window's earlier days, 0 to 100. - **Percentile, 252 sessions**: The same rank over a fixed year, the last 252 trading days, whatever the window. - **Z-score**: Today's 30-day skew in standard deviations from the window's average. - **Partial bars**: How many bars so far had only partial options data. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, 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 CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads the daily data too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. The expiry line reads per-bar options data on crypto, CME and US stock charts ([Option surface](../core-concepts/data-sources.md#option-surface)). Use a daily or intraday chart. Daily bars of the expiry line reach back without limit, and five-minute bars reach back 30 days. ## When data is missing The history starts the day OpenMarket switched on these daily readings. The daily skew line starts on the first trading day. The percentiles, the z-score and the term panel need **Minimum history** (60 trading days). Until then, the card and the panel's caption read "Not enough history yet: 12 of 60 sessions". A bar with no options data leaves a gap in both expiry lines. The card keeps the last expiry it read. Until the **Put tail window** is full, the card's Put tail line reads "Put tail: 31 of 72 bars". It counts only bars with full options data. In the editor's Console (the panel under the code), the put tail's step reads normal until then. The window starts over when the chosen expiry rolls to the next one. The card's Skew vs spot line reads "Needs 24 bars on one expiry" at first. It waits until the bar 24 back shares its expiry. That bar must have full data, so the reading waits a full window after each roll. Before the first trading day, the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". The Sigma strip shows each day's move in standard deviations. It draws once a closed daily candle has an IV reading from an earlier day. ## Customize it - **Another expiry.** Set **Expiry, days out** to 7 for the weekly or 90 for the quarter. - **Further wings.** Switch **Expiry line, delta** to 10 delta to read the tails. - **Another year.** `lookback` sets the sessions the percentile, the z-score and the distribution read. - **A calendar day on crypto.** The Sigma strip prices one trading day as 1/252 of a year on every venue; on a coin that trades every day, set `SIGMA_YEARS` to `1.0 / 365.0`. - **A faster put tail.** Set **Put tail window** to 24 for a day on an hourly chart, or 288 for a day on a five-minute chart. - **A week against spot.** On a daily chart set **Skew vs spot window** to 5, or turn **Tint candles on a divergence** off to read the divergence in the card alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Skew History** under **Beyond the time axis**. 2. Press **Run** on a US stock's chart: the session line and the surface line fill as the statistics allow. 3. At the editor's Console prompt, type `rr30`, `rr_pct`, `rr_pct_1y`, `tail_z`, `vs_code` and `partial_bars`. ## Concepts used - [Option surface](../core-concepts/data-sources.md#option-surface) for `option_surface` on crypto, CME and US stock charts, and [The present mask and partial bars](../core-concepts/data-sources.md#the-present-mask-and-partial-bars) for its present mask and the partial bar - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory`, and [The canonical numbers](../functions/options-kit.md#the-canonical-numbers) for `oneSigmaMove` - [Calendar periods and candle lists](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) for the `candles` stream and `CandleList` - [Panes](../presentation/plotting.md#panes) for the year's percentile, and [Bars](../presentation/cards-frames-panels.md#bars) for the Sigma strip - [Series functions](../functions/series-functions.md#trend-extremes-and-counting) for the put tail's `Zscore` - [Marks, tints and fills](../presentation/cards-frames-panels.md#marks-tints-and-fills) for the candle tint's `render.barcolor` - [Line panels](../presentation/cards-frames-panels.md#line-panels) for the term panel <!-- source: https://openmarket.xyz/wrun/cookbook/vol-regime --> # Volatility regime Volatility regime shows how far implied volatility (how big a move option prices expect) sits from its normal level. Columns under the chart measure it in standard deviations: above +0.5 is high, below -0.5 is low. A card names the regime and the stress level, and candles dim on stressed days. A day is stressed when implied volatility ranks in the top fifth of the window, 252 trading days by default. Use it to tell calm markets from nervous ones, once 60 trading days of daily options data exist. Under the hood: the recipe reads the 30-day at-the-money IV from `option_daily`. The vol of vol is the exponentially weighted deviation of the IV's daily log changes, annualized. Two `DayHistory` rings from the options kit keep both ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws columns coloured by the regime between two muted guides, and a `render.barcolor` that dims a stressed bar's candle ([Plotting](../presentation/plotting.md)). A `render.hud` card with a sparkline tile sits beside them. It is also the `vol-regime` template, the **Volatility Regime** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Volatility Regime: how far implied volatility (how big a move option prices expect) sits from its normal level. High // implied volatility means pricey options and big expected swings. Columns under the chart show how far today's 30-day // reading sits from its usual level, in standard deviations. Above +0.5 the regime is high, below -0.5 it is low. A // card names the regime and the stress level: calm, transitional or stressed. A day is stressed when implied volatility // ranks in the top fifth of the window, and its candle dims. The card also shows the vol of vol: how much implied // volatility itself jumps around. Use it to tell calm markets from nervous ones before you trade. // // Technical notes: whether the chart's underlying's implied volatility is high, normal or low for that name, and how // unsettled it is, from the daily options statistics (option_daily, the 30-day at-the-money IV per session). The regime // score is a z-score: the session's IV against the mean and standard deviation of the window's earlier sessions, high // over +0.5, low under -0.5, neutral between, drawn as columns in a pane under the chart with guides at both edges. The // stress class bins the IV's percentile among the window's earlier sessions: calm under the 55th, transitional from the // 55th to the 80th, stressed from the 80th up; the card names it, and a stressed bar's candle dims to the muted text // colour when Tint candles is on (calm and transitional bars keep the chart's candles). The vol of vol is how much the // IV itself moves: the exponentially weighted standard deviation of its daily log changes over the last Vol of vol // sessions (recent changes weigh more), annualized over 252 days a year (365 on crypto, which trades every day), in // percent, with its own percentile. A card at the bottom right reads the regime, the stress class and the numbers // behind them. Each session's reading is the statistics job's close of that session, held on an intraday chart until // the next one lands. The statistics are short today (they start when the data plane switches the daily job on): every // reading needs Minimum history (60 sessions), and until then the card says how many there are. Daily or finer charts. param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "The past trading days today is compared against. 252 is about a year, or 8 months on crypto." }); param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "Trading days of data needed before a reading shows. Until then the card counts the days so far." }); param.int("vov_days", 30, { min: 5, max: 90, label: "Vol of vol, sessions", description: "The vol of vol is how much implied volatility itself jumps day to day. This sets how many recent days it weighs, the newest most." }); param.bool("tint_candles", true, { label: "Tint candles", description: "Dims the candles on stressed days, when the IV sits at its 80th percentile or higher" }); input("close", ohlcv.close); // the chart's own close: the grid input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of this symbol's options, in percent, one reading per trading day" }); // lands on the first bar of its day, NaN elsewhere market.zone(); // the market's clock: 0 UTC on crypto, which trades every day of the year (the vol of vol's year) output("score", histogram, lower, { color_by: "regime", colors: ["theme.down", "theme.muted", "theme.up"], label: "Regime score", format: "0.00", description: "How far today's 30-day IV sits from the window's average, in standard deviations. Empty until Minimum history is met." }); output("high_guide", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "High", align: "right", description: "+0.5: over it the regime is high" }); output("low_guide", line, lower, { role: "guide", color: "theme.muted", width: 1, label: "Low", align: "right", description: "-0.5: under it the regime is low" }); output("regime", none, lower, { description: "0 low (score under -0.5), 1 normal, 2 high (over +0.5). It reads 1 while there is no score." }); output("stress", none, lower, { description: "0 calm (IV percentile under 55), 1 transitional (55 to 80), 2 stressed (80 and up). Empty while there is no percentile." }); output("tint_on", none, lower, { description: "1 on a stressed bar while Tint candles is on, so the candle dims" }); output("iv", none, lower, { description: "The newest 30-day IV, in percent" }); output("iv_pct", none, lower, { description: "Where today's IV ranks among the window's earlier days, 0 to 100" }); output("vov", none, lower, { description: "The vol of vol: how much the IV itself moves from day to day, as a yearly percent. It counts 365 days a year on crypto, 252 elsewhere." }); output("vov_pct", none, lower, { description: "Where today's vol of vol ranks among the window's earlier days, 0 to 100" }); output("sessions", none, lower, { description: "How many trading days of data the window holds" }); output("status", none, lower, { description: "0 not enough history yet, 1 the regime reads, 2 bars longer than a day" }); string("read", { max_bytes: 64 }); // the headline string("stress_text", { max_bytes: 32 }); // "Stressed, 86th percentile" string("title", { max_bytes: 64 }); render.barcolor("stress_tint", { where: "tint_on", color: "theme.muted" }); // a stressed bar's candle, dimmed; calm and transitional bars keep the chart's own render.hud("regime_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Regime", "read", { headline: true }), tile.pill("Stress", "stress_text"), tile.spark("Vol of vol trend", "vov", { bars: 64 }), tile.rows([ ["IV, 30 days", "iv", "0.00"], ["Regime score", "score", "0.00"], ["IV percentile", "iv_pct", "0"], ["Vol of vol", "vov", "0.0"], ["Vol of vol percentile", "vov_pct", "0"], ["Trading days read", "sessions", "int"], ]), ], }); const DAY = 86400.0; const HIGH = 0.5; // the score's edges const LOW = -0.5; const TRANSITIONAL = 55.0; // the stress class's percentile edges const STRESSED = 80.0; const CAPACITY = 520; const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const ivs = new DayHistory(CAPACITY); // one 30-day IV per session const vovs = new DayHistory(CAPACITY); // one vol of vol per session it could be measured const dateClock = new Clock("UTC"); let lookback = 252; // settings, read in onStart() let need = 60; let vovDays = 30; let tint = true; let yearDays = 252.0; // the year the vol of vol annualizes over, read in onStart() let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let scoreNow: f64 = NaN; // the session readings, held let ivPctNow: f64 = NaN; let vovNow: f64 = NaN; let vovPctNow: f64 = NaN; function onStart(): void { lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; vovDays = i32(p_vov_days()); tint = p_tint_candles() > 0.5; yearDays = i32(p_market_zone()) == 0 ? 365.0 : 252.0; // crypto trades every day of the year } /** The vol of vol over the newest vovDays daily log changes of the IV, each weighing (1 - a)^k with k sessions back * and a = 2 / (vovDays + 1), annualized, percent; NaN until vovDays + 1 sessions are held. */ function volOfVol(): f64 { if (ivs.count() < vovDays + 1) return NaN; const keep = 1.0 - 2.0 / f64(vovDays + 1); let weight = 1.0; let sumW = 0.0; let sumSq = 0.0; for (let k = 0; k < vovDays; k += 1) { const r = Math.log(ivs.value(k) / ivs.value(k + 1)); sumSq += weight * r * r; sumW += weight; weight *= keep; } return Math.sqrt((sumSq / sumW) * yearDays) * 100.0; } function measure(day: f64): void { const v = volOfVol(); if (!isNaN(v)) vovs.push(day, v); vovNow = v; const ready = ivs.span(lookback) >= need; scoreNow = ready ? ivs.zscore(lookback) : NaN; ivPctNow = ready ? ivs.percentile(lookback) : NaN; vovPctNow = ready && !isNaN(v) && vovs.span(lookback) >= 2 ? vovs.percentile(lookback) : NaN; } function regimeOf(): f64 { if (isNaN(scoreNow)) return 1.0; return scoreNow > HIGH ? 2.0 : scoreNow < LOW ? 0.0 : 1.0; } function stressOf(): f64 { if (isNaN(ivPctNow)) return NaN; return ivPctNow >= STRESSED ? 2.0 : ivPctNow >= TRANSITIONAL ? 1.0 : 0.0; } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function writeWords(coarse: bool): void { const held = ivs.span(lookback); sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (ivs.count() == 0) sb_text("Waiting for the daily options statistics"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else if (isNaN(scoreNow)) sb_text("No spread: the IV has not moved in the window"); else { const r = regimeOf(); sb_text(r == 2.0 ? "High IV, score " : r == 0.0 ? "Low IV, score " : "Normal IV, score "); if (scoreNow >= 0.0) sb_text("+"); sb_f64(scoreNow, 2); } str_read_sb(); sb_clear(); const s = stressOf(); if (coarse || isNaN(s)) sb_text("No stress level"); else { sb_text(s == 2.0 ? "Stressed, " : s == 1.0 ? "Transitional, " : "Calm, "); sb_f64(ivPctNow, 0); sb_text(" percentile"); } str_stress_text_sb(); sb_clear(); sb_text("Volatility regime, 30-day IV"); if (!coarse && ivs.count() > 0) { sb_text(", as of "); sbDay(ivs.day(0)); } str_title_sb(); } // onBar() runs once per bar: the spacing, then the session's IV when it lands (measured once, held after); every bar // writes the held readings, and a stressed bar's candle dims. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; const iv = in_iv30(); if (!coarse && !isNaN(iv) && iv > 0.0) { const day = Math.floor(t / DAY); if (ivs.push(day, iv)) measure(day); } out_high_guide(HIGH); out_low_guide(LOW); out_score(coarse ? NaN : scoreNow); out_regime(coarse ? 1.0 : regimeOf()); const s = coarse ? NaN : stressOf(); out_stress(s); out_tint_on(tint && s == 2.0 ? 1.0 : 0.0); out_iv(coarse || ivs.count() == 0 ? NaN : ivs.value(0)); out_iv_pct(coarse ? NaN : ivPctNow); out_vov(coarse ? NaN : vovNow); out_vov_pct(coarse ? NaN : vovPctNow); out_sessions(coarse ? NaN : f64(ivs.span(lookback))); out_status(coarse ? 2.0 : ivs.span(lookback) >= need ? 1.0 : 0.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **The score.** `zscore()` reads the newest IV against the window's earlier sessions, so today never dampens its own score. The edges are fixed at plus and minus 0.5 standard deviations. **The stress level.** `percentile()` is the share of the window's earlier sessions with a lower IV; the level's edges sit at the 55th and 80th percentiles. A stressed bar's candle dims to the muted text colour through a gate output (`tint_on`, 1 on a stressed bar while **Tint candles** is on), so calm and transitional bars keep the chart's own colours, and turning **Tint candles** off leaves every candle as it was. **The vol of vol.** Over the newest `vov_days` daily log changes of the IV, each weighing (1 - a) to the power of its age in sessions with a = 2 / (`vov_days` + 1): recent changes count most. The year it annualizes over follows the market's clock (`market.zone()`): 365 days on crypto, 252 elsewhere. It is measured once per session and joins its own `DayHistory` for its percentile. ## What the settings do - **Window, sessions**: The card compares today with this many past trading days: 252 is about a year, 8 months on crypto. - **Minimum history, sessions**: A reading shows only after this many trading days of data, so a few days never pass for a year. - **Vol of vol, sessions**: The vol of vol is how much implied volatility itself jumps day to day. This sets how many recent days it weighs, the newest most. - **Tint candles**: Dims the candles on stressed days, when the IV sits at its 80th percentile or higher. - **Regime**: The verdict: high, normal or low IV for this symbol, with the score. - **Stress**: Calm under the 55th percentile, transitional up to the 80th, stressed from the 80th up. - **Vol of vol trend**: A small chart of how much the IV itself has jumped around lately. - **IV, 30 days**: Today's 30-day implied volatility, as a yearly percent. - **Regime score**: How far today's IV sits from its window average, in standard deviations. - **IV percentile**: The share of past days in the window with a lower IV. - **Vol of vol**: How much the IV itself moves from day to day, as a yearly percent. - **Vol of vol percentile**: Where today's vol of vol ranks among the window's earlier days, 0 to 100. - **Trading days read**: How many trading days of data the window holds. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, 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 CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. ## When data is missing The history starts the day OpenMarket switched on these daily readings. The score, the percentile and the stress tint need **Minimum history** (60 trading days). Until then, the columns stay empty and the candles keep their colours. The card reads "Not enough history yet: 12 of 60 sessions". The vol of vol needs 31 trading days of its own. A flat IV gives no spread, and the card says so. Before the first trading day, the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". ## Customize it - **Another year.** `lookback` sets how many sessions the score and the percentiles read. - **A faster or slower vol of vol.** `vov_days` of 10 reacts within two weeks, 90 over a quarter. - **Keep the candles.** Turn **Tint candles** off to read the regime in the pane alone. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Volatility Regime** under **Beyond the time axis**. 2. Press **Run** on BTCUSDT's daily chart. 3. At the editor's Console prompt, type `score`, `iv_pct` and `vov`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [Plotting](../presentation/plotting.md) for the columns, the guides and the candle tint - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card and its sparkline <!-- source: https://openmarket.xyz/wrun/cookbook/exposure-history --> # Exposure history One column per session shows how dealers (the market makers who hedge options) are positioned, on the measure you pick. On gamma, above zero is long gamma (dealers calm price), and below zero is short gamma (dealers chase price). Lines mark each session's gamma flip (the price where dealers switch from calming price to pushing it). Others mark the call and put walls (the strikes with the most dealer hedging). On a daily or finer chart, the card's rank shows when positioning is unusual for this symbol. Under the hood: each session's reading is the daily options statistics' close of that session (`option_daily`). They follow the open-interest model, where dealers are long the calls and short the puts. On an intraday chart each reading holds until the next one lands. The gamma flip covers all expiries, labelled `Gamma flip · all expiries` ([Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying)). It keeps one reading per session in a [`DayHistory`](../functions/options-kit.md#a-history-of-daily-statistics) for the change and the percentile. It draws sign-coloured columns and step lines ([Plotting](../presentation/plotting.md)) and a `render.hud` card whose value tile carries its change. It is the `exposure-history` template: **Exposure History** under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Exposure History: one column per session shows how dealers (the market makers who hedge options) are positioned in // this symbol. Pick the measure in Lens. Columns above zero use the up colour, below zero the down colour. Gamma (how // fast dealers must hedge as price moves) shows the regime. Above zero is long gamma (dealers calm price): they sell // rallies and buy dips, so price tends to calm. Below zero is short gamma (dealers chase price): they buy rallies and // sell dips, so price tends to trend. Lines on price mark each session's call and put walls (the strikes with the most // dealer hedging). Another marks the gamma flip (the price where dealers switch from calming price to pushing it). A // third marks max pain, the price where the nearest expiry's options pay out least. A card adds the change from the // last session and how today ranks against past sessions. Use it to spot unusual dealer positioning. // // Under the hood: the readings come from the daily options statistics (option_daily). The Lens setting picks one // greek's net exposure on the open-interest basis the statistics use (dealers long the calls and short the puts): // gamma in USD per 1% move, delta in dollar delta (each option's own sign), vega in USD per volatility point, charm // in dollar delta per day, vanna in dollar delta per volatility point. It is drawn as columns in a pane under the // chart, in the up colour above zero and the down colour below, with the front expiry's gamma as a step line on the // gamma lens; the session's call wall, put wall, gamma flip (the data plane's, over all expiries: the gamma curve's // zero nearest spot, the options kit's rule) and front max pain are drawn on price as step lines when Levels is on. A // card at the bottom right reads the regime (the sign of net gamma, the options kit's dealerRegime: long gamma // dampens moves, short gamma amplifies them), the net exposure, its change from the prior session, its percentile // among the window's earlier sessions, spot against the gamma flip and the levels. Each session's reading is the // statistics job's close of that session, held on an intraday chart until the next one lands. The statistics are // short today (they start when the data plane switches the daily job on): the exposure and the levels read from the // first session, the change from the second, and the percentile needs Minimum history (20 sessions); until then the // card says how many sessions there are. US stock charts, daily or finer. param.choice("lens", ["Gamma", "Delta", "Vega", "Charm", "Vanna"], "Gamma", { label: "Lens", description: "Which dealer measure the columns show. Gamma: hedging per 1% move. Delta: stock dealers hold to hedge. Vega: gain as option prices rise. Charm, Vanna: how that hedge changes with time or option prices." }); param.bool("show_levels", true, { label: "Levels", description: "Draw each session's call wall, put wall, gamma flip and front-expiry max pain on the price chart." }); param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "How many past sessions the percentile ranks today against. 252 is about a year." }); param.int("min_sessions", 20, { min: 5, max: 520, label: "Minimum history, sessions", description: "How many sessions the percentile needs before it shows." }); input("close", ohlcv.close); // the chart's own close: the grid input("gex", option_daily.net_gex, { missing: "nan", description: "Net gamma: the dollars dealers must trade for each 1% move, one reading per session from the daily options statistics." }); // every daily input lands on the first bar of its day, NaN elsewhere input("dex", option_daily.net_dex, { missing: "nan", description: "Net delta: the position dealers hold, in dollars, each option in its own sign." }); input("vex", option_daily.net_vex, { missing: "nan", description: "Net vega: what dealers gain or lose per point of implied volatility, in dollars." }); input("charm", option_daily.net_charm, { missing: "nan", description: "Net charm: how far the dealers' hedge drifts each day as time passes, in dollars." }); input("vanna", option_daily.net_vanna, { missing: "nan", description: "Net vanna: how far the dealers' hedge shifts for each point of implied volatility, in dollars." }); input("front_gex", option_daily.front_net_gex, { missing: "nan", description: "Net gamma of the nearest live expiry, in dollars per 1% move." }); input("call_wall", option_daily.call_wall, { missing: "nan", description: "The call wall: the call strike with the most dealer hedging, often a ceiling." }); input("put_wall", option_daily.put_wall, { missing: "nan", description: "The put wall: the put strike with the most dealer hedging, often a floor." }); input("flip", option_daily.gamma_flip, { missing: "nan", description: "The gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); input("max_pain", option_daily.max_pain_front, { missing: "nan", description: "Max pain of the front expiry: the price where its open options would pay out the least." }); input("spot", option_daily.underlying_price, { missing: "nan", description: "This symbol's price when the statistics were taken." }); output("call_wall_line", line, overlay, { color: "theme.up", width: 1, step: true, label: "Call wall", format: "price", description: "The session's call wall, held until the next session" }); output("put_wall_line", line, overlay, { color: "theme.down", width: 1, step: true, label: "Put wall", format: "price", description: "The session's put wall" }); output("flip_line", line, overlay, { color: "theme.muted", width: 1, step: true, line_style: "dashed", label: "Gamma flip · all expiries", format: "price", description: "The session's gamma flip over all expiries: the price nearest now where dealer gamma crosses zero." }); output("max_pain_line", line, overlay, { color: "theme.muted", width: 1, step: true, label: "Max pain", format: "price", description: "The session's max pain for the front expiry: where its open options pay out the least." }); output("exposure", histogram, lower, { color_by: "sign", colors: ["theme.down", "theme.up"], label: "Net exposure", format: "usd", description: "The session's net dealer exposure for the chosen measure, in its unit (see the Lens setting)." }); output("front_line", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, step: true, label: "Front gamma", format: "usd", description: "Net gamma of the nearest expiry. It shows on the gamma lens only." }); output("sign", none, lower, { description: "1 when the net exposure is at or above zero, 0 below" }); output("change", none, lower, { description: "The net exposure's change from the prior session, same unit" }); output("pctile", none, lower, { description: "The percentile: the share of the window's earlier sessions below today's net exposure, 0 to 100." }); output("flip_dist", none, lower, { description: "How far the price sits from the gamma flip over all expiries, in percent. Above zero means price is above the flip." }); output("regime", none, lower, { description: "The headline's regime as a code: 0 short gamma, 1 neutral, 2 long gamma. Other lenses use the sign of their net the same way." }); output("wall_call", none, lower, { format: "price", description: "The call wall, for the card" }); output("wall_put", none, lower, { format: "price", description: "The put wall, for the card" }); output("pain", none, lower, { format: "price", description: "The front expiry's max pain, for the card." }); output("sessions", none, lower, { description: "How many sessions of statistics the window holds." }); output("status", none, lower, { description: "0 not enough history for the percentile, 1 it shows, 2 the chart is coarser than a day." }); string("read", { max_bytes: 64 }); // the headline string("title", { max_bytes: 64 }); string("history_text", { max_bytes: 48 }); // "62nd percentile of 120 sessions" or the wait render.hud("exposure_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Dealers", "read", { headline: true }), tile.pill("Against past sessions", "history_text"), tile.value("Net exposure", "exposure", { format: "usd", delta: "change" }), tile.rows([ ["Change from last session", "change", "usd"], ["Percentile", "pctile", "0"], ["Front expiry gamma", "front_line", "usd"], ["Distance to gamma flip, %", "flip_dist", "0.00"], ["Call wall", "wall_call", "price"], ["Put wall", "wall_put", "price"], ["Max pain, front expiry", "pain", "price"], ["Sessions in window", "sessions", "int"], ]), ], }); const DAY = 86400.0; const CAPACITY = 520; const LENS_WORDS: String[] = ["gamma", "delta", "vega", "charm", "vanna"]; // the lens in the card's words const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const history = new DayHistory(CAPACITY); // one net exposure per session, the lens's greek const dateClock = new Clock("UTC"); let lens = 0; // settings, read in onStart() let showLevels = true; let lookback = 252; let need = 20; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let netNow: f64 = NaN; // the session readings, held let changeNow: f64 = NaN; let pctNow: f64 = NaN; let frontNow: f64 = NaN; let callWall: f64 = NaN; let putWall: f64 = NaN; let flip: f64 = NaN; let pain: f64 = NaN; let spot: f64 = NaN; let levelsDay: f64 = NaN; function onStart(): void { lens = i32(p_lens()); showLevels = p_show_levels() > 0.5; lookback = i32(p_lookback()); need = i32(p_min_sessions()); if (need > lookback) need = lookback; } function lensInput(): f64 { if (lens == 1) return in_dex(); if (lens == 2) return in_vex(); if (lens == 3) return in_charm(); if (lens == 4) return in_vanna(); return in_gex(); } function measure(): void { netNow = history.value(0); changeNow = history.count() >= 2 ? netNow - history.value(1) : NaN; pctNow = history.span(lookback) >= need ? history.percentile(lookback) : NaN; } function sbUsd(v: f64): void { // "+$1.20M", "-$350.00K" sb_text(v < 0.0 ? "-$" : "+$"); const a = Math.abs(v); if (a >= 1.0e12) { sb_f64(a / 1.0e12, 2); sb_text("T"); } else if (a >= 1.0e9) { sb_f64(a / 1.0e9, 2); sb_text("B"); } else if (a >= 1.0e6) { sb_f64(a / 1.0e6, 2); sb_text("M"); } else if (a >= 1.0e3) { sb_f64(a / 1.0e3, 2); sb_text("K"); } else sb_f64(a, 2); } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function writeWords(coarse: bool): void { const held = history.span(lookback); sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (history.count() == 0) sb_text("Waiting for the daily options statistics"); else if (lens == 0) { const regime = dealerRegime(netNow); sb_text(regime > 0.0 ? "Long gamma, dealers calm price: " : regime < 0.0 ? "Short gamma, dealers chase price: " : "Neutral gamma, no dealer hedging: "); sbUsd(netNow); } else { sb_text("Net "); sb_text(LENS_WORDS[lens]); sb_text(" "); sbUsd(netNow); } str_read_sb(); sb_clear(); if (coarse || history.count() == 0) sb_text("No history"); else if (held < need) { sb_text("Not enough history yet: "); sb_int(held); sb_text(" of "); sb_int(need); sb_text(" sessions"); } else { sb_text("Above "); sb_f64(pctNow, 0); sb_text("% of the last "); sb_int(held); sb_text(" sessions"); } str_history_text_sb(); sb_clear(); sb_text("Exposure history, "); sb_text(LENS_WORDS[lens]); if (!coarse && history.count() > 0) { sb_text(", as of "); sbDay(history.day(0)); } str_title_sb(); } /** The headline's regime: on the gamma lens the dealer regime (the kit's dealerRegime) plus 1, on the other lenses the * net's sign the same way: 0 below zero, 1 at it, 2 above. */ function regimeCode(): f64 { if (lens == 0) return 1.0 + dealerRegime(netNow); return netNow > 0.0 ? 2.0 : netNow < 0.0 ? 0.0 : 1.0; } // onBar() runs once per bar: the spacing, then the session's statistics when they land (the lens's exposure measured // once, the levels kept); every bar writes the held readings, so an intraday chart draws each session as a step. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; if (!coarse) { const day = Math.floor(t / DAY); const v = lensInput(); if (!isNaN(v) && history.push(day, v)) measure(); const landed = !isNaN(in_gex()) || !isNaN(in_call_wall()) || !isNaN(in_spot()); if (landed && day != levelsDay) { // the session's levels, once; a value the session lacks reads NaN levelsDay = day; frontNow = in_front_gex(); callWall = in_call_wall(); putWall = in_put_wall(); flip = in_flip(); pain = in_max_pain(); spot = in_spot(); } } const levels = showLevels && !coarse; out_call_wall_line(levels ? callWall : NaN); out_put_wall_line(levels ? putWall : NaN); out_flip_line(levels ? flip : NaN); out_max_pain_line(levels ? pain : NaN); out_exposure(coarse ? NaN : netNow); out_front_line(!coarse && lens == 0 ? frontNow : NaN); out_sign(coarse || isNaN(netNow) ? NaN : netNow >= 0.0 ? 1.0 : 0.0); out_change(coarse ? NaN : changeNow); out_pctile(coarse ? NaN : pctNow); out_flip_dist(!coarse && spot > 0.0 && flip > 0.0 ? (spot / flip - 1.0) * 100.0 : NaN); out_regime(coarse || isNaN(netNow) ? NaN : regimeCode()); out_wall_call(coarse ? NaN : callWall); out_wall_put(coarse ? NaN : putWall); out_pain(coarse ? NaN : pain); out_sessions(coarse ? NaN : f64(history.span(lookback))); out_status(coarse ? 2.0 : history.span(lookback) >= need ? 1.0 : 0.0); if (bar.isLast()) writeWords(coarse); } ``` ## How it works **One reading per session.** Each field lands on the session's own bar (every bar of a daily chart, the first bar of its day on an intraday chart) and reads `NaN` elsewhere. The lens's value joins a `DayHistory`; the levels are taken once per session, and a level the session lacks reads empty rather than the previous session's. **The regime.** On the gamma lens the sign of net gamma, through the options kit's `dealerRegime`, says what dealers' hedging does: positive, they sell rallies and buy drops (moves dampen); negative, they chase both (moves extend); exactly zero reads neutral. The other lenses read their own sign. The level on price is the data plane's gamma flip over all expiries, the gamma curve's zero nearest spot by the options kit's rule ([The canonical numbers](../functions/options-kit.md#the-canonical-numbers)), labelled `Gamma flip · all expiries`. **The change and the percentile.** The change is the newest session's net exposure minus the one before it; the percentile is the share of the window's earlier sessions below today's. ## What the settings do - **Lens**: which dealer measure the columns show. Gamma: what dealers trade per 1% move. Delta: how much stock dealers must hold to hedge. Vega: how much dealers gain or lose when option prices rise. Charm, Vanna: how that hedge changes with time (charm) or with option prices (vanna). - **Levels**: draws each session's call and put walls, gamma flip and max pain on price. Max pain is the price where the nearest expiry's options pay out least. - **Window, sessions**: how many past sessions the percentile ranks today against, 252 by default (about a year). - **Minimum history, sessions**: how many sessions the percentile waits for before it shows, 20 by default. - **Dealers**: on gamma, whether dealers calm price (long gamma) or chase it (short gamma), with net gamma. On other measures, the net in dollars. - **Against past sessions**: where today ranks among past sessions, or how many sessions it still needs. - **Net exposure**: the session's net for the chosen measure, with its change from the last session. - **Change from last session**: how much the net moved since the session before. - **Percentile**: the share of past sessions below today's net, from 0 to 100. - **Front expiry gamma**: net gamma of the nearest expiry alone. - **Distance to gamma flip, %**: how far the price sits above (positive) or below (negative) the gamma flip. - **Call wall**: the call strike (the option's price level) with the most dealer hedging, often a ceiling. - **Put wall**: the put strike with the most dealer hedging, often a floor. - **Max pain, front expiry**: the price where the front expiry's open options would pay out the least. - **Sessions in window**: how many sessions of statistics the window holds. ## Where it runs It needs a daily or finer chart. On a coin with listed options the chart reads the coin's own daily options statistics. So does a copy you run from the editor (where you write and run your own indicators). On a US stock chart every indicator in the browser can read them. They run 15 minutes behind unless you have real-time US options data. On a futures chart from CME (Chicago futures exchange), every indicator in the browser can read them too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). They run 10 minutes behind unless you have real-time CME data. Crypto trades every day, so the default **Window, sessions** of 252 is about eight months there. Set it to 365 for a calendar year. ## When data is missing The daily statistics start on the day OpenMarket began recording them. The exposure and the levels show from the first session, and the change from the second. The percentile waits for **Minimum history**, 20 sessions. Until then the card's **Against past sessions** line reads "Not enough history yet: 7 of 20 sessions". Before the first session the card reads "Waiting for the daily options statistics". A chart coarser than a day reads "Needs a daily or finer chart". US listed options' daily statistics through 2026-10-20 follow an earlier gamma flip rule and often have no flip. The gamma flip line stays empty on those sessions ([Data sources](../core-concepts/data-sources.md#the-gamma-flip-and-older-rows)). ## Customize it - **Another greek.** Switch **Lens** to Delta, Vega, Charm or Vanna. - **A clean price pane.** Turn **Levels** off. - **Another year.** `lookback` sets the sessions the percentile reads. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Exposure History** under **Beyond the time axis**. 2. Press **Run** on a US stock's daily chart. 3. At the editor's Console prompt, type `exposure`, `change` and `pctile`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` and its units - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [Plotting](../presentation/plotting.md) for the columns and the step lines - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/options-history --> # Options history Options History shows how much this symbol's options trade, day by day, in a pane, a table and a card. Calls (bets on a rise) and puts (bets on a fall) show apart. Pick volume, open interest (contracts still held open) or premium (the money paid for an option) for the pane. Volume far above its average means unusual interest, and more puts than calls often signals fear. Use it to spot busy options days on a coin, a CME (Chicago futures exchange) future or a US stock. Under the hood: volume and premium are the whole session's, read at the close by the statistics job. Open interest is the clearing house's figure the session opened with. On an intraday chart each session holds until the next one lands. The table lists the date, the close, the put/call volume ratio, the volume and its distance from the average. It also lists the total open interest and its change, and the 30-day IV. It reads scalar `option_daily` inputs and keeps one `DayHistory` per field ([Options kit](../functions/options-kit.md#a-history-of-daily-statistics)). It draws stacked `bar` outputs and step lines ([Plotting](../presentation/plotting.md)), a `panel.table` ([Table](../presentation/cards-frames-panels.md#table)) and a `render.hud` card. It is also the `options-history` template, the **Options History** card under **Beyond the time axis** in the editor's starter list, which compiles as written. ## The wrun indicator ```typescript // Options History: how much this symbol's options trade, day by day, from the daily options statistics. A pane under // the chart splits calls (bets on a rise) from puts (bets on a fall). Pick Volume for contracts traded, Open interest // for contracts still held open, or Premium for the money paid for options. A table lists the newest trading days, and // a card reads the newest one. Volume far above its average means unusual interest. More puts than calls often signals // fear or hedging. Use it to spot days when options traders suddenly got busy. // // Technical notes: the options volume and open interest session by session, from the daily options statistics // (option_daily). The View setting picks the pane under the chart: Volume (call and put volume stacked as // columns, calls in the up colour and puts in the down colour, with the average daily volume over the Average window as // a step line), Open interest (call and put open interest as step lines) or Premium (call and put premium in USD, // stacked). A table below the chart lists the newest sessions one per row: the date, the underlying's close, the // put/call volume ratio, the volume and its distance from the average, the total open interest and its change from the // prior session and the 30-day IV. A card at the bottom right reads the newest session and the front expiry's move. // Volume and premium are the whole session's (the statistics job reads them at the close); open interest is the // clearing house's figure the session opened with. Each session's reading is held on an intraday chart until the next // one lands. The statistics are short today (they start when the data plane switches the daily job on): every count // reads from the first session, the open interest change from the second, and the distance from the average needs the // Average window's sessions; until then the card says how many there are. Crypto, CME and US stock charts, daily or // finer. param.choice("view", ["Volume", "Open interest", "Premium"], "Volume", { label: "View", description: "What the pane shows: Volume (contracts traded), Open interest (contracts still held open) or Premium (money paid for options)." }); param.int("avg_sessions", 30, { min: 5, max: 90, label: "Average window, sessions", description: "How many past sessions (trading days) the average daily volume covers." }); param.int("table_rows", 10, { min: 3, max: 30, label: "Sessions in the table", description: "How many of the newest sessions (trading days) the table lists." }); input("close", ohlcv.close); // the chart's own close: the grid input("call_vol", option_daily.call_volume, { missing: "nan", description: "Calls traded per session (bets on a rise): contracts on US options and CME, coins on a crypto chain." }); // every daily input lands on the first bar of its day, NaN elsewhere input("put_vol", option_daily.put_volume, { missing: "nan", description: "Puts traded per session (bets on a fall): contracts on US options and CME, coins on a crypto chain." }); input("call_prem", option_daily.call_premium, { missing: "nan", description: "Money paid for calls in the session, in USD." }); input("put_prem", option_daily.put_premium, { missing: "nan", description: "Money paid for puts in the session, in USD." }); input("call_oi", option_daily.call_oi, { missing: "nan", description: "Call open interest (calls still open): contracts on US options and CME, coins on a crypto chain." }); input("put_oi", option_daily.put_oi, { missing: "nan", description: "Put open interest (puts still open): contracts on US options and CME, coins on a crypto chain." }); input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of options at today's price, in percent." }); input("move", option_daily.implied_move_front, { missing: "nan", description: "The move the options price in for the nearest expiry, as a price distance." }); input("spot", option_daily.underlying_price, { missing: "nan", description: "The price of the stock, coin or future when the statistics were read." }); output("calls", bar, lower, { color: "theme.up", stack: "flow", label: "Calls", format: "si", description: "Calls traded (Volume view) or money paid for calls in USD (Premium view) in the session." }); output("puts", bar, lower, { color: "theme.down", stack: "flow", label: "Puts", format: "si", description: "Puts traded (Volume view) or money paid for puts in USD (Premium view) in the session." }); output("avg_line", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, step: true, label: "Average volume", format: "si", description: "Average daily volume over the Average window, in the Volume view." }); output("call_oi_line", line, lower, { color: "theme.up", width: 2, step: true, label: "Call open interest", format: "si", description: "Call open interest (calls still open), in the Open interest view." }); output("put_oi_line", line, lower, { color: "theme.down", width: 2, step: true, label: "Put open interest", format: "si", description: "Put open interest (puts still open), in the Open interest view." }); output("volume", none, lower, { description: "Contracts traded in the session, calls and puts together." }); output("pc_volume", none, lower, { description: "Puts traded for each call traded." }); output("pc_oi", none, lower, { description: "Open puts for each open call." }); output("pc_premium", none, lower, { description: "Money paid for puts for each dollar paid for calls." }); output("vol_vs_avg", none, lower, { description: "How far the session's volume sits above (+) or below (-) the average before it, in percent." }); output("total_oi", none, lower, { description: "Calls and puts still open, together." }); output("oi_change", none, lower, { description: "How much total open interest changed from the session before, in percent." }); output("move_pct", none, lower, { description: "The move the options price in for the nearest expiry, in percent of the price." }); output("sessions", none, lower, { description: "How many sessions (trading days) of daily data the indicator holds." }); output("status", none, lower, { description: "0 the average needs more sessions, 1 every reading shows, 2 a chart coarser than a day." }); string("read", { max_bytes: 64 }); // the headline string("title", { max_bytes: 64 }); const tableRows = frame("history_rows", { max_bytes: 16384 }); // one row per session, newest first panel.table({ name: "history", title: "Daily options history", x: "category", place: "below", frame: tableRows, height_frac: 0.26, header_text_color: "theme.muted", text_color: "theme.text", grid_color: "theme.grid", grid_width: 1, grid_lines: "rows", font_size: 11, series: [ { name: "Date" }, { name: "Close", align: "right", format: "price" }, { name: "Put/call", align: "right", format: "0.00" }, { name: "Volume", align: "right", format: "si" }, { name: "vs avg, %", align: "right", format: "0.0" }, { name: "Total OI", align: "right", format: "si" }, { name: "OI change, %", align: "right", format: "0.00" }, { name: "30-day IV, %", align: "right", format: "0.0" }, ] }); render.hud("history_card", { position: "bottom_right", title: "{{title}}", columns: 2, tiles: [ tile.pill("Session", "read", { headline: true }), tile.value("Volume", "volume", { format: "si" }), tile.value("Put/call volume", "pc_volume", { format: "0.00" }), tile.rows([ ["vs average, %", "vol_vs_avg", "0.0"], ["Total OI", "total_oi", "si"], ["OI change, %", "oi_change", "0.00"], ["Put/call OI", "pc_oi", "0.00"], ["Put/call premium", "pc_premium", "0.00"], ["Next expiry move, %", "move_pct", "0.00"], ["Sessions held", "sessions", "int"], ]), ], }); const DAY = 86400.0; const CAPACITY = 128; // the sessions each history keeps: the average and the table read no further back const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; const callVols = new DayHistory(CAPACITY); // per session, one history per field const putVols = new DayHistory(CAPACITY); const totals = new DayHistory(CAPACITY); // calls and puts, for the average const callPrems = new DayHistory(CAPACITY); const putPrems = new DayHistory(CAPACITY); const ois = new DayHistory(CAPACITY); // total open interest const ivs = new DayHistory(CAPACITY); const moves = new DayHistory(CAPACITY); // implied move over price, percent const spots = new DayHistory(CAPACITY); const sessions = new DayHistory(CAPACITY); // every session that landed, whatever it lacks: the table's rows const dateClock = new Clock("UTC"); let view = 0; // settings, read in onStart() let avgSessions = 30; let tableRowsN = 10; let prevT: f64 = NaN; // the bar spacing let barSec: f64 = NaN; let sessionDay: f64 = NaN; // the newest session read, and its numbers, held let callVol: f64 = NaN; let putVol: f64 = NaN; let callPrem: f64 = NaN; let putPrem: f64 = NaN; let callOi: f64 = NaN; let putOi: f64 = NaN; let avgNow: f64 = NaN; let vsAvgNow: f64 = NaN; let oiChangeNow: f64 = NaN; let movePctNow: f64 = NaN; function onStart(): void { view = i32(p_view()); avgSessions = i32(p_avg_sessions()); tableRowsN = i32(p_table_rows()); } function ratio(a: f64, b: f64): f64 { return b > 0.0 && !isNaN(a) ? a / b : NaN; } /** The average daily volume over the avgSessions sessions before the one ago back; NaN while fewer are held. */ function averageBefore(ago: i32): f64 { if (totals.count() < ago + 1 + avgSessions) return NaN; let sum = 0.0; for (let k = ago + 1; k <= ago + avgSessions; k += 1) sum += totals.value(k); return sum / f64(avgSessions); } /** The session ago back's total open interest over the one before it, minus 1, percent. */ function oiChangeAt(ago: i32): f64 { const now = ois.value(ago); const before = ois.value(ago + 1); return before > 0.0 && !isNaN(now) ? (now / before - 1.0) * 100.0 : NaN; } /** The value of h for the session on day; NaN when that session lacks it. */ function onDay(h: DayHistory, day: f64): f64 { const ago = h.agoOf(day); return ago < 0 ? NaN : h.value(ago); } // ── A session lands: every field it carries is kept, then the held readings move ── function land(day: f64): void { sessionDay = day; sessions.push(day, 1.0); callVol = in_call_vol(); putVol = in_put_vol(); callPrem = in_call_prem(); putPrem = in_put_prem(); callOi = in_call_oi(); putOi = in_put_oi(); const spot = in_spot(); callVols.push(day, callVol); putVols.push(day, putVol); if (!isNaN(callVol) && !isNaN(putVol)) totals.push(day, callVol + putVol); callPrems.push(day, callPrem); putPrems.push(day, putPrem); if (!isNaN(callOi) && !isNaN(putOi)) ois.push(day, callOi + putOi); ivs.push(day, in_iv30()); const move = in_move(); if (spot > 0.0 && !isNaN(move)) moves.push(day, (move / spot) * 100.0); spots.push(day, spot); const totalAgo = totals.agoOf(day); avgNow = totalAgo < 0 ? NaN : averageBefore(totalAgo); vsAvgNow = avgNow > 0.0 ? (totals.value(totalAgo) / avgNow - 1.0) * 100.0 : NaN; const oiAgo = ois.agoOf(day); oiChangeNow = oiAgo < 0 ? NaN : oiChangeAt(oiAgo); movePctNow = onDay(moves, day); } function sbDay(day: f64): void { // "16OCT" dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) sb_text("0"); sb_int(dateClock.dayOfMonth()); sb_text(MONTHS[dateClock.month() - 1]); } function fbNumber(v: f64, decimals: i32): void { fb_text(","); if (isNaN(v)) fb_text("null"); else fb_f64(v, decimals); } // ── The table: the newest sessions, newest first ── function writeTable(): void { fb_clear(); fb_text("{\"rows\":["); const shown = sessions.count() < tableRowsN ? sessions.count() : tableRowsN; for (let ago = 0; ago < shown; ago += 1) { const day = sessions.day(ago); if (ago > 0) fb_text(","); fb_text("[\""); dateClock.update(day * DAY); if (dateClock.dayOfMonth() < 10) fb_text("0"); fb_int(dateClock.dayOfMonth()); fb_text(MONTHS[dateClock.month() - 1]); fb_text("\""); fbNumber(onDay(spots, day), 2); fbNumber(ratio(onDay(putVols, day), onDay(callVols, day)), 2); const totalAgo = totals.agoOf(day); const total = totalAgo < 0 ? NaN : totals.value(totalAgo); fbNumber(total, 0); const avg = totalAgo < 0 ? NaN : averageBefore(totalAgo); fbNumber(avg > 0.0 ? (total / avg - 1.0) * 100.0 : NaN, 1); const oiAgo = ois.agoOf(day); fbNumber(oiAgo < 0 ? NaN : ois.value(oiAgo), 0); fbNumber(oiAgo < 0 ? NaN : oiChangeAt(oiAgo), 2); fbNumber(onDay(ivs, day), 1); fb_text("]"); } fb_text("],\"caption\":\""); if (sessions.count() == 0) fb_text("Waiting for the daily options statistics"); else { fb_int(sessions.count()); fb_text(sessions.count() == 1 ? " session held" : " sessions held"); if (totals.count() < avgSessions + 1) { fb_text(". The average needs "); fb_int(avgSessions); fb_text(" before the newest"); } } fb_text("\"}"); writeFrameBuffer(FRAME_HISTORY_ROWS); } function writeWords(coarse: bool): void { sb_clear(); if (coarse) sb_text("Needs a daily or finer chart"); else if (sessions.count() == 0) sb_text("Waiting for the daily options statistics"); else if (isNaN(vsAvgNow)) { sb_text("Not enough history yet: "); sb_int(totals.count() > 0 ? totals.count() - 1 : 0); sb_text(" of "); sb_int(avgSessions); sb_text(" sessions for the average"); } else { sb_text(vsAvgNow >= 0.0 ? "Volume over its average by " : "Volume under its average by "); sb_f64(Math.abs(vsAvgNow), 0); sb_text("%"); } str_read_sb(); sb_clear(); sb_text("Options history"); if (!coarse && sessions.count() > 0) { sb_text(", as of "); sbDay(sessionDay); } str_title_sb(); } // onBar() runs once per bar: the spacing, then the session's statistics when they land; every bar writes the held // session, so an intraday chart draws each session as a block. function onBar(): void { const t = bar.time(); if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT; prevT = t; const coarse = !isNaN(barSec) && barSec > 1.5 * DAY; if (!coarse) { const day = Math.floor(t / DAY); const any = !isNaN(in_call_vol()) || !isNaN(in_put_vol()) || !isNaN(in_call_oi()) || !isNaN(in_spot()); if (any && (isNaN(sessionDay) || day >= sessionDay)) land(day); } const has = !coarse && !isNaN(sessionDay); out_calls(has && view == 0 ? callVol : has && view == 2 ? callPrem : NaN); out_puts(has && view == 0 ? putVol : has && view == 2 ? putPrem : NaN); out_avg_line(has && view == 0 ? avgNow : NaN); out_call_oi_line(has && view == 1 ? callOi : NaN); out_put_oi_line(has && view == 1 ? putOi : NaN); out_volume(has && !isNaN(callVol) && !isNaN(putVol) ? callVol + putVol : NaN); out_pc_volume(has ? ratio(putVol, callVol) : NaN); out_pc_oi(has ? ratio(putOi, callOi) : NaN); out_pc_premium(has ? ratio(putPrem, callPrem) : NaN); out_vol_vs_avg(has ? vsAvgNow : NaN); out_total_oi(has && !isNaN(callOi) && !isNaN(putOi) ? callOi + putOi : NaN); out_oi_change(has ? oiChangeNow : NaN); out_move_pct(has ? movePctNow : NaN); out_sessions(coarse ? NaN : f64(sessions.count())); out_status(coarse ? 2.0 : isNaN(vsAvgNow) ? 0.0 : 1.0); if (bar.isLast()) { writeWords(coarse); if (!coarse) writeTable(); } } ``` ## How it works **What a session holds.** Volume and premium are the whole session's: the statistics job reads them at the close. Open interest is the clearing house's figure the session opened with, so its change from the prior session is the positions opened or closed the session before. **The average.** Each session's volume is compared with the mean of the `avg_sessions` sessions before it, never with a window that holds itself. **The table.** On the live bar the module walks the newest `table_rows` sessions and writes one row each; a value a session lacks prints empty, and the row stays. ## What the settings do - **View**: What the pane shows: Volume (contracts traded), Open interest (contracts still held open) or Premium (money paid for options). - **Average window, sessions**: How many past trading days the average daily volume covers. - **Sessions in the table**: How many of the newest trading days the table lists. - **Session**: The newest day's volume against its average, in words. - **Volume**: Calls and puts traded in the newest session. - **Put/call volume**: Puts traded for each call: above 1 means more puts. - **vs average, %**: How far the newest volume sits above or below its average, in percent. - **Total OI**: All calls and puts still open (open interest). - **OI change, %**: How much open interest changed from the session before, in percent. - **Put/call OI**: Open puts for each open call. - **Put/call premium**: Money paid for puts for each dollar paid for calls. - **Next expiry move, %**: The move the options price in for the nearest expiry, in percent. - **Sessions held**: How many trading days of daily data the indicator holds. ## Where it runs It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, 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 CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads it too, once you accept the CME market data terms ([Limitations](../reference/limitations.md)). CME data is 10 minutes behind unless you have real-time CME data. ## When data is missing The daily data starts the day OpenMarket switched it on. Every count shows from the first trading day, and the open interest change from the second. The distance from the average needs **Average window** trading days before the newest. Until then the card reads "Not enough history yet: 11 of 30 sessions for the average". The table's caption says the same. Before the first trading day the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart". ## Customize it - **Another pane.** Switch **View** to Open interest or Premium. - **Another average.** `avg_sessions` of 10 compares with the last two weeks. - **A longer table.** `table_rows` lists up to 30 sessions. ## Run it 1. In the editor's Explorer, press the **Templates** icon and pick **Options History** under **Beyond the time axis**. 2. Press **Run** on a US stock's daily chart. 3. At the editor's Console prompt, type `volume`, `vol_vs_avg` and `oi_change`. ## Concepts used - [Data sources](../core-concepts/data-sources.md#us-listed-options-by-the-charts-underlying) for `option_daily` - [Options kit](../functions/options-kit.md#a-history-of-daily-statistics) for `DayHistory` - [Table](../presentation/cards-frames-panels.md#table) for the table panel - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for the card <!-- source: https://openmarket.xyz/wrun/cookbook/seasonality-grid --> # Seasonality grid ![Weekday by hour grid of average 15-minute moves under a BTC chart, cells in the up and down colours with the best cell outlined, and a card at the top right naming Fri 04:00 with its hit rate and the worst cell](/wrun/images/seasonality-grid.png) A calendar of returns under the chart, shaped by the chart's interval and folded from a fixed span of the chart's own market, read as closed candles, however few bars the chart has loaded. On any chart under a day it is a weekday by UTC-hour grid, Mon to Sun by 00 to 23, each cell the average move of that hour, its hourly candle's open to close in percent, over the newest 26 weeks: one sample per week, so a 1m, a 15m and a 1h chart show the same grid. On a daily or coarser chart it is a year by month grid: one cell per month, the month's return (its last close over the last close of the month before) as signed percent, the years as rows, newest first, at most `max_rows`, and an Avg row under them; the running month shows its move so far at the live price and counts in no average until it closes. Cells that gained take the up colour and cells that lost the down colour, the strongest cells brightest, and zero reads as the chart's background; the best cell is outlined and named in the panel caption ("Best: Fri 08:00", "Best: Oct"), and the pointer opens a readout on any cell. A card at the top right, in the chart's default look, carries the span in its title ("Seasonality, 26 weeks" or "Seasonality, since 2019"), the best cell with its average as the headline ("Fri 08:00 +0.25%", "October +18.2%"), then two rows with dotted leaders: the hit rate (the share of that cell's samples that closed up, with the count) and the worst cell. While no cell has `min_samples` samples there is no grid: one sentence in the muted colour at the top right of the price pane says how much history it found and the way out, and the card's headline reads "Not enough history". The parts are the chart's own close, the bar grid ([Data sources](../core-concepts/data-sources.md)); two `candles` streams of the same market, `hours` at `1h` and `days` at `1d`, each a block of closed candles on every bar, the backlog on the first ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)); `chart.interval_sec()`, read once in `onStart()` to pick the grid ([Sessions and units](../settings/sessions-and-units.md#chart-context)); two `param.int` settings labelled **Years shown** and **Min samples** ([Setting kinds](../settings/kinds.md)); one frame feeding one `panel.heatmap` whose title, caption, outlined cell and Avg row are written per run ([Cards, frames and panels](../presentation/cards-frames-panels.md)); a `render.hud` card of a headline `tile.pill` and a `tile.rows` with dotted leaders, in the chart's default look ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)); and a label handle for the one sentence ([Drawing objects](../presentation/drawing-objects.md)). This is also the `seasonality-grid` template: the **Seasonality Grid** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Seasonality Grid: a calendar of returns below the chart, folded from a fixed span of history whatever the chart has // loaded. On a chart under a day, a weekday x UTC-hour grid: each cell the average move of that hour (its open to its // close) over the newest 26 weeks of hourly candles. On a daily or coarser chart, a year x month grid: each cell the // month's return (its last close over the month before's), over up to 12 years of daily candles. Cells that gained take // the up colour and cells that lost the down colour, the strongest cells brightest, the best cell outlined. The trader // sees when this market tends to move (the month that pays, the hour of the week that drifts), how often the best cell // held, and which cell hurt most. chart.interval_sec(); // the chart's bar interval in seconds, written by the chart: under a day the weekday grid, else the monthly grid param.int("max_rows", 12, { min: 3, max: 12, label: "Years shown", description: "Years kept in the monthly grid, newest first (the weekday grid always has its 7 rows)" }); param.int("min_samples", 3, { min: 1, max: 20, label: "Min samples", description: "Samples a cell needs before it can be named best or worst: years behind a month, weeks behind a weekday hour" }); input("close", ohlcv.close); // the chart's own candles: the bar grid the two streams ride // The two spans, read as closed candles of the chart's own market however few bars the chart has loaded: the weekday grid // folds the hourly one on any chart under a day, the monthly grid folds the daily one on a daily or coarser chart. input("hours", candles.cells, { interval: "1h", bars: 4368, description: "The newest 26 weeks of closed hourly candles: the weekday grid" }); input("days", candles.cells, { interval: "1d", bars: 4392, description: "The newest 12 years of closed daily candles: the monthly grid" }); output("best_avg", none, overlay, { description: "The best cell's average return, percent" }); // data-only, so the Console and a hover can read them output("worst_avg", none, overlay, { description: "The worst cell's average return, percent" }); output("hit_rate", none, overlay, { description: "Share of the best cell's samples that closed up, percent" }); string("best_text", { max_bytes: 32 }); // "October +12.4%" or "Tue 14:00 +0.21%": the card's headline string("worst_text", { max_bytes: 32 }); // the worst cell the same way string("hit_text", { max_bytes: 32 }); // "65% (17 of 26)" string("span_text", { max_bytes: 24 }); // "26 weeks" or "since 2019": the history the grid folds string("words", { max_bytes: 128 }); // the one sentence when the history is too short handles.label({ size: 11 }); // the one sentence, top right, in the muted ink const gridRows = frame("grid_rows", { max_bytes: 16384 }); // the heatmap: one cell per month and year, or per weekday and hour // The grid under the chart: a signed scale around zero (the up colour gained, the down colour lost, the chart's background // at zero, the strongest cells brightest), signed percent in every cell, a readout under the pointer; the title, the // caption, the outlined best cell and the monthly grid's Avg row are written per run in the frame. panel.heatmap({ name: "grid", title: "Seasonality", x: "category", place: "below", frame: gridRows, scale: "signed", positive_color: "theme.up", negative_color: "theme.down", format: "%", decimals: 2, signed: true, hover_card: true, height_frac: 0.35 }); // The card: the span in the title, the best cell and its average as the headline, then the hit rate and the worst cell // as two rows with dotted leaders. render.hud("card", { position: "top_right", title: "Seasonality, {{span_text}}", columns: 1, width: 250, safe_area: true, tiles: [ tile.pill("Best cell", "best_text", { headline: true }), tile.rows([["Hit rate", "hit_text"], ["Worst", "worst_text"]], { leader: "dots" }), ] }); const MAX_YEARS = 12; const MONTHS = 12; const DAYS = 7; const HOURS = 24; // ring sizes for the largest settings const DAY_SEC: f64 = 86400.0; const HOUR_SEC: f64 = 3600.0; const WEEK_SEC: f64 = 604800.0; const MONTH_SHORT: StaticArray<string> = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const MONTH_LONG: StaticArray<string> = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const DAY_NAMES: StaticArray<string> = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const MUTED_INK: i32 = theme.MUTED; // the sentence's ink, the chart's muted text const monthRet = new StaticArray<f64>(MAX_YEARS * MONTHS); // the monthly grid: a return per year slot and month, NaN where empty const yearOfSlot = new StaticArray<i32>(MAX_YEARS); // the year each ring slot holds const hourSum = new StaticArray<f64>(DAYS * HOURS); // the weekday x hour grid: summed hour moves, samples, up samples const hourCount = new StaticArray<i32>(DAYS * HOURS); const hourUp = new StaticArray<i32>(DAYS * HOURS); const monthAvg = new StaticArray<f64>(MONTHS); // the Avg row: each month's mean over the closed years shown, NaN below min_samples const words = draw.label(0); // the one sentence let daily = false; let maxRows = 12; let minSamples = 3; // read in onStart() let lastDayClose: f64 = NaN; let lastDayOpen: f64 = NaN; // the daily fold: the newest closed day let prevMonthEnd: f64 = NaN; // the close that ended the month before the newest one: the base of its return let curMonthKey = -1; let curYear = -1; let curSlot = 0; let curMonth = 0; let yearsSeen = 0; // the month and year row being filled let firstHourOpen: f64 = NaN; let lastHourOpen: f64 = NaN; // the hourly fold's span let wordsShown = false; let civYear = 0; let civMonth = 0; // civil()'s answer // The UTC calendar date of epoch seconds (days to civil), into civYear and civMonth (1..12). function civil(t: f64): void { const z = i64(Math.floor(t / DAY_SEC)) + 719468; const era = (z >= 0 ? z : z - 146096) / 146097; const doe = z - era * 146097; const yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; const doy = doe - (365 * yoe + yoe / 4 - yoe / 100); const mp = (5 * doy + 2) / 153; civMonth = i32(mp < 10 ? mp + 3 : mp - 9); civYear = i32(yoe + era * 400 + (civMonth <= 2 ? 1 : 0)); } function monthKeyOf(t: f64): i32 { civil(t); return civYear * 12 + civMonth - 1; } function sbSigned(v: f64, decimals: i32): void { if (v >= 0.0) sb_text("+"); sb_f64(v, decimals); sb_text("%"); } // "+12.4%", "-0.03%" function sbHour(h: i32): void { if (h < 10) sb_text("0"); sb_int(h); sb_text(":00"); } // "14:00" function fbHour(h: i32): void { fb_text("\""); if (h < 10) fb_text("0"); fb_int(h); fb_text("\""); } // the hour column key, "14" function fbHourText(h: i32): void { if (h < 10) fb_text("0"); fb_int(h); fb_text(":00"); } // "14:00" inside a caption function sbCount(n: i32, one: string, many: string): void { sb_int(n); sb_text(n == 1 ? one : many); } // "1 week", "26 weeks" function showWords(): void { // the sentence: the label at the top right, and the card's headline says why it has no cell str_words_sb(); words.set(56, 14).text(str_words_sb).anchor(ANCHOR_TOP_RIGHT).align(ALIGN_RIGHT).color(MUTED_INK); wordsShown = true; sb_clear(); sb_text("Not enough history"); str_best_text_sb(); } function hideWords(): void { if (wordsShown) { words.delete(); wordsShown = false; } } // onStart() runs once before the first bar: read the settings and the chart's interval, clear the rings. function onStart(): void { daily = p_chart_interval_sec() >= DAY_SEC; maxRows = i32(p_max_rows()); if (maxRows < 1) maxRows = 1; if (maxRows > MAX_YEARS) maxRows = MAX_YEARS; minSamples = i32(p_min_samples()); if (minSamples < 1) minSamples = 1; for (let i = 0; i < MAX_YEARS * MONTHS; i += 1) monthRet[i] = NaN; for (let i = 0; i < DAYS * HOURS; i += 1) { hourSum[i] = 0.0; hourCount[i] = 0; hourUp[i] = 0; } } // The daily stream into its months: a new month closes the one before on the last daily close seen; the newest month is // rewritten by every day that closes in it. A month whose calendar month before it holds no close stays empty (the first // month of the stream, a month after a gap), so a return never spans two months. function foldDays(t: f64): void { const block = in_days_view(); const cells = in_days_cells(); // f64 cells, six per candle: [offset_ms, open, high, low, close, volume] const n = cells < block.length ? cells : block.length; // -1 (no history on this bar) and 0 fold nothing for (let i = 0; i + 6 <= n; i += 6) { const close = block[i + 4]; if (!(close > 0.0)) continue; const open = t + block[i] / 1000.0; // the day's open, epoch seconds const key = monthKeyOf(open); if (key != curMonthKey) { // a new month: the last close seen ended the month before, when that month is the one just before prevMonthEnd = curMonthKey >= 0 && key == curMonthKey + 1 ? lastDayClose : NaN; curMonthKey = key; curMonth = civMonth - 1; if (civYear != curYear) { // a new year row: the next ring slot (the oldest row is reused once the ring is full) curYear = civYear; curSlot = yearsSeen % MAX_YEARS; yearsSeen += 1; yearOfSlot[curSlot] = civYear; for (let m = 0; m < MONTHS; m += 1) monthRet[curSlot * MONTHS + m] = NaN; } } if (!isNaN(prevMonthEnd)) monthRet[curSlot * MONTHS + curMonth] = (close / prevMonthEnd - 1.0) * 100.0; // final once the month's last day is in lastDayClose = close; lastDayOpen = open; } } // The hourly stream into its weekday hours: each hour's move, its open to its close in percent (every price move inside // the hour summed), is one sample of the cell for the weekday and UTC hour it opened in, Monday first. function foldHours(t: f64): void { const block = in_hours_view(); const cells = in_hours_cells(); // f64 cells, six per candle, as the daily stream const n = cells < block.length ? cells : block.length; for (let i = 0; i + 6 <= n; i += 6) { const open = block[i + 1]; const close = block[i + 4]; if (!(open > 0.0) || !(close > 0.0)) continue; const at = t + block[i] / 1000.0; // the hour's open, epoch seconds const day = i64(Math.floor(at / DAY_SEC)); // 1970-01-01 was a Thursday: (day + 3) % 7 is 0 on a Monday const cell = i32((day + 3) % 7) * HOURS + i32(i64(Math.floor(at / HOUR_SEC)) % 24); const move = (close / open - 1.0) * 100.0; hourSum[cell] += move; hourCount[cell] += 1; if (move > 0.0) hourUp[cell] += 1; if (isNaN(firstHourOpen)) firstHourOpen = at; lastHourOpen = at; } } // The monthly grid, on the live bar of a daily or coarser chart. Rows newest year first, every month a cell (null where // the history has none), then the Avg row: each month's mean, the number the best month is picked by. The month still // running shows the live price's move so far and counts in no average until it closes. function writeCalendar(): void { const rows = yearsSeen < maxRows ? yearsSeen : maxRows; const forming = curMonthKey >= 0 && !isNaN(lastDayOpen) && monthKeyOf(lastDayOpen + DAY_SEC) == curMonthKey; // the newest month has days to come let best = -1; let worst = -1; let bestAvg = -Infinity; let worstAvg = Infinity; let bestUp = 0; let bestN = 0; let mostN = 0; for (let m = 0; m < MONTHS; m += 1) { // a month's samples are its closed returns across the years shown let sum = 0.0; let n = 0; let up = 0; for (let k = 0; k < rows; k += 1) { const slot = (curSlot - k + MAX_YEARS) % MAX_YEARS; if (forming && slot == curSlot && m == curMonth) continue; const v = monthRet[slot * MONTHS + m]; if (isNaN(v)) continue; sum += v; n += 1; if (v > 0.0) up += 1; } if (n > mostN) mostN = n; monthAvg[m] = NaN; if (n < minSamples) continue; const avg = sum / f64(n); monthAvg[m] = avg; if (avg > bestAvg) { bestAvg = avg; best = m; bestUp = up; bestN = n; } if (avg < worstAvg) { worstAvg = avg; worst = m; } } sb_clear(); if (yearsSeen > 0) { sb_text("since "); sb_int(yearOfSlot[(curSlot - rows + 1 + MAX_YEARS) % MAX_YEARS]); } str_span_text_sb(); if (best < 0) { // no month has min_samples closed years: one sentence and its way out, never an empty grid sb_clear(); if (mostN == 0) sb_text("No closed month in this market's history yet: open the 1h chart for the weekday grid"); else { sb_text("Only "); sbCount(mostN, " year", " years"); sb_text(" of monthly history here, "); sb_int(minSamples); sb_text(" needed: open the 1h chart for the weekday grid"); } showWords(); return; } hideWords(); const hit = (100.0 * f64(bestUp)) / f64(bestN); out_best_avg(bestAvg); out_worst_avg(worstAvg); out_hit_rate(hit); sb_clear(); sb_text(MONTH_LONG[best]); sb_text(" "); sbSigned(bestAvg, 1); str_best_text_sb(); sb_clear(); sb_text(MONTH_LONG[worst]); sb_text(" "); sbSigned(worstAvg, 1); str_worst_text_sb(); sb_clear(); sb_f64(hit, 0); sb_text("% ("); sb_int(bestUp); sb_text(" of "); sb_int(bestN); sb_text(")"); str_hit_text_sb(); const live = bar.close(); const liveRet = forming && live > 0.0 && !isNaN(prevMonthEnd) ? (live / prevMonthEnd - 1.0) * 100.0 : NaN; fb_clear(); fb_text("{\"title\":\"Monthly returns\",\"caption\":\"Best: "); fb_text(MONTH_SHORT[best]); // the worst rides the card fb_text("\",\"highlight\":{\"col\":\""); fb_text(MONTH_SHORT[best]); fb_text("\"},\"summary\":[{\"label\":\"Avg\",\"values\":["); for (let m = 0; m < MONTHS; m += 1) { if (m > 0) fb_text(","); fb_f64(monthAvg[m], 2); } fb_text("]}],\"rows\":["); let first = true; for (let k = 0; k < rows; k += 1) { // newest year first; every month emitted so the columns keep their calendar order const slot = (curSlot - k + MAX_YEARS) % MAX_YEARS; for (let m = 0; m < MONTHS; m += 1) { if (!first) fb_text(","); first = false; const v = forming && slot == curSlot && m == curMonth && !isNaN(liveRet) ? liveRet : monthRet[slot * MONTHS + m]; fb_text("[\""); fb_text(MONTH_SHORT[m]); fb_text("\",\""); fb_int(yearOfSlot[slot]); fb_text("\","); fb_f64(v, 2); fb_text("]"); } } fb_text("]}"); writeFrameBuffer(FRAME_GRID_ROWS); } // The weekday x hour grid, on the live bar of a chart under a day. Mon..Sun rows, 00..23 UTC columns, each cell the // average move of that hour over the weeks folded (null where no hour closed); the best cell is outlined. function writeHours(): void { const weeks = isNaN(firstHourOpen) ? 0 : i32(Math.round((lastHourOpen - firstHourOpen + HOUR_SEC) / WEEK_SEC)); // the span, in whole weeks let best = -1; let worst = -1; let bestAvg = -Infinity; let worstAvg = Infinity; let mostN = 0; for (let i = 0; i < DAYS * HOURS; i += 1) { const n = hourCount[i]; if (n > mostN) mostN = n; if (n < minSamples) continue; const avg = hourSum[i] / f64(n); if (avg > bestAvg) { bestAvg = avg; best = i; } if (avg < worstAvg) { worstAvg = avg; worst = i; } } sb_clear(); sbCount(weeks, " week", " weeks"); str_span_text_sb(); if (best < 0) { // no weekday hour has min_samples weeks behind it: one sentence and its way out, never an empty grid sb_clear(); if (mostN == 0) sb_text("No hourly history for this market yet: switch to a market that has traded for a few weeks"); else { sb_text("Only "); sbCount(mostN, " week", " weeks"); sb_text(" of hourly history here, "); sb_int(minSamples); sb_text(" needed: lower Min samples in the settings"); } showWords(); return; } hideWords(); const bestN = hourCount[best]; const bestUp = hourUp[best]; const hit = (100.0 * f64(bestUp)) / f64(bestN); out_best_avg(bestAvg); out_worst_avg(worstAvg); out_hit_rate(hit); sb_clear(); sb_text(DAY_NAMES[best / HOURS]); sb_text(" "); sbHour(best % HOURS); sb_text(" "); sbSigned(bestAvg, 2); str_best_text_sb(); sb_clear(); sb_text(DAY_NAMES[worst / HOURS]); sb_text(" "); sbHour(worst % HOURS); sb_text(" "); sbSigned(worstAvg, 2); str_worst_text_sb(); sb_clear(); sb_f64(hit, 0); sb_text("% ("); sb_int(bestUp); sb_text(" of "); sb_int(bestN); sb_text(")"); str_hit_text_sb(); fb_clear(); fb_text("{\"title\":\"Average hourly move by weekday (UTC)\",\"caption\":\"Best: "); fb_text(DAY_NAMES[best / HOURS]); fb_text(" "); fbHourText(best % HOURS); // the worst rides the card fb_text("\",\"highlight\":{\"row\":\""); fb_text(DAY_NAMES[best / HOURS]); fb_text("\",\"col\":"); fbHour(best % HOURS); fb_text("},\"rows\":["); let first = true; for (let d = 0; d < DAYS; d += 1) for (let h = 0; h < HOURS; h += 1) { // every cell emitted so both axes keep their order if (!first) fb_text(","); first = false; const i = d * HOURS + h; fb_text("["); fbHour(h); fb_text(",\""); fb_text(DAY_NAMES[d]); fb_text("\","); if (hourCount[i] > 0) fb_f64(hourSum[i] / f64(hourCount[i]), 4); else fb_text("null"); fb_text("]"); } fb_text("]}"); writeFrameBuffer(FRAME_GRID_ROWS); } // onBar() runs once per bar: fold the closed candles this bar carries from the stream its grid reads (the first bar // carries the whole backlog), then on the live bar write that grid, the card's words and the outputs. function onBar(): void { const t = bar.time(); if (daily) foldDays(t); else foldHours(t); if (!bar.isLast()) return; if (daily) writeCalendar(); else writeHours(); } ``` ## How it works **The chart's interval picks the grid.** `chart.interval_sec()` declares a hidden setting the chart fills with its bar interval in seconds before the first bar, and `onStart()` reads it once through `p_chart_interval_sec()`: 86400 or more, a daily or coarser chart, picks the year by month grid and its `days` stream; anything shorter, 0 included (an unknown interval), picks the weekday by hour grid and its `hours` stream. `onBar()` then folds only that stream, on every bar, the live bar included, and on the live bar (`bar.isLast()`) writes only that grid, the card's words and the outputs. The chart replays the forming bar from a snapshot of the module taken after the last closed bar, so these plain sums never count a candle twice ([Repainting](../core-concepts/repainting.md)). Both streams are declared, so both load on every chart, and only the picked one is folded. **Two streams, two fixed spans.** `input("hours", candles.cells, { interval: "1h", bars: 4368 })` asks for the newest 26 weeks of closed hourly candles (26 weeks of 168 hours), and `input("days", candles.cells, { interval: "1d", bars: 4392 })` for the newest 12 years of closed daily candles (12 years of 366 days), both of the chart's own market, since neither names a `symbol` or an `exchange`. A stream reaches its `bars` back however few bars the chart has loaded (further when the chart has loaded more; the card's title reads the span actually folded), so the grid does not follow the chart's window: a 1m, a 15m and a 1h chart fold the same hourly candles and show the same weekday grid. The first bar carries the backlog, every candle closed up to it, and each later bar the candles that closed since the bar before, so a forming candle never arrives and none arrives twice ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). Each candle is six numbers, `[offset_ms, open, high, low, close, volume]`, oldest first: `in_hours_cells()` counts those numbers, not candles (-1 or 0 on a bar that carries none), so the folds step by six through `in_hours_view()`, and `in_days_view()` the same way; the candle opened at `bar.time() + offset_ms / 1000` epoch seconds, the instant its cell is keyed on. `close` stays the first input, the bar grid the two streams ride. **Why not a pin or the chart's bars.** A scalar `ohlcv` input pinned to `interval: "1h"` hands each chart bar one hourly close, so it covers only the chart's own window plus its pre-roll (a few hours of closes on a 1m chart), and a pin finer than the chart is refused, which would stop the run on every daily chart. The chart's own bars are only what it has loaded (on BTCUSDT on Binance Futures, about 290 on a 1h chart and 481 on a 1d chart), which gives each weekday hour or each month one or two samples, under the default `min_samples` of 3. **An hour is one sample a week.** `foldHours()` turns each hourly candle into one sample, its open to close in percent (`(close / open - 1) * 100`, every price move inside the hour summed), and adds it to the cell of the weekday and UTC hour the candle opened in, Monday first (1970-01-01 was a Thursday, so `(day + 3) % 7` is 0 on a Monday). Each cell keeps its summed moves, its sample count and its count of samples that closed up (`hourSum`, `hourCount`, `hourUp`). A weekday hour comes round once a week, so its count is the weeks behind it, and the cell prints the average of its samples. The hour's own candle reads the same on every chart interval, where an average of a 1m chart's bar returns would round to 0.00%. **A month is its last close over the month before's.** `foldDays()` walks the daily candles into calendar months by the UTC date of each day's open (`civil()` turns epoch seconds into the year and the month). A day in a new month closes the month before on the last daily close seen, and every day that closes in a month rewrites that month's cell in `monthRet` as its close over the close that ended the month before, in percent, so the cell is final once the month's last day is in. The stream's first month has no close before it and stays empty, and so does a month whose calendar month before it holds no candle (a gap in the history): the close that ended a month only bases the next month's return when the two months are adjacent (`key == curMonthKey + 1`), so a return never spans two months. A new year takes the next of 12 ring slots (`MAX_YEARS`, each slot's year in `yearOfSlot`), and once 12 years are held the oldest row is reused. The month still running shows the live price's move so far, `bar.close()` over the close that ended the month before, and counts in no average: a month joins the averages once the day after its newest closed day falls in the next month. **One frame is the grid.** `frame("grid_rows")` carries `[x key, y key, value]` cells: `[month, year, return]` on the monthly grid, newest year first, and `[hour, weekday, average]` on the weekday grid, `null` where the history has none (`fb_f64` writes a NaN month as `null`), so every cell is written and both axes keep their calendar order, since the panel orders keys as the rows first name them. Beside the rows the frame carries what changes per run: `title` ("Monthly returns" or "Average hourly move by weekday (UTC)"), `caption`, which names the best cell only ("Best: Oct", "Best: Fri 08:00"; the worst rides the card, so the title row stays short enough to read), `highlight`, the best month's column (`{"col": "Oct"}`) or the best weekday-hour cell (`{"row": "Fri", "col": "08"}`), which the panel outlines, and on the monthly grid `summary`, one row labelled "Avg" under the years: each month's mean over the closed years shown, `null` below `min_samples`, the number the best month is picked by. The declared `panel.heatmap` holds what does not change: `scale: "signed"` around zero with the up colour as `positive_color` and the down colour as `negative_color`, `format: "%"` with `decimals: 2` and `signed: true` so a cell prints "+2.28%" or "-0.27%", `hover_card: true` for the readout, `height_frac: 0.35` for the pane's share of the chart. The panel prints a cell's value when the cell is at least 34 px wide and 11 px tall; no word toggles it. The grid is built in the frame buffer (`fb_clear`, `fb_text`, `fb_int`, `fb_f64`) and sent with `writeFrameBuffer(FRAME_GRID_ROWS)`, allocation-free on every live tick. **Best and worst need samples.** A cell qualifies once it holds `min_samples` (3) samples: closed years behind a month, counted over the year rows shown with the running month skipped, or weeks behind a weekday hour. Among the qualifying cells the highest average is best and the lowest is worst, so the caption, the outline and the card only ever name a cell that has `min_samples`. `best_avg`, `worst_avg` and `hit_rate` (the share of the best cell's samples that closed up, in percent) are data-only outputs written on the live bar once a cell qualifies, so the Console and a hover can read the numbers behind the card. **The card reads slots.** The headline is a `tile.pill` on the `best_text` slot, so the cell's name rides with its number ("Fri 08:00 +0.25%" with two decimals, "October +18.2%" with one; a `tile.value` would print the number alone), and `tile.rows` with `leader: "dots"` reads `hit_text` ("65% (17 of 26)", so the count shows) and `worst_text` ("Fri 18:00 -0.27%", "June -8.5%"). The title `"Seasonality, {{span_text}}"` resolves the `span_text` slot on the chart: the hourly span folded, in whole weeks ("26 weeks"), or the oldest year row shown ("since 2019"), written on the live bar before the sample check, so the span reads even while no cell qualifies. Every line is built with the `sb_*` builder and sent with `str_<slot>_sb()` ([Strings and text](../functions/text-formatting.md)). With no `look`, the card draws the chart's default look (the headline at 17 px bold with its label hidden, the pill as its word), and `leader: "dots"` on the rows draws the dotted leaders the default look leaves out; `width: 250` and `safe_area: true` keep the card clear of the legend and the pane action bar at the top right. **The sentence is a label handle.** `handles.label({ size: 11 })` declares the kind and `draw.label(0)` makes the one handle. While no cell qualifies, `showWords()` sends the sentence to the `words` slot, sets the label 56 px in from the pane's top right corner and 14 px down (`ANCHOR_TOP_RIGHT`, right-aligned, in the muted colour), and writes "Not enough history" into `best_text` for the card's headline; the first live write that finds a best cell deletes the label (`hideWords()`). ## Where it runs Every market with candles, on any chart from 1m up: crypto perpetuals and spot, gold, prediction markets. It reads only the chart's own market (its candles, an hourly stream and a daily stream), never another one, so no market refuses it, and every cell is keyed on UTC. On a market that pauses (gold), the hours it does not trade stay empty cells. A young market shows the sentence until a cell has `min_samples` samples: at the default 3, a chart under a day draws the grid once one weekday hour has closed in three different weeks, and a daily chart once one calendar month holds three closed returns, which takes over two years; until then the daily chart's sentence points to the 1h chart and its weekday grid. Both streams load on every chart, so a daily chart also fetches the hourly candles back to its first bar, which its grid never reads. On a weekly chart the legend carries one warning: the hourly stream asks back to the chart's first bar, and hourly candles reach back only 25,000 hours ([How far back history reaches](../core-concepts/multi-timeframe.md#how-far-back-history-reaches)). The monthly grid does not read them and is whole. ## When data is missing Until one cell has `min_samples` samples there is no grid: the live bar writes no frame and no outputs (`best_avg`, `worst_avg` and `hit_rate` stay unwritten), and one sentence in the muted colour stands at the top right of the price pane with the history found and the way out. On a chart under a day it reads "Only 2 weeks of hourly history here, 3 needed: lower Min samples in the settings", or "No hourly history for this market yet: switch to a market that has traded for a few weeks" before any hour has closed; on a daily or coarser chart, "Only 2 years of monthly history here, 3 needed: open the 1h chart for the weekday grid", or "No closed month in this market's history yet: open the 1h chart for the weekday grid". The card stays up: its title still reads the span, its headline reads "Not enough history", and the Hit rate and Worst rows print a dash, since their slots are never written. Cells the history has not reached stay empty: the hours a paused market does not trade, the months of the newest year still to come, and the stream's first month, which has no close before it to measure from (the daily history of BTCUSDT on Binance Futures starts in November 2019, so its 2019 row holds December only). The running month shows its move so far at the live price but counts in no average until it closes. ## Customize it - **More or fewer year rows.** `max_rows` (12, 3 to 12), the **Years shown** row, is the years kept in the monthly grid, newest first, and the card's "since" year is the oldest of them; the weekday grid always has its 7 rows. - **A stricter best cell.** `min_samples` (3, 1 to 20), the **Min samples** row, is the samples a cell needs before it can be named best or worst: years behind a month, weeks behind a weekday hour. A higher number waits for more history before the grid draws, and since the monthly grid counts only the years shown, a `min_samples` above `max_rows` keeps a daily chart on the sentence. - **A longer or shorter span.** The spans are the streams' `bars`: 4368 hourly candles (26 weeks) on `hours` and 4392 daily candles (12 years) on `days`. Change either in the source and Run again: `bars` takes up to 5000 (about 30 weeks of hourly candles), and the monthly grid keeps at most 12 year rows whatever the daily span. - **Other colours.** `positive_color` and `negative_color` on the panel are theme words in this source (`theme.up` and `theme.down`, the chart's up and down colours), so here another pair is a source edit. Declare a `param.color` and write `"@<name>"` in either word, and that colour becomes a setting: the build writes the setting's default in its place, and the chart paints the trader's pick ([Panel words](../presentation/cards-frames-panels.md#panel-words)). - **A look of its own.** The card declares no `look`, so it draws the chart's default look, and the Look row on the indicator's Style page switches it to any of the twelve shipped looks without code, "As made" first ([The Style page](../settings/style-page.md#the-look-row)). When the card should stand apart from the chart, add `look:` with one of them, or bind `look` to a `param.choice` over looks (`look: "@card_look"`) and that setting's row becomes the look's one control, with no Look row for the card ([Looks](../presentation/hud-and-hover-cards.md#looks)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Seasonality Grid** under **Beyond the time axis**. 2. Press **Run** on BTCUSDT on Binance Futures at 15m: the weekday by hour grid fills below the chart with the best cell outlined, and the card names it at the top right. Switch the chart to 1m or 1h for the same grid, and to 1D for the year by month grid with its Avg row; no scroll back is needed, since each grid reads its own stream. 3. At the editor's Console prompt, type `hit_rate` to read the best cell's hit rate on the live bar, or `outputs` for `best_avg`, `worst_avg` and `hit_rate` together. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for `ohlcv.close`, the chart's own candles and the bar grid the streams ride - [Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream) for the `candles` stream: `interval`, `bars`, the six-number candle, the backlog on the first bar and the `in_<name>_cells()` / `in_<name>_view()` loop - [How far back history reaches](../core-concepts/multi-timeframe.md#how-far-back-history-reaches) for the 25,000 hourly candles behind the warning on a weekly chart - [Sessions and units](../settings/sessions-and-units.md#chart-context) for `chart.interval_sec()` and `p_chart_interval_sec()` - [Setting kinds](../settings/kinds.md) and [Options on a setting](../settings/options.md) for the two `param.int` settings and their `label` - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames, `panel.heatmap`, the signed scale, the per-run `title`, `caption`, `highlight` and `summary`, and the frame buffer - [Panel words](../presentation/cards-frames-panels.md#panel-words) for `positive_color`, `negative_color` and a colour word bound to a `param.color` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `width` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name and `look` bound to a `param.choice` - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` and `tile.rows` with `leader: "dots"` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Strings and text](../functions/text-formatting.md) for the `sb_*` builders and string slots - [Drawing objects](../presentation/drawing-objects.md) for `handles.label` and the `draw.label` handle <!-- source: https://openmarket.xyz/wrun/cookbook/depth-curve --> # Depth curve ![Depth curve pane under a BTC chart, the bid and ask staircases in the up and down colours meeting at the dashed mid with wall callouts, and the book card at the top right reading Asks 1.2x bids](/wrun/images/depth-curve.png) The market's resting order book as the classic depth curve under the chart: a pane with price across and dollars up, the bids in the up colour stepping up to the left of the mid, the asks in the down colour stepping up to the right, both as staircases (a book is steps, never a smooth curve) filled to the axis. The steeper side is the heavier side. A dashed marker in the muted colour stands at the mid with its price ("Mid 85,115"), and a callout pins on each of the two biggest single levels per side ("$26.1M wall"), where the staircase jumps. The pane's caption gives the verdict within `near_pct` of the mid: "Bids heavier 1.4x", "Asks heavier 1.3x", "Balanced book", or "Thin near the mid" when nothing rests in the band. At the top left of the price pane, under the legend and clear of the newest candles, a card in the chart's default look titled "Order book within 1%" leads with one big line, "Bids 1.4x asks" (in the up colour when the bids are heavier, the down colour when the asks are, the muted colour when balanced), then two rows: "Biggest wall" ("$26.1M bid at 85,100") and "Spread" ("up to 25 (0.03%)" when the touch sits inside one step of the book's grouping, else the percent of the mid and the price gap, as in "0.07% (0.0001)"). Everything is read from the live snapshot the chart serves, about once a second on the live bar; history bars only feed the data outputs and draw nothing. The parts are a `book.cells` input, one `[price, size, side]` tuple per level ([Order flow](../functions/order-flow-kit.md)), a frame feeding a `panel.line` on a number axis with two step series filled to the axis, a dashed mid marker, wall callouts pinned at an exact `y`, a per-run title and a caption ([Cards, frames and panels](../presentation/cards-frames-panels.md)), and a `render.hud` card in the chart's default look whose headline carries the one sentence when the market has no book ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards), [The default look](../presentation/hud-and-hover-cards.md#the-default-look)). This is also the `depth-curve` template: the **Depth Curve** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Depth Curve: the market's resting order book as the classic depth curve under the chart. Cumulative bid dollars step // up to the left of the mid in the up colour, cumulative ask dollars step up to the right in the down colour, each // side filled to the axis, a dashed marker at the mid, and a callout pinned on the two biggest single walls of each // side ("$26.1M wall"). The panel's caption names the heavier side within near_pct of the mid ("Bids heavier 1.4x"). // A card at the top left of the price pane, under the legend and clear of the newest candles, leads with the same // ratio as its one big number and reads the biggest wall and the spread under it. The trader sees which side of the book is heavier, how steep each // side is, and where the walls sit, all from the live snapshot the chart serves about once a second. // A market without an order book (gold, prediction markets) says so on the card, "No order book", and draws nothing else. section("Reach"); param.number("range_pct", 2.0, { min: 0.5, max: 10.0, step: 0.5, label: "Curve reach, percent", description: "How far from the mid the curve reaches, percent each side" }); param.number("near_pct", 1.0, { min: 0.1, max: 5.0, step: 0.1, label: "Ratio band, percent", description: "The band the ratio and the caption read, percent each side of the mid" }); // Inputs: the chart's own candles set the grid, then the book: one [price, size, side] row per level, side +1 a bid // and -1 an ask, sizes in coins. The chart serves its own market's book at its own grouping, up to 500 levels a side, // so 1000 rows hold any bar; block_size is required by the declaration and the chart does not read it. input("close", ohlcv.close); input("book", book.cells, { max_cells: 1000, block_size: 10 }); // Outputs: data-only, one value per bar, so a watch or an alert can read the book too. output("side", none, overlay, { description: "0 asks heavier, 1 balanced or no book, 2 bids heavier, within near_pct of the mid" }); output("ratio", none, overlay, { format: "0.00", description: "Bid dollars over ask dollars within near_pct of the mid" }); output("bids_near", none, overlay, { color: "theme.up", format: "usd", description: "Dollars bid within near_pct of the mid" }); output("asks_near", none, overlay, { color: "theme.down", format: "usd", description: "Dollars offered within near_pct of the mid" }); output("spread_pct", none, overlay, { format: "%", description: "Best ask minus best bid, as a percent of the mid" }); output("bid_wall", none, overlay, { color: "theme.up", format: "price", description: "The price of the biggest bid within range_pct of the mid" }); output("bid_wall_usd", none, overlay, { format: "usd", description: "Dollars resting at the bid wall" }); output("ask_wall", none, overlay, { color: "theme.down", format: "price", description: "The price of the biggest ask within range_pct of the mid" }); output("ask_wall_usd", none, overlay, { format: "usd", description: "Dollars resting at the ask wall" }); string("near_text", { max_bytes: 8 }); // "1%": the card title's band, written on the live bar string("ratio_text", { max_bytes: 40 }); // "Bids 1.4x asks", or "No order book" when the market has none string("wall_text", { max_bytes: 40 }); // "$26.1M bid at 85,100" string("spread_text", { max_bytes: 32 }); // "0.0001% (0.10)" const depth = frame("depth", { max_bytes: 65536 }); // the curve: one row per level, [price, bid dollars | null, ask dollars | null] // The depth curve: price across, dollars up, both sides stepped (a book is a staircase, never a smooth curve) and // filled to the axis in their own ink; the mid marker, the four wall callouts and the caption are written per run. panel.line({ name: "depth_curve", title: "Order book depth", x: "number", place: "below", frame: depth, series: [ { name: "Bids", color: "theme.up", width: 1.5, style: "step", fill: true }, { name: "Asks", color: "theme.down", width: 1.5, style: "step", fill: true }, ], legend_style: "title", hover_card: true, x_format: "usd", format: "usd", decimals: 0, y_zero: true, height_frac: 0.32, }); // The card: the heavier side as the one big number, then the biggest wall and the spread as two rows; at the top left // under the legend, so it covers the oldest candles on screen, never the newest. render.hud("depth_card", { position: "top_left", safe_area: true, title: "Order book within {{near_text}}", columns: 1, width: 300, tiles: [ tile.pill("Heavier side", "ratio_text", { headline: true, font_size: 20, color_by: "side", colors: ["theme.down", "theme.muted", "theme.up"] }), tile.rows([["Biggest wall", "wall_text"], ["Spread", "spread_text"]]), ], }); const LEVELS = 500; // the chart's book carries at most 500 levels a side const ASKS_HEAVIER = 0.0; // the side ladder, in the colours' order const BALANCED = 1.0; const BIDS_HEAVIER = 2.0; const LEAN = 1.05; // the ratio either side of 1 before a side is named const bidPx = new StaticArray<f64>(LEVELS); // the last snapshot with both sides, copied per bar, sorted on the live bar const bidSz = new StaticArray<f64>(LEVELS); const askPx = new StaticArray<f64>(LEVELS); const askSz = new StaticArray<f64>(LEVELS); const bidCum = new StaticArray<f64>(LEVELS); // cumulative dollars from the touch outward, per sorted level const askCum = new StaticArray<f64>(LEVELS); let rangePct = 2.0; // settings, read in onStart() let nearPct = 1.0; let bids: i32 = 0; // levels in the stored snapshot let asks: i32 = 0; let bookBar: i32 = -1; // the bar index the stored snapshot came from, -1 while no bar carried both sides let barIndex: i32 = -1; let mid: f64 = NaN; // this bar's readings, NaN without a usable snapshot let bestBid: f64 = NaN; let bestAsk: f64 = NaN; let bidsNear: f64 = NaN; let asksNear: f64 = NaN; let bidWall: f64 = NaN; let bidWallUsd: f64 = NaN; let askWall: f64 = NaN; let askWallUsd: f64 = NaN; let bidWall2: f64 = NaN; // the second biggest wall per side, for the callouts let bidWall2Usd: f64 = NaN; let askWall2: f64 = NaN; let askWall2Usd: f64 = NaN; let decimals: i32 = 2; // the market's price decimals, read off the book's tick let tick: f64 = NaN; // the book's own price step (the smallest gap between neighbouring levels) // readBook() copies this bar's snapshot into the side arrays. The chart hands the bids best first and the asks from // the highest price down, but every read goes by price and side, never by position. False when the bar has no usable // snapshot (none delivered, a side missing, or a crossed book); the arrays then keep the newest usable one. function readBook(): bool { const n = in_book_cells(); // numbers delivered this bar: 0 for an empty block, -1 when the bar carries none if (n < 6) return false; const cells = in_book_view(); let hiBid = -Infinity; let loAsk = Infinity; let nb: i32 = 0; let na: i32 = 0; for (let i = 0; i + 2 < n; i += 3) { // first pass: is the snapshot usable? (nothing is stored yet) const price = cells[i]; if (!(price > 0.0) || !(cells[i + 1] > 0.0)) continue; // an empty level is served but rests nothing if (cells[i + 2] > 0.0) { nb += 1; if (price > hiBid) hiBid = price; } else if (cells[i + 2] < 0.0) { na += 1; if (price < loAsk) loAsk = price; } } if (nb == 0 || na == 0 || !(loAsk > hiBid)) return false; nb = 0; na = 0; for (let i = 0; i + 2 < n; i += 3) { // second pass: copy the levels, at most LEVELS a side const price = cells[i]; const size = cells[i + 1]; if (!(price > 0.0) || !(size > 0.0)) continue; if (cells[i + 2] > 0.0) { if (nb < LEVELS) { bidPx[nb] = price; bidSz[nb] = size; nb += 1; } } else if (cells[i + 2] < 0.0) { if (na < LEVELS) { askPx[na] = price; askSz[na] = size; na += 1; } } } bids = nb; asks = na; bookBar = barIndex; return true; } function clearReadings(): void { mid = NaN; bestBid = NaN; bestAsk = NaN; bidsNear = NaN; asksNear = NaN; bidWall = NaN; bidWallUsd = NaN; askWall = NaN; askWallUsd = NaN; bidWall2 = NaN; bidWall2Usd = NaN; askWall2 = NaN; askWall2Usd = NaN; } // measure() reads the stored snapshot: the touch and the mid, the dollars within near_pct of the mid per side, and // the two biggest single levels within range_pct per side. function measure(): void { clearReadings(); let hiBid = -Infinity; let loAsk = Infinity; for (let k = 0; k < bids; k++) if (bidPx[k] > hiBid) hiBid = bidPx[k]; for (let k = 0; k < asks; k++) if (askPx[k] < loAsk) loAsk = askPx[k]; bestBid = hiBid; bestAsk = loAsk; mid = (hiBid + loAsk) * 0.5; const near = mid * nearPct / 100.0; const reach = mid * rangePct / 100.0; bidsNear = 0.0; asksNear = 0.0; for (let k = 0; k < bids; k++) { const price = bidPx[k]; const dollars = price * bidSz[k]; const away = mid - price; if (away <= near) bidsNear += dollars; if (away <= reach) { if (isNaN(bidWallUsd) || dollars > bidWallUsd) { bidWall2 = bidWall; bidWall2Usd = bidWallUsd; bidWall = price; bidWallUsd = dollars; } else if (isNaN(bidWall2Usd) || dollars > bidWall2Usd) { bidWall2 = price; bidWall2Usd = dollars; } } } for (let k = 0; k < asks; k++) { const price = askPx[k]; const dollars = price * askSz[k]; const away = price - mid; if (away <= near) asksNear += dollars; if (away <= reach) { if (isNaN(askWallUsd) || dollars > askWallUsd) { askWall2 = askWall; askWall2Usd = askWallUsd; askWall = price; askWallUsd = dollars; } else if (isNaN(askWall2Usd) || dollars > askWall2Usd) { askWall2 = price; askWall2Usd = dollars; } } } } // Insertion sort of one side's price and size pairs by price: bids descending (best first), asks ascending. The // chart's own order is already sorted one way or the other, so this costs little, and it runs on the live bar only. function sortSide(px: StaticArray<f64>, sz: StaticArray<f64>, n: i32, ascending: bool): void { for (let i = 1; i < n; i++) { const p = px[i]; const s = sz[i]; let j = i - 1; while (j >= 0 && (ascending ? px[j] > p : px[j] < p)) { px[j + 1] = px[j]; sz[j + 1] = sz[j]; j -= 1; } px[j + 1] = p; sz[j + 1] = s; } } // The book's price step and the decimals the market prints in, read off the smallest gap between neighbouring levels // of the sorted sides (the chart serves the book at its own grouping, so the step is the grouping, not the exchange tick). function readTick(): void { tick = Infinity; for (let k = 1; k < bids && k < 40; k++) { const gap = bidPx[k - 1] - bidPx[k]; if (gap > 0.0 && gap < tick) tick = gap; } for (let k = 1; k < asks && k < 40; k++) { const gap = askPx[k] - askPx[k - 1]; if (gap > 0.0 && gap < tick) tick = gap; } if (!(tick < Infinity)) { tick = NaN; decimals = 2; return; } let d: i32 = 0; let t = tick; while (d < 6 && Math.abs(t - Math.round(t)) > 1e-6) { t *= 10.0; d += 1; } decimals = d; } // The cumulative dollars at one level of a sorted side (the point a wall callout pins on); NaN when the level is // outside the drawn reach. function cumAt(px: StaticArray<f64>, cum: StaticArray<f64>, n: i32, price: f64): f64 { for (let k = 0; k < n; k++) if (px[k] == price) return cum[k]; return NaN; } // Text sinks: 0 writes into the string builder (the card's slots), 1 into the frame buffer (the panel's labels). function putText(sink: i32, s: string): void { if (sink == 0) sb_text(s); else fb_text(s); } function putInt(sink: i32, v: i32): void { if (sink == 0) sb_int(v); else fb_int(v); } function putFixed(sink: i32, v: f64, d: i32): void { if (sink == 0) sb_f64(v, d); else fb_f64(v, d); } // A price with thousands separators and the market's decimals: 85,115 or 0.1412. function putPrice(sink: i32, v: f64, d: i32): void { let scale = 1.0; for (let i = 0; i < d; i++) scale *= 10.0; const rounded = Math.round(v * scale) / scale; const whole = Math.floor(rounded); let group = 1.0; while (whole >= group * 1000.0) group *= 1000.0; let rest = whole; let first = true; while (group >= 1.0) { const g = Math.floor(rest / group); if (!first) { putText(sink, ","); if (g < 100.0) putText(sink, "0"); if (g < 10.0) putText(sink, "0"); } putInt(sink, i32(g)); rest -= g * group; group /= 1000.0; first = false; } if (d > 0) { putText(sink, "."); let frac = i32(Math.round((rounded - whole) * scale)); if (frac >= i32(scale)) frac = i32(scale) - 1; let place = i32(scale) / 10; while (place > 1 && frac < place) { putText(sink, "0"); place /= 10; } putInt(sink, frac); } } // Money as $26.1M, $950.0K, $1.2B, one decimal at K and up, whole dollars under 1K. function putUsd(sink: i32, x: f64): void { putText(sink, "$"); if (x >= 1.0e9) { putFixed(sink, x / 1.0e9, 1); putText(sink, "B"); } else if (x >= 1.0e6) { putFixed(sink, x / 1.0e6, 1); putText(sink, "M"); } else if (x >= 1.0e3) { putFixed(sink, x / 1.0e3, 1); putText(sink, "K"); } else putFixed(sink, x, 0); } // One wall callout in the frame's markers list: pinned on the side's staircase at the wall's price, at the exact // cumulative value there (an exact y, because the lane pins a named series' callout on the first series only). function fbWallMarker(price: f64, dollars: f64, y: f64, color: string): void { if (isNaN(price) || isNaN(y)) return; fb_text(',{"x":'); fb_num(price); fb_text(',"valign":"point","y":'); fb_f64(y, 0); fb_text(',"color":'); fb_str(color); fb_text(',"label":"'); putUsd(1, dollars); fb_text(' wall"}'); } // The curve frame, from the stored snapshot: rows ascending by price (the far bid up to the best bid, then the best // ask up to the far ask), each row one side's cumulative dollars from the touch outward and null on the other side. function writeCurve(side: f64, ratio: f64): void { const reach = mid * rangePct / 100.0; let nb: i32 = 0; let cum = 0.0; for (let k = 0; k < bids; k++) { if (mid - bidPx[k] > reach) break; cum += bidPx[k] * bidSz[k]; bidCum[k] = cum; nb = k + 1; } let na: i32 = 0; cum = 0.0; for (let k = 0; k < asks; k++) { if (askPx[k] - mid > reach) break; cum += askPx[k] * askSz[k]; askCum[k] = cum; na = k + 1; } fb_clear(); fb_text('{"title":"Depth within '); fb_f64(rangePct, rangePct == Math.floor(rangePct) ? 0 : 1); fb_text('% of the mid","rows":['); let rows: i32 = 0; for (let k = nb - 1; k >= 0; k--) { if (rows > 0) fb_text(","); fb_text("["); fb_num(bidPx[k]); fb_text(","); fb_f64(bidCum[k], 0); fb_text(",null]"); rows += 1; } for (let k = 0; k < na; k++) { if (rows > 0) fb_text(","); fb_text("["); fb_num(askPx[k]); fb_text(",null,"); fb_f64(askCum[k], 0); fb_text("]"); rows += 1; } fb_text('],"markers":[{"x":'); fb_num(mid); fb_text(',"label":"Mid '); putPrice(1, mid, decimals); fb_text('","line_style":"dashed","color":"theme.muted"}'); fbWallMarker(bidWall, bidWallUsd, cumAt(bidPx, bidCum, nb, bidWall), "theme.up"); fbWallMarker(bidWall2, bidWall2Usd, cumAt(bidPx, bidCum, nb, bidWall2), "theme.up"); fbWallMarker(askWall, askWallUsd, cumAt(askPx, askCum, na, askWall), "theme.down"); fbWallMarker(askWall2, askWall2Usd, cumAt(askPx, askCum, na, askWall2), "theme.down"); fb_text('],"caption":"'); if (side == BIDS_HEAVIER) { fb_text("Bids heavier "); fb_f64(ratio, 1); fb_text("x"); } else if (side == ASKS_HEAVIER) { fb_text("Asks heavier "); fb_f64(1.0 / ratio, 1); fb_text("x"); } else if (isNaN(ratio)) fb_text("Thin near the mid"); else fb_text("Balanced book"); if (bookBar != barIndex) { fb_text(", last snapshot "); fb_int(barIndex - bookBar); fb_text(" bars ago"); } fb_text('"}'); writeFrameBuffer(FRAME_DEPTH); } function onStart(): void { rangePct = p_range_pct(); nearPct = p_near_pct(); } // onBar() runs once per bar: read the snapshot and write the data outputs; on the live bar write the card's words and // the curve from the newest snapshot the chart delivered. function onBar(): void { barIndex += 1; if (readBook()) measure(); else clearReadings(); const ratio = bidsNear > 0.0 && asksNear > 0.0 ? bidsNear / asksNear : NaN; let side = BALANCED; if (ratio >= LEAN) side = BIDS_HEAVIER; else if (ratio <= 1.0 / LEAN) side = ASKS_HEAVIER; // a NaN ratio passes neither test and stays balanced const spreadPct = isNaN(mid) ? NaN : ((bestAsk - bestBid) / mid) * 100.0; out_side(side); out_ratio(ratio); out_bids_near(bidsNear); out_asks_near(asksNear); out_spread_pct(spreadPct); out_bid_wall(bidWall); out_bid_wall_usd(bidWallUsd); out_ask_wall(askWall); out_ask_wall_usd(askWallUsd); if (!bar.isLast()) return; sb_clear(); sb_f64(nearPct, nearPct == Math.floor(nearPct) ? 0 : 1); sb_text("%"); str_near_text_sb(); if (bookBar < 0) { // no bar ever carried both sides of a book: the short sentence that fits the headline, nothing else sb_clear(); sb_text("No order book"); str_ratio_text_sb(); return; } if (isNaN(mid)) measure(); // the live bar carries no snapshot: the card and the curve read the newest one instead sortSide(bidPx, bidSz, bids, false); // bids best first, asks best first: the curve walks each side from the touch sortSide(askPx, askSz, asks, true); readTick(); const r = bidsNear > 0.0 && asksNear > 0.0 ? bidsNear / asksNear : NaN; let s = BALANCED; if (r >= LEAN) s = BIDS_HEAVIER; else if (r <= 1.0 / LEAN) s = ASKS_HEAVIER; sb_clear(); if (s == BIDS_HEAVIER) { sb_text("Bids "); sb_f64(r, 1); sb_text("x asks"); } else if (s == ASKS_HEAVIER) { sb_text("Asks "); sb_f64(1.0 / r, 1); sb_text("x bids"); } else if (isNaN(r)) sb_text("Nothing resting within the band"); else sb_text("Balanced book"); str_ratio_text_sb(); sb_clear(); if (isNaN(bidWallUsd) && isNaN(askWallUsd)) sb_text("-"); else if (isNaN(askWallUsd) || bidWallUsd >= askWallUsd) { putUsd(0, bidWallUsd); sb_text(" bid at "); putPrice(0, bidWall, decimals); } else { putUsd(0, askWallUsd); sb_text(" ask at "); putPrice(0, askWall, decimals); } str_wall_text_sb(); sb_clear(); const gap = bestAsk - bestBid; const sp = (gap / mid) * 100.0; if (!isNaN(tick) && gap <= tick * 1.0001) { // the touch sits inside one step of the book's grouping sb_text("up to "); putPrice(0, tick, decimals); sb_text(" ("); sb_f64(sp, sp >= 0.01 ? 2 : 4); sb_text("%)"); } else { sb_f64(sp, sp >= 0.01 ? 2 : 4); sb_text("% ("); putPrice(0, gap, decimals); sb_text(")"); } str_spread_text_sb(); writeCurve(s, r); } ``` ## How it works **The book is a block of tuples.** `input("book", book.cells, { max_cells: 1000, block_size: 10 })` hands `onBar()` this bar's snapshot as one `[price, size, side]` tuple per level, side +1 a bid and -1 an ask, sizes in coins, up to 500 levels a side, so 1000 tuples hold any bar; `block_size` is required by the declaration and the chart keeps its own grouping. `in_book_cells()` counts the numbers delivered (tuples times three), 0 for an empty block and -1 for a bar that carries none, and `in_book_view()` is the cells in place. `readBook()` walks whole tuples by price and side, never by position, and copies the snapshot into the side arrays only when both sides are present and the book is not crossed; otherwise the arrays keep the newest usable one and `bookBar` remembers which bar it came from. **Every bar writes the numbers.** The mid is (best bid + best ask) / 2 and a level's dollars are price times size. `measure()` sums the dollars within `near_pct` of the mid per side and finds the two largest single levels per side within `range_pct`; the ratio is bid dollars over ask dollars in the band, and `side` reads 2 (bids heavier) at `LEAN` (1.05) and up, 0 (asks heavier) at 1/1.05 and under, 1 between or when nothing rests in the band. The nine data-only outputs (`side`, `ratio`, `bids_near`, `asks_near`, `spread_pct`, `bid_wall`, `bid_wall_usd`, `ask_wall`, `ask_wall_usd`) are written on every bar, so a watch or an alert can read the book too; a bar without a usable snapshot writes NaN to them (`side` reads 1). The sort, the tick and the words wait for `bar.isLast()`. **One frame is the curve.** On the live bar `sortSide()` orders each side best first, and `writeCurve()` builds the `depth` frame in the frame buffer with the `fb_*` builders, allocation-free: one row per level within `range_pct`, `[price, bid dollars | null, ask dollars | null]`, ascending by price, each side's cumulative dollars from the touch outward, so the bids fall toward the mid, the asks rise away from it, and the two staircases meet at the mid with the spread as the gap between them. `panel.line` draws it below the chart on a number axis (`x: "number"`, `x_format: "usd"`, so the price ticks read "$85.0K") with `style: "step"` on both series and `fill: true`, so each staircase fills to the axis in its own colour. With no `chrome` the pane draws horizontal value hairlines only, no frame and no vertical lines ([The default look](../presentation/cards-frames-panels.md#the-default-look)); the value axis prints whole dollars (`format: "usd", decimals: 0`), `y_zero: true` keeps zero on it, `hover_card: true` opens a readout under the pointer, and `height_frac: 0.32` gives the pane about a third of the chart. **Markers, callouts, title and caption ride the frame.** Beside `rows`, the frame carries `markers`: the mid as a dashed line in the muted colour (`line_style: "dashed"`, its label "Mid 85,115" through `putPrice()`), and up to four wall callouts, each a marker in its side's colour with `valign: "point"` at the wall's price and an exact `y`, the cumulative dollars at that level from `cumAt()`, so the dot sits on top of the jump and `fbWallMarker()` prints "$26.1M wall" beside it through `putUsd()`. The frame's `caption` is the verdict, its words following `side` ("Bids heavier 1.4x"), with ", last snapshot 3 bars ago" added only when the live bar carried no snapshot and the curve reads an older one. The frame's `title` prints the reach ("Depth within 2% of the mid"). **The card reads slots and a ladder.** `render.hud("depth_card", { position: "top_left", safe_area: true, title: "Order book within {{near_text}}", columns: 1, width: 300, tiles: [...] })` is the card, in the chart's default look: a `tile.pill` headline reading the `ratio_text` slot at `font_size: 20`, coloured by the `side` ladder (`color_by: "side"`, the down, muted and up colours), and a `tile.rows` of `wall_text` and `spread_text`. The slots are written on the live bar with the `sb_*` builders, and the title takes the band from the `near_text` slot ("1%"), since a HUD title resolves outputs and slots, not settings. Prices print with thousands separators and the decimals the book's step needs: `readTick()` reads the smallest gap between neighbouring levels (25 gives 0 decimals, 0.0001 gives 4) and `putPrice()` writes them digit by digit into either sink, so BTC prints "85,115" and a sub-dollar alt prints "0.1412". **The spread is the book's step.** The chart serves the book at its own grouping (25-dollar steps on BTCUSDT), so the best bid and best ask groups sit one step apart whatever the exchange spread is: a touch inside one step reads "up to 25 (0.03%)", and a wider gap prints the percent of the mid and the price gap ("0.07% (0.0001)"), with 2 decimals at 0.01% and up and 4 under. `spread_pct` carries the same percent as a data-only output. ## Where it runs Any market the chart serves an order book for: crypto perpetuals and spot on Binance, Bybit, OKX, Hyperliquid and the other venues, on any interval (15m and 1h alike): the curve reads the live snapshot, not the bars. No market refuses the run by name: where there is no book the lane answers an empty block on every bar and the run goes on without a toast, so the card does the telling (below). The book and the candles are two lanes, so the mid can sit a few dollars off the last trade while the bar forms. The pane sits below the chart and the card at the top left of the price pane, under the legend (`safe_area: true`), where it covers the oldest candles on screen instead of the newest. ## When data is missing On a market without an order book (gold and the other FX_OTC pairs, stocks, a prediction market when the lane serves none) no bar ever carries both sides, so the card's headline prints the short sentence `No order book`, whole at the headline's 20 px, in the muted colour through the `side` ladder; the Biggest wall and Spread rows print a dash (their slots are never written) and the pane is not drawn (the frame is never written). When the live bar carries no usable snapshot (none delivered, a side missing, or a crossed book) the curve and the card read the newest bar that had one and the pane's caption adds how many bars ago that was ("Balanced book, last snapshot 3 bars ago"). Bars before the first usable snapshot write NaN to every data output. When a side has nothing resting within `near_pct` the ratio is NaN: the caption reads "Thin near the mid" and the headline "Nothing resting within the band", in the muted colour; when no level sits within `range_pct` the Biggest wall row prints a dash. ## Customize it - **Reach.** `range_pct` (2, from 0.5 to 10 in steps of 0.5) sets how far from the mid the curve reaches, percent each side; the pane's title follows it ("Depth within 2% of the mid") and the walls are searched within the same reach. - **The band.** `near_pct` (1, from 0.1 to 5 in steps of 0.1) is the band the ratio, the caption and the card's headline read; the card's title prints it ("Order book within 1%"). - **A wider lean.** `LEAN` (1.05) is the ratio either side of 1 before a side is named; raise it in the source and more books read as "Balanced book". - **Other inks.** The bid and ask colours are the theme words `theme.up` and `theme.down` on the two series, repeated on the wall callouts and the headline ladder, so they follow the chart's up and down colours; change them in the source and Run again. - **A look of its own.** When the card should stand apart from the chart, add `look:` with any of the twelve shipped looks ([Looks](../presentation/hud-and-hover-cards.md#looks)); the Look row on the indicator's Style page switches it without code ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Depth Curve** under **Beyond the time axis**. 2. Press **Run** on a chart with an order book, such as BTCUSDT on Binance Futures at 15m: the depth curve fills the pane under the chart with the verdict in its caption, and the card appears at the top left of the price pane, under the legend. 3. At the editor's Console prompt, type `last 20 ratio` to read bid dollars over ask dollars within the band on the last 20 bars. ## Concepts used - [Order flow](../functions/order-flow-kit.md) for `book.cells`, its `[price, size, side]` tuple, `max_cells` and the `in_book_cells()` / `in_book_view()` loop - [Data sources](../core-concepts/data-sources.md) for the `book` source and the empty block a market without a book answers - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames and the `fb_*` builders, `panel.line` on a number axis, step series and fills, markers, callouts with `valign: "point"` and `y`, the per-run `title` and the `caption` - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `safe_area` and `width` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` and `tile.rows` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Strings and text](../functions/text-formatting.md) for the `sb_*` builders and string slots <!-- source: https://openmarket.xyz/wrun/cookbook/yield-curve --> # Yield curve ![Treasury curve pane below a BTC chart with today's curve, the 2Y and 10Y callouts and the 2s10s card at the top right](/wrun/images/yield-curve.png) The US Treasury par curve as it prints today, against a week ago and a month ago, in a pane below the chart: the nine tenors evenly spaced across, 1M to 30Y, so the front end reads as wide as the long end, yield in percent on the y axis, today's curve in the text colour and widest, the week curve muted, the month curve muted, thinner and dashed, each tenor a dot. Today's 2Y and 10Y points are called out on the curve with their yields, and the 2s10s spread (10Y minus 2Y) is the headline of a card at the top right, in the chart's default look, with the 10Y and 3M yields under it. The legend names the curves the way the settings do (Today, Week curve, Month curve), and the pane's caption says how far back the week and month curves really are. The trader reads whether the curve is steep, flat or inverted at the front (a negative 2s10s is an inverted curve), and which way it moved over the week and the month, beside the coin's price. The parts are nine `economic.value` inputs pinned to FRED's daily series DGS1MO through DGS30 on the default `carry` policy ([Data sources](../core-concepts/data-sources.md)), two `param.int` day settings turned into bars by `chart.interval_sec()` ([Sessions and units](../settings/sessions-and-units.md)), a frame feeding a `panel.line` on a category axis with three series, two point callouts, a caption and a value axis set per run ([Cards, frames and panels](../presentation/cards-frames-panels.md)), a `render.hud` card of a headline `tile.pill` and a `tile.rows` with no `look` word ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)), and a `render.label` at the top centre for the one sentence ([Plotting](../presentation/plotting.md)). This is also the `yield-curve` template: the **Yield Curve** card under **Beyond the time axis** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Yield Curve: the US Treasury par curve as it prints today against a week ago and a month ago, the tenors evenly spaced // across a pane below the chart, today's 2Y and 10Y points called out, the 2s10s spread (10Y minus 2Y) named on a // card at the top right with the 10Y and 3M yields under it. The trader sees // whether the curve is steep, flat or inverted at the front, and which way it moved over the week and the month, // beside the coin's price. The yields are FRED's daily constant-maturity series (DGS1MO to DGS30), in percent, on the // default carry policy: every bar reads the newest print at or before its day, the chart's first bar included (the // chart also fetches the prints from before its window), so a 1m chart that opens in the middle of a day still has // today's curve. A new print first shows on the first bar of its day; the week and month curves read the newest print // at or before their day. param.int("week", 7, { min: 1, max: 60, label: "Week curve, days back", description: "Days back for the week curve, the second line" }); param.int("month", 30, { min: 2, max: 365, label: "Month curve, days back", description: "Days back for the month curve, the third line" }); chart.interval_sec(); // the bar interval in seconds, written by the chart: days become bars without reading the clock input("close", ohlcv.close); // the primary input: the chart's own candles define the grid the daily prints land on input("y1m", economic.value, { publisher: "FRED", series: "DGS1MO", description: "1-month Treasury yield, percent" }); input("y3m", economic.value, { publisher: "FRED", series: "DGS3MO", description: "3-month Treasury yield, percent" }); input("y1", economic.value, { publisher: "FRED", series: "DGS1", description: "1-year Treasury yield, percent" }); input("y2", economic.value, { publisher: "FRED", series: "DGS2", description: "2-year Treasury yield, percent" }); input("y5", economic.value, { publisher: "FRED", series: "DGS5", description: "5-year Treasury yield, percent" }); input("y7", economic.value, { publisher: "FRED", series: "DGS7", description: "7-year Treasury yield, percent" }); input("y10", economic.value, { publisher: "FRED", series: "DGS10", description: "10-year Treasury yield, percent" }); input("y20", economic.value, { publisher: "FRED", series: "DGS20", description: "20-year Treasury yield, percent" }); input("y30", economic.value, { publisher: "FRED", series: "DGS30", description: "30-year Treasury yield, percent" }); output("spread", none, overlay, { description: "2s10s: the 10Y yield minus the 2Y yield in percentage points, below zero while the curve is inverted" }); string("spread_text", { max_bytes: 16 }); // "+0.12", the card's headline, or "no print" string("y10_text", { max_bytes: 16 }); // "4.12%", or "no print" string("y3m_text", { max_bytes: 16 }); string("note", { max_bytes: 96 }); // the one muted sentence, with its way out, while no tenor has a print on this chart const curveRows = frame("curve_rows", { max_bytes: 4096 }); // nine rows: [tenor, today, the week curve, the month curve], null for a tenor without a print // The curve: three smooth lines over the tenors, evenly spaced so the front end reads as wide as the long end, today in // the text ink and widest, the week curve muted, the month curve muted, thinner and dashed, each tenor a dot; the 2Y // and 10Y callouts, the value axis with its headroom and the caption with each curve's real distance ride the frame. panel.line({ name: "curve", title: "US Treasury curve", x: "category", place: "below", frame: curveRows, smooth: true, points: true, hover_card: true, format: "%", decimals: 2, height_frac: 0.32, series: [{ name: "Today", color: "theme.text", width: 2 }, { name: "Week curve", color: "theme.muted", width: 1.5 }, { name: "Month curve", color: "theme.muted", width: 1, line_style: "dashed" }] }); // The card: the 2s10s spread as the headline, then the 10Y and the 3M yields. render.hud("yields", { position: "top_right", title: "US Treasury curve, latest print", columns: 1, width: 240, safe_area: true, tiles: [ tile.pill("2s10s, 10Y minus 2Y, pts", "spread_text", { headline: true }), tile.rows([["10Y", "y10_text"], ["3M", "y3m_text"]]), ] }); // The sentence, only while no tenor has a print: top centre, clear of the card, and drawn whole (a corner label is // centred on its anchor, so at a right-hand corner half of a long sentence would run past the pane edge). render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] }); const TENORS = 9; const TENOR_NAMES: StaticArray<string> = ["1M", "3M", "1Y", "2Y", "5Y", "7Y", "10Y", "20Y", "30Y"]; // the x keys, in order const OBS = 256; // prints kept per tenor: the value and the bar it first showed on; a print equal to the newest kept one is not kept again const NO_PRINT = "no print"; // a card value without a print: words, never the dash an unwritten slot shows const obsBar = new StaticArray<i32>(TENORS * OBS); const obsVal = new StaticArray<f64>(TENORS * OBS); const obsHead = new StaticArray<i32>(TENORS); // the newest kept slot per tenor, -1 before the first print const obsCount = new StaticArray<i32>(TENORS); const today = new StaticArray<f64>(TENORS); // the live bar's three curves, NaN for a tenor without a print const weekAgo = new StaticArray<f64>(TENORS); const monthAgo = new StaticArray<f64>(TENORS); const todaySlot = new StaticArray<i32>(TENORS); // the kept print each curve read per tenor, -1 for none const weekSlot = new StaticArray<i32>(TENORS); const monthSlot = new StaticArray<i32>(TENORS); let barIndex = -1; // bars since the oldest loaded one let intervalSec = 900.0; // settings, read in onStart() let weekBars = 672; let monthBars = 2880; let weekFallback = 0; // how the week and month curves were found on the live bar: 0 at their day, 1 the oldest print loaded, 2 none let monthFallback = 0; let weekDup = false; // the week curve repeats today's print for every tenor (no older print loaded): it is not drawn twice let monthDup = false; // the month curve repeats the week's let weekDays = 7.0; // the real distance of each curve in days, for the caption let monthDays = 30.0; function onStart(): void { intervalSec = p_chart_interval_sec(); if (intervalSec <= 0.0) intervalSec = 900.0; // interval unknown: count as a 15-minute chart weekBars = i32(Math.round((f64(p_week()) * 86400.0) / intervalSec)); monthBars = i32(Math.round((f64(p_month()) * 86400.0) / intervalSec)); if (weekBars < 1) weekBars = 1; if (monthBars <= weekBars) monthBars = weekBars + 1; for (let k = 0; k < TENORS; k += 1) { obsHead[k] = -1; obsCount[k] = 0; } } // Keep this bar's print of tenor k, unless it repeats the newest kept one: every bar of a day reads the day's print and // a weekend bar Friday's, so a print is kept once, on the bar it first shows on. function keep(k: i32, v: f64): void { const h = obsHead[k]; if (h >= 0 && obsVal[k * OBS + h] == v) return; const next = (h + 1) % OBS; obsBar[k * OBS + next] = barIndex; obsVal[k * OBS + next] = v; obsHead[k] = next; if (obsCount[k] < OBS) obsCount[k] += 1; } // The newest kept print of tenor k at or before bar 'at': its slot, or -1 when every kept print landed later. function slotAtOrBefore(k: i32, at: i32): i32 { const n = obsCount[k]; const h = obsHead[k]; for (let j = 0; j < n; j += 1) { const s = (h + OBS - j) % OBS; if (obsBar[k * OBS + s] <= at) return s; } return -1; } function oldestSlot(k: i32): i32 { const n = obsCount[k]; return n == 0 ? -1 : (obsHead[k] + OBS - (n - 1)) % OBS; } function daysBack(bar: i32): f64 { return (f64(barIndex - bar) * intervalSec) / 86400.0; } // One curve 'back' bars behind the live bar into 'into': a tenor's print at or before that bar, else the oldest print // loaded (fallback 1), else NaN (fallback 2). Returns the fallback of the curve as a whole, records the slot each tenor // read and leaves the curve's real distance in days. function curveAt(back: i32, into: StaticArray<f64>, slots: StaticArray<i32>): i32 { const at = barIndex - back; let fallback = 2; let oldestBar = -1; for (let k = 0; k < TENORS; k += 1) { let s = slotAtOrBefore(k, at); if (s >= 0) { into[k] = obsVal[k * OBS + s]; slots[k] = s; fallback = 0; continue; } s = oldestSlot(k); slots[k] = s; if (s < 0) { into[k] = NaN; continue; } into[k] = obsVal[k * OBS + s]; if (fallback == 2) fallback = 1; if (obsBar[k * OBS + s] > oldestBar) oldestBar = obsBar[k * OBS + s]; } if (fallback == 1 && oldestBar >= 0) { if (into == weekAgo) weekDays = daysBack(oldestBar); else monthDays = daysBack(oldestBar); } return fallback; } // True when curve 'a' read the same kept print as curve 'b' at every tenor: the same line twice. function sameCurve(a: StaticArray<i32>, b: StaticArray<i32>): bool { for (let k = 0; k < TENORS; k += 1) if (a[k] != b[k]) return false; return true; } let lo: f64 = Infinity; // the drawn curves' lowest and highest yield on the live bar let hi: f64 = -Infinity; function widen(v: f64): void { if (!isNaN(v)) { if (v < lo) lo = v; if (v > hi) hi = v; } } function fbPct(v: f64): void { // a yield as "4.12%" inside a JSON string the caller opened fb_f64(v, 2); fb_text("%"); } function fbCallout(tenor: string, v: f64, color: string): void { // a callout on today's curve at a tenor, named and valued fb_text('{"x":'); fb_str(tenor); fb_text(',"valign":"point","series":"Today","label":"'); fb_text(tenor); fb_text(" "); fbPct(v); fb_text('","color":"'); fb_text(color); fb_text('"}'); } function fbDays(d: f64): void { fb_int(i32(Math.round(d))); fb_text("d back"); } function fbCurveNote(fallback: i32, dup: bool, same: string, days: f64): void { // "7d back", "oldest, 16d back", "same as today" or "no older print" if (fallback == 2 || (dup && fallback == 1)) { // nothing older than the newer curve is loaded fb_text("no older print"); return; } if (dup) { fb_text("same as "); fb_text(same); return; } // read at its day, the very prints of the newer curve: drawn once, named here if (fallback == 1) fb_text("oldest, "); fbDays(days); } // The card's three values, each written only when it is known, else "no print": every slot is written, so no tile // ever shows the dash an unwritten slot reads as. function writeCard(spread: f64, y10: f64, y3m: f64): void { sb_clear(); if (isNaN(spread)) sb_text(NO_PRINT); else { if (spread >= 0.0) sb_text("+"); sb_f64(spread, 2); } str_spread_text_sb(); sb_clear(); if (isNaN(y10)) sb_text(NO_PRINT); else { sb_f64(y10, 2); sb_text("%"); } str_y10_text_sb(); sb_clear(); if (isNaN(y3m)) sb_text(NO_PRINT); else { sb_f64(y3m, 2); sb_text("%"); } str_y3m_text_sb(); } // onBar() runs once per bar: keep each tenor's print where it first shows; on the live bar read today's curve, the // week's and the month's, write the card's slots and the pane's frame. Nothing is drawn per bar. function onBar(): void { barIndex += 1; // Under carry a tenor reads NaN only before its series' first print, so a NaN is skipped, never kept. const v1m = in_y1m(); if (!isNaN(v1m)) keep(0, v1m); const v3m = in_y3m(); if (!isNaN(v3m)) keep(1, v3m); const v1 = in_y1(); if (!isNaN(v1)) keep(2, v1); const v2 = in_y2(); if (!isNaN(v2)) keep(3, v2); const v5 = in_y5(); if (!isNaN(v5)) keep(4, v5); const v7 = in_y7(); if (!isNaN(v7)) keep(5, v7); const v10 = in_y10(); if (!isNaN(v10)) keep(6, v10); const v20 = in_y20(); if (!isNaN(v20)) keep(7, v20); const v30 = in_y30(); if (!isNaN(v30)) keep(8, v30); if (!bar.isLast()) return; let printed = 0; for (let k = 0; k < TENORS; k += 1) { const h = obsHead[k]; todaySlot[k] = h; today[k] = h < 0 ? NaN : obsVal[k * OBS + h]; if (h >= 0) printed += 1; } if (printed == 0) { // no tenor has a print on this chart yet: the one sentence with its way out, the card in words str_note("No Treasury prints reached this chart yet: open the 1h chart or pan back a day"); writeCard(NaN, NaN, NaN); return; } str_note(""); // the sentence is absent while a print stands (an empty text draws no label) weekDays = f64(weekBars) * intervalSec / 86400.0; monthDays = f64(monthBars) * intervalSec / 86400.0; weekFallback = curveAt(weekBars, weekAgo, weekSlot); monthFallback = curveAt(monthBars, monthAgo, monthSlot); weekDup = sameCurve(weekSlot, todaySlot); monthDup = sameCurve(monthSlot, weekSlot); const spread = today[6] - today[3]; // 2s10s, NaN while 2Y or 10Y has no print out_spread(spread); writeCard(spread, today[6], today[1]); fb_clear(); fb_text('{"rows":['); for (let k = 0; k < TENORS; k += 1) { fb_text(k == 0 ? "[" : ",["); fb_str(TENOR_NAMES[k]); fb_text(","); fb_f64(today[k], 2); fb_text(","); fb_f64(weekDup ? NaN : weekAgo[k], 2); fb_text(","); fb_f64(monthDup ? NaN : monthAgo[k], 2); fb_text("]"); } fb_text('],"markers":['); let callouts = 0; if (!isNaN(today[3])) { fbCallout("2Y", today[3], "theme.text"); callouts += 1; } if (!isNaN(today[6])) { if (callouts > 0) fb_text(","); fbCallout("10Y", today[6], "theme.text"); } fb_text("]"); lo = Infinity; // the value axis: the drawn curves' range, with headroom above it hi = -Infinity; for (let k = 0; k < TENORS; k += 1) { widen(today[k]); if (!weekDup) widen(weekAgo[k]); if (!monthDup) widen(monthAgo[k]); } if (hi >= lo) { const pad = Math.max(0.05, (hi - lo) * 0.1); fb_text(',"y_min":'); fb_f64(lo - pad, 2); fb_text(',"y_max":'); fb_f64(hi + 3.0 * pad, 2); } fb_text(',"caption":"Week '); // at most 64 characters: how far back each curve really is fbCurveNote(weekFallback, weekDup, "today", weekDays); fb_text("; month "); fbCurveNote(monthFallback, monthDup, "week", monthDays); fb_text('"}'); writeFrameBuffer(FRAME_CURVE_ROWS); } ``` ## How it works **Nine pins are the inputs.** `input("y10", economic.value, { publisher: "FRED", series: "DGS10" })` and its eight twins (`DGS1MO`, `DGS3MO`, `DGS1`, `DGS2`, `DGS5`, `DGS7`, `DGS20`, `DGS30`) read FRED's daily constant-maturity yields in percent; the chart's own close is the first input, so the daily prints land on the chart's bars. Under the default `carry` policy every bar reads the newest print at or before its day, the window's first bar included (the chart also fetches the prints from before its window), so a 1m chart that opens in the middle of a day still has today's curve; a new print first shows on the first bar of its day. A tenor reads NaN only before its series' first print, and `onBar()` skips a NaN. **Prints ride a ring, not bars.** Each tenor keeps its last 256 distinct prints with the bar each landed on (`obsVal` and `obsBar`, a head and a count per tenor). `keep()` skips a print equal to the newest kept one, so the later bars of a day and a weekend bar (each carrying the newest print) never count as a new observation: a print is kept once, on the bar it first shows on (the window's first bar for the print that stood before the window), and the ring covers 256 prints on any interval. A week ago is `slotAtOrBefore()`: the newest kept print at or before the bar `weekBars` behind the live bar. When every kept print landed later, `curveAt()` falls back to the oldest print loaded and records the curve's real distance in days from the bar it read; `sameCurve()` then tells whether the week curve read the same prints as today's, or the month the same as the week's, in which case that curve is written as `null` instead of being drawn twice (its legend entry stays). **Days become bars through the chart's interval.** `week` (7) and `month` (30) are days. `chart.interval_sec()` is a hidden setting the chart fills with the bar interval in seconds, read in `onStart()` through `p_chart_interval_sec()`, so `weekBars` is 672 on a 15m chart, 168 on 1h and 7 on 1d, with `monthBars` 2880, 720 and 30; an unknown interval (0) counts as 15m, and the month is kept at least one bar beyond the week. **One frame is the curve.** On the live bar only, the frame builder (`fb_clear()`, `fb_text()`, `fb_str()` and `fb_f64()`, sent with `writeFrameBuffer(FRAME_CURVE_ROWS)`) writes `curve_rows`: nine rows of `[tenor, today, week curve, month curve]` keyed by the tenor's name from `TENOR_NAMES` ("1M" to "30Y"), two `markers` with `valign: "point"` pinned to the `Today` series at x "2Y" and x "10Y" (the 2Y and 10Y callouts, each a label printing its tenor and yield in the text colour), a `y_min` and `y_max` around the drawn curves with three times the margin above them as below, and a `caption` of at most 64 characters ("Week 7d back; month oldest, 12d back"). `panel.line({ name: "curve", x: "category", place: "below", ... })` draws the frame below the chart, every tenor the same width, with `smooth` and `points` on and `format: "%"`; with no `chrome` it draws horizontal hairlines only, and the legend is the regular one ([The default look](../presentation/cards-frames-panels.md#the-default-look)). Today's series is in the text colour and widest (2 against the muted week curve's 1.5), and the month curve is muted, thinner (1) and carries `line_style: "dashed"`. **The card reads three slots and one output.** `spread` is the only output, data-only, the 10Y minus the 2Y in percentage points on the live bar; `spread_text` ("+0.46"), `y10_text` and `y3m_text` ("5.24%") are string slots built with `sb_clear()` and `sb_f64()` and sent with `str_spread_text_sb()` and its twins. `writeCard()` writes all three on the live bar, each as a number when it is known and as "no print" when it is not, so no tile ever shows the dash an unwritten slot reads as. The `render.hud` card sits at `top_right` in one column, 240 px wide, with `safe_area: true` so it starts under the pane action bar and clear of the price-axis tags; its headline `tile.pill` reads `spread_text` and its `tile.rows` the 10Y and 3M slots. With no `look`, the card draws the chart's default look: the pill as text with no capsule and no dot, the rows 22 px tall with a hairline between them and no leader marks; the Style page's Look row switches the look without code. **The sentence is a positioned label.** `render.label("note_label", { position: "top_center", text: "note", color: "theme.muted", style: "plain", offset: [0, 8] })` prints the `note` slot as plain muted text at the top centre of the price pane, clear of the card and the legend. The slot is written on the live bar: the sentence while no tenor has a print, and empty otherwise (an empty text draws no label), so the label is absent while the yields are served; on that path the card's three slots read "no print". Nothing is drawn per bar: the ring fills on every bar, and the pane, the card and the output are written on the live bar alone. ## Where it runs Every chart the economic lane serves. The yields do not depend on the chart's market, so the same curve draws beside a crypto perpetual (BTCUSDT on Binance Futures at 1m, 15m and 1h) and beside gold (XAU/USD at 15m and 1h), and on a 1d chart the day settings read as bars one to one. How many curves the pane draws depends on how many days the chart has loaded: a 1m chart holds a few hours, so it draws today's curve and its caption reads "no older print" for the week and the month; a 15m chart holds about four days, so the week curve falls back to the oldest print loaded ("Week oldest, 4d back") and the month, which would read the same print, is not drawn twice; a 1h chart holds about twelve days, enough for the week curve at its day and the month curve at the oldest print. No market refuses the run by name. ## When data is missing If FRED answers nothing for one of the nine series, the chart stops the run with its own message that the economic series data is unavailable: on the default `carry` policy an empty series has nothing to carry. If no tenor has a print on this chart, one sentence sits at the top centre of the price pane, "No Treasury prints reached this chart yet: open the 1h chart or pan back a day", the card's three values read "no print", and the curve pane is not opened: the frame and the `spread` output are not written on that bar. A single tenor without a print is written `null` in its row (no dot) and its callout is left out; while the 2Y or the 10Y has none, the spread reads NaN and the card's headline reads "no print". The card never shows a dash: each of its values is a number when known, else "no print". When the loaded history is shorter than a week or a month, the curve falls back to the oldest print loaded and the caption says how far back that is ("month oldest, 12d back"); when that oldest print is today's at every tenor, the curve is not drawn (its legend entry stays) and its caption part reads "no older print", the usual state on a 1m chart. A curve read at its day that finds the same prints as the newer one (a 3-day week curve on a Monday reads Friday's print, today's newest) is drawn once too, and its caption part reads "same as today" ("same as week" for the month curve). ## Customize it - **Further back.** `week` (**Week curve, days back**: 7 days, 1 to 60) and `month` (**Month curve, days back**: 30 days, 2 to 365) set how far back the week and month curves read; the chart's interval turns the days into bars, so the same numbers read right on 1m, 15m, 1h and 1d charts, and the month is kept at least one bar beyond the week. - **Another spread.** The 2s10s is `today[6] - today[3]`, the 10Y and 2Y slots of the tenor list (`TENOR_NAMES` runs 1M, 3M, 1Y, 2Y, 5Y, 7Y, 10Y, 20Y, 30Y). For the 5s30s read `today[8] - today[4]`, and move the two `fbCallout()` calls to "5Y" and "30Y" with their slots so the callouts follow the spread. - **Tenor in years.** A category axis gives every tenor the same width. For a true maturity scale, write each row's years (0.083 to 30) with `fb_num()` in place of its name, give the callouts their years as `x`, and declare `x: "number"` with `x_format: "auto"`, `x_decimals: 0` and `x_unit: "Y"`; 1M to 2Y then pack into the first few percent of the axis. - **A look of its own.** The card is made in the chart's default look; when it should stand apart from the chart, add `look:` with any of the twelve shipped looks ([Looks](../presentation/hud-and-hover-cards.md#looks)), or switch it without code on the Look row of the indicator's Style page, "As made" first ([The Style page](../settings/style-page.md#the-look-row)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Yield Curve** under **Beyond the time axis**. 2. Press **Run** on any chart, such as BTCUSDT on Binance Futures at 1h: the curve pane opens below the chart with its callouts and caption, and the card appears at the top right of the price pane. 3. At the editor's Console prompt, type `last 20 spread` to read the 2s10s in percentage points: it is written on the live bar only, so only the last row carries a number. ## Concepts used - [Data sources](../core-concepts/data-sources.md) for the `economic` source, its `publisher` and `series` words, and the default `carry` policy on a daily series - [Sessions and units](../settings/sessions-and-units.md) for `chart.interval_sec()` and the other facts the chart fills before the first bar - [Cards, frames and panels](../presentation/cards-frames-panels.md) for frames and the `fb_*` builder, `panel.line` on a category axis, point callouts, the caption and a per-run value axis - [HUD cards](../presentation/hud-and-hover-cards.md#hud-cards) for `render.hud`, its anchors, `width` and `safe_area` - [The default look](../presentation/hud-and-hover-cards.md#the-default-look) for what a card with no `look` draws, and [Looks](../presentation/hud-and-hover-cards.md#looks) for the twelve it can name - [Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles) for the headline `tile.pill` and `tile.rows` - [The Style page](../settings/style-page.md#the-look-row) for the Look row that switches the look without code - [Plotting](../presentation/plotting.md) for the `render.label` placed by `position` <!-- source: https://openmarket.xyz/wrun/cookbook/strategy-ma-cross --> # Moving-average cross ![Moving-average cross strategy with ribbon, cross marks and Strategy Tester](/wrun/images/strategy-ma-cross.png) A strategy: long when the fast average crosses above the slow one, flat when it crosses back under. The fast average (in the text colour) and the slow average (fainter) on price, a ribbon between them, in the up colour while the fast average leads and the down colour while it trails, and a mark on the bar of each cross at the price where the lines met: in the up colour for a cross up (the entry fills at the next open), the down colour for a cross down (the position closes at the next open). The Strategy Tester under the chart holds the fills on the candles, equity against buy and hold, net profit, win rate, profit factor, drawdown, Sharpe and the trade list. The parts are `strategy(...)` declared in the source with the order calls in `onBar()` ([Strategies overview](../strategies/overview.md)), a `range` between the two averages tinted by a data-only output ([Styling](../presentation/styling.md)), and two `shape` outputs for the cross marks. This is also the `strategy-ma-cross` template: the **Moving-Average Cross** card under **Strategies** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Moving-Average Cross: long when the fast average crosses above the slow one, flat when it crosses back under. // The trader sees both averages on price, a ribbon between them tinted by which one leads (the up colour while the // fast average is on top, the down colour while it trails), a mark on the bar of each cross at the price where the // lines met, and the Strategy Tester under the chart with the fills, the equity curve and the numbers. // strategy({...}) makes the package a strategy: equity, sizing (50% of equity per entry), commission and slippage live here. strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: 50, commissionPercent: 0.05, slippageBps: 2 }); param.int("fast_len", 9, { min: 1, max: 200, label: "Fast length in bars", row: "lengths", description: "Fast average length in bars" }); // two whole numbers on one dialog line: rows naming the same row word sit side by side param.int("slow_len", 21, { min: 2, max: 400, label: "Slow length in bars", row: "lengths", description: "Slow average length in bars" }); const fastLine = output("fast_ma", line, overlay, { color: "theme.text", width: 2, label: "Fast", format: "price", description: "Simple moving average of the close over fast_len bars" }); // the handle names it for the hover card output("slow_ma", line, overlay, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Slow", format: "price", description: "Simple moving average of the close over slow_len bars" }); output("trend", none, overlay, { description: "1 while the fast average is above the slow one, else 0" }); hover(fastLine, [block.value("Fast", "fast_ma", { format: "price" }), block.rows([["Slow", "slow_ma", "price"], ["Trend", "trend", "int"]])]); // the card the fast average opens under the cursor output("entry_cross", shape, overlay, { color: "theme.up", width: 6, description: "The price where the fast average crossed above the slow one; the long entry fills at the next open" }); output("exit_cross", shape, overlay, { color: "theme.down", width: 6, description: "The price where the fast average crossed below the slow one; the position closes at the next open" }); range("fast_ma", "slow_ma", { color_by: "trend", colors: ["rgba(239, 83, 80, 0.14)", "rgba(38, 166, 154, 0.14)"] }); // the ribbon, tinted by the trend in the chart's default down and up hues (a band colour carries its own alpha) let fastSma = new Sma(9); // onStart() rebuilds both at the chosen lengths let slowSma = new Sma(21); const cross = new Cross(); // +1 on the bar the fast average crosses above the slow one, -1 below, 0 otherwise // onStart() runs once before the first bar: read each setting (i32() = whole bars). function onStart(): void { fastSma = new Sma(i32(p_fast_len())); slowSma = new Sma(i32(p_slow_len())); } // onBar() runs once per bar: fold the close into both windows and leave while either is still warming up (nothing // written, no orders); then place the orders (an order fills at the next bar's open, never earlier) and write the // outputs. The cross marks are NaN on every bar without a cross, so nothing is drawn there. function onBar(): void { const close = bar.close(); const fast = fastSma.update(close); const slow = slowSma.update(close); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); const trend = fast > slow ? 1.0 : 0.0; if (crossed == 1) strategy.long("L").send(); // a market entry under the id L, sized by the settings above if (crossed == -1) strategy.closeAll(); // every open entry closes at the next open const crossPrice = (fast + slow) * 0.5; // where the two averages met on this bar out_fast_ma(fast); out_slow_ma(slow); out_trend(trend); out_entry_cross(crossed == 1 ? crossPrice : NaN); out_exit_cross(crossed == -1 ? crossPrice : NaN); } ``` ## How it works **The file is the strategy.** `strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: 50, commissionPercent: 0.05, slippageBps: 2 })` makes the package a strategy: 10,000 starting equity, 50% of equity per entry, 0.05% commission, 2 bps slippage. The primary input is the chart's own close (`bar.close()`, no input line needed), the candles the broker fills against. **Orders fill at the next open.** `onBar()` folds the close into two `Sma` windows (`fast_len` 9, `slow_len` 21) and returns early while either is warming up (nothing written, no orders); `Cross.update(fast, slow)` is +1 on the bar the fast average crosses above the slow one and -1 on the way back. On a cross, `strategy.long("L").send()` places a market entry under the id L and `strategy.closeAll()` closes every open entry; both fill at the next bar's open, never earlier. **The look is three outputs.** `trend` (1 while the fast average is above the slow one) is data-only and drives `range("fast_ma", "slow_ma", { color_by: "trend", colors: ["rgba(239, 83, 80, 0.14)", "rgba(38, 166, 154, 0.14)"] })`, the ribbon in the chart's default down and up hues at a low alpha; `entry_cross` and `exit_cross` carry the price where the two averages met on a cross bar (NaN elsewhere), the two marks. ## Where it runs Every market with candles: perps, spot, prediction markets, FX. The Strategy Tester replays it in your browser over the chart's loaded window and recomputes as you pan; orders fill against the chart's own candles. The **Strategies** group of the starter list shows where the chart has the Strategy Tester. ## When data is missing The first `slow_len` bars are warm-up: nothing written, no orders, nothing drawn. A market whose candles stop (a resolved prediction market) leaves the last position where the tester closed it. ## Customize it - **Other lengths.** `fast_len` and `slow_len` are settings; the tester replays any pair. - **Both directions.** Add `strategy.short("S").send()` on a cross down in place of the flat exit ([Writing strategies](../strategies/writing-strategies.md)). - **Costs and sizing.** The five numbers in `strategy({ ... })` are the file's: change them and Run again. The tester's **Strategy settings** opens the overlay's settings, where a param changes a strategy field only when the file links it, the way the risk setting is linked into `qtyValue` in [Your first strategy](../strategies/first-strategy.md#5-tune-it-honestly); [Risk-sized reversion](strategy-risk-reversion.md) sizes each entry from its stop instead. - **Alert on the trades.** Once the indicator is published and on a chart, the alert dialog adds the strategy's own choices: "Strategy order placed", "Strategy trade opened or closed", "Strategy position" and "Strategy equity" ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Moving-Average Cross** under **Strategies**. 2. Press **Run**: the two averages, the ribbon and the cross marks draw on price, and the Strategy Tester under the chart shows the fills, the equity against buy and hold, and the trade list. ## Concepts used - [Strategies overview](../strategies/overview.md) for `strategy(...)`, the order builders and where they fill - [Reading the tester](../strategies/reading-the-tester.md) for the numbers under the chart - [Styling](../presentation/styling.md) for `range` bands and colour ladders <!-- source: https://openmarket.xyz/wrun/cookbook/strategy-risk-reversion --> # Risk-sized reversion ![RSI reversion strategy with entry, stop and target rails](/wrun/images/strategy-risk-reversion.png) A strategy: buy the dip as RSI climbs back out of oversold, protect it with a stop under the entry and a target above it (both sized in ATR), leave on recovery; each entry is sized so a trade stopped out loses the risk setting's percent of the equity (1% by default), never buying more than the equity holds. RSI in the text colour in its own pane under the chart, with the oversold level (30, dashed), the recovery level (55, dotted) and the overbought level (70, dashed), all three muted. On price, the rails of each trade from the fill bar to the bar it closed: the entry (the text colour), the stop (the down colour, dashed) and the target (the up colour, dashed). The open trade's rails are bright; past trades' rails stay dim, the newest 20 kept. The Strategy Tester under the chart holds the fills, equity against buy and hold, the numbers and the trade list. The parts are an entry sized from its stop with `qty(...)` and `strategy.equity()` ([Writing strategies](../strategies/writing-strategies.md)), a stop and a limit exit re-armed each bar the trade is held ([Your first strategy](../strategies/first-strategy.md)), the `Rsi`, `Atr` and `Cross` helpers ([TA library](../functions/ta-library.md)), and line handles in chart time and price for the rails ([Drawing objects](../presentation/drawing-objects.md)). This is also the `strategy-risk-reversion` template: the **Risk-Sized Reversion** card under **Strategies** in the editor's starter list, and it compiles as written. ## The wrun indicator ```typescript // Risk-Sized Reversion: buy the dip as RSI climbs back out of oversold, protect it with a stop under the entry and a // target above it, both sized in ATR so they fit the market and the interval, and leave on recovery. Each entry is // sized so a trade stopped out loses risk_pct of the equity, never buying more than the equity holds. // The trader sees RSI in its own pane with the oversold, recovery and overbought levels, and on price the rails of // each trade: the entry (the text ink), the stop (the down colour, dashed) and the target (the up colour, dashed), // drawn from the fill bar to the bar the trade closed; the open trade's rails are bright, past trades' rails stay dim. // The Strategy Tester under the chart holds the fills and the numbers. // The settings sit on two pages of the dialog: page() opens one, and the rows declared after it land on it. page("Signal"); param.int("rsi_len", 14, { min: 2, max: 200, label: "RSI length in bars", description: "RSI length in bars" }); param.range("rsi_band", [30, 70], { min: 5, max: 95, label: "Oversold / overbought", hint: "A dip must climb back through the low end to enter; the high end is drawn as the upper reference" }); // a low..high pair on one slider: p_rsi_band_lo() and p_rsi_band_hi() param.number("recovery", 55, { min: 30, max: 90, label: "Recovery level", description: "RSI level that ends the trade" }); page("Risk"); param.number("risk_pct", 1, { min: 0.1, max: 10, step: 0.1, label: "Risk per trade, percent", description: "Percent of the equity a trade loses at its stop: each entry is sized to it, never past what the equity buys" }); // strategy({...}) makes the package a strategy; every entry passes its own size, so the default order size is the cap: all of the equity. strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: 100, commissionPercent: 0.05, slippageBps: 2 }); param.int("atr_len", 14, { min: 2, max: 200, label: "ATR length in bars", description: "ATR length in bars, the unit of the stop and the target" }); param.number("stop_atr", 1.5, { min: 0.1, max: 10, step: 0.1, label: "Stop distance in ATR", description: "Stop distance under the entry price, in ATR" }); param.number("target_atr", 3, { min: 0.1, max: 20, step: 0.1, label: "Target distance in ATR", description: "Target distance above the entry price, in ATR" }); const rsiLine = output("rsi", line, lower, { color: "theme.text", width: 2, label: "RSI", format: "0.0", description: "Wilder RSI of the close, 0 to 100" }); // the handle names it for the hover card output("oversold_line", line, lower, { color: "theme.muted", width: 1, line_style: "dashed", label: "Oversold", format: "int", description: "The oversold level" }); output("recovery_line", line, lower, { color: "theme.muted", width: 1, line_style: "dotted", label: "Recovery", format: "int", description: "The recovery level" }); output("overbought_line", line, lower, { color: "theme.muted", width: 1, line_style: "dashed", label: "Overbought", format: "int", description: "The overbought level" }); handles.line({ color: "#38bdf8", width: 1 }); // the rails: line handles in chart time and price; every rail sets its own colour below hover(rsiLine, [block.value("RSI", "rsi", { format: "0.0" }), block.rows([["Oversold", "oversold_line", "int"], ["Recovery", "recovery_line", "int"], ["Overbought", "overbought_line", "int"]])]); // the card the RSI line opens under the cursor: its value and the three levels const ENTRY_INK = theme.TEXT; // the entry rail: the chart's text ink const STOP_INK = theme.DOWN; // the stop rail: the chart's down colour const TARGET_INK = theme.UP; // the target rail: the chart's up colour const TRADES_KEPT = 20; // rails ride a ring: the newest 20 trades keep theirs, 3 line handles each, never past 60 const rails: LineHandle[] = []; for (let i = 0; i < TRADES_KEPT * 3; i += 1) rails.push(draw.line(i)); // handle objects allocate once, at module load let rsi = new Rsi(14); // onStart() rebuilds it at the chosen length let atr = new Atr(14); // the unit of the stop and the target const dip = new Cross(); // +1 on the bar RSI crosses above the oversold level const recovery = new Cross(); // +1 on the bar RSI crosses above the recovery level let oversoldLevel = 30.0; let recoveryLevel = 55.0; let overboughtLevel = 70.0; let stopAtr = 1.5; let targetAtr = 3.0; let riskPct = 1.0; let stopDistance: f64 = NaN; // the entry's stop and target distances, fixed when its order goes out let targetDistance: f64 = NaN; let atrValue: f64 = NaN; // this bar's ATR let barTime: f64 = NaN; // this bar's open time in epoch seconds let prevBarTime: f64 = NaN; let intervalSec = 0.0; // the bar spacing, measured from consecutive bars, so a rail ends at the bar's close let inTrade = false; let tradeCount = 0; let railBase = 0; // the first of the open trade's three handles let entryTime: f64 = NaN; let entryPrice: f64 = NaN; let stopPrice: f64 = NaN; let targetPrice: f64 = NaN; // A fill landed on this bar: place the stop and the target the order was sized by around the entry price, start the rails. function openRails(): void { entryPrice = strategy.positionAvgPrice(); if (!isFinite(entryPrice) || !isFinite(barTime) || !isFinite(stopDistance)) return; // every draw coordinate must be finite inTrade = true; tradeCount += 1; entryTime = barTime; stopPrice = entryPrice - stopDistance; targetPrice = entryPrice + targetDistance; railBase = ((tradeCount - 1) % TRADES_KEPT) * 3; const right = barTime + intervalSec; rails[railBase].set(entryTime, entryPrice, right, entryPrice).color(ENTRY_INK).style(LineStyle.Solid).width(1.5).opacity(1.0); rails[railBase + 1].set(entryTime, stopPrice, right, stopPrice).color(STOP_INK).style(LineStyle.Dashed).width(1.0).opacity(1.0); rails[railBase + 2].set(entryTime, targetPrice, right, targetPrice).color(TARGET_INK).style(LineStyle.Dashed).width(1.0).opacity(1.0); } // While the trade is open, every bar extends the three rails to the bar's close. function extendRails(): void { const right = barTime + intervalSec; rails[railBase].setXy2(right, entryPrice); rails[railBase + 1].setXy2(right, stopPrice); rails[railBase + 2].setXy2(right, targetPrice); } // The trade closed on this bar: its rails stay where they ended, dimmed. function closeRails(): void { inTrade = false; rails[railBase].opacity(0.5); rails[railBase + 1].opacity(0.5); rails[railBase + 2].opacity(0.5); } // onStart() runs once before the first bar: read each setting through its p_ reader. function onStart(): void { rsi = new Rsi(i32(p_rsi_len())); oversoldLevel = p_rsi_band_lo(); recoveryLevel = p_recovery(); overboughtLevel = p_rsi_band_hi(); atr = new Atr(i32(p_atr_len())); stopAtr = p_stop_atr(); targetAtr = p_target_atr(); riskPct = p_risk_pct(); } // onBar() runs once per bar: fold the close into the RSI and leave while it warms up (nothing written, no orders); // then keep the rails in step with the position (the getters read the position after this bar's fills), place the // orders (they fill at the next bar's open) and write the outputs. function onBar(): void { const close = bar.close(); prevBarTime = barTime; barTime = bar.time(); if (isFinite(prevBarTime) && barTime > prevBarTime) intervalSec = barTime - prevBarTime; atrValue = atr.update(bar.high(), bar.low(), close); const value = rsi.update(close); // this bar's RSI, NaN until the window is full if (isNaN(value) || isNaN(atrValue)) return; const dipped = dip.update(value, oversoldLevel); const recovered = recovery.update(value, recoveryLevel); const size = strategy.positionSize(); if (size > 0.0 && !inTrade) openRails(); if (inTrade) extendRails(); if (size == 0.0 && inTrade) closeRails(); if (dipped == 1 && size == 0.0 && atrValue > 0.0 && close > 0.0) { // a market entry under the id Dip stopDistance = stopAtr * atrValue; targetDistance = targetAtr * atrValue; const equity = strategy.equity(); let qty = (equity * riskPct) / 100.0 / stopDistance; // stopped out at the stop, the trade loses risk_pct of the equity if (qty * close > equity) qty = equity / close; // never more than the equity buys strategy.long("Dip").qty(qty).send(); } if (size > 0.0 && isFinite(stopPrice) && isFinite(targetPrice)) { strategy.exit("Protect").from("Dip").stop(stopPrice).limit(targetPrice).send(); // re-armed each bar held } if (recovered == 1) strategy.closeAll(); // the signal exit: every open entry closes at the next open out_rsi(value); out_oversold_line(oversoldLevel); out_recovery_line(recoveryLevel); out_overbought_line(overboughtLevel); } ``` ## How it works **The risk is a setting.** `risk_pct` (**Risk per trade, percent**, 1, from 0.1 to 10) is the share of the equity a trade loses at its stop. On the signal bar the entry fixes its stop distance, `stop_atr` times this bar's ATR, and its quantity: the equity times `risk_pct` over 100, divided by the stop distance, so a fill stopped out loses `risk_pct` percent of the equity (before costs and any gap through the stop). A quantity whose notional would pass the equity is cut to what the equity buys, so with a tight stop on a short interval the entry buys the whole equity and risks less. `strategy.long("Dip").qty(qty).send()` passes the size on the order, so the `strategy({ ... })` declaration's own size, `qtyType: "percentOfEquity"` at `qtyValue: 100`, is the cap and never decides an entry. 10,000 starting equity, 0.05% commission and 2 bps slippage are the file's. **Three rules.** Entry: RSI (`rsi_len` 14) crosses above the low end of `rsi_band` (30, the oversold level) while flat, and the sized `strategy.long("Dip")` fills at the next open. Protection: `strategy.exit("Protect").from("Dip").stop(stopPrice).limit(targetPrice).send()` re-armed every bar the trade is held, the stop `stop_atr` (1.5) ATR under the fill price and the target `target_atr` (3) ATR above it, the ATR (`atr_len` 14) of the signal bar, the distances the entry was sized by. Exit: RSI crosses above `recovery` (55) and `strategy.closeAll()` closes every open entry at the next open. The high end of `rsi_band` (70, the overbought level) is drawn as a reference line only. **Rails follow the position.** `strategy.positionSize()` and `strategy.positionAvgPrice()` read the position after the bar's fills: the bar a fill lands fixes the entry, the stop and the target and opens three line handles at the bar's open time; every bar held extends them to the bar's close; the bar the position goes flat dims them. Twenty trades keep their rails on a ring of 60 handle ids. ## Where it runs Every market with candles: perps, spot, prediction markets, FX. The Strategy Tester replays it in your browser over the chart's loaded window and recomputes as you pan; orders fill against the chart's own candles. The **Strategies** group of the starter list shows where the chart has the Strategy Tester. ## When data is missing The first `rsi_len` and `atr_len` bars are warm-up: nothing written, no orders, no rails. A trade still open when the loaded history ends keeps its bright rails extended to the last bar. ## Customize it - **Tighter protection.** `stop_atr` and `target_atr` are settings in ATR, so they fit the market and the interval; a tighter stop buys more at the same risk, up to the whole equity. - **Risk more or less.** `risk_pct` moves every entry's size and reruns the strategy over the same candles. - **A different dip.** Move the two ends of `rsi_band` (one slider in the dialog) and `recovery`; the reference lines follow. - **Shorts too.** Mirror the rules with `strategy.short(...)` on RSI leaving overbought ([Writing strategies](../strategies/writing-strategies.md)). - **Alert on the trades.** Once the indicator is published and on a chart, the alert dialog adds the strategy's own choices: "Strategy order placed", "Strategy trade opened or closed", "Strategy position" and "Strategy equity" ([Alerts](../functions/alerts.md)). ## Run it 1. In the editor's Explorer, press the **Templates** icon ("Browse starter templates") and pick **Risk-Sized Reversion** under **Strategies**. 2. Press **Run**: RSI and its three levels draw in a pane under the chart, each trade's rails draw on price, and the Strategy Tester under the chart shows the fills, the equity against buy and hold, and the trade list. ## Concepts used - [Your first strategy](../strategies/first-strategy.md) for the protective exit - [Writing strategies](../strategies/writing-strategies.md) for the order builders, `qty(...)` on an entry and the position and equity getters - [Drawing objects](../presentation/drawing-objects.md) for line handles in chart time and price <!-- source: https://openmarket.xyz/wrun/faq/general --> # General FAQ Short answers to the questions people ask most about wrun, each with a link to the page that has the details. ## Getting started ### What is a wrun indicator? One file in TypeScript syntax. You write it in the chart's editor, **Run** draws it on your chart, and **Publish** shares it. It has no filesystem, no network and no order capability. Start with [Your first indicator](../getting-started/primer-first-indicator.md). ### Do I need to know TypeScript? About a page of it. The file is AssemblyScript: TypeScript syntax over fixed-width numbers (`f64`, `i32`), with no `any` and no dynamic typing. If you can read the **Moving Average** starter, you can write one. ### Why does an indicator declare its outputs instead of drawing them? The chart draws from the declarations, so one file computes the same way in your browser, in each reader's, on OpenMarket's servers and in alerts. [What is wrun](../getting-started/introduction.md) has the full picture. ### Do files written with init, state, finalize and reset still work? Yes, unchanged ([Execution model](../core-concepts/execution-model.md#the-four-function-form)). ## Account, plans and support ### Do I need a paid plan? No. Every plan can write and run indicators, Free included; you need an account and a desktop browser. Plus raises the [limits](../reference/limits.md#plans), and its price is on the [Plus page](https://openmarket.xyz/chart/plus). ### Can I write an indicator on my phone? No. The editor opens only in a desktop browser. ### How do I reach the team? Use **Reach out** in the app, or join [Discord](https://discord.gg/hjQRzQtbNu). ## Data sources and context ### How does an indicator know which market the chart shows? It follows the chart: `bar.close()` and an unpinned input read the chart's own market and interval. To read a fixed market, pin a secondary input with `symbol` and `exchange` ([Data sources](../core-concepts/data-sources.md)). ### Why is the start of my line empty? Warm-up. TA classes return `NaN` until their window fills, and `NaN` draws nothing: a 200-bar average has no value on bar 50 ([Execution model](../core-concepts/execution-model.md)). ### Can I read the previous bar? Yes, with `History` from `./sdk/stats`: `push()` once per bar, then `ago(1)` is the previous value ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). There is no `close[1]`. By hand, keep the value in a module-level variable: ```typescript param("bars", 5, { min: 2, max: 50, description: "Bars in the trailing window" }); output("change", line, lower, { description: "Close minus the previous bar's close" }); output("window_high", line, overlay, { description: "Highest high of the trailing window" }); const MAX_BARS = 50; const highs = new StaticArray<f64>(MAX_BARS); let n: i32 = 5; let cursor: i32 = 0; let count: i32 = 0; let prevClose: f64 = NaN; function onStart(): void { n = i32(p_bars()); } function onBar(): void { const close = bar.close(); // The previous close is whatever we kept from the previous call: there is no close[1] to read. const change = isNaN(prevClose) ? NaN : close - prevClose; prevClose = close; highs[cursor] = bar.high(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n || isNaN(change)) return; let h = -Infinity; for (let i = 0; i < n; i++) if (highs[i] > h) h = highs[i]; out_change(change); out_window_high(h); } ``` ### Can I analyze multiple markets in one indicator? Yes: one pinned `ohlcv` input per market, with `symbol` and `exchange` together. The first input stays unpinned and sets the bar grid. Trades, funding, open interest and liquidations always read the chart's own market. Stocks, forex and gold pin the same way ([Stocks, forex and gold](../core-concepts/multi-source.md#stocks-forex-and-gold)). ```typescript // The first input is the grid: it follows the chart's own market. input("close", ohlcv.close); // Pinned inputs read fixed markets; symbol and exchange always pin together. input("btc_close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES" }); input("eth_close", ohlcv.close, { symbol: "ETHUSDT", exchange: "BINANCE_FUTURES" }); output("eth_btc", line, lower, { description: "ETH priced in BTC" }); output("vs_btc", line, lower, { unit: "%", description: "This market's close as a percent of BTC's" }); function onBar(): void { const btc = in_btc_close(); if (isNaN(btc) || btc <= 0.0) return; out_eth_btc(in_eth_close() / btc); out_vs_btc((bar.close() / btc) * 100.0); } ``` ### Can I write an indicator without a data source? It always runs on the chart's own candles, even with no `input(...)` line, but it needs at least one `output(...)`. ### Can I declare inputs inside if, a loop, or a function? No. Declarations are top-level statements, read before anything runs, so there are no conditional inputs. ### How do I read the order book? Declare a celled `book` input after the first input and scan its `[price, size, side]` tuples in `onBar()`: `input("book", book.cells, { max_cells: 1000, block_size: 10 })`. The chart serves up to 500 levels a side, so `max_cells` must cover 1,000 tuples. [Order flow](../functions/order-flow-kit.md#depth-window-scans-by-hand) has worked scans. ### How does an indicator handle data gaps? Each input declares a `missing` policy: a secondary input repeats its last value by default (`"carry"`), `"nan"` gives `NaN` and `"zero"` gives `0`. Lines never interpolate across `NaN`. For your own fill, handle it in `onBar()`: ```typescript input("close", ohlcv.close); // A sparse feed: bars with no liquidation deliver NaN instead of repeating the last value. input("liqs", liquidations.liquidations, { missing: "nan" }); output("liq", line, lower, { description: "Liquidation volume this bar, 0 on quiet bars" }); output("last_liq", line, lower, { description: "The most recent liquidation volume, carried forward" }); let lastLiq: f64 = NaN; function onBar(): void { const x = in_liqs(); let liq: f64; if (isNaN(x)) { liq = 0.0; // your own zero policy } else { liq = x; lastLiq = x; // your own forward fill } out_liq(liq); out_last_liq(lastLiq); } ``` On the primary input, `"nan"` and `"zero"` also turn a sparse feed into one row per bar ([Data sources](../core-concepts/data-sources.md)). ## Technical indicators ### Why am I getting NaN in my calculations? Usually a TA class still warming up, a division by zero, or a `missing: "nan"` input on an empty bar. Test with `isNaN(x)`, then skip the bar, write `NaN`, or substitute a value ([Best practices](best-practices.md)). ### Which TA classes exist? 52 in `./sdk/ta` (`Sma`, `Ema`, `Rsi`, `Atr`, `Bb`, `Macd` and more) on the [TA library](../functions/ta-library.md), and 30 more in `./sdk/ta-plus` on [Extra indicators](../functions/extra-indicators.md). ### How do I use a param as a period? Cast it in `onStart()`: `sma = new Sma(i32(p_period()))`. Params are `f64`, periods are `i32`. ## Plotting and visualization ### How do I draw several lines on the same chart? One `output(...)` per line: `overlay` on the price pane, `lower` in its own pane ([Plotting](../presentation/plotting.md)). ### Can I plot conditional signals? Yes. A `shape` output draws only on bars where the output named in `shape_where` is nonzero: ```typescript param("len", 14, { min: 2, max: 200 }); param("level", 30, { min: 5, max: 50, description: "RSI at or below this counts as oversold" }); output("rsi", line, lower, { color: "#a78bfa" }); // The mark sits at the output's value (this bar's low) and draws only on bars where the gate is 1. output("buy", shape, overlay, { color: "#22c55e", shape_where: "oversold" }); output("oversold", none); let rsi = new Rsi(14); let level: f64 = 30.0; function onStart(): void { rsi = new Rsi(i32(p_len())); level = p_level(); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; out_rsi(value); out_buy(bar.low()); out_oversold(value <= level ? 1.0 : 0.0); } ``` ### How do I change plot colors dynamically? Give the output a `colors` palette and name a data-only output in `color_by`; each bar's value picks the color: ```typescript param("fast", 10, { min: 1, max: 200 }); param("slow", 30, { min: 2, max: 400 }); // Each bar's trend value (0 or 1) indexes the palette: red below the slow average, green above. output("price", line, overlay, { width: 2, color_by: "trend", colors: ["#ef4444", "#22c55e"] }); output("trend", none); let fast = new Sma(10); let slow = new Sma(30); function onStart(): void { fast = new Sma(i32(p_fast())); slow = new Sma(i32(p_slow())); } function onBar(): void { const close = bar.close(); const f = fast.update(close); const s = slow.update(close); if (isNaN(s)) return; out_price(close); out_trend(f > s ? 1.0 : 0.0); } ``` ### Can I write an output inside a conditional or a loop? Yes. Each output holds one value per bar and the last write wins. Write `NaN`, or skip the write, to draw nothing on a bar. ### What is the difference between line, area, histogram and scatter? Only the look: `line` joins the points, `area` fills under them, `histogram` and `bar` draw columns, `scatter` draws points. `candle` draws four outputs as a candle, `shape` draws a gated mark, and `none` computes without drawing ([Plotting](../presentation/plotting.md)). ### How does positioning work for shapes and text? A `shape` draws at its value on its bar, so write the bar's low or high to place it. Text comes from string slots: `render.text` draws one mark per bar, `render.label` one label ([Drawing objects](../presentation/drawing-objects.md)). ### My line hugs the bottom of the price chart It is a small-number series on the price axis. Declare it `lower`. ### My box draws with no fill Its `opacity` is `0`; the default is 0.2. ### My mark draws on every bar Add a data-only gate output, name it in `shape_where`, and write `0` to it on quiet bars. ## Common issues and troubleshooting ### My indicator isn't displaying anything Check, in order: 1. The editor's Console: a failed build draws nothing, and it says when an output was `NaN` on every bar. 2. Whether `onBar()` reaches its writes: a TA class short of bars returns `NaN`. 3. Whether the output is declared `none`. 4. Whether the chart's market serves the input's source: the legend shows **Could not load**. 5. Whether a pin was refused. [Debugging](debugging.md) has the full workflow. ### Undefined identifier errors `Cannot find name 'out_sma'` means the declaration was renamed, removed or misspelled. Accessors are generated from declaration names, lowercased, with other characters turned into `_`: `param("fast.len", ...)` is `p_fast_len()`. ### How do I debug my indicator? Three ways in the editor: print lines with a `debug` string slot, read values at the Console prompt after a **Run**, or declare the suspect value as an output ([Debugging](debugging.md)). ### Why isn't my indicator updating in real time? It is, about once a second: the forming bar runs again on live updates, without double-counting. Polled sources (open interest, implied volatility, ETF flows) move when their poll lands. A draft stops on reload: **Run** it again. ### Can I use null instead of NaN for missing data? No. Outputs are `f64`, which has no `null`: `NaN` means "nothing here" and draws a gap, while `0` draws a zero. ### The chart refuses my symbol or interval pin Pins have rules: - A market pin goes only on a secondary `ohlcv` input, and never on a CME Group venue. - An interval pin must be coarser than the chart and a whole multiple of it. - The first input takes no pin. The Console names the refusal ([Limitations](../reference/limitations.md), [Multi-timeframe](../core-concepts/multi-timeframe.md), [exchange ids](../reference/symbol-format.md)). ## Language features and syntax ### Does it support switch statements? Yes, over integers, with TypeScript's fallthrough rules (write `break`). Bucket a float into an integer first: ```typescript param("len", 14, { min: 2, max: 200 }); output("score", line, lower, { description: "-1 oversold, 0 neutral, 1 overbought" }); let rsi = new Rsi(14); // A switch runs over integers: bucket the value first, then branch. Each case breaks. function zone(value: f64): i32 { if (value <= 30.0) return 0; if (value >= 70.0) return 2; return 1; } function onStart(): void { rsi = new Rsi(i32(p_len())); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; let score: f64 = 0.0; switch (zone(value)) { case 0: score = -1.0; break; case 2: score = 1.0; break; default: score = 0.0; break; } out_score(score); } ``` ### Are objects and arrays supported? Yes, with static types: `StaticArray<f64>` for fixed windows, `Array<f64>`, `Map`, and classes with typed fields. Allocate in `onStart()`, never in `onBar()` ([Collections](../core-concepts/collections.md), [User-defined types](../core-concepts/user-defined-types.md)). ### Can an indicator read another indicator's values? No. Combine the logic into one file. ### Can I use inputs and TA classes inside my own functions? Yes: readers such as `bar.close()` work in any function `onBar()` calls, and a TA class is an ordinary object. Functions cannot capture locals, so keep shared state at module level ([User functions](../core-concepts/user-functions.md)). ### Does it support alerts? Yes. Publish the indicator, add it to a chart, and open the alert dialog from its bell in the legend to pick an output and a condition. The file can also define a ready-made signal with `alert(...)`. Alerts run in OpenMarket's cloud ([Alerts](../functions/alerts.md)). ### Can trades be executed from an indicator? No. An indicator has no order capability. A strategy places orders only in the Strategy Tester's simulation ([Strategies overview](../strategies/overview.md)). ### Can I show text? Yes, through a string slot and a renderer: `render.label`, `render.text` or `render.table` ([Drawing objects](../presentation/drawing-objects.md)). ### Can I move or delete a shape after drawing it? Yes, with a drawing handle (a line, box, label or polyline) that you update or delete by id ([Drawing objects](../presentation/drawing-objects.md)). ### How many shapes can I have? 16 declared boxes and 16 segments, up to 1,000 live drawing handles per kind (1,500 in all), and 2,000 drawings per run. [Limits](../reference/limits.md) has every cap. ## Performance and optimization ### My indicator is running slowly. How can I optimize it? Cut the per-bar work: - Allocate buffers once, in `onStart()`, sized from a param's `max`; never `new` in `onBar()`. - Bound loops by a param with a `max`. - Compute a value once and reuse it. ### Should I use const for constants? Yes. A module-level `const` costs nothing per bar and can size a `StaticArray`. A value that depends on a param is a module-level `let` set in `onStart()`. ## Common error messages ### Conversion from type 'f64' to 'i32' requires an explicit cast You passed a float where a whole number is needed (a period, loop bound or index). Cast it with `i32(p_period())`, and declare floats as `f64`. [Common errors](common-errors.md) lists every message with its fix. ## Still have questions? - [Common errors](common-errors.md): every message and its fix - [Debugging](debugging.md): when it runs but draws the wrong thing - [Limitations](../reference/limitations.md): what is out of scope today - [Quick reference](../reference/quick-reference.md): every declaration on one page - **Reach out** in the app, or [Discord](https://discord.gg/hjQRzQtbNu) <!-- source: https://openmarket.xyz/wrun/faq/best-practices --> # Best practices Guidelines for writing wrun indicators that are fast, honest about warm-up, and safe to replay: where state lives, what belongs in `onStart()` and what in `onBar()`, why the generated accessors beat slot literals, and the handful of habits that keep a file fast and readable. ## Code structure ### Variable declarations An indicator has three kinds of state, and each has one right home. **Module-level `let` for anything that survives between bars.** This is where accumulators, the previous bar's close, running session highs, and the TA objects live. Give every one a type and a starting value (`let cvd: f64 = 0.0`, `let prevClose: f64 = NaN`). **Locals inside `onBar()` for this bar's arithmetic.** A `const typical = (high + low + close) / 3.0` that nothing needs next bar belongs in the function, not at module level. It is cheaper and it cannot go stale. **A `StaticArray<f64>` ring buffer for a window.** A window you index into (the value five bars back) is a buffer you fill yourself: allocate it once, sized from the param's `max`, walk it with a cursor, and count how full it is. `History` from `./sdk/stats` is that buffer ready-made, with `ago(n)` for the value `n` bars back ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). The zone tracker and the [previous-bar FAQ sample](general.md) show the shape. Module-level state and a ring buffer are how rolling math remembers earlier bars, and they are right for it; they also mean a pan-back recomputes the whole loaded history. A script whose math needs nothing from earlier bars (a reading of the bar's own candle, book or profile) keeps every value in locals and assigns module variables only in `onStart()`: the compiler can then prove it per bar, and a proven file's pan-back computes only the newly loaded bars ([Per-bar scripts](../core-concepts/per-bar-scripts.md) lists what the proof accepts). ### Build what lasts in `onStart()`, let `onBar()` make temporaries `onBar()` runs once per loaded bar and again on the forming bar as live updates arrive. An array, a string or an object made there and dropped by the next bar is fine: the module frees it, and the build reserves scratch for it before the first bar, so memory stays flat across a long history. What the chart stops is memory that grows once the bars start ("The Indicator allocated memory after init() ... the sandbox forbids growth once the bars start."): a history you push onto on every bar, a map that gains a key per bar. So build what lives across bars once, at module start or in `onStart()`, sized from the param's declared `max`, and let `onStart()` set the live length: ```typescript param("window", 100, { min: 10, max: 500, description: "Bars the rank is measured against" }); output("rank", line, lower, { unit: "%", description: "Share of the window's closes below this bar's close" }); // Allocate once, at module start, sized from the param's max: never inside onBar(). const MAX_WINDOW = 500; const closes = new StaticArray<f64>(MAX_WINDOW); let n: i32 = 100; let cursor: i32 = 0; let count: i32 = 0; function onStart(): void { n = i32(p_window()); } function onBar(): void { const close = bar.close(); let below = 0; for (let i = 0; i < count; i++) if (closes[i] < close) below += 1; closes[cursor] = close; cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n) return; out_rank((100.0 * f64(below)) / f64(n)); } ``` The TA classes follow the same rule: `new Sma(period)` allocates its window in the constructor and `update()` never allocates, which is why they are constructed in `onStart()` and fed in `onBar()`. A file that writes the four functions itself (`init`, `state`, `finalize`, `reset`) gets no scratch, so it keeps the stricter rule: allocate in `init()`, never per bar. ### Nothing to reset There is no reset step to write. The chart runs the module once over the loaded bars, and the forming bar does not depend on any reset: the chart replays that bar from a snapshot of the module's memory taken after the last closed bar, so a live value never double-counts. Give every module-level `let` its starting value where it is declared, build what depends on a param in `onStart()`, and let a `count` field say how much of a buffer is valid instead of clearing the buffer. ### Accessors over slot literals Params, inputs, and outputs reach the code by name: `p_period()`, `bar.close()`, `in_funding()`, `out_sma(value)`, generated from the declarations on every check. Underneath, the host passes values positionally, and the raw calls (`getFloat(0)`, `setOutput(0, ...)`) bind by position, so adding a declaration above them silently rebinds them. The editor refuses the raw form in your source (`Raw slot literal 0 passed to getFloat(): raw positional slots rebind silently when the sheet changes`) and names the accessor to use instead. The same rule keeps a rename honest: rename `output("sma", ...)` to `output("average", ...)` and the compiler points at every stale `out_sma` ([Declarations and the sheet](../reference/declarations.md)). ## Technical indicators ### Read the period once, cast it once Params are `f64`; a period is `i32`. Read each param in `onStart()`, cast it there (`new Sma(i32(p_period()))`), and keep the class in a module-level variable. Reading `p_period()` in `onBar()` works but does the cast on every bar for nothing, and a class constructed in `onBar()` starts over on every bar, with no history. Never read a param at the top of the file: that code runs before start-up, so the setting has no value yet and the build refuses the read on its line. ### Be honest about warm-up A window that is not full has no value, and the honest output is `NaN`. Two ways to write it, both correct: `return` from `onBar()` before any write while nothing on the bar is meaningful (every output stays `NaN`, and the bar draws nothing), or write `NaN` to the one output that is still warming while the others draw ([Execution model](../core-concepts/execution-model.md)). What is never correct is a placeholder that draws as if it were true. The chart reads no warm-up count: every bar has a row, and what `onBar()` writes alone decides what is drawn. ### Name what the module computes, not how it is drawn A decision is an output too. Emit `1` or `0` from a data-only `none` output and let a declaration turn it into a look (`shape_where`, `color_by`, a box's `when`). That keeps the numeric surface reusable: the same gate that draws a mark can drive a declared `alert(...)`, and you can read it by name at the Console prompt. ## Plotting and visualization ### Describe every declaration `label` on a setting is its name in the settings dialog (`description` stands in when there is none, and `hint` is the words behind the row's glyph); on an input `description` documents the input in the sheet **Run** derives; on an output it is the note the Console prompt shows beside the output's name. Write them the way you would want to read them a month later: "Bars of history that define normal volume" beats "lookback". Give small-magnitude series (oscillators, percentages, counts) the `lower` panel and a `unit` (`%`, `price`, or a short label) so the axis formats itself. ### One namespace for shape names Outputs, boxes, segments, renderers, and drawings share one namespace. A box named `range` beside an output named `range` is refused at the sheet (`box name 'range' is already taken by an output`). Name shapes for what they draw (`demand_zone`, `pdh_line`) and outputs for what they compute (`demand_top`, `pdh`). ## Debugging ### Probe with an output Log it or draw it. The debug log is the indicator's `print()`: a string slot named `debug`, written in `onBar()`, prints each bar's line in the editor's Console. For a number, declare the suspect intermediate as `none` (readable by name at the Console prompt, never drawn) or as a `lower` line to see its shape across every bar, then delete the declaration when you are done. [Debugging](debugging.md) is the full workflow. ## Error prevention ### NaN checks and safe division `NaN` is the only "nothing here" value, and it propagates: `NaN + 1` is `NaN`, and `NaN > 0` is `false`. Test with `isNaN(x)` before a comparison that decides something, and guard every division by a value that can be zero. The two helpers most indicators need are two lines each: ```typescript param("len", 20, { min: 1, max: 200 }); output("ratio", line, lower, { description: "Volume over its average, 0 while the average warms" }); output("smooth", line, lower, { description: "Close average, last good value carried across gaps" }); // nz: a number, or the fallback when it is NaN. function nz(value: f64, fallback: f64): f64 { return isNaN(value) ? fallback : value; } // Division that refuses to blow up: NaN when the denominator is zero or missing. function safeDiv(numerator: f64, denominator: f64): f64 { return isNaN(denominator) || denominator == 0.0 ? NaN : numerator / denominator; } let avgVolume = new Sma(20); let avgClose = new Sma(20); let lastGood: f64 = NaN; function onStart(): void { avgVolume = new Sma(i32(p_len())); avgClose = new Sma(i32(p_len())); } function onBar(): void { const volume = bar.volume(); out_ratio(nz(safeDiv(volume, avgVolume.update(volume)), 0.0)); // fixnan: keep the last non-NaN value instead of showing a gap. const smooth = avgClose.update(bar.close()); if (!isNaN(smooth)) lastGood = smooth; out_smooth(lastGood); } ``` ### Buffer bounds A ring buffer never reads past what it has been given: keep a `count` beside the `cursor` and only scan `count` entries until the buffer is full. There is no `barIndex` to compare against and no negative index to worry about; the buffer's own bookkeeping is the bound. A `History` from `./sdk/stats` keeps that bookkeeping for you: `ago(n)` reads `NaN` until it holds `n + 1` values ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). ### `missing` on sparse primaries A feed that only has rows when something happened (liquidations, for one) makes a poor primary input as-is: the grid has holes. Declare `missing: "zero"` (or `"nan"`) on it and the grid densifies to one row per bar, with the fill on the quiet bars. A candle source (`ohlcv`, `odds`) never densifies, whatever its policy: a bar with no candle is no bar, so the rows stay the candles the venue printed, and an RSI or an EMA reads straight across a gap in the venue's history instead of meeting a `NaN` bar. On a secondary sparse input the same policies decide what the module sees on bars without an observation; the default carries the last value forward, which is right for a coarse candle and wrong for a volume you would double-count ([Data sources](../core-concepts/data-sources.md)). ## Performance optimization ### Avoid redundant calculations Compute a value once and keep it in a local for every output that needs it; do not fold the same input into two classes when one class and a copy will do. Loops are fine when they are bounded by a param with a declared `max`; a loop whose bound comes from history length is the thing to avoid. ### Keep the row cheap `onBar()` should be arithmetic and writes. A line built with `+` or `toString()` is a temporary the module frees, so it is fine in a file with `onBar()`; the string channel's shared buffer (`sb_clear` / `sb_text` / `sb_f64`) allocates nothing at all, which makes it the cheaper choice on a long history and the only one in a file with the four functions. ## Canvas cost A price canvas costs what it draws. A TPO costs rows x letters x the periods on screen: the chart folds every row from the candles and paints every letter as a block. The folding counts toward the "is slowing your chart" notice like your script's own time, and a live tick refolds only the forming period. On BTC at 15m the chart's 75-dollar rows make about 230 blocks a day; 1.5-dollar rows would make about 9,300. ### Prefer `"auto"` Leave `row_height` out. `"auto"` takes the row from what the chart serves for the market (the bucket width of your `cells`, else the market's TPO or volume profile catalog) times the chart's row table, so your canvas draws the rows the chart's own footprint, TPO or profile would: on BTC at 15m, a TPO gets about 25 to 90 rows a day, each tall enough for its letters ([Row height](../presentation/price-canvases.md#row-height)). ### When to declare a number - **A market with no catalog, whose tick you know.** `"auto"` falls back to a quarter of the median candle range there; a whole number of ticks (`row_height: 0.25` on a market that trades in 0.05 steps) keeps every row on a price the market can print. - **A deliberately coarse profile.** Fewer, taller rows than auto, such as `row_height: 250` for a BTC day profile read at a glance. Size the number from the range: a period's high minus its low, divided by `row_height`, is the rows it holds, and under 512 the chart keeps your height. ### The coarsening notice `tpo 'tpo': row_height 1 coarsened to 8 (512 rows per day is the chart's limit)`, a warning row in the Console and the warning on the legend chip, means a period held more than 512 rows at the height you declared, so the chart doubled it until the period fit (at most 6 times). The TPO still draws, at the coarser height, and the notice repeats on every run. To clear it, declare the height it names or a larger one, or remove `row_height` and let `"auto"` pick. On `"auto"` (`row_height auto coarsened from 1.5 to 12`) the market's own unit is too fine for how far its price moves in a period: declare a `row_height` of at least the height the notice names. ## Code organization ### Group related code Read top to bottom: declarations, state, helpers, then `onStart()` and `onBar()` in the order the chart calls them. A complete indicator laid out that way: ```typescript // 1. Declarations: settings and outputs, each with the description the settings dialog and the Console prompt show. param("fast", 9, { min: 2, max: 100, description: "Fast EMA length" }); param("slow", 21, { min: 5, max: 400, description: "Slow EMA length" }); output("fast", line, overlay, { color: "#38bdf8", description: "Fast EMA" }); output("slow", line, overlay, { color: "#f59e0b", width: 2, description: "Slow EMA" }); output("entry", shape, overlay, { color: "#22c55e", shape_where: "is_entry", description: "Fast crossed above slow" }); output("is_entry", none); // 2. State: everything that lives between bars, with its starting value. let fast = new Ema(9); let slow = new Ema(21); let cross = new Cross(); // 3. Lifecycle: onStart reads settings, onBar folds the bar and writes the row. function onStart(): void { fast = new Ema(i32(p_fast())); slow = new Ema(i32(p_slow())); cross = new Cross(); } function onBar(): void { const close = bar.close(); const fastValue = fast.update(close); const slowValue = slow.update(close); const crossed = cross.update(fastValue, slowValue); if (isNaN(slowValue)) return; out_fast(fastValue); out_slow(slowValue); out_entry(bar.low()); out_is_entry(crossed == 1 ? 1.0 : 0.0); } ``` ### Comment the why The declarations already say what the indicator reads and writes, and the accessors keep the code readable, so comments earn their place explaining a decision: why a bucket folds in only on the next bucket's first bar, why a session that was already running stays `NaN`, why a pinned input reads `NaN` on a stock chart. The cookbook recipes are written that way. <!-- source: https://openmarket.xyz/wrun/faq/common-errors --> # Common errors The messages a wrun indicator author meets in the chart, each with its cause and its fix, in the order they arrive: the checks the editor runs on your code (declarations, lint, the sheet, the compiler, the module), then what a **Run** reports, then what the chart itself says. Every heading is the text the editor prints, so a browser find on the message you got lands on its fix. If your indicator ran but drew nothing, the problem is probably not an error at all. Skip to [Ran but blank](#ran-but-blank) at the end. ## Where errors show - **In the editor's Console.** The editor checks your code as you type, and **Run** reuses those checks before it runs anything. Each problem is a row in the Console with its line number, its stage in brackets (`declarations`, `lint`, `metadata`, `validate`), and the message; a compiler row carries the compiler's message and a hint that links to these docs. The same text shows as a squiggle under the span, and clicking a row jumps to its line. The status bar counts errors and warnings (its tooltip reads **Open Problems**) and opens the Console, and a blocked **Run** says "Cannot run: 2 error(s) must be fixed first." - **After a Run.** What the run itself finds prints as a `compute` row with a "Fix:" line, next to the indicator's debug log ([Debugging](debugging.md)). - **On the chart.** An overlay whose run fails keeps its last good drawing; its legend shows a **Could not load** chip with the message and a **Retry**. An overlay that never drew anything also raises a one-time toast that starts "Indicator could not load:". The checks are staged, so one problem hides the ones behind it: a declaration error stops the build before the sheet is checked, and a sheet error stops it before the compiler runs. Declaration errors arrive together, one row per finding, each on the line of the declaration it names. ## `option 'top' takes an output handle, not a string literal` **Symptom:** the `declarations` stage refuses a `box(...)` or `segment(...)` line with `option 'top' takes an output handle, not a string literal (bind a handle with a top-level const h = output(...) and pass h)`. **Cause:** a box or segment coordinate is the value `output(...)` returned, not the output's name. `box("band", { top: "hi", ... })` passes a string where a handle goes. **Fix:** bind the output to a top-level const and pass the const. The same rule covers `bottom`, `yFrom`, `yTo`, `when`, and an output-valued `from` / `to`: ```typescript param("period", 20, { min: 1, max: 200 }); output("sma", line, overlay); // Bind each coordinate output to a const: the box names the handle, never the string. const hi = output("hi", none); const lo = output("lo", none); box("band", { top: hi, bottom: lo, color: "#38bdf8", opacity: 0.15, borderWidth: 0 }); let sma = new Sma(20); function onStart(): void { sma = new Sma(i32(p_period())); } function onBar(): void { const value = sma.update(bar.close()); out_sma(value); out_hi(value * 1.01); out_lo(value * 0.99); } ``` ## `segment 'ray' option 'yTo' references 'top', which is not an output handle` **Symptom:** `segment 'ray' option 'yTo' references 'top', which is not an output handle; bind the output first (const top = output("...", ...)) and pass that const`. **Cause:** the identifier you passed is a variable, but not one bound to an `output(...)` call. **Fix:** bind it with `const`, `let`, or `var` at the top level (the binding may sit below the shape that uses it). The sheet records the output's name, never the handle. ## `output(...) declarations must be top-level statements` **Symptom:** `output(...) declarations must be top-level statements, not inside a function, class, or expression` (or the same for `param`, `input`, `box`, `segment`, `render.text`, and the rest). **Cause:** declarations are read from the text without running it, so one inside `onStart()`, inside an `if`, or inside a class is invisible to the sheet and refused. **Fix:** move the declaration to the top level of the file. Declarations are static: they cannot depend on a param or a condition. ## `param options accept only { required, min, max, description }, not 'step'` **Symptom:** the family's option list, followed by the option you wrote. On a typed setting the list is longer: `param.int options accept only { required, min, max, description, label, step, group, row, hint, when, hide, slider, unit, unit_default, confirm, visible_by }, not 'tooltip'`. **Cause:** every family lists its options in the message. Plain `param(...)` is the number field and keeps its four keys: it takes any value inside `min`..`max` and the settings dialog labels its row with `description`. The dialog's words (`label`, `step`, `group`, `row`, `hint`, `when`, `hide`, `slider`, `unit`, `unit_default`, `confirm`, and `tz` on a session) belong to the typed settings, `param.int(...)`, `param.bool(...)` and the rest. A tooltip is `hint`, and there is no `constraints` object. A number-field key on a kind that is not a number field is refused by name too: `param.bool 'x' takes no min option (its value is not a number field)`. **Fix:** declare the setting with the kind that takes the option (`param.int("length", 20, { min: 5, max: 500, step: 5 })`), or drop the option. The option list per kind is on [Options on a setting](../settings/options.md), the full grammar in [Declarations and the sheet](../reference/declarations.md#the-declaration-grammar). ## `param 'symbol' uses a reserved name` **Symptom:** `param 'symbol' uses a reserved name (the chart keeps symbol, exchange, interval, transformations, ticksPerBar, currency, runMode, devViewerTier, ... beside script settings, so a param under that name would be read as the chart's own); rename it`, or `param '__style__x' uses the reserved prefix __style__ (the chart's own style rows); rename it`, or `param.range 'band' derives param 'band_lo', which is already declared; rename one`. **Cause:** a setting's name is a key the chart saves beside the overlay's own keys, so the chart's own names and its Style rows' prefix are off limits; a range, list, session, unit menu or `market.*` call also derives names of its own (`band_lo`, `levels_n`, `rth_tz`, `offset_unit`, `market_tick_size`), which another setting cannot take. **Fix:** rename the setting. Every other name is free, `smooth`, `width` and `opacity` included; the reserved list is on [What the build checks](../settings/checks.md). ## `output 'h' color references "@k", which is not a param.color` **Symptom:** `output 'h' color references "@k", which is not a param.color`, `output 'h' color references "@nope", which names no declared param (a param.color)`, `input 'c2' interval references "@k", which is not a param.timeframe`, or `output 'h' binds a param to its colour or line style, but the output is data-only (plot none): there is nothing to paint`. **Cause:** a string that starts with `@` names a setting, and the spot decides the kind: `color` and a `colors` entry take a `param.color`, `line_style` a `param.choice` over `solid`, `dashed`, `dotted`, an input's `interval` a `param.timeframe`, its `symbol` a `param.symbol`. A `none` output draws nothing, so there is nothing for a color to paint. **Fix:** declare the setting with the kind the spot needs and name it after the `@`, or write the literal. ## `duplicate output name 'sma'` **Symptom:** `duplicate output name 'sma'`, `duplicate param name`, `duplicate input name`, `duplicate box name`, or `duplicate render declaration name`. **Cause:** names are unique per family, and shapes share one namespace with outputs (below). **Fix:** rename one of them. ## `expected a string literal` **Symptom:** `expected a string literal`, `expected a numeric literal`, `param.int 'len' default must be a numeric literal, not 'LEN'; write the number, e.g. param.int("len", 14)`, `option 'from' takes an output handle or a bar offset literal, not a string literal`, or `option 'panel' takes "overlay" or "lower" (a string literal), not 'price'`. **Cause:** a name built from a variable, a default or an option computed from an expression or read from a constant (the default's message quotes what it found: `'LEN'`, `'10 * 2'`), a bar offset spelled as a string, or a panel outside the two names. The extractor reads literals only, because the code never runs while it is checked. **Fix:** use literals: `param("period", 20, ...)`, `from: -4`, `panel: "lower"`. A comma after a declaration's last argument is fine (a formatter that wraps the call writes one); a second comma, or an empty argument before the last, is refused. ## `This indicator declares nothing` **Symptom:** `This indicator declares nothing. Add param(...), input(...), and output(...) statements (imported from ./sdk/declare) at the top level of the source; the metadata sheet is derived from them.` **Cause:** the editor builds the sheet from your declarations, and there are none: an empty tab, code with no `param` / `input` / `output` statement and no `onBar()`, or a file with `onBar()` that also exports one of `init`, `state`, `finalize` or `reset` (that one export makes it a file of the four functions, whose declarations need their import lines). A file with `onBar()` and no declaration is told it needs an output instead (below). **Fix:** start from **New indicator** or a template in the editor's Explorer, keep the `//@lang=wrun-ts` line first, and declare what the file reads and writes at the top level. ## `This looks like Pine Script, not an Indicator` **Symptom:** `This looks like Pine Script, not an Indicator.`, on the first line of a paste. **Cause:** the tab holds code from another language. A wrun indicator is TypeScript syntax compiled in your browser. **Fix:** start from a template, keep the `//@lang=wrun-ts` line first, declare `param(...)` / `output(...)` (and an `input(...)` for anything beyond the chart's own candles), and write the bar's work in `function onBar(): void`. ## `code-first declarations need at least one input(...) and one output(...) statement` **Symptom:** `code-first declarations need at least one input(...) and one output(...) statement (found 0 input(s), 1 output(s))`, in a file with the four functions (`init`, `state`, `finalize`, `reset`). **Cause:** such a file has no bar grid to walk without an input, and nothing to compute without an output. A file with `onBar()` needs no input line (the chart's own candles are its grid) and hears the next message instead when it has no output. **Fix:** declare the primary input (`input("close", ohlcv.close)` is the usual one) and at least one output, even a `none`. ## `a file with onBar() needs at least one output(...) statement` **Symptom:** `a file with onBar() needs at least one output(...) statement: declare what the Indicator draws, e.g. output("value", line, overlay), and write it in onBar() with out_value(...)`, on the file's first declaration (or on the `onBar` line when there is none). **Cause:** a file with `onBar()` runs on the chart's own candles without an `input(...)` line, but it still has to declare what it draws: with no `output(...)` there is no row to fill. **Fix:** declare at least one output, even a `none`, and write it in `onBar()` through its `out_<name>()` writer. ## `onBar must be a function with no arguments that returns nothing` **Symptom:** on the hook's own line: `onBar must be a function with no arguments that returns nothing: write function onBar(): void { ... } (the build calls it once per bar)`, or the same for `onStart` (ending `(the build calls it once, before the first bar)`) and `onReset` (ending `(the build calls it when the host resets the run)`). **Cause:** a hook with an argument (`onBar(x: i32)`), a return type other than `void` or none at all (`function onBar() {}`), a type parameter (`onBar<T>()`), or the name `onStart` / `onReset` bound to something that is not a function (`const onReset = 1;`). **Fix:** write the hook exactly as the message shows: a plain top-level function with no arguments and `: void`. An arrow (`const onBar = (): void => {}`) is not seen as a hook at all; the file then counts as one without `onBar()`, and with no import lines its declarations are not read (`This indicator declares nothing`, above). ## `uses the prefix __wrun_lean_, which the build keeps for the functions it adds around onBar()` **Symptom:** on the line of its first use: `'__wrun_lean_x' uses the prefix __wrun_lean_, which the build keeps for the functions it adds around onBar(); rename it`. **Cause:** in a file with `onBar()` the build adds its own functions around yours under that prefix, so a name of yours that starts the same way would collide with them. **Fix:** rename it; any other spelling is free. ## `is already declared with another feed; rename the declared input` **Symptom:** on the line of the first `bar.close()`: `bar.close() reads the chart's own ohlcv.close through an input named 'close', and input 'close' is already declared with another feed; rename the declared input (open, high, low, close, volume and bar_t are the bar's own names)`, or the same for `open`, `high`, `low`, `volume` and `bar_t` (`bar.time()`). **Cause:** `bar.close()` adds an input named `close` on the chart's own close to the sheet (or reuses an `input("close", ohlcv.close)` line with no options), and the file declares an input under that name that reads something else: a pinned market, another interval, a `missing` policy, or another source. **Fix:** rename the declared input (`input("btc", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES" })`) and read it with `in_btc()`. The same name is fine in a file that never reads that field through `bar`. ## `reads the setting 'len' before start-up` **Symptom:** on the line of the read, in a file with `onBar()`: `p_len() reads the setting 'len' before start-up (code at the top of the file runs before any setting is read, so it gets no value): read it in onStart() and keep what you build from it in a module variable`, or the same for a `pb_` or `pt_` reader. **Cause:** code at the top of the file, outside every function, runs when the module starts, before the settings are read, so a reader there gets no value. `const sma = new Sma(i32(p_len()))` at the top builds a one-bar average whatever the setting says. **Fix:** declare the variable with a placeholder and build it in `onStart()`: `let sma = new Sma(14);` at the top, `sma = new Sma(i32(p_len()));` in `function onStart(): void { ... }`. ## `is never read, so changing the setting changes nothing` **Symptom:** a warning, not an error, on the declaration's line: `param.int 'len' is never read, so changing the setting changes nothing: read it with p_len() in onStart(), or remove the declaration` in a file with `onBar()`, and `param 'len' is never read, so changing the setting changes nothing: read it with p_len() where the code needs it, or remove the declaration` in a file of the four functions. The reader it names follows the kind: `pb_<name>()` for a toggle, `pt_<name>()` for text, `fromPacked(p_<name>())` for a colour, the `_lo` and `_hi` pair for a range, the `_start`, `_end` and `_tz` readers for a session. **Run** is not blocked: the indicator builds and runs as written. **Cause:** no reader of the setting appears anywhere in the file, and the chart does not read it by name either (an `"@<name>"` reference on a colour, a line style or a pin, a `when` gate, a section toggle, a strategy or warm-up link, an output's `displacement_bars_by`, a `{{<name>}}` title). The settings dialog shows it and changing it does nothing. The usual case is a rebuild forgotten in `onStart()`: the class is built at a fixed length and the setting never reaches it. A script converted from Pine keeps every input of its original as a setting, so one its code no longer uses stays in the dialog and does nothing. A source, timeframe or symbol setting needs no reader: the chart reads it through the input it binds. **Fix:** read the setting where what it sizes is built, usually in `onStart()`; bind it by name where the chart paints with it; or remove the declaration. A setting you keep on purpose can stay: the warning changes nothing about the run. ## `is read only inside branches ... decides` **Symptom:** a warning, not an error, on the declaration's line: `param 'wait_for_close' is read only inside branches 'timeframe' decides (line 18), so its row changes nothing while 'timeframe' closes them: give it a when naming 'timeframe' ...`. **Run** is not blocked. **Cause:** every read of the setting sits in a branch another setting's test decides: an `if` arm, a `? :` arm, the right side of an `&&` or `||`, or the code after an `if` that returns. While that branch is closed the setting does nothing, and the dialog shows its row live, so a person changes it and sees nothing move. "Wait for close" read only off the chart's own timeframe is the common case. **Fix:** name the deciding setting in the row's `when`, in the form that opens the branch: `when: "timeframe"` (any value but the first), `when: "smoothing=2"` (one option), `when: "!use_absolute"` (the toggle off), `when: "lens in 2,3,4"` (any of several). The dialog then dims the row while the branch is closed ([Options on a setting](../settings/options.md)). ## `history_independent, which is derived by the compiler, never written by hand` **Symptom:** a warning, not an error, when the build reads a sheet that carries the key: `wrun/metadata.json carries history_independent, which is derived by the compiler, never written by hand: the build drops it, and a build that proves it writes it again`. **Run** is not blocked. A sheet that carries `history_warmup` gets the same warning, naming that key. **Cause:** `history_independent` is the compiler's verdict on one compiled module: every bar's outputs depend on that bar's inputs alone, so the chart recomputes only the new bars on a pan-back ([Per-bar scripts](../core-concepts/per-bar-scripts.md) says what the compiler accepts). `history_warmup` is the other answer, for a file whose only memory is finite-window kit classes: a fresh run started W bars early matches the run from the first bar, so the chart recomputes only the new bars after a running start of W bars ([Rolling math that settles within W](../core-concepts/per-bar-scripts.md#rolling-math-that-settles-within-w)). Only the build that proved one writes it, beside `wasm_sha256`. A workspace sheet copied from a built package still carries it. **Fix:** nothing to fix: the build drops the key and writes it again when it proves the module. Remove it from `wrun/metadata.json` to silence the warning. ## `reads the colour setting 'up' as a plain number` **Symptom:** `i32(p_up()) reads the colour setting 'up' as a plain number, which paints the wrong colour: read it with fromPacked(p_up())`. **Cause:** a colour setting arrives packed into one number, the colour with its opacity; `i32()` keeps that number, which is not a colour the kit draws, so every mark painted with it comes out wrong. **Fix:** decode it with `fromPacked(p_up())`, or paint with the setting by name (`color: "@up"` on the output) and read nothing. ## `strategy.<call>(...) needs a top-level strategy({ ... }) declaration` **Symptom:** on the first order call: `strategy.<call>(...) needs a top-level strategy({ ... }) declaration in src/indicator.ts (an empty strategy() enables the channel with the engine's defaults)`. **Cause:** `strategy.long("L").send()` or another order call or getter in a file that never declares `strategy(...)`, so the sheet has no strategy section for the Strategy Tester to run. **Fix:** add `strategy({ ... })` (or an empty `strategy()`) at the top level with the other declarations ([Strategies overview](../strategies/overview.md)). ## `celled input 'profile' needs max_cells` **Symptom:** `celled input 'profile' needs max_cells, e.g. input("profile", volume_profile.cells, { max_cells: 512 }) (guests preallocate from it and the host refuses bigger blocks)`. **Cause:** a celled input (`volume_profile`, `book`, `intrabar`, `trade_volume_by_size`, `options_chain`, `option_strikes`) preallocates its block once, so the cap is part of the declaration. **Fix:** add `max_cells`, sized for the largest block the bar can carry. A block over the cap is refused at run, never truncated (below). ## `input 'btc-close' and 'btc_close' both escape to accessor 'in_btc_close'` **Symptom:** the `declarations` stage says the two names `both escape to accessor 'in_btc_close'; rename one so generated accessors stay unambiguous`. **Cause:** an accessor name is the declared name lowercased with every run of characters outside `[a-z0-9_]` collapsed to `_`. Two names that escape to the same identifier would silently share one accessor. **Fix:** rename one of the two so the escaped forms differ. Prefer snake_case names in the file and the accessors read as written. ## `param names 'fastLen' and 'fastlen' differ only by case` **Symptom:** the `declarations` stage says `param names 'fastLen' and 'fastlen' differ only by case; the build reads names without case (both would be 'fastlen'), so rename one`, on the second declaration's line. Outputs, inputs, string slots, frames, renderers, drawings, levels and panels say the same with their own word; box, segment and alert names keep their spelling, so `Zone` and `zone` are two boxes. **Cause:** names may carry capitals, but the build reads them without case: params, inputs, string slots and frames are stored lowercase, and every accessor is lowercase (`p_fastLen()` and `p_fastlen()` are one reader). Two names that differ only by case would be one setting, or share one accessor. **Fix:** rename one of the two. ## `raw positional slots rebind silently when the sheet changes` **Symptom:** a `lint` row per finding, such as `Raw slot literal 0 passed to getFloat(): raw positional slots rebind silently when the sheet changes: use in_close() from ./gen/inputs in state() or p_period() from ./gen/params in init()`. **Cause:** `getFloat(0)`, `setOutput(0, ...)`, and the raw host imports bind by position and rebind when a declaration is added above them. **Fix:** use the accessor the message names (in a file with `onBar()`, read it there). The raw host calls stay available for variable-index access only. ## `default above max` **Symptom:** a `metadata` row on the param's line: `Param 'period' (default): default above max`, `default below min`, or `min must be <= max`. **Cause:** the derived sheet is checked with the same schema the registry and the runtime use; a default outside its own range fails there. **Fix:** move the default inside the range, or widen the range. ## `an output cannot color itself with color_by` **Symptom:** a `metadata` row on the output's line: `Output 'price' (color_by): an output cannot color itself with color_by`, `color_by 'regime' does not match a declared output`, or `color_by needs 'colors' with at least 2 entries`. **Cause:** `color_by` names a different, declared output (usually a data-only `none`), and `colors` lists at least two entries. **Fix:** declare the decision output and name it; give the palette two or more entries. `width_by` and `widths` follow the same rules (`width_by needs 'widths' beside it (both or neither)`), and `shape_where` cannot gate its own output (`shape_where 'gate' does not match a declared output` when the gate is missing). ## `has a name the sheet refuses` **Symptom:** `Output 'my line' has a name the sheet refuses: use letters, digits, dots, dashes and underscores, starting with a letter or digit (no spaces).` (or the same for a param, an input, or a string slot). **Cause:** declared names become keys of the sheet and the accessors, and a space or a symbol cannot be one. **Fix:** rename it within the rule: `my_line`, `ema.fast`, `rsi-14`. ## `color must be a hex, rgb() or hsl() color (the fill takes the opacity)` **Symptom:** `boxes.0.color: color must be a hex, rgb() or hsl() color (the fill takes the opacity)`. **Cause:** a named color (`"red"`) cannot carry an alpha channel, and the box fill applies the opacity to its color. **Fix:** use `"#ef4444"`, `"rgb(239, 68, 68)"`, or `"hsl(0, 84%, 60%)"`. Segment and output colors are free-form strings; only the box fill has this rule. ## `a literal bar offset must be within -500..500 bars of the current bar` **Symptom:** `segments.0.x_from: a literal bar offset must be within -500..500 bars of the current bar`. **Cause:** a literal offset (whole or fractional) stays within 500 bars of the current bar. **Fix:** stay within the range, or pass an output handle for a longer or data-driven reach: its per-bar value is truncated to the offset, and any offset clamps to the loaded range. ## `boxes must declare at most 16 entries` **Symptom:** `boxes: boxes must declare at most 16 entries` or `segments: segments must declare at most 16 entries`. **Cause:** sixteen of each per indicator. **Fix:** a repeating pattern is one declaration gated per bar, not one declaration per occurrence. The zone tracker draws every zone a side ever has with one box and a `when` gate; for objects that live and move across bars, use a drawing handle ([Drawing objects](../presentation/drawing-objects.md)). ## `box name 'range' is already taken by an output` **Symptom:** `boxes.0.name: box name 'range' is already taken by an output; box and segment names must be unique across outputs, boxes, segments, renderers, and drawings`. **Cause:** one namespace for everything drawn. **Fix:** rename the shape. ## `the primary input (index 0) cannot declare missing: "carry"` **Symptom:** `inputSources.close.missing: the primary input (index 0) cannot declare missing: "carry": its rows define the request grid, so there is no earlier bar to carry a missing one from; remove the policy: an ohlcv primary keeps its own candles and is never densified`. On a sparse primary (liquidations, open interest, funding) the message ends `declare "nan" or "zero" to densify the grid instead`. **Cause:** the first `input(...)` is the grid. **Fix:** give it no `missing` policy (the usual case), or `"zero"` / `"nan"` to densify a sparse primary (a candle primary, `ohlcv` or `odds`, keeps its own candles under either); put `"carry"`, `"zero"`, or `"nan"` on the secondary inputs ([Data sources](../core-concepts/data-sources.md)). ## `source 'ohlcv' has no stream lane to gate` **Symptom:** `inputSources.d.chart_interval_below: wrun_chart_interval_below_needs_candles: source 'ohlcv' has no stream lane to gate; ...`. On the first input the line reads `wrun_chart_interval_below_primary: the primary input (index 0) takes no chart_interval_below: ...`, and beside a live candle `wrun_chart_interval_below_forming: a candles input read with view "forming" takes no chart_interval_below: ...`. **Cause:** `chart_interval_below` gates a stream (`candles`, `oi_candles` or `volume_profile_candles`): the chart fetches it only on a chart finer than the word. Any other input has no stream to skip, the first input is the bar grid itself, and a `view: "forming"` input carries one live candle with no history to spare. **Fix:** put the word on the stream input whose closed candles only fine charts need, `input("h", candles.cells, { interval: "1h", bars: 1488, chart_interval_below: "1h" })`, and drop it everywhere else ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). ## `source 'trades' requires a side (BUY or SELL)` **Symptom:** `inputSources.buy.side: source 'trades' requires a side (BUY or SELL)` or `inputSources.iv.tenor: source 'implied_volatility' requires a tenor (ONE_D, THREE_D, ONE_W, ONE_M, TWO_M, THREE_M, SIX_M, ONE_Y)`. **Cause:** the per-source knobs: `side` on `trades`, `tenor` on `implied_volatility` and `skew`, `fund` on the ETF feeds (`source 'etf_holdings' requires a fund ...`), `publisher` and `series` on `economic`, `token` on `token_supply`. **Fix:** add the knob to the input's options: `input("buy", trades.volume, { side: "BUY" })`. For a tenor, pick one the chart serves: `ONE_W`, `ONE_M`, `TWO_M`, `THREE_M`, or `SIX_M` (`ONE_D`, `THREE_D` and `ONE_Y` are refused when the run starts, below). ## `feed sources pin a fixed market with symbol AND exchange together` **Symptom:** `inputSources.btc.exchange: feed sources pin a fixed market with symbol AND exchange together (never one alone: symbols are venue-native, so a lone symbol or a lone exchange names a market that does not exist on that venue); pin both, or omit both to follow the selector`. **Cause:** a `symbol` without an `exchange`, or the reverse. **Fix:** pin both, spelled the way the venue spells them ([Exchange and symbol format](../reference/symbol-format.md)), or neither to follow the chart. A Polymarket `odds` input is the exception: it pins the condition id in `symbol` alone. ## `max_bytes must be <= 4096 (the per-slot byte cap)` **Symptom:** `String slot 'note' (max_bytes): max_bytes must be <= 4096 (the per-slot byte cap)`, `renderers.0.size: size must be >= 6`, `renderers.0.cells: table 'stats' declares 2x2 = 4 cells but lists 3`, `renderers.0.text: 'note' does not name a declared string slot`, or `renderers.0.y: 'mid' does not name a declared numeric output`. **Cause:** text fields name string slots, numeric fields name outputs, and the two never substitute for each other; text sizes are 6..64 pixels; a table lists exactly `rows * cols` cells; a slot holds at most 4,096 bytes. **Fix:** declare the slot or output the renderer names, and keep the numbers inside the caps ([Drawing objects](../presentation/drawing-objects.md)). ## `Conversion from type 'f64' to 'i32' requires an explicit cast.` **Symptom:** a compiler row with the squiggle under the value, followed by the hint `Numbers convert explicitly in AssemblyScript: wrap the value in i32(), u32() or f64() (a switch needs an integer, an f64 slot needs f64).` A typical line is `function onStart(): void { sma = new Sma(p_period()); }`, with the squiggle under `p_period()`. **Cause:** the file is AssemblyScript, TypeScript syntax over fixed-width numbers. Params and inputs are `f64`; a class period, a loop bound, an array index, or a counter declared as `let count = 0` (an integer) is `i32`, and the compiler refuses to guess. **Fix:** write `i32(p_period())`, put `i32(...)` around any float used as an integer, and declare float variables as `f64` (`let value: f64 = 0.0`). Going the other way, an integer written to an output widens with `f64(count)`: ```typescript param("period", 20, { min: 1, max: 200 }); output("bars_above", line, lower, { description: "Consecutive bars closing above the average" }); let sma = new Sma(20); let streak: i32 = 0; // an integer counter: declare the type, never let it default from a float let above: bool = false; // a truth value: compare to get one, never assign a number function onStart(): void { // Params are f64; a period is i32, so the cast is explicit. sma = new Sma(i32(p_period())); } function onBar(): void { const close = bar.close(); const average = sma.update(close); if (isNaN(average)) return; above = close > average; streak = above ? streak + 1 : 0; // Outputs are f64; an integer goes out through an explicit widening. out_bars_above(f64(streak)); } ``` ## `Conversion from type 'f64' to 'bool' requires an explicit cast.` **Symptom:** the compiler points at an assignment of a number to a `bool`. **Cause:** `ready = value` where `ready` is a `bool` and `value` an `f64`. A number is not a truth value here. **Fix:** compare: `ready = !isNaN(value)`, `above = close > average`. (`if (value)` on a number does compile, as a nonzero test; write the comparison you mean anyway.) ## `Module 'src/gen/outputs' has no exported member 'out_sma'.` **Symptom:** `Cannot find name 'out_sma'.` at every call site, with the hint `out_sma would be generated from a output("sma", ...) declaration; declare it at the top level, or match the name you declared.` In a file with the four functions, which imports its accessors, the import line fails first: `Module 'src/gen/outputs' has no exported member 'out_sma'.` **Cause:** you renamed or removed a declaration and the generated accessor went with it, or the call misspells the name. The accessors are generated from the declarations on every check, so the compiler names every stale call (and every stale import). **Fix:** update the call: `output("average", ...)` is `out_average(...)`, `param("fast_len", ...)` is `p_fast_len()`, `input("btc_close", ...)` is `in_btc_close()`. ## `Cannot find name 'close'.` **Symptom:** `Cannot find name 'close'.` (or `'hl2'`, `'na'`, `'bar_index'`), usually in code carried over from Pine Script. **Cause:** nothing is in scope by name except the kit, the readers and writers generated from your declarations, the bar's own fields through `bar`, and what you declare yourself. The hint says what the name should become: a bar series is the bar's own field (`close` is `bar.close()`, `high` is `bar.high()`; anything else is a declared input read with `in_<name>()`), and a Pine builtin has its own spelling (`na` is `NaN`, tested with `isNaN(x)`; `hl2` is `(bar.high() + bar.low()) / 2.0`; `bar_index` is a counter you increment in `onBar()`). **Fix:** follow the hint. A `Cannot find name` on something that was never an accessor, a series, or a kit class is a plain undeclared variable. ## `this line uses a syntax form the build cannot read yet in a file with onBar()` **Symptom:** `this line uses a syntax form the build cannot read yet in a file with onBar() (syntax node kind <n>); rephrase the line, or write the file with the four exported functions (init, state, finalize, reset), which take every form the compiler does`, on the line in question. **Cause:** a file with `onBar()` is read through the compiler's own syntax tree to find the names it uses, and that line holds a form the reader does not know. Every form the editor's compiler accepts today is known, so the message is not expected on any file; it is the build refusing loudly rather than guessing. **Fix:** rephrase the line (a plain `function`, `let`, `if`, `for`, `switch`, class or arrow is always readable); if it persists, the message names the other way out. ## `finalize() must be declared as finalize() -> void` **Symptom:** in a file with the four functions (`init`, `state`, `finalize`, `reset`), after a clean compile, the `validate` stage refuses the module on your `export function finalize` line: `finalize() must be declared as finalize() -> void (it is () -> f64 here). Write every output through its out_<output>() writer, then call emitRow().` A missing export reads `Missing export reset(): void`, followed by the line to add and what the function does. A file with `onBar()` never meets either: the build writes those four functions around it. **Cause:** a redesigned signature (`init(args: Array<f64>)`, a `finalize` that returns the value) compiles under AssemblyScript and fails the contract check afterwards. The contract is exactly `init(): void`, `state(): i32`, `finalize(): void`, `reset(): void`: no parameters, and no return value except `state`'s ([Execution model](../core-concepts/execution-model.md#the-four-function-form)). **Fix:** keep the four signatures. Values leave through `out_<name>(value)` and `emitRow()`, never as return values; params arrive through `p_<name>()`, never as arguments. ## `console.* is not available in an Indicator` **Symptom:** the `validate` stage refuses `console.log(...)` with `console.* is not available in an Indicator (it runs in a sandbox with no console). Log through the debug output instead: declare string("debug", { max_bytes: 256 }) next to the outputs and call str_debug(text) in finalize(); the lines show in the editor console.` `Date`, `Math.random()`, and `performance.now()` are refused the same way. **Cause:** the sandbox provides no host functions beyond the indicator's own: no console, no clock, no randomness. **Fix:** log through the debug slot the message names, written in `onBar()` ([Debugging](debugging.md)); read bar time from `bar.time()`; derive any variation from the bar data, so a run is reproducible bar for bar. ## `setOutput writes an output straight to the host` **Symptom:** in a file with `onBar()`, the `declarations` stage says `setOutput writes an output straight to the host, and a file with onBar() hands every output to the host once, after onBar() returns, so that row would overwrite it: write the output with out_<name>(...) instead`, on the import line (or the `@external` line of your own declaration over `wrun_output_f64`). **Cause:** each `out_<name>()` keeps its value for the bar, and the row goes to the host in one step after `onBar()` returns. A value written by slot number, around the writers, would be replaced by that row. **Fix:** write every output through its `out_<name>()` writer. A file that needs writes by slot number keeps the four functions. ## `was never written: finalize() must write every declared output before emitRow()` **Symptom:** after a **Run** of a file with the four functions, a `compute` row: `Output 'sma' (#1) was never written: finalize() must write every declared output before emitRow().`, with `Fix: In finalize(), call out_sma(value) for every bar state() returned 1 on, then emitRow().` The sibling row is `finalize() never called emitRow(): the outputs were written but no row reached the chart.` A file with `onBar()` never meets either: every output starts each bar as `NaN`, an unwritten one draws nothing on that bar, and the row is emitted for you. **Cause:** a `finalize()` that skips a writer on some path (an early `return`, an `if` without an `else`), or one that never calls `emitRow()`. **Fix:** write every declared output on every ready bar (write `NaN` to draw nothing), then call `emitRow()` last. ## `AssemblyScript abort` **Symptom:** a `compute` row such as `AssemblyScript abort: Index out of range at ~lib/array.ts:...`, or one anchored on your own line when the abort came from a `throw` in your code. **Cause:** a trap inside the module: an array read past its length, a `throw`, or an explicit `abort()`. The run stops at that bar. **Fix:** guard the index (keep a `count` beside a ring buffer's `cursor`, and scan only what has been filled), and test a condition instead of throwing. For a window of past values, a `History` from `./sdk/stats` does that guarding: `ago(n)` reads `NaN` when fewer than `n + 1` values were pushed or `n` is outside the window ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). ## `The run did not finish within 20 s.` **Symptom:** the run stops, and the overlay's **Could not load** chip carries the sentence with a **Retry**. **Cause:** a `while` or `for` loop that does not end on some bar, or per-bar work that grows with history. A run queued behind another slow one can meet the deadline too, which is why this one stays on the chip instead of a standing Console row. **Fix:** bound every loop by a param with a declared `max`, keep per-bar work constant, and **Retry**. ## `The Indicator allocated memory after init()` **Symptom:** `The Indicator allocated memory after init() (1048576 to 1114112 bytes): the sandbox forbids growth once the bars start.`, with `Fix: Create arrays, strings and objects once in init() and reuse them per bar; a string built per bar (concatenation, toString()) allocates too.` Past the ceiling itself the run stops with `memory ... bytes exceeds limit 4194304 bytes`. **Cause:** memory that grows once the bars start. In a file with `onBar()`, what a bar makes and drops is freed, so the cause is memory you keep: an array pushed onto on every bar, a map that gains a key per bar, more temporaries alive at once than the 256 KiB the build reserves for them (the module sweeps what bars dropped once about 32 KiB of it has piled up, so a bar's temporaries alive at the same moment, plus those 32 KiB, must fit), or a module that held more than 2 MiB before the first bar and left too little room (it gets no scratch). In a file with the four functions, which gets none either, any `new`, array or string made per bar. The memory ceiling is a fixed 4 MiB. (The message's `init()` is the step before the first bar, where `onStart()` runs.) **Fix:** keep what lives across bars bounded and allocate it once, at module start or in `onStart()`, sized from a param's declared `max`: overwrite a `StaticArray` ring instead of pushing. In a file with the four functions, allocate in `init()` and build per-bar text with the allocation-free `sb_*` builder ([Best practices](best-practices.md)). ## `reads min_size from param 'min_size', which holds no finite number > 0` **Symptom:** the run is refused before it fetches: `wrun_tape_min_size_invalid: input 'prints' reads min_size from param 'min_size', which holds no finite number > 0`. **Cause:** the tape input's floor follows a setting, and the setting holds 0, a negative number or no number. **Fix:** set the floor above zero in the settings dialog; a `min` above zero on the setting keeps the dialog from reaching 0 ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). ## `the smallest print value must be finite and above zero` **Symptom:** the run is refused before it fetches: `WRUN <id>: input 'prints' (tape) binds min_value to param 'min_value', which is 0: the smallest print value must be finite and above zero (wrun_tape_min_value_invalid)`, or `declares min_value 0` for a number written in the file. **Cause:** the tape input's dollar floor is 0, a negative number or no number, written in the file or held by the setting it follows. **Fix:** set the dollar floor above zero, in the file or in the settings dialog; a `min` above zero on the setting keeps the dialog from reaching 0 ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). ## `the smallest print in coins must be finite and above zero` **Symptom:** the run is refused before it fetches: `WRUN <id>: input 'tape_coins' (tape) binds min_coins to param 'min_coins', which is 0: the smallest print in coins must be finite and above zero (wrun_tape_min_coins_invalid)`, or `declares min_coins 0` for a number written in the file. **Cause:** the tape input's coin floor is 0, a negative number or no number, written in the file or held by the setting it follows. **Fix:** set the coin floor above zero, in the file or in the settings dialog; a `min` above zero on the setting keeps the dialog from reaching 0 ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). ## `holds no price for the window it reads, so the floor cannot be priced in dollars` **Symptom:** a coin-floored tape is refused: `wrun_tape_coins_unpriced: input 'tape_coins' (tape) floors by coins (min_coins), and the chart's browser lane holds no price for the window it reads, so the floor cannot be priced in dollars`. **Cause:** the host asks a `min_coins` tape in dollars at the window's lowest price, and it holds no candle with a price for that window. **Fix:** load the chart's candles over the window, or floor the tape by `min_value` ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). ## `a tape takes exactly one floor, min_size (the raw stored unit), min_value (US dollars) or min_coins (coins, on a market that counts coins)` **Symptom:** the build's sheet check, or the run before it fetches: `WRUN <id>: input 'prints' (tape) declares both min_size and min_value (wrun_tape_floor_invalid): a tape takes exactly one floor, min_size (the raw stored unit), min_value (US dollars) or min_coins (coins, on a market that counts coins)`, or the same with `declares no floor`. **Cause:** the tape input declares more than one floor, or none. The floors read different units, so a tape takes one. **Fix:** keep one: `min_value` to floor by dollars (the same meaning on every market), `min_size` to floor by the size the venue stores, or `min_coins` to floor by coins on coin markets ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). ## `a min_coins tape is read on markets that count coins alone` **Symptom:** the build refuses `input 'tape_coins' floors by min_coins, which is read on markets that count coins alone: declare needed_by: { size_unit: [1] } (1 coins), and beside it at most the param.choice that picks the coin floor`. **Cause:** the coin floor floors coins, so the tape must name coin markets alone. **Fix:** add `needed_by: { size_unit: [1] }` to the tape, with the choice that picks it beside `size_unit` if one does ([Size units](../settings/sessions-and-units.md#the-dialog-and-the-lanes)). ## `the browser lane serves market pins on secondary ohlcv inputs only` **Symptom:** before anything is fetched: `Input 'funding_btc' (funding) pins the market 'BINANCE_FUTURES/BTCUSDT': the browser lane serves market pins on secondary ohlcv inputs only (typed feeds, cells and time follow the chart's own market)`, or `... on the primary input (index 0): the primary input follows the chart's market; market pins are served on secondary inputs only`. **Cause:** a market pin on a source other than a secondary `ohlcv` input, or on the first input. **Fix:** pin another market's candles only, on a secondary input; everything else follows the chart's market ([Multi-source](../core-concepts/multi-source.md)). ## `the browser lane serves interval pins coarser than the chart only` **Symptom:** before anything is fetched: `Input 'close_1m' pins interval '1m', finer than the chart's: the browser lane serves interval pins coarser than the chart only`. Its siblings: `not a whole multiple of the chart's interval: a pinned leg must be a whole number of chart bars`, `the browser lane serves interval pins on secondary ohlcv inputs and the funding and oi feeds only`, and `the primary input follows the chart's interval; interval pins are served on secondary inputs only`. Two view mistakes stop earlier, at the sheet check: `view "confirmed" needs an interval pin`, and `view "forming" folds rolling buckets up to WEEK`. **Cause:** the chart serves a pinned interval only when it is coarser than the chart's and divides into whole chart bars, and only on those sources; a view reads a pinned leg, so it needs one. **Fix:** pin a coarser interval that is a whole multiple of the chart's (a `4h` pin on a `1h` chart, `DAY` on `4h`), or change the chart's interval ([Multi-timeframe](../core-concepts/multi-timeframe.md)). ## `pins the template's placeholder market` **Symptom:** a prediction-market starter refuses: `Input 'yes' (odds) pins the template's placeholder market (wrun_odds_placeholder_market): paste the market's condition id (0x…) into the input's symbol and Run again`. The other odds refusals: `binds its market per use ... the chart has no market picker yet; pin the market's condition id (0x…) in the input's symbol` and, on a 1s chart, `prediction markets are served on MINUTE and coarser charts`; the sheet check refuses a slug (`odds sources are keyed by the Polymarket conditionId (0x + 64 hex), not the market slug`) and an exchange (`exchange is implicit (POLYMARKET) for odds sources`). **Cause:** an `odds` input names its Polymarket market by condition id in `symbol`; the templates ship a placeholder, and the chart has no picker. **Fix:** paste the market's condition id into the input's `symbol`, drop any `exchange` or `binding`, and **Run** on a one-minute chart or coarser. ## `max_cells is 4, so the evaluation is refused (a block is never truncated)` **Symptom:** the run stops: `input 1 bar at ts ... has 5 cells; max_cells is 4, so the evaluation is refused (a block is never truncated)`. **Cause:** `max_cells` is a contract, not a hint: the module preallocates that many tuples, and a bar whose block is larger would overflow it. **Fix:** raise `max_cells` on the input (`input("profile", volume_profile.cells, { max_cells: 8192 })`) and **Run** again. Nothing is ever truncated on your behalf. On a volume profile the indicator can do without for a bar, `missing: "empty"` reads such a bar as an empty block instead of stopping the run. ## "Drawings capped" on the legend row **Symptom:** the run draws, but the indicator's legend row says "Drawings capped" and its card reads, for example, "2,000 of 2,350 drawings": the chart drew the newest 2,000 and left the oldest out. **Cause:** a segment or box drawn on every bar of a long window, or handles that are created and never deleted. **Fix:** gate the shape with `when` so it draws only where it means something, delete handles you no longer need, or narrow the span. The chart never refuses the run for this; the 2,000 that show are the newest. ## `render result exceeds 8388608 bytes expanded` **Symptom:** a run refuses because the expanded render selection (every selected text mark, label, table cell, shape, and drawing) passed 8 MiB: `render result exceeds 8388608 bytes expanded (wrun_render_result_too_large): fewer rows, shorter strings, or fewer renderers/drawings`. **Cause:** a per-bar text renderer over a long history, or a large table rewritten on every bar. **Fix:** write the slot only on the bars that need a mark (an unwritten slot draws nothing), or move the readout to `render.label`, which keeps one label. The string caps refuse the same way, never truncating: `string slot 0 write of 300 bytes exceeds the slot's max_bytes 256` (raise the declaration's `max_bytes`, up to 4,096), `over the per-row limit 65536; emit less text per bar`, and `over the per-run limit 2097152; emit less text or fewer rows` (text and frames together, a live session counting as one run). ## `data is unavailable for '...', so the indicator cannot compute.` **Symptom:** a toast such as `Volume profile data is unavailable for 'My VP' (the volume_profile source lane answered empty or was declined), so the indicator cannot compute.`, or `Pinned market candle (BINANCE_FUTURES/BTCUSDTT) data is unavailable for ...` for a pin. **Cause:** the chart asked for a source it needs and got nothing back: a market the venue does not serve that source for, or a misspelled pin. **Fix:** switch to a market that serves the source, or correct the pin's spelling ([Exchange and symbol format](../reference/symbol-format.md)). ## Other messages from a run - **`funding field 'rate_open' is not served by the browser lane`**: the chart serves `funding.rate_close` only, as a percent normalized to a one-hour interval. - **A tenor the chart does not serve** (`ONE_D`, `THREE_D` or `ONE_Y` on `implied_volatility` or `skew`): the run is refused naming the tenor. The chart serves five, `ONE_W`, `ONE_M`, `TWO_M`, `THREE_M` and `SIX_M`, from the coin's Deribit summaries. - **A feed the chart in front of you cannot have**: `options_oi`, `options_volume` and `ethena_positions` need a BTC or ETH chart, `long_short_ratio` a chart of 5 minutes or coarser, `token_supply` a chart coarser than one minute and a token the chart lists, `economic` a publisher the chart knows, a pinned `options_chain` venue a coin that venue lists. Each is refused before anything is fetched, with a message naming the input and the reason. - **`Input 'flow' (etf_flow) needs a chart of a coin with listed spot ETFs (BTC, ETH, SOL)`** and **`Input 'flow' (etf_flow) pins fund 'IBIT', not one of the ETH spot ETFs (...)`**: the class follows the chart's coin; open a BTC, ETH, or SOL chart, or declare one of that coin's funds (the message lists them) or `all`. - **`input 'es' pins exchange CME: wrun_pin_venue_refused: CME is CME Group market data and cannot be read from another market's script`**: a CME Group venue (`CME`, `CBOT`, `NYMEX`, `COMEX`, `GLOBEX`) cannot be pinned; pin an ETF on the same market (`SPY/USD` on `POLYGON`) or leave the input out. - **`input 'spy' pins symbol "SPY/USD + CME|ES1!": wrun_pin_symbol_literal: ...`**: a pin names one market; give each market its own input. - **`Input 'spx' pins SPX on POLYGON_INDICES; index series (SPX, NDX, VIX, DJI) are not served yet: ...`**: a warning, not a failure. The input reads its missing fill (`NaN`) on every bar; pin an ETF instead (`SPY/USD`, `QQQ/USD`). - **`Input 'spy' pins interval '3d' on POLYGON/SPY/USD: a multi-day candle on a session venue groups trading days ...`**: a `3d` candle on a stock, forex or gold market would close too early; pin `1d` or `1w` ([Stocks, forex and gold](../core-concepts/multi-source.md#stocks-forex-and-gold)). - **`Nothing was drawn`** and **`is NaN on all ... ready bars`**: see [Ran but blank](#ran-but-blank). ## Messages from the chart - **Indicator checks are unavailable:** (a warning row) and **Run failed before it started:**: the browser could not load the compiler (an offline tab, a blocked worker). Reload; nothing in the file is wrong. - **Publish is available once the Indicator has no errors**: clear the Console's errors first; Publish unlocks once the code builds cleanly. - **The publish window was blocked. Allow popups for this site and try again.**, **OpenMarket did not answer in time. Try again.**, and **Publish failed:** followed by the registry's reason (a version that already exists, for one): the publish itself, not your file ([Publishing](../functions/publishing.md)). - **Where this Indicator runs was fixed by its first version: keep the same sharing choice.**: a later version cannot switch between the browser choices (Compiled, Open source) and Protected. Publish under a new name to move it. - **The source is 300 KB; the limit is 256 KB.**: Open source code is capped at 256 KB; publish the code Compiled (readers get a compiled module, never the source), or trim it. - **CME market data terms are required** and **Accept the CME market data terms to run your own scripts on CME markets.**: on a CME market your own scripts read CME data once you accept the terms; **Accept the terms** on the banner opens them. Keep editing, or switch the chart to a non-CME market. - **Cloud runs aren't available on CME markets. Choose Browser under Run on to run this script here.**: on a CME market an indicator runs in the browser; choose **Browser** under **Run on**. - **Strategy testing isn't available on CME markets. Switch to a non-CME symbol to test this strategy.**: backtests do not run on CME markets; switch the chart to test the strategy. - **CME study results are available only within the entitled chart.**: a console copy on a CME chart carries the code and the diagnostics but leaves out the values the indicator printed. - **Indicators you write or add from the community read a CME option chain on a CME futures chart only.**: the indicator names a CME root through `underlying` (`"ES"`) on a chart that is not a CME future, such as a stock, a coin or an index. Open a CME futures chart to read it: there `underlying` reads another CME root's chain too (the ES chain on an NQ chart). - **Publish first**, **Publish the current version first**, and **Runs in the browser. Only a Protected Indicator runs in the cloud.**: the editor's **Run on** menu runs in the cloud only for a published Protected indicator whose published version matches your code. - **The console does not run strategy Indicators; Run the tab and inspect its outputs.** and **This Indicator reads ...; the console runs over the chart's candles only.**: the Console prompt compiles expressions over the chart's candles only. **Run** the tab, then read outputs by name at the prompt ([Debugging](debugging.md)). - **Publish the Indicator before adding an alert.**: an alert needs a published version. Publish, then add the alert on the published indicator ([Alerts](../functions/alerts.md)). - **This Indicator is pinned to a different interval than the chart.** and **This Indicator reads a data source alerts cannot evaluate yet.**: OpenMarket's alerts engine reads another market's candles and a coarser pin that is a whole multiple of the chart's interval, over at most 600 bars, but not every pin or feed. A pin on the first input, a finer pin, a custom timeframe, a `forming` view too long for those 600 bars, or a feed alerts do not read keeps its alerts off ([Alerts](../functions/alerts.md)). - **This Indicator reads a market alerts cannot evaluate yet (an index).** and **Indicator alerts are not allowed on this venue.**: an alert evaluates pinned stock, forex and gold candles, but not an index pin or a CME Group market ([Alerts](../functions/alerts.md)). - **This Indicator was built for a runtime version alerts do not support. Rebuild and publish it again.**: the message is the fix. - **Indicator alerts are not enabled yet.** and **Only price alerts are available on CME markets right now.**: alerts on wrun indicators are switched off there. ## Ran but blank An indicator that builds cleanly and draws nothing has no error to show, only a symptom. For a draft, the Console turns the commonest into a warning after a **Run**: `Output 'sma' is NaN on all 480 ready bars, so nothing is drawn for it.` (A file with the four functions can also hear `Nothing was drawn: state() returned 0 on all 500 bars, so every bar counted as warm-up.`) | Symptom | What is happening | Fix | | --- | --- | --- | | nothing on any bar | every output is `NaN` on every bar: a class whose period exceeds the loaded history, or a guard that sends `onBar()` back before it writes | load more history; read the guard at the Console prompt, or log it ([Debugging](debugging.md)) | | a line is empty on every bar | the output is `NaN` on every bar (written so, or never written), or it is declared `none` | find the first `NaN` input; change the plot kind | | a line stops partway | a value that went `NaN` mid-history: a division by zero, a `missing: "nan"` secondary with no more observations | guard the division; choose `"zero"` or `"carry"` | | very few marks | a `shape` gate that rarely fires | usually intentional; lower the threshold to check the gate works | | a pinned input is empty | an index pin, or no candle closed yet | pin an ETF (`SPY/USD`); check for `NaN` | | the newest bar moves, older ones hold | the forming bar re-evaluates as live updates arrive, at most about once a second | expected: a bar's value settles when the bar closes | The workflow that turns a symptom into the line that causes it is in [Debugging](debugging.md). <!-- source: https://openmarket.xyz/wrun/faq/debugging --> # Debugging A practical workflow for finding out why a wrun indicator is wrong: make visible what you cannot see, read the Console, isolate one output, read the numbers at the Console prompt, then check the usual suspects. Work it in order. Your indicator compiles and runs but the signal is wrong, or it draws nothing, or a line is mysteriously flat. There is no `console.log` (the module runs in a sandbox with no console), but there is a debug log that prints in the editor's Console, a prompt that reads the last run's numbers, and one fact that makes indicators easy to debug: every value the module computes can be an output. ## 1. Emit what you cannot see The fastest debugger is an output or a log line. You cannot step through the bar loop, but you can make any intermediate value visible on every bar. Three forms: - **A `lower` line** shows the shape of a value over every bar. Seeing it usually tells you immediately whether it is doing what you think: pinned at zero, flatlining, a spike where there should be none. - **A `none` output** is a probe: computed and written every bar, never drawn, and readable by name at the Console prompt (step 4). It keeps the picture clean while you check a number. - **The debug log** prints text: a string slot named `debug`, written in `onBar()`, prints each bar's line in the editor's Console. ```typescript param("len", 14, { min: 2, max: 200 }); // The value under suspicion, drawn in its own pane so its shape is visible on every bar. output("range_pct", line, lower, { unit: "%", color: "#ef4444", description: "high minus low as a percent of close" }); output("smooth", line, lower, { unit: "%", color: "#f59e0b", description: "EMA of the range" }); // A probe: computed every bar and readable at the Console prompt, never drawn. Delete it when done. output("raw_spread", none, lower, { description: "debug: high minus low before the percent" }); let ema = new Ema(14); function onStart(): void { ema = new Ema(i32(p_len())); } function onBar(): void { const close = bar.close(); const spread = bar.high() - bar.low(); const rangePct = close > 0.0 ? (spread / close) * 100.0 : NaN; if (isNaN(rangePct)) return; out_range_pct(rangePct); out_smooth(ema.update(rangePct)); out_raw_spread(spread); } ``` The debug log is the indicator's `print()`. Declare `string("debug", { max_bytes })`, build a line with the allocation-free `sb_*` builder, and send it with `str_debug_sb()` (or send a finished string with `str_debug(text)`). Write it only on the bars worth reading: a bar that writes nothing prints nothing. ```typescript param("len", 20, { min: 2, max: 200, description: "Bars in the volume average" }); input("volume", ohlcv.volume); output("ratio", line, lower, { description: "Volume over its average" }); // The debug log: a string slot named exactly debug. Each non-empty line prints in the editor's Console. string("debug", { max_bytes: 128 }); let average = new Sma(20); function onStart(): void { average = new Sma(i32(p_len())); } function onBar(): void { const volume = bar.volume(); const mean = average.update(volume); if (isNaN(mean) || mean <= 0.0) return; const ratio = volume / mean; out_ratio(ratio); // Log only the bars worth reading. The builder allocates nothing, so logging never grows memory. if (ratio > 3.0) { sb_clear(); sb_text("spike ratio="); sb_f64(ratio, 2); sb_text(" volume="); sb_f64(volume, 0); str_debug_sb(); } } ``` After a **Run**, the Console prints one line per bar whose slot is not empty, oldest bar first, after the bar's time in ISO 8601 UTC: ```text 2026-09-30T14:00:00.000Z spike ratio=3.41 volume=1824 2026-09-30T19:00:00.000Z spike ratio=4.07 volume=2210 ``` Every run rebuilds the lines, so they always belong to the run on screen, and the Console keeps the newest 400 ("… N earlier print lines truncated to keep the console fast"). The lines print before the chart draws, so they are there even when drawing fails. Build the text with `sb_*`, not with `+` or `toString()`: text built that way allocates on every bar, and memory that grows once the bars start stops the run. When you need the exact number on the chart rather than in the Console, a string slot and a `render.label` print it on the newest bar. It switches the file to the second runtime contract, which **Run** derives for you: ```typescript output("range_pct", line, lower, { unit: "%", color: "#ef4444" }); output("tag_x", none, lower, { description: "This bar's open time, the label's x" }); string("readout", { max_bytes: 32 }); // One label, on the newest bar that wrote the slot: the exact number, read off the chart. render.label("range_readout", { x: "tag_x", y: "range_pct", text: "readout", color: "#f59e0b", size: 12 }); function onBar(): void { const close = bar.close(); const rangePct = close > 0.0 ? ((bar.high() - bar.low()) / close) * 100.0 : NaN; if (isNaN(rangePct)) return; out_range_pct(rangePct); out_tag_x(bar.time()); sb_clear(); sb_text("range% = "); sb_f64(rangePct, 2); str_readout_sb(); } ``` This works for any expression. Lift the part you doubt into a variable, declare an output or a log line for it, and read the answer instead of guessing. Delete the probe and the log when you are done: whoever adds a published indicator gets everything it declares. ## 2. Read the Console If **Run** stops before the chart changes, the message is in the editor's Console, tagged with the stage that produced it, and one problem hides the ones behind it. The status bar's problem counter (its tooltip reads **Open Problems**) opens the Console, and clicking a row jumps to its line: | Stage | What it checked | Typical message | | --- | --- | --- | | `declarations` | the `param` / `input` / `output` / shape statements, read from the text | `option 'top' takes an output handle, not a string literal` | | `lint` | raw positional slot literals in your source | `Raw slot literal 0 passed to getFloat(): raw positional slots rebind silently when the sheet changes` | | `metadata` | the sheet derived from your declarations, against the schema | `Output 'price' (color_by): color_by needs 'colors' with at least 2 entries` | | `compile` | the AssemblyScript compiler, with a hint | `Conversion from type 'f64' to 'i32' requires an explicit cast.` | | `validate` | the built module's exports and the sandbox | `console.* is not available in an Indicator (it runs in a sandbox with no console).` | | `compute` | the run itself, after **Run** | `AssemblyScript abort: Index out of range at ~lib/array.ts:...` | Fix the first one and **Run** again. Every message is listed with its fix in [Common errors](common-errors.md). A run that reaches the chart and draws nothing is usually not an error at all. It is an output that is `NaN` on every bar (`onBar()` returned before writing it, or wrote `NaN`), an output declared `none`, or a source the chart's market does not serve (the chart says which, by name). For a draft, the Console says which after the run: `Output 'range_pct' is NaN on all 480 ready bars, so nothing is drawn for it.` Step 5 covers the rest. ## 3. Isolate When several outputs are wrong at once, stop reasoning about all of them. Reduce the module to one output: leave the others unwritten in `onBar()` (an unwritten output is `NaN`, and `NaN` draws nothing), or switch their plot to `none`, and keep only the suspect series drawn. Once that one is correct, bring the others back one at a time. This is the cheapest way to find which input poisoned a calculation downstream, because a wrong value in an indicator has exactly one place it can come from: the bar's inputs, the state carried from the previous bar, or the arithmetic between them. ## 4. Read the numbers at the Console prompt The chart shows shapes; the Console prompt shows numbers. After a **Run**, type at the prompt ("Type an expression, an output name, or / for commands") to read the last run without compiling anything: ```text range_pct the newest value range_pct[-3] the value three bars back last 20 raw_spread the newest 20 bars (a none output reads like any other) at 2026-01-01T00:00Z range_pct the value on the bar that opened at that time rows the bar count, the first and last bar, the warm-up rows params each param and the value the last run used outputs every output and its last value sheet the sheet derived from your declarations ``` A range reads over the ready bars; warm-up rows are left out. Anything else you type is an expression: it compiles into the current source, runs once per ready bar after your own code for the bar, over the chart's candles, and leaves the overlay alone, so your module-level variables and the kit are in scope. Expressions run over candles only: a strategy indicator, or one that reads another source, is refused ("The console does not run strategy Indicators; Run the tab and inspect its outputs."), and its outputs stay readable by name after a **Run**. `/help` lists the grammar, and `/clear` empties the Console. ## 5. The usual suspects Most "wrong indicator" bugs are one of a handful of patterns. Scan this list against your symptom: - **Line starts blank, then appears.** Warm-up. Anything with a period is `NaN` until it has enough bars, and a `NaN` output draws nothing on those bars. That leading gap is expected; if the line never appears, the chart has fewer bars loaded than the window needs. - **Flat line.** A module-level variable assigned in `onStart()` and never updated in `onBar()`, or an output written from a different variable than the one the bar updates. Log the value per bar and check that it moves. - **Everything is NaN.** A secondary input under `missing: "nan"` on bars without an observation, an arithmetic chain fed by one `NaN` input, or a division by zero. Probe each input as a `none` output and find the first `NaN`. - **Wrong pane.** A percent or a count drawn `overlay` hugs the price axis floor. Declare it `lower`. - **A mark on every bar.** A `shape` output without `shape_where`. Add the gate output. - **The newest bar jumps around.** It is still forming: the chart re-evaluates it as live updates arrive, at most about once a second, starting each time from the module's state as it stood after the last closed bar. A bar's value settles when the bar closes. - **Nothing at all, no error.** `onBar()` never reaches a write (a class whose period exceeds the loaded history), the only rendered output is declared `none`, or the chart's market does not serve the source (the chart names it, for example `celled source class 'tape' is not served by the browser lane yet`, or `Volume profile data is unavailable for ...`). - **A pinned input reads `NaN` everywhere.** An index pin (`POLYGON_INDICES`) reads `NaN`, and the legend says why; any pin reads `NaN` until its first candle closes. A misspelled pin is refused instead: `Pinned market candle (...) data is unavailable for ...` ([Exchange and symbol format](../reference/symbol-format.md)). - **An alert does not match the chart.** An alert runs the published version and the settings of the overlay it was set on, in OpenMarket's cloud, on the chart's own market; the draft in your editor is not what it evaluates. Publish the change, add the new version to the chart, and set the alert on it. A declared `alert(...)` fires on the bar its `when` output turns from zero to nonzero, so a gate that stays at `1` fires once ([Alerts](../functions/alerts.md)). Walk these top to bottom. The fix for each is one line, and the probe from step 1 usually tells you which one you are looking at. ## See also - [Common errors](common-errors.md) for every build and runtime message with its fix. - [Execution model](../core-concepts/execution-model.md) for warm-up, the forming bar, and where an indicator runs. - [Repainting](../core-concepts/repainting.md) for what can change on the forming bar and what cannot. - [Alerts](../functions/alerts.md) for what an alert on an indicator evaluates. <!-- source: https://openmarket.xyz/wrun/strategies/overview --> # Strategies overview A strategy is a wrun indicator that places orders. The file declares `strategy({ ... })` beside its outputs and calls `strategy.long`, `strategy.exit`, `strategy.closeAll` and the position getters inside `onBar()`; the chart's Strategy Tester runs it with the engine's own broker, and its trade list, equity curve and stats come out the same wherever it runs. This page is the map: what a strategy file is, what the Strategy Tester shows, the guarantees, and what each page in this section covers. ## What a strategy file is The smallest useful one: long when the fast EMA crosses above the slow one, flat when it crosses back under. ```typescript // Moving average cross as a strategy: long when the fast EMA crosses above the slow one, flat when it crosses back under. strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: 50, commissionPercent: 0.05, slippageBps: 2 }); output("fast", line, overlay, { description: "9-period EMA of close" }); output("slow", line, overlay, { description: "21-period EMA of close" }); const fastEma = new Ema(9); const slowEma = new Ema(21); const cross = new Cross(); function onBar(): void { const fast = fastEma.update(bar.close()); const slow = slowEma.update(bar.close()); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); if (crossed == 1) strategy.long("L").send(); if (crossed == -1) strategy.closeAll(); out_fast(fast); out_slow(slow); } ``` To try it, open the editor from the chart toolbar's **Editor** button, press **New indicator** in the Explorer, keep the `//@lang=wrun-ts` line at the top of the draft and replace the starter under it with this file, then press **Backtest**. A fuller version of this file is a starter in the editor's template picker: the Explorer's **Templates** icon ("Browse starter templates") lists it as **Moving-Average Cross** under **Strategies** (`strategy-ma-cross`), with `Sma` in place of `Ema`, a ribbon between the averages and a mark on each cross ([Moving-average cross](../cookbook/strategy-ma-cross.md)), commented throughout. Three things make it a strategy rather than an indicator: - `strategy({ ... })` at the top level is the broker: starting equity, sizing (`50%` of equity per entry), commission and slippage live in the file, so a published strategy carries its own assumptions. Every field is optional; a bare `strategy()` takes every default. Run derives a `strategy` section into the sheet, and that section is what makes the file a strategy: once it builds, the editor's toolbar shows a **Strategy** badge and the **Run** button reads **Backtest**. - `strategy.long("L").send()` in `onBar()` queues a market order under the id `L`. An order placed on a bar fills no earlier than the next bar's open; nothing in a run can act on information it did not have. - `strategy.closeAll()` is the signal exit. Orders and the position getters (`strategy.positionSize()` and the rest) both go in `onBar()`; a getter reads the position after the bar's fills. The outputs stay outputs: `fast` and `slow` draw on the chart like any indicator's, and once the strategy is published they can carry alerts. A strategy adds four alert choices of its own, "Strategy order placed", "Strategy trade opened or closed", "Strategy position" and "Strategy equity" ([Alerts](../functions/alerts.md)), which is why `strategy.position` and `strategy.equity` are reserved: an output with either name is refused by name. ## What the Strategy Tester shows The file compiles in your browser, and **Backtest** puts the draft on the chart's price pane, where its trade markers land; a drawn output on `lower` gets a pane of its own below. The Strategy Tester docks under the chart with the engine's own result: a **trades list** (entries, exits, per-trade PnL, fees, exit reason), an **equity curve** with its drawdown, **performance stats** (net profit, win rate, profit factor, Sharpe, Sortino, max drawdown, exposure and the rest), and the **open trades and pending orders** as of the last bar, with a marker on the price series for every fill. [Reading the Strategy Tester](reading-the-tester.md) walks the panel. The broker fills every order against the chart's own candles, which is why a strategy's price input reads the chart's `ohlcv` and carries no symbol or exchange pin (any other primary input is refused by name). The run covers the candles the chart has loaded and recomputes as you pan, so panning back tests more history. ## Core guarantees - **Deterministic.** The same file over the same bars produces the same trades wherever it runs: the broker is the engine's own code, pinned to one engine version, run under the engine's own phase order. - **Lookahead-free.** Orders placed while bar N computes fill no earlier than bar N+1's open. The position a guard reads in `onBar()` is the position after that bar's fills, so a flat guard is already flat on the bar its exit filled. - **Honest accounting.** A bar that could have filled two levels settles by the declared `fillModel` and counts in `ambiguousFillCount` (the Tester's **Model-settled fills**); rejected orders (the pyramiding cap, a size the equity cannot fund, an order placed on a live chart's forming bar) are counted, never dropped. The chart attaches no finer-interval data, no order book and no funding data to a strategy run, and the Tester's **Run details** say so: "Fill precision: bar resolution" once the fill model has settled a fill, and "Funding data did not cover N bars" on a perps run that held a position under `funding: "data"`. ## What the broker is, and is not A research tool: fast iteration and honest reporting over bar closes. It settles orders at the next open, resting limits and stops when touched, protective exits under the fill model, isolated margin, liquidation and maker or taker fees on perps. It does not model queue position, partial fills at a level, replenishment, latency, or venue fees beyond the declared commission or maker and taker rates, and on the chart it does not walk finer bars, price fills off a recorded book (`slippageModel: "bookEstimate"` is refused by name) or settle recorded funding (`funding: "data"` counts the bars it could not settle). Each is disclosed by name rather than approximated. ## Section contents - [Build your first strategy](first-strategy.md): an RSI reversion from a sentence to a read result, tuned honestly, then published. - [Writing strategies](writing-strategies.md): the declaration table, the order API, the position and sizing model. - [Fill simulation](fill-simulation.md), [Slippage and costs](slippage-and-costs.md): the phase order, fill prices and fill models; commission, flat slippage, maker and taker rates. - [Perps: margin, liquidation, funding](perps.md): the leveraged model, its formulas and its counters. - [Reading the Strategy Tester](reading-the-tester.md), [Stats reference](stats-reference.md): the panel and every stat. - [Examples](examples.md): the five perps scenarios and a Hyperliquid perp walkthrough, complete files to start from. <!-- source: https://openmarket.xyz/wrun/strategies/first-strategy --> # Build your first strategy One idea taken from a sentence to a backtest you can evaluate honestly: write the strategy as one wrun indicator file in the chart's editor, backtest it, read every part of the Strategy Tester, then tune it like you mean it. It is the strategy sibling of the first indicator primer. ## 1. The idea, in one sentence "When RSI leaves oversold, buy the dip with a quarter of my equity; take the trade off when momentum recovers; protect it with a stop 4% below." ## 2. Write it Open the editor from the chart toolbar's **Editor** button. In the Explorer, press **New indicator**: the draft opens with a moving-average starter under a `//@lang=wrun-ts` line, the marker that makes the tab a wrun indicator. Keep that line and replace everything under it with this file: ```typescript // RSI reversion with a protective stop: buy the dip on the bar RSI crosses up through oversold, protect it 4% under the close, leave on recovery. strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: 25, commissionPercent: 0.05, slippageBps: 2 }); param("period", 14, { min: 2, max: 200, description: "RSI length in bars" }); output("rsi", line, lower, { description: "Wilder RSI of close, 0 to 100" }); let rsi = new Rsi(14); const dip = new Cross(); const recovery = new Cross(); function onStart(): void { rsi = new Rsi(i32(p_period())); } function onBar(): void { const close = bar.close(); const value = rsi.update(close); if (isNaN(value)) return; const dipped = dip.update(value, 30.0); const recovered = recovery.update(value, 55.0); if (dipped == 1) strategy.long("Dip").send(); if (strategy.positionSize() > 0) strategy.exit("Protect").from("Dip").stop(close * 0.96).send(); if (recovered == 1) strategy.closeAll(); out_rsi(value); } ``` Reading it top to bottom: - `strategy({ ... })` is the broker. Starting equity, sizing (`25%` of equity per entry), commission and slippage live here, so a published strategy carries its own assumptions. It takes the engine's own setting names; every field is optional. - `Cross.update(a, b)` returns `1` on the bar `a` crosses above `b`, so `dipped == 1` is the bar RSI crosses up through oversold. Returning early from `onBar()` while RSI warms up keeps those bars off the chart and out of the broker's reach: a bar that returns before the order calls places nothing, and its unwritten `rsi` is NaN, which is not drawn. - `strategy.long("Dip").send()` queues a market order under the id `Dip`. It fills at the next bar's open, never earlier. - `strategy.exit("Protect").from("Dip").stop(close * 0.96).send()` arms a protective stop against the named entry, re-placed every bar the position is held, at 4% under that bar's close. `strategy.positionSize()` reads the position after the bar's fills, so the guard is already flat on the bar the stop filled. - `strategy.closeAll()` is the signal exit for the recovery case. Order calls and the getters both belong in `onBar()`. ## 3. Backtest it The editor compiles the file in your browser as you type, and each build derives the sheet from it (the two declarations, the `close` input the file reads through `bar.close()`, and the strategy section). Once the file builds, the toolbar shows a **Strategy** badge and the **Run** button reads **Backtest**. Press it: the draft goes on the chart's price pane, RSI gets a pane of its own below, and the Strategy Tester docks under the chart. The Tester runs the file in your browser over the candles the chart has loaded, lets the broker fill every order against those candles, and recomputes as you pan, so panning back tests more history. A problem in the file stops the build instead, and prints in the editor's **Console** with the stage it came from. ## 4. Read the result critically Four places to look, in order: 1. **Run details.** The info icon in the Tester's header opens "Run details": the chart's interval, the depth ("Follows chart (recomputes as you pan)"), the bars the run covered, the declared fill model and the compute time, then a precision line: "Fill precision: exact" when no bar had to be settled by the fill model, "Fill precision: bar resolution" once one was. The costs are the file's own `commissionPercent` and `slippageBps`: a strategy that declares none is a gross result, whatever its return says. 2. **The numbers.** The Overview's net profit, win rate, profit factor, drawdown, Sharpe and trade count, and the Performance tab's full table, read together, never one alone: a strategy that wins 70% of the time with a payoff ratio of 0.3 loses money. Every stat has an exact formula in the [stats reference](stats-reference.md). 3. **The trades.** The Trades tab lists every closed trade with its exit reason under **Exit via** (`signal`, `stop`, `limit`, `trail`, `closeAll`, or **Liquidated**), then the open trade and the pending orders. A **± fill** badge marks a trade the fill model settled where one bar touched both the stop and the target, and **Model-settled fills** in the Performance tab counts them (`ambiguousFillCount`): the Tester says so instead of hiding it. 4. **The chart.** Every fill is a marker on the bar that filled it. Hover a row in the Trades tab to highlight its trade on the chart, or click it to scroll the chart to the entry, and check that each entry sits where the rule says it should. ## 5. Tune it honestly Results are deterministic, so every change you see is yours. Change things in this order: - **Costs first.** Set `commissionPercent` and `slippageBps` to what you actually pay on your venue. Most retail strategies die here, and it is cheaper to learn that from the Tester than from a book. - **Sizing.** Try `qtyType: "fixed"` with a small quantity against `percentOfEquity`. Compounding changes the drawdown's character, not only the end number. - **The stop.** Tighten `0.96` to `0.99` and watch the **Exit via** mix shift from `signal` to `stop`. A stop narrow relative to the bar range asks intrabar questions the interval cannot answer; read [fill simulation](fill-simulation.md) before tightening further. - **A setting as a parameter.** Link a numeric setting to a param and it becomes a number field in the strategy's settings dialog (the Tester's **Strategy settings** gear opens it). Change the value and the strategy reruns over the same candles at the new risk, without a recompile. ```typescript // The same reversion with the risk per entry as a setting: the strategy's qtyValue reads the risk_pct param when the run starts. const risk = param("risk_pct", 25, { min: 1, max: 100, description: "Percent of equity per entry" }); strategy({ initialCapital: 10000, qtyType: "percentOfEquity", qtyValue: risk, commissionPercent: 0.05, slippageBps: 2 }); param("period", 14, { min: 2, max: 200, description: "RSI length in bars" }); output("rsi", line, lower, { description: "Wilder RSI of close, 0 to 100" }); let rsi = new Rsi(14); const dip = new Cross(); const recovery = new Cross(); function onStart(): void { rsi = new Rsi(i32(p_period())); } function onBar(): void { const close = bar.close(); const value = rsi.update(close); if (isNaN(value)) return; const dipped = dip.update(value, 30.0); const recovered = recovery.update(value, 55.0); if (dipped == 1) strategy.long("Dip").send(); if (strategy.positionSize() > 0) strategy.exit("Protect").from("Dip").stop(close * 0.96).send(); if (recovered == 1) strategy.closeAll(); out_rsi(value); } ``` A fuller version is a starter in the editor's template picker: the Explorer's **Templates** icon ("Browse starter templates") lists it as **Risk-Sized Reversion** under **Strategies** (`strategy-risk-reversion`), with the stop and a target sized in ATR, each entry sized so a trade stopped out loses `risk_pct` percent of the equity (never more than the equity buys), and each trade's rails drawn on price ([Risk-sized reversion](../cookbook/strategy-risk-reversion.md)), commented throughout. In the file above, `param(...)` returns a handle; passing it as `qtyValue` derives `"qty_value": { "param": "risk_pct" }` into the sheet, and the broker reads the param once, when the run starts. A value outside the setting's rule (here, not a positive number) falls back to the default, the engine's own behavior for a bad override. ## 6. Keep it The editor saves the file to your account as you type, but the strategy on the chart is a draft: it lasts for the session and is not saved with the layout. **Publish** in the editor turns it into a versioned indicator that you, the people you invite, or everyone can add to a chart, with its costs and sizing inside it ([Publishing](../functions/publishing.md)). A published strategy can also carry alerts from the chart: beside its outputs (`rsi` here), the alert dialog offers four choices of its own, "Strategy order placed", "Strategy trade opened or closed", "Strategy position" and "Strategy equity", and OpenMarket's alerts engine evaluates them in the cloud ([Alerts](../functions/alerts.md)). ## 7. What you have, and what you do not You have a deterministic, lookahead-free replay of your rules with disclosed costs and disclosed shortcuts, wherever the file runs. You do not have a promise about the future: no backtest survives contact with a regime change, and a parameter tuned until the curve looks good is a fit to the past. Prefer fewer parameters, realistic costs, and results that stay acceptable when you nudge every setting. Next: the full [order API](writing-strategies.md), [how fills are simulated](fill-simulation.md), and [every stat defined](stats-reference.md). <!-- source: https://openmarket.xyz/wrun/strategies/writing-strategies --> # Writing strategies The `strategy({ ... })` declaration, the order API, the position model and sizing. The chart's Strategy Tester runs the engine's broker, so every rule below is the rule it applies. ## The declaration `strategy(options)` is one top-level statement of the file, beside `param`, `input` and `output`. It takes the engine's setting names; every field is optional and `strategy()` enables the broker with every default. A numeric field may be the handle `param(...)` returns: the setting then shows as a number field in the strategy's settings dialog, starting at the param's default, and changing it reruns the strategy without a recompile. | Setting | Sheet field | Default | Meaning | | --- | --- | --- | --- | | `initialCapital` | `initial_capital` | 10000 | Starting equity, more than 0. | | `currency` | `currency` | `"USD"` | Display label for money-denominated stats. | | `commissionPercent` | `commission_percent` | 0 | Spot commission on every fill, percent of notional. Ignored on perps. | | `slippageBps` | `slippage_bps` | 0 | Adverse basis points on market, stop and trailing fills. Limit fills are exempt: a limit price is a bound. | | `slippageModel` | `slippage_model` | `"fixed"` | `"bookEstimate"` is refused by name when the strategy runs (the chart attaches no order book). | | `qtyType`, `qtyValue` | `qty_type`, `qty_value` | `"percentOfEquity"`, 100 | Default sizing. `"fixed"`: `qtyValue` units per entry. `"percentOfEquity"`: `qtyValue / 100 * equityAtFill / fillPrice`. `"cash"`: `qtyValue / fillPrice`. On perps the last two size margin, and notional is margin times leverage. | | `pyramiding` | `pyramiding` | 1 | Maximum stacked same-direction entries; excess entries are rejected and counted. | | `fillModel` | `fill_model` | `"pessimistic"` | Intrabar ordering assumption when a bar could fill two levels; see [fill simulation](fill-simulation.md). | | `instrument` | `instrument` | `"spot"` | `"perps"` enables isolated leveraged margin, liquidation, maker and taker fees and funding. | | `leverage` | `leverage` | 1 | Perps leverage, more than 0. | | `maintenanceMarginPercent` | `maintenance_margin_percent` | 0.5 | Perps maintenance margin, at least 0 and under 100. | | `makerFeePercent`, `takerFeePercent` | `maker_fee_percent`, `taker_fee_percent` | 0, 0 | Perps fee rates, percent of notional; maker on limit-bound fills, taker on market-crossing fills. Ignored on spot. | | `funding` | `funding` | `"data"` | `"off"` is an exact no-op; `"data"` settles recorded funding when funding data is attached, and counts the bars it cannot settle otherwise (the chart attaches none). | | `onLiquidation` | `on_liquidation` | `"continue"` | `"halt"` rejects every entry after the first liquidation. | Run derives the section into the sheet with the field names in the second column, and checks every value with the engine's rules as the file builds: a value out of range stops the build, with the problem in the editor's **Console**. A strategy's price input reads `ohlcv` on the chart's own market, with no symbol or exchange pin (a file with no `input` line gets the chart's close as that input): the broker fills against the chart's own candles, and any other primary input is refused by name. The names `strategy.position` and `strategy.equity` are reserved for the strategy's own alert choices ("Strategy position" and "Strategy equity"): an output with either name is refused by name. There is no `calc_on_every_tick`: live behavior is fixed, [fill simulation](fill-simulation.md) explains it. ## The order API Every call maps to one engine broker call, with the engine's own validation: ```text strategy.long(id).qty(n).limit(px).stop(px).oca(name).send() // strategy.entry(id, "long", ...) strategy.short(id).qty(n).limit(px).stop(px).oca(name).send() // strategy.entry(id, "short", ...) strategy.exit(id).from(entryId).qty(n).qtyPercent(p) .profit(pts).limit(px).loss(pts).stop(px) .trail(points, offset).oca(name).send() // strategy.exit(id, fromEntry, ...) strategy.close(id) strategy.closeAll() // market, next open strategy.cancel(id) strategy.cancelAll() // pending unfilled orders ``` - A plain `strategy.long(id).send()` is a market order for the next bar's open. `limit` or `stop` makes it a resting order that fills when touched; both on one entry is rejected and counted. Re-issuing an id replaces the pending unfilled order with that id. - `strategy.exit(id)` attaches bracket legs to an entry: `profit` and `loss` in price points, `limit` and `stop` as absolute prices, at least one leg. Without `from` it protects every open entry. Stop, limit and trail legs under one exit id are one-cancels-all. - `trail(points, offset)` activates a trailing stop once the trade's favorable excursion reaches `points`, then ratchets with new extremes at `offset` behind them. - `oca(name)` joins any orders, entries and exits alike, into a one-cancels-all group: when one fills, the rest cancel. - The builders are preallocated singletons: `strategy.long`, `strategy.short` and `strategy.exit` each reset one builder, the setters fill its legs, and `send()` is the only call that reaches the broker, so finish one order before starting the next. An unset leg is absent. There is no `comment`: the engine keeps it on no record. - Getters, valid in `onBar()` beside the order calls: `strategy.positionSize()` (signed), `strategy.positionAvgPrice()`, `strategy.equity()`, `strategy.openProfit()`, `strategy.netProfit()`, `strategy.closedTradeCount()`, `strategy.winTradeCount()`, `strategy.lossTradeCount()`, `strategy.maxDrawdown()`. A crossover entry bracketed by both a stop and a take-profit limit; whichever the market touches first closes the trade and cancels the other side: ```typescript // Trend entries with bracket exits: a stop and a take-profit limit on one exit id, whichever the market touches first closes the trade and cancels the other. strategy({ initialCapital: 10000, qtyType: "fixed", qtyValue: 1, pyramiding: 1, fillModel: "pathHeuristic" }); output("fast", line, overlay, { description: "5-period SMA of close" }); output("slow", line, overlay, { description: "20-period SMA of close" }); const fastSma = new Sma(5); const slowSma = new Sma(20); const cross = new Cross(); function onBar(): void { const close = bar.close(); const fast = fastSma.update(close); const slow = slowSma.update(close); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); if (crossed == 1) strategy.long("Trend").send(); if (strategy.positionSize() > 0) strategy.exit("Protect").from("Trend").stop(close * 0.97).limit(close * 1.05).send(); out_fast(fast); out_slow(slow); } ``` ## Position model The broker nets to one position. An entry in the opposite direction is a reversal: it closes the existing position fully at the same fill, then opens the new one at the requested quantity. `pyramiding` caps same-direction stacking; rejected entries are counted in the broker's `rejectedOrders` rather than thrown. Sizing details worth knowing: - An explicit `qty(...)` on an order always wins over the declaration's `qtyType`. - Sized-at-fill quantities (`percentOfEquity`, `cash`) resolve from the slippage-adjusted fill price, and fractional quantities are legal (the broker does not round lots). - On perps, `percentOfEquity` and `cash` size the isolated margin commitment, not the notional. Explicit quantities and `qtyType: "fixed"` stay direct quantities and are margin-checked. Perps entries also pass an isolated-margin admission check before the opening leg applies; unrealized PnL is not collateral. [Perps](perps.md#margin) has the model. - A computed size is rejected and counted when equity at fill is not positive or the quantity is not finite and positive. Order calls are recorded as rejected, not thrown, when the current bar has non-finite prices or is not confirmed (a live chart's forming bar). On the last bar, unfilled orders remain visible under **Pending orders** in the Strategy Tester's Trades tab. ## Limits At most 64 distinct order ids per run (`closeAll` counts as one; ids are slots, re-issuing one replaces its pending order), 64 bytes of UTF-8 per id, 4096 strategy calls per bar, and 10000 closed trades per run. Each breach refuses the run by name, and every engine rejection stays a counted rejection; the [limits](../reference/limits.md) page lists them. <!-- source: https://openmarket.xyz/wrun/strategies/fill-simulation --> # Fill simulation How the broker decides when and at what price orders fill, how a bar that could have filled two levels is settled, and how the run reports its own precision. The chart's Strategy Tester runs the engine's broker, one bar ahead of your file. ## The execution model Orders are processed at each new confirmed bar in a fixed sequence, before your file's `onBar()` runs on that bar: 1. Protective exits of the open position (stop, limit, trail) are evaluated against the bar's range under the fill model. 2. Pending signal exits from `close` and `closeAll`, in insertion order. 3. Pending entries, in insertion order: market orders at the open, resting limit and stop orders if touched. 4. On perps, the phase-end liquidation check against the final position. 5. Your file runs at the bar's close; the orders it places join the queue for the next bar. Fill prices follow bar mechanics: - **Market fills** execute at the next bar's open, slippage-adjusted. - **Limit fills** execute when the bar trades through the level (long entry: `low <= limit`), at the better of the open and the limit, with no slippage: a limit price is a bound by definition. - **Stop fills** mirror the touch rule and are slippage-adjusted, because stops cross the market. - **Trailing stops** activate when favorable excursion reaches the trail points, then ratchet with new extremes and fill under stop rules with `exitReason: "trail"`. Equity is recorded on every bar (cash plus the open position marked at that bar's close, fees already paid), so drawdown and exposure account for flat periods too. ```text one confirmed bar ----------------------------------------------------------------> [funding settles] [protective exits] [signal exits] [entries fill] perps only stop / limit / close() / market at open, trail vs the closeAll() resting limit / bar's range stop if touched | | v v .................. phase-end liquidation check .................. | v [onBar() runs at bar close] -> orders placed here queue for the NEXT bar ``` Two consequences worth internalizing: your file always sees the bar's completed fills, and nothing your file places can fill until the following bar. The first is why a flat guard works without a flag of its own: ```typescript // The flat guard: an entry only while flat, read from the position AFTER the bar's fills, so the bar an exit filled on can re-arm the entry. strategy({ qtyType: "fixed", qtyValue: 1 }); output("sma", line, overlay, { description: "10-period SMA of close" }); output("position", none, lower, { description: "Signed position after the bar's fills" }); const sma = new Sma(10); function onBar(): void { const close = bar.close(); const mean = sma.update(close); const held = strategy.positionSize(); if (isNaN(mean)) return; if (held == 0 && close > mean) strategy.long("L").send(); if (held > 0 && close < mean) strategy.close("L"); out_sma(mean); out_position(held); } ``` `strategy.positionSize()` inside `onBar()` reads the position after the bar's fills. On the bar the `close("L")` order filled, `held` is already `0`, so the entry guard can re-arm on that very bar; keep entry zones disjoint from your exit prices unless that is what you want. The data-only `position` output records `held` on every row. ## The newest bar On a full run (the first render, or a rerun after you pan back or change a setting) every bar is confirmed, the newest included: an order placed on the last bar rests pending, exactly as the engine's full run treats it. On a live chart the newest bar is the forming bar: the broker marks equity at its close but fills nothing on it, and an order placed on it is rejected and counted, exactly as the engine treats a live update's last bar. Live updates re-evaluate the forming bar on a clone of the committed state, coalesced to at most about once a second rather than on every tick; when the bar closes, the closed row is folded into the committed broker once (fills for the orders queued before it, then the file's own orders) and the next forming bar starts on a fresh clone. A live session therefore equals a full run from bar 0, including the one-time shift of pending-order and stat values between the first render and the first live update. ## Intrabar ordering and fill models A single bar tells you the range it traded, not the path it took. When both a protective stop and a profit limit sit inside one bar's range, the bar alone cannot say which traded first. Decisions certain at bar level never involve an assumption (a leg already marketable at the open fills at the open); the rest settle by the declared `fillModel`: - `"pessimistic"` (default): the stop is assumed to have filled first. The decision is counted in `ambiguousFillCount` (the Strategy Tester's **Model-settled fills**) and the trade is flagged `ambiguousFill` (a **± fill** badge in the Trades tab). - `"pathHeuristic"`: the open moves toward the nearer of high and low first. Natural path resolutions are not counted; only exact distance ties fall back to the pessimistic rule and count. Both models are fully deterministic. The chart attaches no finer-interval bars to a strategy run, so every contested fill settles by the model: the Strategy Tester's **Run details** read "Fill precision: bar resolution" once one has ("Fill precision: exact" while none has), and `fineResolvedCount` stays `0`. Uncontested fills are identical either way. ## Choosing an interval to trust Brackets arm on the bar after the entry fills. On a 1-hour chart that protection gap is an hour of price movement; on a 1-minute chart it is a minute. A strategy whose stops are tight relative to its interval will genuinely behave differently at finer intervals, because it is seeing different information. Backtest at the interval you intend to run on, keep stops and targets wide relative to the interval's typical bar range or move to a finer chart, and treat **Model-settled fills** (`ambiguousFillCount`) as part of the result. <!-- source: https://openmarket.xyz/wrun/strategies/slippage-and-costs --> # Slippage and costs Commission on spot, maker and taker fees on perps, and flat slippage, each declared in the file so a published strategy carries its own assumptions. The book-estimate slippage model is the one piece of the accounting the chart refuses rather than approximates. ## Commission (spot) On `instrument: "spot"` (the default), `commissionPercent` is charged on every fill as a percent of the fill's notional, on entries and exits alike. Fees reduce equity immediately and are reported per trade (`fees` on each trade record) and in the totals as `stats.feesPaid`. ## Maker and taker fees (perps) On `instrument: "perps"`, fills are charged `makerFeePercent` or `takerFeePercent` instead of commission, by how the fill reached the market: - **Taker** (`takerFeePercent`): market-crossing fills. Market entries, stop entries, protective stops, trailing stops, signal exits, `closeAll`, liquidation, and the flattening leg of a reversal a market or stop entry triggered. - **Maker** (`makerFeePercent`): limit-bound fills. Limit entries, take-profit limit legs, and the flattening leg of a reversal a limit entry triggered. - `stats.feesPaid` is exactly `makerFeesPaid + takerFeesPaid` on perps. ```typescript // Perps maker-fee routing: a resting limit entry pays the maker rate, the market close pays the taker rate. strategy({ initialCapital: 10000, instrument: "perps", leverage: 2, makerFeePercent: 0.1, takerFeePercent: 0.05, funding: "off", qtyType: "fixed", qtyValue: 1, pyramiding: 1 }); output("equity", line, lower, { description: "Strategy equity" }); const fastMa = new Sma(4); const slowMa = new Sma(9); const cross = new Cross(); function onBar(): void { const close = bar.close(); const fast = fastMa.update(close); const slow = slowMa.update(close); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); if (crossed == 1) strategy.long("Long").limit(close * 0.999).send(); if (crossed == -1) strategy.close("Long"); out_equity(strategy.equity()); } ``` The resting limit just under the market is a maker fill when a later bar trades through it (`makerFeesPaid` grows); the market close crosses the market and pays the taker rate (`takerFeesPaid` grows); `feesPaid` is their exact sum. ### One fee schedule per instrument Declaring the other instrument's fee settings never double-charges: the broker ignores them. - Perps plus a nonzero `commissionPercent`: fees come from the maker and taker rates only. - Spot plus `makerFeePercent` or `takerFeePercent`: the run charges commission only. `onLiquidation` on spot is ignored the same way. Funding on perps is a holding cashflow, not a fill cost, and has its own stats and series; see [perps](perps.md). ## Flat slippage `slippageBps` applies adversely to every fill that crosses the market: market entries, stop entries, protective stops and trailing stops. Buys fill at `price * (1 + bps / 10000)`, sells mirror. Limit fills, including take-profit legs, are exempt. Slippage is priced into the fill itself: the trade records carry the slipped price, and there is no separate slippage line to subtract, which is why the Strategy Tester shows fees but no slippage figure. Flat slippage is honest about being a constant: it neither grows with your order size nor tightens on liquid pairs. ## The book estimate The book estimate (`slippageModel: "bookEstimate"`) walks recorded order-book depth to price market-crossing fills by size. The chart attaches no order book to a strategy run, so a strategy declaring it is refused by name when it runs (`wrun_strategy_slippage_model_unsupported`) rather than silently priced at the flat rate. Declare `"fixed"` with a `slippageBps` that is realistic for the pair. ## Where the costs show The Strategy Tester's Performance tab carries **Fees paid** (`feesPaid`), and on perps **Maker fees paid** and **Taker fees paid** under it. The costs are the file's own and the Tester has no fee or slippage field: to test another fee tier or slippage, change the declaration, or link the setting to a param and change it in the strategy's settings dialog. ## Practical guidance - Set `slippageBps` to what a taker actually pays on the pair, and `commissionPercent` or the maker and taker rates to your tier. Most retail rules die here. - Size matters: a strategy that trades a fraction of equity and one that trades at 10x see very different fee bills on the same signals, because fees are a percent of notional. - Read **Fees paid** against **Net profit** before reading the win rate: a strategy that crossed the spread 34 times in a quarter has paid for it. <!-- source: https://openmarket.xyz/wrun/strategies/perps --> # Perps: margin, liquidation, funding `instrument: "perps"` switches the broker from spot accounting to isolated-margin perpetual futures: leverage, maker and taker fees, funding settlement and liquidation, each with its own counters, so a result is never quietly shaped by machinery you cannot see. This page names what each mechanic does, with the engine's own formulas, and what the chart does not attach. The five scenarios that pin the numbers are on the [examples](examples.md#the-five-perps-scenarios) page. ## What perps mode changes Perps mode keeps the same order API and one-net-position model. Four mechanics turn on: | Mechanic | What changes | | --- | --- | | Margin | Every entry commits isolated margin of `notional / leverage`; an entry that cannot be margined is rejected and counted. | | Maker and taker fees | Fills are charged `makerFeePercent` or `takerFeePercent` instead of `commissionPercent`. | | Funding | Recorded funding events settle against the open position (`funding: "data"`, the default) when funding data is attached, or funding is off entirely (`funding: "off"`). | | Liquidation | A position that exhausts its margin is force-closed at the broker's implicit liquidation stop, and `onLiquidation` decides whether the run keeps trading or halts. | A spot run carries none of this, and spot economics are unchanged until you opt in: the perps stats report zero (`makerFeesPaid`, `takerFeesPaid`, `fundingPaid`, `fundingEventsApplied`, `fundingUnavailableCount`, `liquidationCount` all `0`, `liquidationHalted: false`) and the perps-only series are omitted. The defaults, echoed by a bare declaration: `instrument: "spot"`, `leverage: 1`, `maintenanceMarginPercent: 0.5`, `makerFeePercent: 0`, `takerFeePercent: 0`, `funding: "data"`, `onLiquidation: "continue"`. ## Margin Each perps entry commits isolated margin equal to the fill's notional divided by `leverage`; `committedMarginSeries` on the output carries the committed total at each bar's close, `0` when flat. Any number above `0` is legal leverage, fractions included; `maintenanceMarginPercent: 0` is legal (the lower bound is inclusive). | Declared sizing | Under perps | | --- | --- | | `qtyType: "percentOfEquity"`, `qtyType: "cash"` | Size the margin commitment. The broker then computes `notional = margin * leverage` and `qty = notional / fillPrice`. | | `qtyType: "fixed"`, an explicit `.qty(...)` | Direct quantities, margin-checked as `abs(qty) * fillPrice / leverage`. | **Leverage scales margin, not PnL.** The same signals with the same fixed quantity produce the same `netProfit` as spot, whatever the leverage, until fees or a liquidation differ. Leverage decides how much equity a position ties up and where liquidation sits, not what a trade earns. ```typescript // Perps margin sizing: percentOfEquity sizes the margin commitment, and notional is that margin times leverage. strategy({ initialCapital: 10000, instrument: "perps", leverage: 10, maintenanceMarginPercent: 0.5, qtyType: "percentOfEquity", qtyValue: 10, makerFeePercent: 0.02, takerFeePercent: 0.05, slippageBps: 0, funding: "off" }); output("close", line, overlay, { description: "Close price" }); let bars: i32 = 0; function onBar(): void { bars += 1; if (bars == 1) strategy.long("MarginLong").limit(100.0).send(); out_close(bar.close()); } ``` On bars priced near 100, that entry fills at 100 with `qtyType: "percentOfEquity"`, `qtyValue: 10` and `leverage: 10`: the open trade has `qty` 100, `committedMargin` 1000 and `fees` 2, with `makerFeesPaid` 2 and `takerFeesPaid` 0. The 10% sizing setting committed 1000 of margin, not 1000 of notional; the notional was margin times leverage. The `bars` counter is a first-bar gate: the file keeps its own row count. ### Admission Entries are admitted against realized-basis equity: `committedMargin + entryFee <= availableMargin`, where the available margin excludes unrealized PnL from the open position. A winning open position does not become collateral for adding exposure. An entry whose fee-inclusive requirement (`notional / leverage` plus the entry's fee) exceeds the available margin is rejected and counted in `stats.rejectedOrders`. Reversals stay atomic: the broker simulates the closing leg, then checks whether the new opening leg fits; if it does not, the whole reversal is rejected and the old position remains open. ## Liquidation ```text long 1 unit at 100, leverage 10, maintenance 0.5% entry 100 -+------------------------------------ | committed margin = 100/10 = 10 | the price may fall ~9.55 before | margin (less maintenance) is gone P_liq ----+---- 90.4522... <- liquidation | +-- lower leverage pushes this line further away ``` The broker maintains an implicit liquidation stop on the final open net position, from the entry fill onward. It is not a user order: it is not in your pending queue, cannot be canceled, and closes the trade with `exitReason: "liquidation"` when the bar proves or assumes the level traded. It uses the bar's traded prices, not a mark price the broker does not have. | Side | Liquidation level | | --- | --- | | Long | `P_liq = (Q * E - M) / (Q * (1 - m))` | | Short | `P_liq = (E + M / Q) / (1 + m)` | `Q` is the absolute quantity, `E` the average entry, `M` the committed isolated margin and `m` the maintenance margin as a fraction. For a single entry the long level reduces to `entry * (1 - 1 / leverage) / (1 - maintenanceMarginPercent / 100)`: a 10x long entered at 100 with 0.5% maintenance liquidates at `90.45226130653266`, and the short mirror at `109.45273631840797`. Three cases the bar decides: - **Entry-bar liquidation** is possible, because a market entry fills at the bar's open and the phase-end check sees the same bar's range. - **Same-bar fills that change the final position.** The bar cannot prove whether the adverse extreme came before or after the change, so the broker assumes liquidation if the final level is reached, clamps the fill into the bar's traded range, counts it in `ambiguousFillCount` and flags the trade. - **A gap through the level.** The fill is the bar price, because that is where the market traded; the loss beyond committed margin is `stats.bankruptcyDeficit`, and equity floors at zero. | `onLiquidation` | Behavior | | --- | --- | | `"continue"` (default) | Trading continues; every liquidation counts in `liquidationCount`. | | `"halt"` | The first liquidation stops the strategy: `liquidationHalted: true`, and every subsequent entry is rejected and counted. | ```typescript // Liquidation with on_liquidation "continue": 25x leverage puts the broker's liquidation stop inside an ordinary swing, and trading goes on after each one. strategy({ initialCapital: 10000, instrument: "perps", leverage: 25, maintenanceMarginPercent: 0.5, funding: "off", onLiquidation: "continue", qtyType: "fixed", qtyValue: 1, pyramiding: 1 }); output("equity", line, lower, { description: "Strategy equity" }); const fastMa = new Sma(4); const slowMa = new Sma(9); const cross = new Cross(); function onBar(): void { const close = bar.close(); const fast = fastMa.update(close); const slow = slowMa.update(close); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); if (crossed == 1) strategy.long("Long").send(); out_equity(strategy.equity()); } ``` At 25x the liquidation level sits about 3.5% under the entry, inside an ordinary swing on most pairs: expect trades closed by `liquidation` (**Liquidated** under **Exit via** in the Strategy Tester's Trades tab), `liquidationCount` counting them, and trading continuing after each one. ## Maker and taker fees Perps ignores `commissionPercent`: a fill pays `makerFeePercent` when it is limit-bound and `takerFeePercent` when it crosses the market. [Slippage and costs](slippage-and-costs.md#maker-and-taker-fees-perps) classifies every fill, shows a worked example, and covers what happens to the other instrument's fee settings. ## Funding `funding: "data"` settles recorded funding events against the open position, and `funding: "off"` disables funding entirely; only those two literals are accepted. The rate is decimal (1 bp is `0.0001`), and positive rates mean longs pay and shorts receive. `fundingPaid` is signed from the strategy's side (positive when the strategy paid), `fundingEventsApplied` counts the settlements applied, and `fundingPaidSeries` is the cumulative series. Funding is a drip against isolated margin. Settlements apply only while a position is open, and debit cash and committed margin together, so the liquidation line moves closer with every settlement paid. A settlement that erodes committed margin to zero or below liquidates the position at that bar's open with zero price PnL, and later same-bar fills cannot rescue it. The chart attaches no funding data to a strategy run. `funding: "data"` therefore settles nothing and counts every bar an open position could not be settled in `fundingUnavailableCount`: partial coverage is counted, never charged, and no rate is ever invented. The Strategy Tester discloses the count on every run it applies to: **Run details** read "Funding data did not cover N bars", and the Overview's **Funding** chart says "No funding was applied on this run." `funding: "off"` is the exact no-op it always was, and a strategy that should not depend on funding declares it. ## Perps stats and series A run's stats always carry the perps fields, zero on spot; the [stats reference](stats-reference.md#perps) defines each exactly. | Stat | Meaning | | --- | --- | | `makerFeesPaid`, `takerFeesPaid` | Fees by fill class. | | `fundingPaid` | Net funding settled, signed from the strategy's side. | | `fundingEventsApplied` | How many funding settlements the run applied. | | `fundingUnavailableCount` | Bars with an open position and no settlement data. | | `liquidationCount` | Trades force-closed by the liquidation stop. | | `liquidationHalted` | `true` once `onLiquidation: "halt"` stopped the run. | | `bankruptcyDeficit` | How far equity would have gone below zero before the floor. | Perps runs also add two bar-aligned series to the output, present on every perps run and omitted on spot: `committedMarginSeries` (margin committed to the open position at each bar close) and `fundingPaidSeries` (cumulative funding paid, ending at `stats.fundingPaid`). The Strategy Tester draws them as the Overview's **Margin** and **Funding** charts, each with **Show on chart**, shows the fee split and the funding in the Performance tab, and the liquidations in the Overview and the Trades tab. ## Validation The settings are checked with the engine's rules as the file builds, and a value out of range stops the build with the problem in the editor's **Console**. A setting linked to a param is checked when the run starts, with the same rules, and an out-of-range value falls back to the default. | Setting | Rule | | --- | --- | | `instrument` | `"spot"` or `"perps"` | | `leverage` | More than 0 | | `maintenanceMarginPercent` | At least 0 and under 100 | | `makerFeePercent`, `takerFeePercent` | At least 0 | | `funding` | `"data"` or `"off"` | | `onLiquidation` | `"continue"` or `"halt"` | <!-- source: https://openmarket.xyz/wrun/strategies/reading-the-tester --> # Reading the Strategy Tester The Strategy Tester is where a strategy's result lives on the chart: it docks under the chart whenever the chart holds a strategy, carries the trades, the equity curve and the stats, and marks each fill on the price series. This page is the map of the panel, and of where its honesty disclosures live. ```text Strategy Tester Tabs one per strategy: its name, its net result in percent, an eye, a menu Header Compare, the bars the run covered, Run details, Strategy settings Overview the headline stats beside the equity curve, a drawdown lane, Buy & hold (a perps strategy adds Margin and Funding) Performance Returns, Risk, Trades, then Long vs short and the P&L distribution Trades Closed trades, Open trades, Pending orders ``` ![The Strategy Tester expanded under the chart on its Overview tab: the strategy tab with its net result, the header, the headline stats beside the equity curve, and the fill markers with their rails on the price pane](/wrun/images/tester-overview.png) - The strategy's tab at the top left carries its name and its net result; the header holds **Compare**, the bars chip ("1,029 bars · to Oct 4"), **Run details** and the gear. - **Overview**: the stats column (Net profit, Win rate, Profit factor, Max drawdown, Sharpe, Trades) beside the equity curve, the **DD** lane under it and **Buy & hold** at the top right. - On the chart, each fill is an arrow on its bar; this strategy also draws the stop and target rails of every trade, and its RSI in the pane below. ## Where it opens Press **Backtest** in the editor, or add a published strategy from the chart's **Indicators** dialog, and the Tester docks under the chart. Collapsed, it is a strip: the strategy's name, a sparkline of its equity, and its **Net**, **Win**, **DD** and **Trades**. Click the strip to expand the panel, or open a strategy from the chip on its legend entry ("Open ... in Strategy Tester"). Each strategy on the chart gets a tab with its name, its net result in percent, and an eye that hides its plots and trade markers together. The tab's menu has **Remove from chart**, **Open settings**, **Hide markers**, and **Trade markers**: the marker shape (**Chevron**, **Bubble** or **Badge**), its size, and the long and short colors. ## Overview A column of headline stats, **Net profit** (with its percent), **Win rate** (with wins and losses), **Profit factor**, **Max drawdown** (in percent and money), **Sharpe** and **Trades** (with the exposure), beside the equity curve, which has a drawdown lane (**DD**) under it and a **Buy & hold** toggle that draws holding the market over the same bars. Hover the curve and the chart highlights the same bar. A perps strategy adds two small charts, **Margin** (the margin committed to the open position at each bar) and **Funding** (the cumulative funding), each with **Show on chart** to project it onto the chart, and a line when a liquidation happened: when and at what price (or how many times, from the first), then whether the strategy continued or halted. ## Performance Three groups, then two cards built from the closed trades: - **Returns**: Net profit, Gross profit / loss, Buy & hold return, Sharpe / Sortino. - **Risk**: Max drawdown, Max runup, Exposure. - **Trades**: Total / win rate, Avg trade / payoff, Fees paid (on perps also Maker fees paid, Taker fees paid, and Funding paid or Funding received), and Model-settled fills. - **Long vs short**: each side's net result, trade count and win rate. - **P&L distribution**: the spread of trade results, the largest win and loss, and the best and worst streaks. Every number has an exact formula in the [stats reference](stats-reference.md). ![The Performance tab: the Returns, Risk and Trades groups, then Long vs short and the P&L distribution](/wrun/images/tester-performance.png) - Three groups left to right: **Returns**, **Risk**, **Trades**; a strategy on perps adds its fee and funding rows to Trades. - **Long vs short** splits the net result and the win rate by side; a side without trades reads "No trades". - **P&L distribution** draws the closed trades from the largest loss to the largest win, with the streaks under it. ## Trades **Closed trades** come first, numbered, with side, quantity, entry and exit, PnL in cash and percent, cumulative PnL, and the exit reason under **Exit via** (`signal`, `stop`, `limit`, `trail`, `closeAll`, or **Liquidated**). A **± fill** badge marks a trade the fill model settled where one bar held both the stop and the target. **Open trades** (quantity, entry, entry price, unrealized PnL and fees) and **Pending orders** (id, side, type, quantity, price and legs) follow in their own sections. Hover a row to highlight its trade on the chart; click it to scroll the chart to the entry. ![The Trades tab: eight closed trades with side, quantity, entry and exit bars, PnL, cumulative PnL and the exit reason under Exit via](/wrun/images/tester-trades.png) - **Exit via** reads the reason per row: `closeAll`, `stop` and `limit` here; the fill badge on row 4 marks the trade the fill model settled. - The column headers sort; **Cum** runs the PnL down the table. - **Open trades** and **Pending orders** follow only when the run ends with a position or a working order; this run ended flat. ## On the chart Every fill is a marker on the bar that filled it, colored by direction in the chart's own candle colors unless you pick others under **Trade markers**; a liquidation exit carries its own mark. Past 150 closed trades a strategy's markers cluster into count pills, and **Run details** says "markers clustered · N trades". ## Run details The info icon in the header opens the run's own disclosure: - **Interval**: the chart's interval. - **Depth**: "Follows chart (recomputes as you pan)". The run covers the candles the chart has loaded and recomputes as you pan; a chip in the header reads the bars it covered and the date of the last one. - **Bars**, **Fill model** (the declared `fillModel`) and **Compute time**. - The precision line: "Fill precision: exact" when no bar had to be settled by the fill model, "Fill precision: bar resolution" once one was. The chart attaches no finer-interval data to a strategy run, so a contested fill is always the fill model's call ([fill simulation](fill-simulation.md)). - On a perps strategy that held a position under `funding: "data"`: "Funding data did not cover N bars". The chart attaches no funding data, so nothing was charged ([perps](perps.md)). ## Compare mode With two or more visible strategies on the chart, **Compare** puts them side by side: a normalized equity chart, a table of Net profit, Win rate, Profit factor, Max DD, Sharpe and Trades per strategy plus a **Combined** column (the equal-notional sum of their PnL), and their **Pairwise correlation**. Trade markers step aside while it is on. ## Strategy settings The gear in the header (**Strategy settings**) opens the strategy's settings dialog. The broker's settings (capital, sizing, costs, fill model, perps) live in the file's `strategy({ ... })`, not in the Tester. Of those, only a setting the author linked to a param shows in the dialog, as a number field beside the file's other params, and changing it reruns the strategy over the same candles ([Writing strategies](writing-strategies.md)). ## Live On a live chart the newest bar is still forming. Live updates re-evaluate it on a copy of the committed broker, coalesced to at most about once a second rather than on every tick: nothing fills on the forming bar, and an order placed on it is counted as rejected. When the bar closes it is folded into the committed broker once, so what the panel shows at any moment equals a full run over the closed bars plus the forming bar's mark. A strategy published as **Protected** runs on OpenMarket's servers with the same broker at the same fidelity, and the Tester reads its result the same way ([Publishing](../functions/publishing.md)). <!-- source: https://openmarket.xyz/wrun/strategies/stats-reference --> # Stats reference Every performance stat a strategy run computes, its exact formula, its edge cases, and where the Strategy Tester shows it. The stats come from the engine's own statistics module, and the Tester reads them from the run's result. Percent-scaled fields end in `Pct` and are already multiplied by 100. One run's stats record: ```json { "netProfit": 123.4, "netProfitPct": 1.234, "grossProfit": 310.2, "grossLoss": 186.8, "profitFactor": 1.66, "totalTrades": 12, "winTrades": 7, "lossTrades": 5, "winRatePct": 58.33, "avgTrade": 10.28, "avgWin": 44.31, "avgLoss": 37.36, "payoffRatio": 1.19, "largestWin": 96.1, "largestLoss": 61.5, "avgBarsInTrade": 9.4, "maxDrawdown": 402.6, "maxDrawdownPct": 3.98, "maxRunup": 640.2, "sharpe": 0.91, "sortino": 1.4, "confirmedBars": 480, "exposurePct": 22.1, "buyHoldReturnPct": 4.1, "feesPaid": 32.1, "makerFeesPaid": 0, "takerFeesPaid": 0, "fundingPaid": 0, "fundingEventsApplied": 0, "fundingUnavailableCount": 0, "liquidationCount": 0, "liquidationHalted": false, "bankruptcyDeficit": 0, "rejectedOrders": 1, "ambiguousFillCount": 0, "fineResolvedCount": 0, "fineFillCoveragePct": null, "fillResolutionByLane": {}, "bookSlippageFillCount": 0, "bookSlippageUnavailableCount": 0, "bookSlippageAvgBps": null, "long": { "netProfit": 123.4, "totalTrades": 12, "winRatePct": 58.33 }, "short": { "netProfit": 0, "totalTrades": 0, "winRatePct": 0 } } ``` ## Returns <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `netProfit` | Sum over closed trades of `pnl - fees` (a trade record's `pnl` is the price move, its `fees` the trade's total). `netProfitPct` is relative to `initialCapital`. | | `grossProfit` / `grossLoss` | Sum of winning trades' net results and the absolute sum of losing trades'. | | `profitFactor` | `grossProfit / grossLoss`; `null` when there are no losses. | | `buyHoldReturnPct` | `(lastConfirmedClose / firstTradableClose - 1) * 100` over the run's confirmed bars: what doing nothing would have returned. The Performance tab's **Buy & hold return** is this number. | In the Tester: **Net profit** (with `netProfitPct`) and **Profit factor** sit in the Overview's stats column, and the Performance tab's **Returns** group shows Net profit, **Gross profit / loss** and Buy & hold return. ## Trades <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `totalTrades`, `winTrades`, `lossTrades` | Closed trades and the split; `winRatePct` is `winTrades / totalTrades * 100`. | | `avgTrade`, `avgWin`, `avgLoss` | Mean net result per closed trade, per winner, per loser (`avgLoss` is a magnitude). | | `payoffRatio` | `avgWin / avgLoss`; `null` when there are no losers. Read it with the win rate: 40% winners at a 3.0 payoff is profitable, 70% at 0.3 is not. | | `largestWin`, `largestLoss` | The single best and worst closed trades. If `largestWin` dominates `netProfit`, one trade made the backtest. | | `avgBarsInTrade` | Mean holding time in bars (`exitBar - entryBar`). | | `rejectedOrders` | Orders the broker refused and counted: the pyramiding cap, conflicting or missing legs, a size the equity could not fund, a non-finite or unconfirmed bar (a live chart's forming bar included); on perps also insufficient margin and post-halt entries. | In the Tester: the Overview's **Win rate** is `winRatePct` and the Performance tab's **Avg trade / payoff** is `avgTrade` and `payoffRatio`. The trade counts in both tabs are counted from the trade list (the Overview's **Trades** includes a trade still open), and the **Long vs short** and **P&L distribution** cards (largest win and loss, best and worst streaks) are worked out from the closed trades. ## Risk <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `maxDrawdown` | Largest peak-to-trough equity decline over the run, in money; `maxDrawdownPct` is relative to the peak it fell from. The per-bar `drawdown` series is the money distance from the running peak. | | `maxRunup` | Mirror of drawdown: the largest trough-to-peak climb. | | `sharpe` | `mean(r) / sampleStd(r) * sqrt(barsPerYear)` over per-bar equity returns on confirmed bars, `barsPerYear = 31,536,000,000 / intervalMs`; zero with no variance. Annualized from the run's interval, so compare across runs at the same interval. | | `sortino` | Sharpe with the downside deviation (returns below zero) in the denominator. | | `confirmedBars` | How many bars, from the first, the five figures above cover: `maxDrawdown`, `maxDrawdownPct`, `maxRunup`, `sharpe` and `sortino` are computed over the first `confirmedBars` values of `equity`. On a live chart the forming bar is left out, so it is one less than the length of `equity` during a live update. | | `exposurePct` | Bars with a nonzero position over all confirmed bars, times 100. | In the Tester: **Max drawdown** (`maxDrawdownPct` and `maxDrawdown`) and **Sharpe** sit in the Overview, where the equity curve's **DD** lane is the drawdown bar by bar and **Trades** carries the exposure; the Performance tab's **Risk** group shows Max drawdown, **Max runup** and **Exposure**, and **Sharpe / Sortino** sits under Returns. ## Costs <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `feesPaid` | Total fees across all fills, already subtracted from equity and `netProfit` (funding excluded). Spot: `commissionPercent` of each fill's notional. Perps: exactly `makerFeesPaid + takerFeesPaid`. | | `makerFeesPaid` / `takerFeesPaid` | Perps fees by fill class; both `0` on spot even with rates declared. | | `fundingPaid` | Net funding settled against open perps positions, signed from the strategy's side; `0` under `funding: "off"`, on spot, and on the chart, which attaches no funding data to a strategy run. | | `fundingEventsApplied` | Settlements applied to an open position. | | `fundingUnavailableCount` | Bars an open perps position had no covering funding data under `funding: "data"`: on the chart every such bar. The disclosure counter; no rate is ever invented. | Slippage is not a separate stat line: it is priced into every fill. In the Tester: the Performance tab's **Trades** group carries **Fees paid**, and on perps **Maker fees paid**, **Taker fees paid**, and **Funding paid** (or **Funding received** when the strategy was paid); **Run details** show `fundingUnavailableCount` as "Funding data did not cover N bars". ## Perps <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `liquidationCount` | Trades force-closed by the broker's liquidation stop; those trades carry `exitReason: "liquidation"`. One liquidation can close several open trade records in the same net position. | | `liquidationHalted` | `true` when `onLiquidation: "halt"` stopped the run at the first liquidation; every subsequent entry counts as rejected. | | `bankruptcyDeficit` | The shortfall a liquidation fill left beyond the position's committed margin: how far equity would have gone below zero before the floor. | Perps runs also add `committedMarginSeries` and `fundingPaidSeries` beside the stats; both are omitted on spot. In the Tester: a liquidated trade reads **Liquidated** under **Exit via**, and the Overview says when and at what price the first liquidation happened, how many there were, and whether the strategy continued or halted. Its **Margin** chart draws `committedMarginSeries`, and its **Funding** chart draws `fundingPaidSeries` with the sign flipped, so paying walks down. ## Long and short splits `long` and `short` carry `netProfit`, `totalTrades` and `winRatePct` per direction. A "market-neutral" idea whose entire profit sits in `long` during a bull window is a long-only idea with extra steps. ## Simulation-quality stats These describe how the result was produced, not how the strategy performed: <!-- wrun:cards group="stats" --> | Stat | Definition | | --- | --- | | `ambiguousFillCount` | Intrabar ordering decisions settled by the declared `fillModel` rather than data; see [fill simulation](fill-simulation.md). | | `fineResolvedCount`, `fineFillCoveragePct`, `fillResolutionByLane` | Ordering questions settled by walking finer bars. The chart attaches no finer-interval data to a strategy run, so `fineResolvedCount` is `0` and `fillResolutionByLane` is `{}`; `fineFillCoveragePct` is `null` while no fill was contested and `0` once one was. | | `bookSlippageFillCount`, `bookSlippageUnavailableCount`, `bookSlippageAvgBps` | The book-estimate slippage model's counters: `0`, `0` and `null`, because the chart refuses that model by name. | In the Tester: `ambiguousFillCount` is **Model-settled fills** in the Performance tab, with a **± fill** badge on each such trade, and the fine-fill fields become the **Run details** precision line: "Fill precision: exact" while `fineFillCoveragePct` is `null`, "Fill precision: bar resolution" once a contested fill was settled by the model. ## Equity accounting, precisely Equity on every bar `i` is cash plus the open position marked at `close[i]`, fees already paid, recorded on flat bars too. Per-bar returns for Sharpe and Sortino are `r_i = equity_i / equity_{i-1} - 1` over confirmed bars with positive prior equity. On a live chart the forming bar is marked, never filled, so pending-order and stat values can shift once between the first render and the first live update, and settle when the bar confirms; [fill simulation](fill-simulation.md#the-newest-bar) says which bars count as confirmed. <!-- source: https://openmarket.xyz/wrun/strategies/examples --> # Examples Complete strategy files to start from: the five perps scenarios behind the engine's acceptance battery and a Hyperliquid perp walkthrough, each with a line on what it shows. The three spot examples live on the pages that teach them, listed first. To run one, replace the starter in a **New indicator** draft with the file and press **Backtest**; the [overview](overview.md#what-a-strategy-file-is) has the steps. The strategy trades the chart's own market, and the Strategy Tester docks under the chart with the trades and the stats ([Reading the Strategy Tester](reading-the-tester.md)). ## Spot examples | File | What it shows | Page | | --- | --- | --- | | Moving average cross | The smallest useful strategy: one entry rule, one exit rule. `percentOfEquity` sizing keeps the position proportional as equity compounds, and `commissionPercent` plus `slippageBps` make every fill pay realistic costs. | [Strategies overview](overview.md#what-a-strategy-file-is) | | RSI reversion with a protective stop | Buys oversold dips and arms a stop under every entry, so a dip that keeps dipping is cut instead of riding to the bottom. `strategy.exit(...).from("Dip")` scopes the stop to the named entry, and the stop follows the close at placement time. Built up line by line on its page. | [Build your first strategy](first-strategy.md) | | Trend entries with bracket exits | A crossover entry bracketed by a stop and a take-profit limit on one exit id, a one-cancels-all pair: whichever the market touches first closes the trade and cancels the other. `fillModel: "pathHeuristic"` decides a bar that touches both ([fill simulation](fill-simulation.md#intrabar-ordering-and-fill-models)). | [Writing strategies](writing-strategies.md#the-order-api) | ## The five perps scenarios The five canonical perps scenarios behind the engine's acceptance battery: liquidation on both sides, fee classification, funding erosion and bankruptcy accounting. They are reproduction scripts: each lands on the number the engine's battery pins for bars priced near 100, which is what makes it verifiable. On a chart they run against that chart's own prices, where a scenario that waits for a price near 100 may never trade, so read them for the mechanics rather than to match the numbers. [Perps](perps.md#liquidation) has the formulas. A first-bar gate is a row counter the file keeps itself. ### 1. Long liquidation What it shows: a 10x long entered at 100 with 0.5% maintenance margin must liquidate at exactly `(100 - 10) / 0.995 = 90.45226130653266`. ```typescript // Scenario 1, long liquidation: a 10x long at 100 with 0.5% maintenance margin must liquidate at (100 - 10) / 0.995. strategy({ initialCapital: 10000, instrument: "perps", leverage: 10, maintenanceMarginPercent: 0.5, qtyType: "fixed", qtyValue: 1, slippageBps: 0, makerFeePercent: 0, takerFeePercent: 0, funding: "off" }); output("close", line, overlay, { description: "Close price" }); let bars: i32 = 0; function onBar(): void { bars += 1; if (bars == 1) strategy.long("L").send(); out_close(bar.close()); } ``` ### 2. Short liquidation with taker fees What it shows: the short side of the same formula, `(100 + 10) / 1.005 = 109.45273631840797`, with a market entry so both the entry fill and the liquidation fill pay `takerFeePercent`. ```typescript // Scenario 2, short liquidation with taker fees: the short formula (100 + 10) / 1.005, both fills paying the taker rate. strategy({ initialCapital: 10000, qtyType: "fixed", qtyValue: 1, instrument: "perps", leverage: 10, maintenanceMarginPercent: 0.5, takerFeePercent: 0.05, funding: "off" }); output("close", line, overlay, { description: "Close price" }); function onBar(): void { const close = bar.close(); if (strategy.positionSize() == 0 && close < 100.5) strategy.short("S").send(); out_close(close); } ``` ### 3. Maker and taker split What it shows: two trades, four fills, four fee classifications. A limit entry and its take-profit limit pay maker; a market entry and its protective stop pay taker. Also a guard-design lesson: the file runs at the bar's close, after fills, so entry zones stay disjoint from exit prices or the flat-position guard re-arms on the very bar an exit filled. ```typescript // Scenario 3, maker and taker split: a limit entry and its take-profit pay maker, a market entry and its stop pay taker. strategy({ initialCapital: 10000, qtyType: "fixed", qtyValue: 1, instrument: "perps", leverage: 5, makerFeePercent: 0.01, takerFeePercent: 0.05, funding: "off" }); output("close", line, overlay, { description: "Close price" }); function onBar(): void { const close = bar.close(); const held = strategy.positionSize(); if (held == 0 && close > 100.5 && close < 103.0) strategy.long("LimitIn").limit(95.0).send(); if (held == 0 && close > 110.5) strategy.long("MarketIn").send(); if (held > 0) { strategy.exit("TP").from("LimitIn").limit(105.0).send(); strategy.exit("SL").from("MarketIn").stop(92.0).send(); } out_close(close); } ``` ### 4. Funding erosion What it shows: funding settlements debit cash and committed margin together, so the liquidation price tightens as margin erodes, and a settlement that depletes the margin liquidates the position at that bar's open with zero price PnL. The chart attaches no funding data to a strategy run, so on the chart this file charges nothing and counts every unsettled open bar in `fundingUnavailableCount`, and the Strategy Tester's **Run details** say "Funding data did not cover N bars" ([Funding](perps.md#funding)). ```typescript // Scenario 4, funding erosion: settlements debit cash and committed margin together, and a depleting settlement liquidates at that bar's open. strategy({ initialCapital: 10000, qtyType: "fixed", qtyValue: 1, instrument: "perps", leverage: 10, maintenanceMarginPercent: 0.5, funding: "data" }); output("close", line, overlay, { description: "Close price" }); function onBar(): void { const close = bar.close(); if (strategy.positionSize() == 0 && close > 99.5) strategy.long("L").send(); out_close(close); } ``` ### 5. Bankruptcy gap What it shows: price gaps straight through the liquidation level. The fill is the bar price because it is worse, the loss beyond committed margin is recorded as `bankruptcyDeficit`, and equity floors at exactly zero. ```typescript // Scenario 5, bankruptcy gap: a gap through the liquidation level fills at the worse bar price, the loss past the margin is the bankruptcy deficit, and equity floors at zero. strategy({ initialCapital: 10, instrument: "perps", leverage: 10, maintenanceMarginPercent: 0.5, qtyType: "fixed", qtyValue: 1, slippageBps: 0, makerFeePercent: 0, takerFeePercent: 0, funding: "off" }); output("equity", line, lower, { description: "Strategy equity" }); let bars: i32 = 0; function onBar(): void { bars += 1; if (bars == 1) strategy.long("L").send(); out_equity(strategy.equity()); } ``` ## Backtest a Hyperliquid perp strategy What it shows: a trend strategy under perps accounting on a venue that is leveraged, funded and liquidatable, with isolated margin at 10x, maker and taker fees, recorded funding and a protective stop off the average entry. A backtest that ignores those three venue facts will happily approve a strategy the venue would have destroyed. ```typescript // A funding-aware trend strategy at 10x: isolated margin, maker and taker rates, recorded funding, and a stop 3% under the average entry. strategy({ initialCapital: 10000, instrument: "perps", leverage: 10, qtyType: "percentOfEquity", qtyValue: 10, makerFeePercent: 0.015, takerFeePercent: 0.045, funding: "data", slippageBps: 2 }); output("fast", line, overlay, { description: "21-period EMA of close" }); output("slow", line, overlay, { description: "55-period EMA of close" }); const fastEma = new Ema(21); const slowEma = new Ema(55); const cross = new Cross(); function onBar(): void { const fast = fastEma.update(bar.close()); const slow = slowEma.update(bar.close()); if (isNaN(fast) || isNaN(slow)) return; const crossed = cross.update(fast, slow); if (crossed == 1) strategy.long("Trend").send(); if (crossed == -1) strategy.closeAll(); if (strategy.positionSize() > 0) strategy.exit("Protect").from("Trend").stop(strategy.positionAvgPrice() * 0.97).send(); out_fast(fast); out_slow(slow); } ``` Put the chart on a Hyperliquid perpetual (BTC, for example) before you press **Backtest**: the file reads the chart's own close through `bar.close()` and pins no market, so the chart you run it on is the market it tests. Reading the declaration, which does most of the perps work: - `instrument: "perps"` with `leverage: 10`: sizing commits **margin**, not notional. `qtyValue: 10` means each entry commits 10% of equity as isolated margin; the notional is that margin times leverage. The broker tracks the liquidation price from your leverage and maintenance margin and closes you there if a bar proves or assumes the level traded. - `makerFeePercent: 0.015, takerFeePercent: 0.045`: fees route by fill type, so market entries, stops and `closeAll` pay taker while limit-bound fills pay maker. Set your own tier's numbers; they travel inside the indicator when you publish it. - `funding: "data"`: the broker settles recorded funding against the open position when funding data is attached. The chart attaches none to a strategy run, so the run counts every unsettled open bar in `fundingUnavailableCount` and charges nothing; the count is the disclosure, and `funding: "off"` declares a strategy that should not depend on funding. - `strategy.positionAvgPrice() * 0.97`: the stop tracks the average entry, re-armed every held bar. ### Reading the result Three lines to check before believing the equity curve: 1. **Funding.** "Funding data did not cover N bars" in **Run details** (`fundingUnavailableCount`) is how many held bars went unsettled, and the Overview's **Funding** chart says no funding was applied. A long that looks fine gross can bleed through settlements while it holds, and this run has not charged them. 2. **Liquidations.** Trades that read **Liquidated** under **Exit via** (`liquidationCount` counts them), and the Overview's line saying when the first one happened. At 10x, a 3% protective stop and the liquidation level are uncomfortably close neighbors. If liquidations show up, the venue closed you before your stop did. 3. **Model-settled fills.** The Performance tab's count (`ambiguousFillCount`) and the **± fill** badge in the Trades tab: fills the declared fill model settled where one bar touched the stop and a level; **Run details** read "Fill precision: bar resolution" once one has. ### Tune it like it is real - **Leverage down first.** At 5x the liquidation level sits twice as far; watch the **Liquidated** exits disappear before you tune anything else. - **Widen the stop or drop the interval.** Brackets arm on the bar after entry, so a tight stop on a coarse chart is exposed for one full bar; [fill simulation](fill-simulation.md#choosing-an-interval-to-trust) covers the trade-off. - **Run the spot twin.** Copy the file into a second **New indicator** draft, drop the perps settings, and press **Backtest** on both: with two strategies on the chart, the Strategy Tester's **Compare** shows what leverage and fees cost you. That difference is the part most backtests never model. <!-- source: https://openmarket.xyz/wrun/reference/quick-reference --> # Quick reference The wrun kit on one screen, then the parts of it that are easiest to forget: the two hooks, the generated accessors (the `p_` / `in_` / `out_` families plus the cell and string families and the bar's own fields), every declaration signature, the fifteen setting kinds and the block kit, the sources the chart serves and their fields, the TA classes, and the kit modules. This page lists what a wrun indicator declares, because an indicator says what it reads and writes and the chart does the calling. ## One screen ### The hooks A file is its declarations at the top, then module state, then one or two plain functions (no `export`, nothing to import): | Hook | Runs | Do this here | Never here | | --- | --- | --- | --- | | `onStart(): void` (optional) | once per evaluation, before any bar | read params through `p_<param>()`, size buffers, construct TA objects | read an input (every `in_` reader and `bar.*()` return NaN before the first bar) or write an output (a write here never reaches a row) | | `onBar(): void` (required) | once per bar, oldest first | read inputs through `in_<input>()`, `bar.*()` and the cell readers, update module state, write outputs through `out_<output>(value)`, string slots, frames, handles and orders; the row is emitted when it returns | grow memory that lasts (size what lives across bars at module start or in `onStart()`; a temporary the bar drops is freed); `emitRow()`: the build sends the row once, after `onBar()` returns, and a call of your own does nothing | Every bar emits a row: an output `onBar()` does not write is NaN on that bar and draws nothing there, so warm-up is a `return` before the writes, or a NaN written as it is. There is no fourth function to write: the chart replays the forming bar from a snapshot of the module's memory. ### Accessors (generated from your declarations each time the editor compiles, in scope with nothing to import) | Accessor | Phase | Meaning | | --- | --- | --- | | `p_<param>(): f64` | `onStart()` on | the param's value: its default, or the setting the chart user chose | | `pb_<param>(): bool`, `p_<range>_lo()` / `_hi()`, `p_<list>(): f64[]`, `p_<session>_start()` / `_end()` / `_tz()`, `p_<param>_unit()`, `pt_<param>(): string` | `onStart()` on | a typed setting's readers: a toggle, a range's ends, a list's filled slots, a session's parts, a unit menu's code, a text setting's words ([Setting kinds](../settings/kinds.md)) | | `in_<input>(): f64` | `onBar()` | this bar's scalar input; NaN on a celled input's slot | | `bar.open()`, `bar.high()`, `bar.low()`, `bar.close()`, `bar.volume()`, `bar.time()`, `bar.isLast()`, `bar.count()` | `onBar()` | the chart's own candle, its open in epoch seconds, whether this is the newest bar, and how many bars the run holds; no `input` line needed, reading a field adds its input to the sheet | | `out_<output>(value: f64): void` | `onBar()` | writes one output; the row is emitted when `onBar()` returns, NaN in every output it did not write | | `in_<input>_cells(): i32` | `onBar()` | f64 cells in this bar's block: `0` for a present empty block, `-1` when the bar carries no block (and before the first bar) | | `in_<input>_view(): StaticArray<f64>` | `onBar()` | the build's own buffer holding this bar's block, no copy; only the first `in_<input>_cells()` values belong to this bar | | `in_<input>_read(ptr: i32): i32` | `onBar()` | copies the block into module memory at `ptr`, for code that owns its own buffer; returns bytes written, `0`, or `-1` | | `in_<input>_max_cells: i32` | constant | the declared `max_cells`, in source tuples | | `in_<input>_capacity: i32` | constant | the f64 count of the build's buffer (the input's capacity x the class's tuple width: `max_cells`, or `max_cells` + `newest` for a print read's union) | | `sb_clear()`, `sb_text(s)`, `sb_int(n)`, `sb_f64(x, decimals)` | `onBar()` | build one UTF-8 line into a shared buffer, allocation-free | | `str_<slot>(s: string)`, `str_<slot>_sb()` | `onBar()` | send a whole string, or the built line, to one slot | ### Declarations (top-level statements of your file) | Declaration | Signature | | --- | --- | | Param | `param(name, default, { required?, min?, max?, description? })`, a number field | | Typed setting | `param.int`, `param.number`, `param.bool`, `param.choice`, `param.color`, `param.time`, `param.price`, `param.range`, `param.multi`, `param.list`, `param.source`, `param.timeframe`, `param.symbol`, `param.session` `(name, default, { required?, min?, max?, description?, label?, step?, group?, row?, hint?, when?, hide?, slider?, unit?, unit_default?, confirm?, visible_by? })`, `tz?` on a session; `market.tick_size()`, `market.price_precision()`, `market.kind()`, `market.point_value()`, `market.zone()`, `market.quote_is_usd()`, `market.session_open()` | | Settings layout | `page(title)`, `section(title, { toggle?, collapsed?, when? })`, `divider()`, `note(text)`, `presets({ Name: { param: value } })`, `legend({ title })` | | Setting bindings | `"@<param>"` as `color`, a `colors` entry or `line_style` on an output or renderer (a `param.color`, a line-style `param.choice`), as `interval` or `symbol` on an input (a `param.timeframe`, a `param.symbol`) | | Input | `input(name, <source>.<field>, { symbol?, exchange?, follow?, interval?, bars?, view?, views?, offset?, side?, tenor?, delta?, fund?, asset?, publisher?, series?, venue?, token?, outcome?, ref?, missing?, needed_by?, when?, when_bit?, description? })` | | Celled input | `input(name, <class>.cells, { max_cells, interval?, bars?, chart_interval_below?, symbol?, exchange?, block_size?, max_depth?, venue?, expiries?, currency?, ticks_per_bar?, description? })`; `max_cells` may be left out on `candles` and `oi_candles`, and `chart_interval_below` rides the three streams alone (`candles`, `oi_candles`, `volume_profile_candles`) | | Output | `output(name, plot?, panel?, { description?, unit?, color?, colors?, width?, opacity?, line_style?, glow?, corner?, color_by?, shape_where?, displacement_bars?, width_by?, widths?, label?, format?, legend?, visible?, visible_by?, price_line?, axis_label?, tooltip?, hover?, badges?, hint? })`, returns an `OutputHandle` | | Hover card | `hover(handle, [block.value(label, output, { format?, delta?, tooltip?, hint? }), block.spark(label, output, { bars?, color? }), block.gauge(label, output, { min, max, format? }), block.pill(label, slot, { color_by?, colors? }), block.rows(label?, [[label, output or slot, format?]]), block.meter(label, output, { min, max, marks? }), block.chips(slot or ladder)])`; the same list inline as an output's `hover` | | Range | `range(upper, lower, { color?, colors?, color_by?, edge_width?, edge_line_style?, smooth?, gradient?, gradientMode?, legend?, label?, z? })`; `edge_width: 0` keeps the band and drops the edge lines | | Fill | `fill(upper, lower, { color?, opacity?, opacity_by?, color_by?, colors?, color_packed_by?, z?, behind_candles? })`, the interior only between two drawn outputs on one pane; `opacity_by` an output whose value is each bar's opacity; `behind_candles: true` paints it under the candles, both sides on the price pane | | Pane | `pane(name, { title?, place?, height?, scale?, invert?, padding?, min?, max?, format?, decimals?, signed?, unit? })`, at most 4; an output names it with `pane` | | Box | `box(name, { top, bottom, from?, to?, when?, panel?, color?, borderColor?, opacity?, borderWidth?, borderStyle?, z?, colorBy?, colors?, colorPackedBy?, borderColorBy?, borderColors?, borderColorPackedBy? })` | | Segment | `segment(name, { yFrom, yTo, from?, to?, when?, panel?, color?, width?, lineStyle? })` | | String slot | `string(name, { max_bytes, description? })` | | Renderers | `render.text(name, { y, text, color?, size?, style?, align?, valign?, label_position?, background_color?, background_color_by?, background_colors?, border_color?, corner_radius?, font_weight?, font_family?, emblem_shape?, emblem_color?, size_by?, color_by?, colors?, color_packed_by?, panel?, tooltip?, hover?, badges? })`, `render.label(name, { x, y, text, color?, size?, style?, position?, offset?, align?, valign?, background_color?, border_color?, corner_radius?, padding?, font_weight?, font_family?, emblem_shape?, emblem_color?, size_by?, tooltip?, hover?, badges? })` (a corner label takes `position` and `offset` and no point), `render.table(name, { rows, cols, cells, position?, ...look, styles? })` ([Styled tables](../presentation/cards-frames-panels.md#styled-tables)), `render.shape(name, { output, shape, where?, color?, color_by?, colors?, width?, location?, glow?, fill?, fill_opacity?, char?, font_family?, tooltip? })`, `render.stats_row(name, { output, title?, format?, polarity?, color?, colors?, color_by?, color_packed_by?, priority?, visible? })`, `render.bgcolor(name, { where, color?, color_by?, colors?, width?, line_style? })`, `render.barcolor(name, { where, color?, color_by?, colors? })` | | Legend and HUD | `render.legend(name, { text?, value?, format?, color?, color_by?, colors? })`, `render.hud(name, { position, title?, columns?, tiles: [tile.value(...), tile.spark(...), tile.gauge(...), tile.pill(...), tile.rows(...), tile.meter(...), tile.chips(...), tile.rings(...)], look?, width?, offset?, z?, chrome?, texture?, text_glow?, title_case?, label_case?, accent_color?, accent_color_by?, accent_colors?, background_color?, background_opacity?, background_gradient?, gradient_direction?, border_color?, border_width?, border_style?, corner_radius?, padding?, shadow?, opacity?, text_color?, title_text_color?, font_family?, safe_area?, mobile? })` | | Drawings | `draw.line(name, { x1, y1, x2, y2, color?, width?, line_style?, extend?, arrow?, glow?, glow_color?, sticky_right?, axis_label?, opacity?, tooltip? })`, `draw.box(name, { left, top, right, bottom, color?, border_color?, opacity?, border_width?, border_style?, corner_radius?, extend?, shape?, gradient?, gradient_direction?, glow?, glow_color?, text?, text_color?, font_size?, font_weight?, font_family?, align?, valign?, padding?, tooltip? })`, `draw.polyline(name, { points, color?, width?, line_style?, opacity?, fill_color?, closed?, smooth?, arrow?, glow?, glow_color?, tooltip? })`, `draw.label(name, { x, y, text, color?, style?, align?, valign?, background_color?, border_color?, border_width?, corner_radius?, font_weight?, font_family?, padding?, max_width?, angle?, glow?, glow_color?, emblem_shape?, emblem_color?, sticky_right?, axis_label?, opacity?, tooltip? })` | | Widgets | `draw.card(name, { title, anchor?, offset?, z?, state_by?, rows, headline?, rule?, rule_color?, show_state?, state_colors?, ...look })`, `draw.feed(name, { frame, anchor?, offset?, z?, title?, time_format?, ...look })`, `draw.meter(name, { label, fraction, ramp, text?, anchor?, offset?, z?, title?, bar_height?, track_color?, ...look })`, `draw.ladder(name, { frame, side, divider?, title?, width_frac?, offset?, opacity?, color?, labels?, format?, decimals?, signed?, unit?, text_color?, font_size?, font_family?, font_weight?, divider_color?, panel? })`; the look is `chrome`, `stripe`, `controls`, `accent_color`, `title_text_color`, `title_font_size`, `title_font_weight`, `background_color`, `background_opacity`, `background_gradient`, `gradient_direction`, `border_color`, `border_width`, `border_style`, `corner_radius`, `padding`, `width`, `opacity`, `font_size`, `font_family`, `font_weight`, `text_color`, `label_text_color`, `above_drawings`, `safe_area`, `panel` | | Frames and panels | `frame(name, { max_bytes? })`; `plot.levels({ name, frame, dock, width_frac?, poc?, labels?, color?, span?, ...style })`; `panel.bars` / `line` / `scatter` / `histogram` / `pie` / `heatmap` / `table` / `tiles({ name, title, x, place, frame, series?, ...style })`; `plot.matrix({ name, frame, dock?, columns?, ...style })`; `out.inset(name, { dock, height_px?, shape?, color?, colors?, color_by?, opacity? })` | | Price canvases | `plot.heatmap({ name, cells | grid, value?, price_low?, price_step?, ...style })`, `out.grid(name, { rows })`, `plot.footprint({ name, cells, ...style })`, `plot.tpo({ name, cells?, period?, letter_minutes?, ...style })`, `plot.profile({ name, cells, span?, session?, start?, end?, ...style })` | | Marks, spans and rays | `plot.marks({ name, slots, size?, opacity_pct?, look?, text?, x?, colors?, tooltip? })` written through `out_<name>_mark(slot, price, qty, side, fills, offsetMs)`; `plot.spans({ name, slots, colors?, opacity?, border?, words?, tooltip? })` through `out_<name>_span(slot, top, bottom, lengthBars, style, word, extend)`, or timed through `out_<name>_span_at(slot, top, bottom, startTs, endTs, style, word, extend)`; `plot.rays({ name, slots, colors?, width?, line_style?, opacity?, words?, tooltip? })` through `out_<name>_ray(slot, y1, y2, lengthBars, style, word, extend)`, or timed through `out_<name>_ray_at(slot, y1, y2, startTs, endTs, style, word, extend)`; `out_<name>_clear()` empties a section | | Handles | `handles.line`, `handles.box`, `handles.label`, `handles.polyline({ anchor?, safe_area?, ...the drawing's keys })`, the defaults for handles the module creates in `onBar()` | | Chart | `chart.contrast_guard(false)` (keep the author's colours on a light chart), `chart.stack_handles(true)` (keep clear of another indicator's anchored handles), `chart.up_color()`, `chart.down_color()`, `chart.grid_color()`, `chart.bg_color()` (the chart's colours as packed numbers, read in `onStart()`) | | Alert | `alert(name, { when, message?, text?, every_bar?, description? })`, `when` an output handle bound by a top-level `const`, `text` a string slot ([Alerts](../functions/alerts.md)) | Vocabulary the declarations take: | Slot | Values | | --- | --- | | `plot` | `line`, `bar`, `area` (filled down to zero), `histogram`, `candle` (four in a row draw one candle series: open, high, low, close), `shape`, `scatter` (one mark per value), `none` (data-only: computed, never drawn) | | `panel` | `overlay` (the price pane), `lower` (a pane below the chart) | | `line_style` / `lineStyle` / `edge_line_style` | `solid`, `dashed`, `dotted` | | `format` (outputs, panes, panels, levels, cards, ladders, canvases, blocks, `{{name:format}}`) | `price` (the chart's price digits), `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd` (`$1.2M`), `auto` (six significant digits with thousands separators); a card row or headline also takes `pct`; `decimals` (0..8), `signed` and `unit` (up to 8 characters on the new surfaces; unbounded on an output, as it always was) refine a declared format | | `style` (labels) | `plain`, `price_label`, `pill`, `callout`, `badge`, `box`, `knockout`, `emblem`, on `render.text`, `render.label`, `draw.label` and `handles.label`; a drawing or handle label takes `box` for the tag look, never `price_label`, and a corner label takes neither `price_label` nor `callout` | | `position` (tables, HUD, corner labels) and `anchor` (cards, feeds, meters, anchored handles) | `top_left`, `top_center`, `top_right`, `middle_left`, `middle_center`, `middle_right`, `bottom_left`, `bottom_center`, `bottom_right` | | `font_family`, `font_weight`, `valign` | `ui`, `mono`, `serif`, `rounded` (system stacks, nothing downloads); `normal`, `medium`, `bold`; `top`, `middle`, `bottom` | | `gradient_direction`, `corner_radius`, `opacity` | `vertical`, `horizontal`; 0..32 px; 0..1, multiplying every colour's own alpha | | `location` (marks) | `absolute`, `above_bar`, `below_bar`, `top`, `bottom` | | `chrome` | a panel: `box`, `grid`, `none`; a card, feed or meter: `state`, `plain`; a HUD frame: `card`, `none`, `brackets`, `rules`, `tag`, `title_bar`, `window`, `cover` | | `look` (HUD) | `default`, `glass`, `stage`, `signal`, `terminal`, `broadsheet`, `chart_desk`, `dial`, `grid`, `cockpit`, `phosphor`, `classic`; a word declared beside it wins | | `param.timeframe` default | `chart`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w` | | `param.source` default | `ohlcv.open`, `.high`, `.low`, `.close`, `.volume`, and the blends `.hl2`, `.hlc3`, `.ohlc4`, `.hlcc4` | | `market.kind()` | `p_market_kind()`: 1 crypto, 2 stock or ETF, 3 forex, 4 metal, 5 index, 6 economic series, 0 unknown | | `market.quote_is_usd()` | `p_market_quote_is_usd()`: 1 US dollars, 2 another currency or coin, 0 unknown | | `market.zone()` | `p_market_zone()`: the market's zone as its `tz` index below (0 UTC, also unknown) | | `market.session_open()` | `p_market_session_open()`: the minute the trade day opens on the market's clock, 1020 on CME and on forex, 0 (midnight) elsewhere; with the zone it feeds `sessionDayOpen`, `sessionTradeDate`, `sessionWeekOpen`, `sessionGapBefore` ([Venue trade day](../settings/sessions-and-units.md#venue-trade-day)) | | `market.size_unit()` | declares `market.kind()`, `market.point_value()` and `market.zone()` for `sizeUnit(kind, pointValue, zone)`: 0 units, 1 coins, 2 shares, 3 contracts ([Size units](../settings/sessions-and-units.md#size-units)) | | `market.notional()` | declares `market.point_value()` and `market.zone()` for `notional(qty, price, pointValue, zone)`: `qty * price * pointValue`; `NaN` on the CME zone when the point value is 0 or 1, elsewhere a point value of 0 read as 1 | | `market.earnings_next_ms()`, `market.earnings_prev_ms()` | the underlying's next and last earnings report, epoch ms, read through `earningsMs(p_market_earnings_next_ms())` (`NaN` when the chart does not know the date); a US stock chart, upcoming (no surface fills it yet) | | `market.earnings_session()` | `i32(p_market_earnings_session())`: `1` before the open, `-1` after the close, `0` unknown; upcoming (no surface fills it yet) | | `market.option_multiplier()` | `p_market_option_multiplier()`: the US dollars one price unit times one size unit of an option on the chart's chain is worth, so a premium is size times price times it: 100 on US listed options, the root's point value on CME (50 on ES, 20 on NQ), 1 on a crypto chain; `0` where the host does not know it (every host but the chart): draw no premium then, never 0 | | `market.dollar_multiplier()` | `p_market_dollar_multiplier()`: the US dollars one size unit of the market's own trades is worth at one unit of price, so a trade's dollar value is size times price times it: the point value on CME (50 on ES, 20 on NQ, 50 on ZC priced in cents), 1 on a market priced in US dollars or a dollar stablecoin; `0` where the host does not know it (the cloud and the alerts engine, a market quoted in another currency): value nothing then, never 0 | | `market.option_contract()` | `i32(p_market_option_contract())`: `1` on the chart of a single option contract (an OPRA contract, a CME option, a Deribit option), `0` on every other chart; every chart fills it. On `1` the price axis is the contract's premium, not the underlying's price: draw no price marks or levels on it (strikes, walls, the expected move, the gamma flip) | | `unit` | `price`, `ticks`, `%`, `atr` (codes 0, 1, 2, 3 in `p_<param>_unit()`) | | `tz` (a session) | `UTC`, `America/New_York`, `America/Chicago`, `Europe/London`, `Europe/Berlin`, `Asia/Tokyo`, `Asia/Hong_Kong`, `Asia/Singapore`, `Australia/Sydney`, `Asia/Kolkata`, `America/Los_Angeles`, `America/Toronto`, `America/Mexico_City`, `America/Sao_Paulo`, `America/Argentina/Buenos_Aires`, `Europe/Paris`, `Europe/Amsterdam`, `Europe/Zurich`, `Europe/Madrid`, `Europe/Rome`, `Europe/Stockholm`, `Europe/Oslo`, `Europe/Copenhagen`, `Europe/Warsaw`, `Europe/Helsinki`, `Europe/Athens`, `Europe/Istanbul`, `Europe/Moscow`, `Asia/Jerusalem`, `Asia/Riyadh`, `Asia/Dubai`, `Africa/Johannesburg`, `Asia/Karachi`, `Asia/Bangkok`, `Asia/Jakarta`, `Asia/Ho_Chi_Minh`, `Asia/Kuala_Lumpur`, `Asia/Shanghai`, `Asia/Taipei`, `Asia/Manila`, `Asia/Seoul`, `Pacific/Auckland` (42 zones; each with its offset and daylight rule on [Sessions and units](../settings/sessions-and-units.md)) | | `shape` (renderer) | `circle`, `cross`, `triangle_up`, `triangle_down`, `diamond`, `arrow_up`, `arrow_down`, `flag`, `square` | | `missing` | `carry` (the default: the latest value carries forward), `nan`, `zero`: what a bar with no observation of its own reads | | `side` | `BUY`, `SELL` | | `follow` (`trades` only, beside `exchange`) | `coin`: the venue's main market for the coin of the chart's market (its USDT market on a stablecoin venue, its USD market on Coinbase, Kraken, Bitstamp, Bitfinex and Gemini), picked by the chart and again on a coin switch; a venue that lists no market for the coin reads the input's `missing` fill. Never beside `symbol`, never on the first input | | `when`, `when_bit` (a secondary feed) | `when` names a `param.bool`, or a `param.multi` with `when_bit` the option's bit (0 for the first option): while the setting is off the lane is not fetched and the input reads its `missing` fill. Read the setting in your code too: a host that ignores the word still fetches the lane | | `tenor` | `ONE_W`, `ONE_M`, `TWO_M`, `THREE_M`, `SIX_M`; required on `implied_volatility` and `skew` | | `delta` | `5`, `15`, `25` (the default), `35`; `skew` only | | `fund` | an ETF ticker (`IBIT`, `FBTC`, `ETHA`, ...) or `all` (the sum over every fund listed for the chart's coin); required on `etf_flow`, `etf_holdings` and `etf_premium`, and `etf_premium` takes one ticker, never `all` | | `venue` | on `options_chain` and the chain sources (`option_strikes`, `option_contract_state`, `option_surface`, `option_daily`, `option_stats_10m`, `option_prints`, `option_contract_flow`, `option_prints_v2`): `auto` (the default), `deribit`, `cme`, `binance`, `okx`, `bybit`, `bullish`, `derive`; on `options_oi` and `options_volume`: `deribit` (the default), `binance`; on `options_flow` with `scope: "venue"` only (required there): the exchange id | | `book` | the chain sources, and `options_flow` under `scope: "ticker"` only: `auto` (the default: the book named like the coin, else the first in name order) or one book's name as the data spells it (`BTC`, `BTC_USDC`, `BTC-USD_UM`); a word that is no book name is refused when the indicator is built, a book the chain does not list when it runs | | `underlying` | `options_chain`, `option_strikes` and `options_flow`: `auto` (the default, the chart's own chain), `derived` (the first root the options kit's `DERIVED_ROOTS` maps the chart's root to: NDX on NQ, SPX on ES), a root in capitals (`SPX`, `QQQ`, `ES`, `BTC`) or `"@<param>"` naming a select setting; that root's chain or flow, read on the plane that lists it. On `options_flow` anything but `auto` is read under `scope` `ticker` or `prints` only (the other scopes span underlyings); the chart's own price stays the price input | | `scope`, `dte`, `moneyness` | `options_flow` only: `scope` `ticker` (the default, the chart's underlying, one book by `book`), `market`, `equity`, `etf`, `index` or `venue`, each read per market (on crypto and CME `equity`, `etf` and `index` read the fill, and so does `venue` on CME); `dte` `all` (the default), `0dte`, `week`, `month`, `later`; `moneyness` `all` (the default), `otm`, `itm` | | `publisher`, `series` | the publisher's upper-case id (`FRED`, `US_TREASURY`, `ECB`, ...) and that publisher's series id (`DGS10`); `economic` only, both required | | `ref` | a published feed's address, `@scope/name`; the `series` source only, required there | | `asset` | an upper-case ticker (`BTC`); `treasury_balance` only, the chart's coin when absent | | `token` | the token's display name (`Bitcoin`, `Ethereum`, `Solana`), never its ticker; `token_supply` only, required | | `outcome` | `YES`, `NO` (`NO` on the `close` field only) | | `interval` (a pin) | `MINUTE`, `FIVE_MINUTES`, `FIFTEEN_MINUTES`, `THIRTY_MINUTES`, `HOUR`, `FOUR_HOURS`, `DAY`, `WEEK` (or `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w`); chart only, the custom timeframes `TWO_MINUTES`, `THREE_MINUTES`, `TEN_MINUTES`, `FORTY_FIVE_MINUTES`, `TWO_HOURS`, `SIX_HOURS`, `EIGHT_HOURS`, `TWELVE_HOURS`, `THREE_DAYS` (or `2m`, `3m`, `10m`, `45m`, `2h`, `6h`, `8h`, `12h`, `3d`) | | `view` (with an interval pin) | `confirmed` (the default), `forming`, `is_new_period`; `views` lists the extra ones as `"forming,is_new_period"`; `offset: N` writes the `offset` view for you | | `offset` (with an interval pin) | `1` to `500`: the pinned candle N candles before the confirmed one, `NaN` until N + 1 have closed | | `bars` (an interval pin or a stream) | `1` to `5000`: how many of the pin's own candles to reach back from the newest; it only deepens the fetch | | `chart_interval_below` (the three streams only) | an interval word (`1h`, `HOUR`, ...): the stream is fetched only on a chart finer than it; on that interval's chart or a coarser one the input reads an empty block on every bar, with no fetch and no warning. Never on the first input or beside `view: "forming"` | | Box and segment offsets | literals in -500..500, whole or fractional (a fraction places the edge inside its bar), or an output handle whose per-bar value truncates to the offset | | Colors | any string on outputs, segments, renderers and drawings; a box fill (a box's or a box handle's `color`) needs hex, `rgb()`, `hsl()` or a theme token; every style word this reference lists on panels, levels, cards, feeds, meters, ladders, HUDs and canvases takes `#rrggbb`, `#rrggbbaa` or a theme token; the seven tokens `theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid`, `theme.accent` pass on every colour key and frame colour (a colour param's default and presets excepted) and follow the chart's theme at paint time | ### Settings Fifteen kinds, each a top-level `param.<kind>(name, default, options?)`: the control the dialog draws for it, and the reader `onStart()` calls (it answers from then on) ([Setting kinds](../settings/kinds.md)). | Kind | The dialog draws | `onStart()` reads | | --- | --- | --- | | `param.int("length", 20, { min: 2, max: 500 })` | a number field that steps by 1 | `p_length()`, a whole number | | `param.number("mult", 2.0, { min: 0.5, max: 5, step: 0.1 })` | a number field that steps by `step` | `p_mult()` | | `param.bool("show_bands", true)` | an on/off toggle | `pb_show_bands()`, a `bool` | | `param.choice("kind", ["Simple", "Exponential"], "Simple")` | a menu of the labels | `p_kind()`, the picked index (0 for the first label) | | `param.color("basis_color", "#2962ff")` | a color picker | `p_basis_color()`, the color packed into one number; most files bind it to an output with `color: "@basis_color"` instead | | `param.time("since", "2024-01-01 00:00")` | a date and time field with **Pick**: the next click on the chart sets it | `p_since()`, epoch seconds | | `param.price("floor", 0.0)` | a number field with **Pick**: the next click on the chart sets the price | `p_floor()` | | `param.range("band_pct", [0.5, 2.0], { min: 0, max: 10 })` | one slider with two handles | `p_band_pct_lo()` and `p_band_pct_hi()` | | `param.multi("days", ["Mon", "Tue", "Wed"], ["Mon", "Wed"])` | a chip per option up to four options, a multi-select menu past that | `p_days()`, a bitmask (bit 0 is the first option); `multiHas(mask, i)` tests one | | `param.list("lookbacks", [5.0, 20.0], { max: 4 })` | an editable list of numbers with **Add**, up to `max` long | `p_lookbacks()`, an `f64[]` of the filled slots | | `param.source("src", ohlcv.close)` | a menu of `open`, `high`, `low`, `close`, `hl2`, `hlc3`, `ohlc4`, `volume`, `hlcc4` | nothing: it declares the input too, and `in_src()` reads the picked field per bar | | `param.timeframe("htf", "chart")` | a menu of `chart`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w` | nothing: `{ interval: "@htf" }` on an input pins that input to the pick | | `param.symbol("pair", "BINANCE_FUTURES:ETHUSDT")` | a market button that opens the symbol search | nothing: `{ symbol: "@pair" }` on an input pins that input to the pick | | `param.session("rth", "09:30-16:00", { tz: "America/New_York" })` | a day strip with the window shaded, a start and an end on the 24-hour clock, and a zone menu | `p_rth_start()` and `p_rth_end()` (minutes from midnight), `p_rth_tz()` (the zone's index) | | `param.text("label", "Session average", { max_bytes: 64 })` | a text field (a text area for `param.text_area`) | `pt_label()`, the words as a `string` | Every kind takes one options object, every key optional ([Options on a setting](../settings/options.md)). The words that lay the dialog out are on [Pages, sections, dividers, notes](../settings/layout.md), the named sets of values on [Presets](../settings/presets.md), the per-output rows the dialog adds by itself on [The Style page](../settings/style-page.md), the session zones and the unit codes on [Sessions and units](../settings/sessions-and-units.md), where a pick applies and the 128-setting cap on [Picks, lanes, the cap](../settings/picks-and-lanes.md), and every refusal on [What the build checks](../settings/checks.md). ### Presentation One kit of seven blocks with two homes: the card the cursor opens (`block.<kind>`, on a line, its legend entry, a HUD tile, a text or label mark) and a HUD card at one of the nine anchors (`tile.<kind>`). Every block reads the newest row; outputs and slots are named by a bound handle or by their name as a string ([Blocks and tiles](../presentation/hud-and-hover-cards.md#blocks-and-tiles)). | Block or tile | Renders in | Options | | --- | --- | --- | | `value(label, output)` | a hover card as `block.value`, a HUD card as `tile.value`: the output's newest value under its label, a signed delta from the `delta` output beside it | `format`, `delta`, `tooltip`, `hint`, `color` or `color_by` + `colors`, `headline` (one per card, spanning every column), `font_size` | | `spark(label, output)` | both: a sparkline of the output's last bars (64 at most) | `bars`, `color` or `color_by` + `colors`, `draw` (`line`, `area`, `dots`, `bars`, `text`), `height` (16..120) | | `gauge(label, output)` | both: a dial between `min` and `max` | `min` and `max` (required), `format`, `color` or `color_by` + `colors`, `draw` (`arc`, `ring`, `dial`, `ticks`, `bar`, `blocks`, `text`) | | `pill(label, slot)` | both: the slot's words as a chip, colored by a ladder | `color`, `color_by`, `colors`, `draw` (`capsule`, `dot`, `led`, `text`), `headline`, `font_size` | | `rows(label?, [[label, output or slot, format?], ...], options?)` | both: rows of label and value | a `format` per row; `color` or `color_by` + `colors`, `leader` (`none`, `dots`) | | `meter(label, output)` | both: a bar between `min` and `max` with marks | `min` and `max` (required), `marks`, `color` or `color_by` + `colors`, `draw` (`bar`, `split`, `blocks`, `segments`, `scale`, `text`), `height` | | `chips(slot or ladder output)` | both: the slot's words, or the ladder's labels, as chips | none | | `rings(label?, [[label, output, { min, max, color? }], ...])` | both: 1..3 concentric rings, outermost first, each a share of its own range, with a legend beside | `height` (16..120) | The hover card is `hover: [...]` on an output, a `render.text` or a `render.label`, or `hover(handle, [...])` at the top level ([Hover cards](../presentation/hud-and-hover-cards.md#hover-cards)); the HUD card is `render.hud(name, { position, title?, columns?, tiles })` ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)). The third home, the legend, takes words rather than blocks: `legend({ title })` after the indicator's name and `render.legend(name, { text?, value?, format?, color?, color_by?, colors? })` per entry, with `label`, `format` and `legend: false` on an output shaping its own entry ([Legend](../presentation/legend.md)). The `tooltip` templates, the label `style` words and `badges` are on [Labels, tooltips, badges](../presentation/labels-and-tooltips.md); `glow`, `corner`, `opacity`, `width`, `line_style`, a range's gradient and the `color_by` and `width_by` ladders are on [Styling](../presentation/styling.md). ### Sources the chart serves | Source | Fields | Knobs and units | | --- | --- | --- | | `ohlcv` | `open`, `high`, `low`, `close`, `volume` | the chart's own candles; a secondary input may pin another market or a coarser interval | | `trades` | `volume` | `side` REQUIRED: that side's volume per bar, in the base asset; `currency` `"USD"` reads it in dollars, `"Coin"` in coins (one lane per unit), `"Auto"` contracts on a futures market and dollars elsewhere, or `"@<param>"`: a `param.choice` of the units (`["USD", "Coin"]`) picks it, the default's word when the setting is untouched; `follow: "coin"` beside `exchange` reads another venue's market for the chart's coin | | `funding` | `rate_close` | in percent, normalized to a one-hour rate; may pin a coarser interval | | `oi` | `open`, `high`, `low`, `close` | in USD by default; `currency: "Coin"` reads the venue's own units (coins or contracts); may pin a coarser interval | | `liquidations` | `liquidations` | `side` optional (absent = both sides summed); in USD; sparse, so an indicator usually declares `missing: "nan"` or `"zero"` | | `long_short_ratio` | `total_account`, `top_trader_account`, `top_trader_position` | plain ratios of longs over shorts (a value at or below 0 reads `NaN`); the chart must be 5 minutes or coarser | | `implied_volatility` | `implied_volatility` | `tenor` REQUIRED; Deribit's summary for the chart's coin | | `skew` | `skew` | `tenor` REQUIRED, `delta` optional (25 when absent); Deribit's skew for the chart's coin | | `volatility_index` | `open`, `high`, `low`, `close` | Deribit's volatility index (DVOL) for the chart's coin, in index points; BTC and ETH | | `options_oi` | `puts`, `calls` | `venue` optional; open interest in the venue's units (contracts on Deribit, the base coin on Binance); BTC and ETH | | `options_volume` | `puts`, `calls` | `venue` optional; volume in contracts; BTC and ETH | | `etf_flow` | `flow_usd` | `fund` REQUIRED; the chart's coin must be BTC, ETH or SOL; daily (on an intraday chart the day's value lands on the first bar of its day); served in the browser, and an alert on an indicator that reads it is refused | | `etf_holdings` | `holdings` | `fund` REQUIRED (a ticker or `all`); in coins of the fund's underlying; a coin with listed spot ETFs | | `etf_premium` | `premium_rate` | `fund` REQUIRED (one ticker); in percent; daily, read as the newest value at or before the bar's day | | `ethena_positions` | `collateral` | Ethena's collateral in the chart's coin; BTC and ETH | | `bitfinex_funding` | `funding_size`, `credit_size`, `active_credit_size`, `margin_rate` | the three sizes in the funding currency, `margin_rate` an APR in percent; the chart's coin | | `treasury_balance` | `balance` | `asset` optional; Binance's own balance in coins, published monthly | | `token_supply` | `marketcap`, `first_marketcap`, `marketcap_dominance_percent`, `circulating_supply`, `total_supply`, `max_supply`, `total_value_locked`, `fully_diluted_valuation`, `cg_marketcap_rank`, `total_volume`, `usd_price` | `token` REQUIRED; daily; a one-minute chart is refused | | `economic` | `value` | `publisher` and `series` REQUIRED; the publisher's unit; daily or slower | | `series` | `value` | `ref` REQUIRED; a published feed's reading, `missing` `carry` or `nan`; never the primary input; 1m to 1W charts ([Feeds as inputs](../core-concepts/feeds-as-inputs.md)) | | `odds` | `open`, `high`, `low`, `close` (default), `volume` | the market's condition id (`0x` plus 64 hex characters) as `symbol`, plus `outcome`; `exchange` is implied and refused; the chart has no market picker, so `binding` is refused | | `time` | `bar_open_sec`, `trade_date`, `session` | the bar's open, its exchange trade date (epoch seconds at 00:00 UTC) and its session (`1` regular, `2` pre-market, `3` after-hours, `0` closed); no knobs, never the primary input | Ten feeds share the `etf_flow` rule (served in the browser, and an alert on an indicator that reads one is refused): `long_short_ratio`, `volatility_index`, `options_oi`, `options_volume`, `etf_holdings`, `etf_premium`, `ethena_positions`, `bitfinex_funding`, `treasury_balance` and `economic`. Pins: `symbol` and `exchange` go together (a lone half is refused), in the chart's own ids (`{ symbol: "ETHUSDT", exchange: "BINANCE_FUTURES" }`). The chart checks every pin before it fetches anything. A secondary `ohlcv` input may pin another market, read bar by bar at the chart's interval, and an interval coarser than the chart's that is a whole multiple of it, read as of the coarser candle's close; `funding` and `oi` may pin a coarser interval on the chart's own market. Everything else is refused by name: a pin on the primary input, a market pin on any other source, a finer interval, and an interval on any other feed (`trades`, `liquidations`, `implied_volatility`, `skew`, `etf_holdings`, `economic`, ...), on `time` or on a celled input. Four celled inputs are the exception: `intrabar` and the three streams (`candles`, `oi_candles`, `volume_profile_candles`) require an `interval` and may pin another market. [Multi-timeframe](../core-concepts/multi-timeframe.md) has the views. ### Celled classes (`abi_version: "wrun-2"`) | Class | Tuple | Width | Knobs | On the chart | | --- | --- | --- | --- | --- | | `volume_profile` | `[low, high, buy, sell]` per price bucket, ascending by price | 4 f64 | `ticks_per_bar` (1 to 500 of the market's buckets merged into one), `currency` (`"USD"`, `"Coin"` by default, or `"Auto"`: contracts on a futures market, dollars elsewhere) | served, history and live, on the chart's own market | | `book` | `[price, size, side]` per level, side `+1` bid / `-1` ask | 3 f64 | `block_size` REQUIRED by the declaration | served, history and live: the chart's own order book at its own grouping, at most 500 levels a side, whatever `block_size` and `max_depth` say; bids come best first, then asks from the farthest to the best, so branch on `side`, never on position | | `intrabar` | `[offset_ms, open, high, low, close, volume]` per closed finer bar, ascending | 6 f64 | `interval` REQUIRED (finer than the chart's and dividing it evenly, `1m` at the finest); `max_cells` at least the finer bars in one chart bar; `symbol` + `exchange` for another market | served on the chart's own market or a pinned one | | `candles` | `[offset_ms, open, high, low, close, volume]` per closed candle of the stream's interval, oldest first | 6 f64 | `interval` REQUIRED (any word); `bars` 1 to 5000; `max_cells` filled when left out; `symbol` + `exchange` for another market; `view: "forming"` (the live candle on the live bar) or `"forming_open"` (on every bar the open of the candle holding it, `[offset_ms, open, NaN, NaN, NaN, NaN]`), each without `bars`; `chart_interval_below` (fetched only on a chart finer than it, an empty block on every bar elsewhere) | served: the backlog on the first bar, then each candle on the bar it closes with | | `oi_candles` | `[offset_ms, open, high, low, close]` per closed open interest candle of the stream's interval, oldest first | 5 f64 | `interval` REQUIRED (any word); `bars` 1 to 5000; `max_cells` filled when left out; `currency` (`"Coin"` by default: the venue's own units, coins or contracts; `"USD"` dollars); `symbol` + `exchange`; `chart_interval_below`; no `view` | served: the `candles` rules on the leg's open interest | | `volume_profile_candles` | `[offset_ms, low, high, buy, sell]` per price row of each closed candle of the stream's interval; the rows of one candle share its `offset_ms`, candles oldest first, rows ascending by price | 5 f64 | `interval` REQUIRED (any word); `bars` 1 to 5000; `max_cells` REQUIRED, at least `bars` (the rows one candle holds times `bars`); `ticks_per_bar` and `currency` as on `volume_profile`; `symbol` + `exchange`; `chart_interval_below`; no `view` | served: the `candles` rules on the leg's volume profile | | `trade_volume_by_size` | `[bucket, buy_usd, sell_usd, buy_count, sell_count]` per USD trade-size bucket that traded (each fill at its own size), ascending; `bucket` 1 (under 1K) to 7 (10M and up) | 5 f64 | none (`max_cells` 7 holds a full bar) | served on the chart's own market; a bar with no trades is an empty block | | `options_chain` | `[strike, expiry_ms, side, oi, gamma, delta, mark_iv, underlying, multiplier, vega]` per listed contract, side `+1` call / `-1` put | 10 f64 | `venue` (`"auto"` default, `"deribit"`, `"cme"`, `"binance"`, `"okx"`, `"bybit"`, `"bullish"`, `"derive"`), `expiries` (`"all"` default or `"nearest:N"`) | served on the LAST row only (history rows are empty blocks), a snapshot refreshed about every 30 seconds | | `option_strikes` | `[strike, expiry_ms, net_gex, call_gex, put_gex, net_dex, net_vex, call_oi, put_oi, call_iv, put_iv, underlying]` per (expiry, strike) row of the bar's strike snapshot; a side the strike does not list reads NaN; open interest in the chain's own size (coin on a crypto chain, contracts on US listed options and CME) | 12 f64 | `venue` and `expiries` as on `options_chain` (`"nearest:N"` keeps each bar's N earliest expiries), `book` | served on EVERY bar on crypto, CME and US stock charts: the newest minute of strike rows of one book inside the bar, an empty block where there is none; one chain per indicator | | `tape` | `[offset_ms, price, size, side]` per print, side `+1` buy / `-1` sell, `size` in the floor's unit | 4 f64 | exactly one floor REQUIRED: `min_value` (dollars, `size` the print's dollar value), `min_size` (the size the venue stores) or `min_coins` (coins on coin markets, `size` the print's dollar value), each a number or a setting the floor follows; `history` (`"0"` by default, or a duration up to `"30d"`); on a second tape, `needed_by` (the markets that read it, zero prints elsewhere, and beside `size_unit` one `param.choice` that picks it) | served: history from the large-print lane over the chart's window, then live prints; the lane keeps prints of $10,000 or more on USD markets and the contracts floor on CME, so a lower floor reads history at the lane's; a `1s` chart and a calendar interval are refused | | `option_prints` | `[offset_ms, print_key, root_code, expiry_ms, side_cp, strike, price, size, premium, aggressor, outside, underlying, iv, delta, venue, present]` per print; size in the chain's own size, price in USD per unit of the underlying, the taker's side off US listed options | 16 f64 | `venue`, `book`, `min_premium` REQUIRED (USD), `expiries`, `history` (`"live"` default, `"3d"`, `"90d"`), `overflow` (`"refuse"` default, `"largest"`) | served per bar on crypto, CME and US stock charts, one book of the chain `venue` picks; one set of knobs a package | | `option_contract_flow` | `[root_code, expiry_ms, side_cp, strike, vol_ask, vol_bid, vol_mid, vol_none, prem_ask, prem_bid, share_delta_net, vwap, last_price, iv_last, vol_above_ask, vol_below_bid, present]` per contract that traded; off US listed options the side is the taker's and the mid, none and outside values read 0 | 17 f64 | `venue`, `book`, `expiries`, `strike_window_pct`, `min_volume` | served per bar on crypto, CME and US stock charts, one book of the chain `venue` picks | | `option_contract_state` | `[root_code, expiry_ms, side_cp, strike, bid, ask, last, prev_close, theta, volume_day, oi, oi_prev, present]` per contract; sizes in the chain's own size (coin on a crypto chain, contracts on US listed options and CME), prices in USD per unit of the underlying | 13 f64 | `venue`, `book`, `expiries`, `strike_window_pct` | served on the LAST row only on crypto, CME and US stock charts, one book of the chain `venue` picks, a read of its own beside `options_chain` | | `option_surface` | `[expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present]` per expiry | 9 f64 | `venue` as on `options_chain` (`"auto"` default), `book` (`"auto"` default: the book named like the coin; or one book's name, `"BTC_USDC"`) | served on EVERY bar on crypto, CME and US stock charts: one book of the chain `venue` picks; one chain per indicator | | `option_prints_v2` | `option_prints`' 15 values, then `block_key` (the block trade, 0 for a screen print), `rfq_key` (the RFQ, 0 for none), `legs` (the leg count, 1 single, 0 unknown) and `present` per print | 19 f64 | `option_prints`' knobs and `structure` (`"all"` default, `"blocks"`, `"rfq"`) | served per bar on crypto, CME and US stock charts, one book of the chain `venue` picks; one set of knobs a package | ### The TA classes (`./sdk/ta`) One class per calculation, each fed one bar at a time. Construct in `onStart()`, `.update(...)` once per bar in `onBar()` (it returns the primary value, `NaN` until warm). `update(x)` takes one value unless noted. A class with a finite window (every one below but `Ema`, `Rma`, `Rsi`, `Tsi`, `Macd`, `Atr`, `Keltner`, `Adx`, `Cum`, `Obv`, `Fixnan`, `Psar`, `Supertrend`, `Vwap` and the series helpers that remember an event) lets a pan-back recompute only the new bars after a running start ([Per-bar scripts](../core-concepts/per-bar-scripts.md#rolling-math-that-settles-within-w)). | Group | Classes | Per bar | | --- | --- | --- | | Averages | `Sma`, `Ema`, `Rma`, `Wma`, `Hma`, `Alma`, `Swma`, `Linreg` | `update(x)`; `Vwma` is `update(x, volume)` | | Statistics and series | `Sum`, `Median`, `Percentile`, `Variance`, `Stdev`, `Zscore`, `Change`, `Mom`, `Roc`, `Cum`, `Fixnan` | `update(x)`; `Correlation` is `update(a, b)` | | Oscillators | `Rsi`, `Cmo`, `Tsi`, `Macd` | `update(x)` | | Oscillators over OHLC | `Cci`, `Wpr`, `Stoch`, `Stochastic` | `update(high, low, close)`; `Mfi` is `update(high, low, close, volume)`; `Obv` is `update(close, volume)` | | Ranges and bands | `Tr`, `Atr` | `update(high, low, close)`; `Bb` is `update(x)`, `Keltner` is `update(x, high, low, close)`, `Donchian` is `update(high, low)` | | Window extremes | `Highest`, `Lowest`, `HighestBars`, `LowestBars` | `update(x)` (pass the high for a highest high, the low for a lowest low) | | Trend systems | `Adx`, `Ichimoku`, `Psar`, `Supertrend` | `update(high, low, close)`; `Vwap` is `update(open, high, low, close, volume, tsMs)`, `tsMs` the bar's open time, `bar.time()` in seconds or the time in milliseconds | | Events | `Rising`, `Falling`, `PivotHigh`, `PivotLow` | `update(x)`; `ValueWhen` is `update(condition, x)`, `BarsSince` is `update(condition)`, `Cross` is `update(a, b): i32` (`+1` up, `-1` down, `0` otherwise); `PineCross` is the same call with Pine's rule, read through its fields `over`, `under` and `cross` | Multi-output classes return the primary line and carry the rest as fields: `Bb`, `Keltner`, `Donchian` (`basis`, `upper`, `lower`); `Macd` (`macd`, `signal`, `hist`); `Stoch`, `Stochastic` (`k`, `d`); `Supertrend` (`line`, `direction`); `Adx` (`adx`, `plusDi`, `minusDi`); `Ichimoku` (`tenkan`, `kijun`, `senkouA`, `senkouB`, `chikou`); `Highest`, `Lowest` (`bars`, how many bars ago); `HighestBars`, `LowestBars` (`value`, the matching extreme). Every class allocates in its constructor and restores its just-constructed state on `.reset()`. Honest exceptions to bit-exactness: `Ichimoku`'s `chikou` is the current close (the engine reads a future bar), `Vwap` anchors other than none, `"day"` and a millisecond bucket are unproven, and a few classes follow TradingView where a Pine port needs its answer: `PivotHigh` / `PivotLow` (a tie on the left counts, 0 bars on a side allowed), `Ema` and the classes built on it (an na is skipped, never a restart), `Mfi` and `Dmi` (a difference within 1e-10 is equal), and `PineCross` beside the engine's `Cross`. The composite and every convention are in [TA library](../functions/ta-library.md). ### Kit modules (`./sdk/...`) Ten kits beside the TA classes, every name in scope with nothing to import. Construct their classes in `onStart()`; each page lists every export with its rules. | Kit | Main exports | Page | | --- | --- | --- | | `./sdk/ta-plus` | 26 more classes: `Dev`, `PercentRank`, `Bbw`, `Kcw`, `AccDist`, `Wad`, `Wvad`, `Nvi`, `Pvi`, `Pvt`, `RunningMax`, `RunningMin`, `Mode`, `Range`, `Cog`, `Iii`, `Dema`, `Tema`, `Zlema`, `Trix`, `Ultimate`, `Vortex`, `Aroon`, `Choppiness`, `Efficiency`, `Kama` | [Extra indicators](../functions/extra-indicators.md) | | `./sdk/stats` | `History` (`push(v)`, `ago(n)`, `max()`, `min()`, `mean()`, `sum()`); `stats.sum`, `mean`, `variance`, `stdev`, `min`, `max`, `argmin`, `argmax`, `slope`, `covariance`, `correlation`, `zscore`, `sortAscending`, `median`, `percentile` over a `StaticArray<f64>` and a count | [Stats, history and lists](../functions/stats-history-lists.md) | | `./sdk/fmt` | `TextBuilder` (`text`, `char`, `int`, `f64`, `auto`, `price`, `pct`, `signed`, `compact`, `time`, `duration`, `spaces`); the generated `sb_*` calls wrap one (`sb_price`, `sb_pct`, `sb_signed`, `sb_compact`, `sb_time`, `sb_duration` and the rest) | [Strings and text](../functions/text-formatting.md) | | `./sdk/clock` | `Clock` (`update(t)`, `hour`, `minute`, `weekday`, `dayOfMonth`, `month`, `year`, `isNewDay`, `isNewWeek`, `isNewMonth`, `index`, `intervalSec`, `barCloseSec`); `Session` (`update(t)`, `isIn`, `isFirst`, `closed`, `key`); `BarTimes` (`update(t)`, `index`, `at`, `ago`, `intervalSec`: a drawing's x for Pine's `bar_index` arithmetic) | [Clock and sessions kit](../functions/time-and-sessions-kit.md) | | `./sdk/resample` | `Resampler` (`update`, `closed`, `newBucket`, `last`, `forming`, `source`, `confirmed`, `refused`); `ClosedWindow` (`push`, `mean`, `wma`, `stdev`, `highest`, `lowest`, `sum`, `vwma`, `back`); `Smoothed` (`commit`, `value`, `peek`); `tf.*`, `field.*` | [Higher-timeframe kit](../functions/higher-timeframe-kit.md#from-the-chart-bars-resampler) | | `./sdk/candles` | `Periods` over a `candles` stream (`load`, `confirmed(n)`, `developing`, `isNew`, `startSec`, `endSec`, `complete`), each period a `PeriodCandle` (`open`, `high`, `low`, `close`, `volume`, `vwap()`); `CandleList` (`load`, `count`, `openSec(i)`, `open(i)` ... `volume(i)`); `period.*` | [Higher-timeframe kit](../functions/higher-timeframe-kit.md#calendar-periods-and-candle-lists) | | `./sdk/color` | `ink.*` (twenty packed colors), `fromHex`, `alpha`, `mix`, `lighten`, `darken` for handle colors; `ColorScale`, `Thresholds` for a `color_by` index | [Colors](../functions/colors-kit.md) | | `./sdk/orderflow` | `delta`, `deltaPct`, `Cvd`, `VolumeProfile` (`poc`, `vah`, `val`), `BookImbalance`, `Absorption`, `LiquidationBurst` | [Order flow](../functions/order-flow-kit.md) | | `./sdk/levels` | `PeriodLevels`, `SessionLevels`, `PivotPoints`, `roundLevels`, `SupportResistance` | [Levels kit](../functions/levels-kit.md) | | `./sdk/structure` | `Swings`, `MarketStructure`, `FairValueGaps`, `OrderBlocks`, `Divergence`, `candles.*` | [Market structure kit](../functions/market-structure-kit.md) | ### Caps 16 boxes, 16 segments, 64 renderers, 64 drawings (8 cards among them, and 32 cards, feeds and meters per pane), 64 polyline points, 16 declared alerts, 64 string slots of at most 4096 bytes, 8 frames of at most 96 KiB, 4 docked profiles, 8 panels, 4 heatmaps, 4 footprints, letter and time-anchored profiles together, 4 matrices, 4 panes, 64 KiB of strings per row, 2 MiB of strings and frames per run, 8 MiB of expanded render result, 2,000 drawings per run, offsets in -500..500, 4 MiB of module memory, 20 seconds per run. Every number, with the refusal it produces, is in [Limits](limits.md). ## The four-function form The module the chart runs exports four functions, `init`, `state`, `finalize` and `reset`, with exact signatures that Run checks before anything reaches the chart. A file with `onBar()` gets them from the build; a file may still export the four itself, and it builds the same way ([Execution model](../core-concepts/execution-model.md#the-four-function-form)). How the hooks map onto them: | Export | The build's version, around a file with `onBar()` | In a file that exports it | | --- | --- | --- | | `init(): void` | reads every param once, then calls `onStart()` when the file declares one | runs once before any bar; the only place `p_<param>()` reads | | `state(): i32` | reads this bar's inputs and returns `1` on every bar | runs once per bar; the only place `in_<input>()` and the cell accessors read; `0` abstains the row | | `finalize(): void` | writes NaN to every output, calls `onBar()`, then emits the row | runs after each bar whose `state()` returned `1`: writes outputs and string slots, then `emitRow()` LAST | | `reset(): void` | calls `onReset()` when the file declares one; otherwise nothing is reset | required: reassigns every module-level variable, `.reset()` on every TA object | One `export` of `init`, `state`, `finalize` or `reset` makes the whole file the four-function form. The chart replays the live forming bar from a snapshot of the module's memory and globals taken after the last closed bar, so every replay of the forming bar starts from the state that bar left. ## Generated accessors The runtime contract is positional; the accessors are how your source stays name-attached. One function per declared name, regenerated from your declarations each time the editor compiles: - `p_<param>(): f64` (params, readable from `onStart()` on), plus `pb_<param>(): bool` on a toggle, `p_<range>_lo()` / `_hi()`, `p_<list>(): f64[]`, `p_<session>_start()` / `_end()` / `_tz()` and `p_<param>_unit()` on the composite settings, and `pt_<param>(): string` on a text setting - `in_<input>(): f64` (inputs, read in `onBar()`); the chart's own candle and bar time also read as `bar.open()`, `bar.high()`, `bar.low()`, `bar.close()`, `bar.volume()` and `bar.time()` with no declaration - `out_<output>(value: f64): void` (outputs, written in `onBar()`; the row is emitted when it returns) A declared name becomes its accessor by lowercasing it and collapsing every run of characters outside `[a-z0-9_]` to one `_`: param `fast.len` becomes `p_fast_len()`, input `btc-close` becomes `in_btc_close()`, output `BTC-Ratio` becomes `out_btc_ratio()`. Any name may be written with capitals. Param, input, string-slot and frame names are stored lowercase (`param("fastLen", 12)` is the setting `fastlen`), and so is every option that names one (`"@lineColor"`, `when: "showBands"`, a preset's keys) and the name inside a `{{fastLen}}` placeholder of a legend title, tooltip or HUD title; output names keep their capitals (`[A-Za-z0-9][A-Za-z0-9._-]*`). The accessor answers to the spelling your file uses: `p_fastLen()` and `p_fastlen()` are the same reader, `out_BTC_Ratio()` and `out_btc_ratio()` the same writer. Two names in one family that differ only by case (box, segment and alert names excepted: they keep their spelling), or that escape identically, are refused, and so are duplicate param names. Every accessor family gets the same treatment: a string slot `summary` sends through `str_summary()` and `str_summary_sb()`, a celled input `profile` reads through `in_profile_cells()` and `in_profile_read()`. Declarations whose names need escaping, and the source that reads them (the `close` line stays first because the first input sets the request grid, and `bar.close()` reads through it; the `btc-close` input pins BTCUSDT on Binance Futures, which the chart reads bar by bar at its own interval): ```typescript param("fast.len", 12, { min: 1, max: 200 }); param("slow.len", 26, { min: 2, max: 400 }); input("close", ohlcv.close); input("btc-close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", description: "Fixed BTC reference market" }); output("spread", line, lower); output("BTC-Ratio", line, lower); let fast = new Ema(12); let slow = new Ema(26); function onStart(): void { fast = new Ema(i32(p_fast_len())); slow = new Ema(i32(p_slow_len())); } function onBar(): void { const close = bar.close(); const btc = in_btc_close(); const spread = fast.update(close) - slow.update(close); const ratio = btc > 0.0 ? close / btc : NaN; if (isNaN(spread) || isNaN(ratio)) return; out_spread(spread); out_btc_ratio(ratio); } ``` Reordering declarations moves the SLOT inside each accessor while your source keeps the NAME, so reordering params or inputs never changes what the module computes; a renamed declaration renames its accessor, and the compiler then points at every stale reader or writer. Raw positional slot literals (`getFloat(0)`, `getInt(0)`, `setOutput(0, ...)`, `wrun_arg_f64(0)`, `wrun_output_f64(0, ...)`) are refused before the compiler runs ("Raw slot literal 0 passed to getFloat(): raw positional slots rebind silently when the sheet changes"), because slots silently rebind when declarations change. Variable indexes stay legal: `./sdk/sdk` wraps the raw host imports for genuinely dynamic access. ## Declarations, in one place The signatures in the table above are the whole grammar; the rules the editor enforces, each as a named error in the Console: - Names are string literals; defaults and option values are literals; the code never runs when the editor reads the declarations. - Names may carry capitals (`fastLen`). Params, inputs, string slots and frames are stored lowercase, and so is a `{{fastLen}}` placeholder that names one; outputs keep their spelling. Two names of one family that differ only by case are refused, naming both (boxes, segments and alerts keep their spelling and may differ by case). - Declarations are top-level statements of your file; one anywhere else is refused with its line. An indicator is one file. - Indexes follow declaration order: the first `input(...)` is slot 0, the primary input. The rows are always the chart's own bars and every input aligns to them; reordering declarations reorders slots while the generated accessors keep your source name-attached. A candle field read through `bar.*()` with no `input(...)` line is appended after the declared inputs, and a file with no `input(...)` line gets `close` as slot 0 whether or not it reads `bar.close()`; a declared input that reads exactly that feed serves the field instead. - Box and segment coordinates are output handles bound by a top-level `const` (`let`, `var`, and `export const` bind too; a handle may be bound below the shape that uses it); the sheet records the output's name, never the handle. - `color_by`, `width_by`, and `shape_where` name a DIFFERENT declared output; an output cannot color, widen, or gate itself. `colors` needs at least two entries beside `color_by`; `widths` and `width_by` go together. - A celled input (`<class>.cells`) requires `max_cells`; scalar-feed knobs (`side`, `tenor`, ...) are refused on it; `book` requires `block_size`. Run derives the contract from what you declare: a string slot, a renderer, a drawing, or a celled input stamps the derived sheet `abi_version: "wrun-2"`; a handle, `strategy(...)` or `bar.isLast()` stamps `"wrun-3"`; a frame, a level profile or a panel stamps `"wrun-4"`; a text setting (`param.text`) stamps `"wrun-5"`; a `bar.count()` read stamps `"wrun-6"`; scalar-only declarations keep the first contract. `range`, `box`, `segment` and `alert` are contract-neutral: they never flip the sheet. The derived sheet records `generated_from: "declarations"` plus a `source_digest`, and it is derived state: to change it, edit the declaration. The editor has no hand-written sheet to fall back to, so a file that declares nothing is refused ("This indicator declares nothing. Add param(...), input(...), and output(...) statements ..."). A file with `onBar()` needs at least one `output(...)`; it needs no `input(...)` line, because the chart's own candle reads through `bar.*()`. The sheet's fields are on [Declarations and the sheet](declarations.md#the-sheet-run-derives), its pins on [Multi-timeframe](../core-concepts/multi-timeframe.md) and [Multi-source](../core-concepts/multi-source.md), odds modes on [Data sources](../core-concepts/data-sources.md#beyond-the-charts-venue); the styling ladders are in [Styling](../presentation/styling.md). ## The cell channel (`wrun-2`) Modules on the second contract or later may read celled inputs: a variable-length block of f64 cells per bar (a volume profile's per-price rows, a book snapshot's levels) beside the scalar argument block. A celled input is declared in the source, `input(name, <class>.cells, { max_cells })` (the derived sheet records it as `cellType: "array"` with `max_cells`), reads a celled source class ([Data sources](../core-concepts/data-sources.md)), and receives cells in fixed-width TUPLES per class: `volume_profile` = `[low, high, buy, sell]` (4 f64s), `book` = `[price, size, side]` (3 f64s), `intrabar` = `[offset_ms, open, high, low, close, volume]` (6 f64s), `trade_volume_by_size` = `[bucket, buy_usd, sell_usd, buy_count, sell_count]` (5 f64s), `options_chain` = 10 f64s per contract, `option_strikes` = 12 f64s per (expiry, strike) row, and the option classes 9 to 17 f64s, each tuple ending with its `present` mask. `max_cells` counts tuples. The editor generates one accessor family per celled input (no scalar accessor: the input's slot in the scalar block holds NaN), read in `onBar()`: - `in_<input>_cells(): i32`: f64 cells in this bar's block (tuples x tuple width); `0` for a present, empty block; `-1` when the bar carries no block, and before the first bar. - `in_<input>_view(): StaticArray<f64>`: the build's own buffer, holding this bar's block with no copy. Only the first `in_<input>_cells()` values belong to this bar: every index past them up to the capacity reads NaN (an absent or empty bar reads NaN throughout), and an index past the capacity stops the run, so bound every loop by the count. - `in_<input>_read(ptr: i32): i32`: copies the block into the module's exported memory at `ptr`, for code that owns its own buffer; returns bytes written, `0` for a zero-cell block, `-1` for a missing block. - `in_<input>_max_cells: i32`: the declared `max_cells` (source tuples). - `in_<input>_capacity: i32`: the f64 count of the build's buffer (the input's capacity x the class's tuple width: `max_cells`, or `max_cells` + `newest` for a print read's union, the `capacity` the build writes on the sheet); generated when the class's width is known. Cells are IEEE 754 f64, little-endian, 8 bytes each, contiguous in block order. `max_cells` is a contract, not a hint: the build allocates one buffer of `max_cells` tuples per celled input when the module starts (`in_<input>_capacity` f64s), reads each bar's block into it once, and a bar whose block exceeds the cap refuses the WHOLE run by name ("... has 1200 cells; max_cells is 1000, so the evaluation is refused (a block is never truncated)"). An out-of-bounds `ptr` is refused naming the sizes, and a read of an input not declared as celled is refused naming the declared set. Underneath the accessors sit two host imports in the `wrun` namespace, `wrun_arg_len(index)` and `wrun_arg_bytes(index, ptr)`; positional literals on them are refused exactly like `getFloat(0)`, so source goes through the accessors. A second-contract module that reads no celled input is legal: such packages may be scalar-only, and scalar behavior is bit-identical across every contract. Alignment is an exact join, never a fill: each chart bar gets the celled observation with the same bar open, a bar with no observation gets a PRESENT EMPTY block (the module sees `0` cells, not `-1`), and celled values are never carried forward (a replayed block would double-count volume). Celled inputs never abstain a row: on a bar with no block, leave the output unwritten or `return` from `onBar()`. A celled class can never be the primary input (so a scalar `input(...)` line stays in front of it) and follows the chart's own market (a market pin on it is refused); only `intrabar` takes an `interval`, the finer bars it folds. Summing a bar's volume profile (total volume = buy + sell in every `[low, high, buy, sell]` tuple): ```typescript input("close", ohlcv.close); // One tuple per price level: an hour of BTCUSDT carries several hundred, so leave room. input("profile", volume_profile.cells, { max_cells: 8192 }); output("total", line, lower); function onBar(): void { const n = in_profile_cells(); if (n < 0) return; // this bar carries no block let total = 0.0; if (n > 0) { const cells = in_profile_view(); for (let i = 0; i + 3 < n; i += 4) { total += cells[i + 2] + cells[i + 3]; // buy + sell per [low, high, buy, sell] tuple } } out_total(total); } ``` The first contract is frozen: its import allowlist never grows, and a module on it that imports the cell functions is refused naming the way in (a celled input moves the derived sheet to `wrun-2`). Which celled classes the chart serves is in the table above; an alert on an indicator that reads a source the alerts engine cannot evaluate is refused when you save it ([Alerts](../functions/alerts.md)). ## The string channel (`wrun-2`) From the second contract on, a file may declare string slots: numbered, named, byte-capped text channels written from `onBar()`. Slots are NOT outputs: outputs stay numeric; strings exist so renderers and drawing labels can carry text, and they are never outputs. When the file declares `string(...)`, the editor generates the string family, in scope with nothing to import: - `sb_clear()`, `sb_text(s)`, `sb_int(value)`, `sb_f64(value, decimals)` build one UTF-8 line allocation-free into a shared buffer sized to the largest declared `max_bytes` (allocated once at module start, so per-bar string work allocates nothing). - `str_<slot>(s: string)` encodes and sends `s` to that slot; `str_<slot>_sb()` sends the built line. Both pass the REQUIRED byte count, so a line over the slot's `max_bytes` refuses by name; strings are never truncated. A slot named `debug` is also the editor's debug log: each non-empty line prints in the Console as `<ISO bar time> <text>`, the newest 400 lines kept. A slot not written that bar is ABSENT, which is distinct from a written empty string: `render.text` draws every present slot (empty included), `render.label` keeps the last present NONEMPTY one, and `render.table` waits for a row where every cell is present. Writing the same slot twice in one `onBar()` replaces its bytes. The channel belongs to the row being committed, the bar `onBar()` runs on: the underlying import (`wrun_output_str(slot, ptr, len)`, `wrun` namespace) traps by phase anywhere else, and positional literals on it are refused like the cell imports (use the generated senders). Caps the chart enforces, each a named refusal: `max_bytes` per slot (at most 4096), 64 slots per indicator, 64 KiB of string bytes per row, 2 MiB of strings and frames together per run (a live session counts as one run). Bytes must be valid UTF-8; a broken sequence refuses the run instead of landing as a replacement character. An RSI with two slots: a readout the label renderer keeps on the newest bar, and a zone word written only on bars that are in a zone, so the text mark stays absent everywhere else: ```typescript param("period", 14, { min: 2, max: 200 }); output("rsi", line, lower, { color: "#38bdf8" }); output("tag_x", none, lower, { description: "Bar time in epoch seconds, the label's x" }); string("readout", { max_bytes: 32 }); string("zone", { max_bytes: 16 }); // One label, riding the newest bar whose readout slot was written. render.label("rsi_tag", { x: "tag_x", y: "rsi", text: "readout", color: "#38bdf8", size: 11 }); // One text mark per bar whose zone slot was written; quiet bars leave it absent. render.text("rsi_zone", { y: "rsi", text: "zone", color: "#f59e0b", size: 10 }); let rsi = new Rsi(14); let period: i32 = 14; function onStart(): void { period = i32(p_period()); rsi = new Rsi(period); } function onBar(): void { const value = rsi.update(bar.close()); if (isNaN(value)) return; out_rsi(value); out_tag_x(bar.time()); sb_clear(); sb_text("RSI "); sb_int(period); sb_text(": "); sb_f64(value, 1); str_readout_sb(); // "RSI 14: 63.2", at most 32 bytes if (value >= 70.0) str_zone("overbought"); else if (value <= 30.0) str_zone("oversold"); } ``` Renderers and drawings are selected after the run ([Plotting](../presentation/plotting.md) and [Drawing objects](../presentation/drawing-objects.md)); the worked table example in [Declarations and the sheet](declarations.md#string-slots-renderers-drawings) writes four slots per bar through this module surface. ## Language cheat The file is AssemblyScript: TypeScript syntax over fixed-width numbers, compiled to a module with no filesystem, no network, and no memory growth after `onStart()` (a temporary the bar drops is freed). Data types, math, strings, control flow, and user functions take these forms: | Need | Form | | --- | --- | | Numbers | `f64` for every param, input, and output; `i32` for counts, periods, and loop bounds; `bool` for flags. Casts are explicit: `i32(p_period())`, `f64(count)`. | | Missing value | `NaN`, tested with `isNaN(x)`; write NaN to an output for "nothing here", or `return` from `onBar()` before the writes: an output left unwritten is NaN on that bar. `Infinity` in an output is refused by name. | | Windows and history | `History` from `./sdk/stats`: `push(x)` once per bar, then `ago(1)` for the previous bar's value and `max()`, `min()`, `mean()`, `sum()` over the window ([Stats, history and lists](../functions/stats-history-lists.md#history-xn-from-pine)). There is no `close[1]`. By hand: yesterday's value in a module-level variable, or a `StaticArray<f64>` sized once (from a param's `max`) and written as a ring buffer. | | Collections | `StaticArray<T>` and `Array<T>` that live across bars are allocated at module start or in `onStart()`; one `onBar()` makes and drops is freed, but one that grows on every bar is refused; `Map<K, V>` for keyed state, sized up front. In a file with the four functions, nothing is allocated per bar. | | Math | `Math.abs`, `Math.max`, `Math.min`, `Math.sqrt`, `Math.pow`, `Math.exp`, `Math.log`, `Math.floor`, `Math.ceil`, `Math.round`, `Math.trunc`, `Math.sign`, the trigonometric set, `Math.PI`, `Math.E`, all over `f64`. | | Strings | only in string slots; build with `sb_text` / `sb_int` / `sb_f64`, which allocate nothing. `+` on a string per bar makes a temporary the module frees, so it works in a file with `onBar()`; in a file with the four functions it grows memory and the run is refused. | | Control flow | `if` / `else`, `for`, `while`, `break`, `continue`, `switch` on integers; a number is not a truth value (`if (value > 0.0)`, not `if (value)`). | | Functions | `function name(x: f64, n: i32): f64 { ... }` at module scope, typed params and return; closures cannot capture locals, so a reducer is a named function over a buffer. | | Types | `class Zone { top: f64 = NaN; bottom: f64 = NaN; alive: bool = false; }`, constructed in `onStart()`; a `type` alias for readability. | | Time | `bar.time()` gives the bar's open in epoch seconds. Feed it to a `Clock` (the hour, the weekday, new-day tests, in a named zone) or a `Session` (an `"0930-1600"` window on the weekdays you list) from `./sdk/clock` ([Clock and sessions kit](../functions/time-and-sessions-kit.md)). By hand, sessions are integer math on it (UTC). | | Colors | never computed: declared per output, box, segment, or renderer (hex, `rgb()`, `hsl()`, or a named color where a fill is not involved, or a `theme.` token the chart resolves at paint time), or chosen per bar through a `color_by` ladder. A handle's colour is a packed number from `./sdk/color`, where `theme.UP` and its six siblings are the same tokens. | A rolling highest-high that shows the shapes above (a buffer sized once, a typed helper function, explicit casts; the `high` line is kept as the first input, which sets the request grid, and `bar.high()` reads through it): ```typescript param("bars", 20, { min: 1, max: 500, description: "Lookback in bars" }); input("high", ohlcv.high); output("highest", line, overlay, { color: "#38bdf8" }); const MAX_BARS: i32 = 500; // the param's max: the buffer is sized once, never per bar const highs = new StaticArray<f64>(MAX_BARS); let n: i32 = 20; let cursor: i32 = 0; let count: i32 = 0; // A plain function: typed params, a typed return, no closure over locals. function maxOf(values: StaticArray<f64>, len: i32): f64 { let best = -Infinity; for (let i = 0; i < len; i++) { if (values[i] > best) best = values[i]; } return best; } function onStart(): void { n = i32(p_bars()); } function onBar(): void { highs[cursor] = bar.high(); cursor = (cursor + 1) % n; if (count < n) count += 1; if (count < n) return; out_highest(maxOf(highs, n)); } ``` ## The sheet Run derives Run turns your declarations into a sheet, the metadata a published indicator carries; you never write it. Where each of its top-level fields is explained: | Field | Meaning | Page | | --- | --- | --- | | `id`, `name`, `description` | the sheet's short name and display strings | [Declarations and the sheet](declarations.md#the-sheet-run-derives) | | `abi_version` | `wrun-1` (absent means this) through `wrun-5`, derived from what the declarations use | [Declarations and the sheet](declarations.md#abi-versions-the-five-contracts) | | `wasm_sha256` | the compiled module's digest, stamped by Run | [Declarations and the sheet](declarations.md#the-sheet-run-derives) | | `history_independent` | `true` when the compile proved each bar depends on that bar's inputs alone: derived by the compiler, never written by hand; the chart recomputes only new bars on a pan-back | [Declarations and the sheet](declarations.md#the-sheet-run-derives) | | `history_warmup` | `{ kind: "exact", windows, plus }` when the compile proved the file's only memory is finite-window kit instances: derived by the compiler, never written by hand; the chart recomputes only new bars on a pan-back, after a running start of W bars (or a declared warmup, when larger). A mode guard's file (a second mode behind one select, or behind several joined by `&&`) adds one window with a term per select at multiplier `WRUN_WARMUP_MODE_UNBOUNDED` (1000000000), the same shape: a conditional proof encoding, not a bound, so W holds while every select reads 0 and runs past every chart's cap once any picks another option | [Per-bar scripts](../core-concepts/per-bar-scripts.md#rolling-math-that-settles-within-w) | | `params[]` | `{name, default, required?, min?, max?, description?}` | [Declarations and the sheet](declarations.md#the-sheet-run-derives) | | `inputSources{}`, `inputs[]` | sources keyed by input name; `{index, name, description?, cellType?, max_cells?}` | [Data sources](../core-concepts/data-sources.md) | | `outputs[]` | `{index, name, plot?, panel?, unit?, displacement_bars?, ...styling}` | [Plotting](../presentation/plotting.md) | | `ranges[]` | a band between two outputs, with edges, a ladder or a gradient | [Styling](../presentation/styling.md) | | `boxes[]`, `segments[]` | per-bar shapes over outputs (16 each) | [Drawing objects](../presentation/drawing-objects.md) | | `string_slots[]`, `renderers[]`, `drawings[]` | the second contract's text and decoration vocabulary | [Declarations and the sheet](declarations.md#string-slots-renderers-drawings) | | `handles`, `strategy` | the third contract's drawing handles and strategy settings | [Drawing objects](../presentation/drawing-objects.md), [Writing strategies](../strategies/writing-strategies.md) | | `frames[]`, `levels[]`, `panels[]`, `matrices[]` | the fourth contract's snapshots, docked profiles, panels and strike matrices | [Cards, frames and panels](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets) | | `heatmaps[]`, `profiles[]` | the canvases drawn from cells or a grid of outputs, on any contract | [Price canvases](../presentation/price-canvases.md) | | `panes[]`, `fills[]`, `contrast_guard`, `stack_handles` | named lower panes, interior fills between two lines, and the two chart flags | [Styling](../presentation/styling.md) | | `alerts[]` | the declared signals the chart's alert dialog offers | [Alerts](../functions/alerts.md) | | `generated_from`, `source_digest` | provenance of the sheet derived from declarations | this page | The full validation list, every refusal by path, is at the end of [Declarations and the sheet](declarations.md#validation-in-one-list); the messages you will actually meet, with their fixes, are in [Common errors](../faq/common-errors.md). <!-- source: https://openmarket.xyz/wrun/reference/declarations --> # Declarations and the sheet A wrun indicator declares what it reads, writes and draws as top-level statements at the top of its file, and **Run** derives the sheet from them: the description of the indicator the chart draws from and a published indicator carries. This page is the grammar of those statements, the rules the editor enforces, the sheet's fields and provenance, and the runtime contract the sheet records. What each declaration does on the chart is on the page that owns it, and every signature with every option is one table on [Quick reference](quick-reference.md). ## param `param(name, default, { required?, min?, max?, description? })` is a number field, read from `onStart()` on through `p_<name>()`. `param.<kind>(name, default, options?)` is a typed setting (`int`, `number`, `bool`, `choice`, `color`, `time`, `price`, `range`, `multi`, `list`, `source`, `timeframe`, `symbol`, `session`, `text`), each naming the control the dialog draws, its literal default and its reader: [Setting kinds](../settings/kinds.md). `param.text` (one line) and `param.text_area` (several) take words, read once in `onStart()` through `pt_<name>()` ([Text settings](../settings/kinds.md#text-settings)). The options, and which kind takes each: [Options on a setting](../settings/options.md). `market.tick_size()`, `market.price_precision()`, `market.kind()`, `market.point_value()`, `market.zone()`, `market.quote_is_usd()`, `market.session_open()`, `chart.interval_sec()`, `chart.bg_color()`, `chart.fg_color()`, `chart.up_color()`, `chart.down_color()` and `chart.grid_color()` declare hidden settings the host writes before `onStart()`, 0 where it cannot know one ([Chart context](../settings/sessions-and-units.md#chart-context)). `market.size_unit()` and `market.notional()` declare the market facts the size helpers `sizeUnit(...)` and `notional(...)` read, and add no setting of their own ([Size units](../settings/sessions-and-units.md#size-units)). ## input `input(name, source.field, options?)` declares one per-bar number, read in `onBar()` through `in_<name>()`; the chart's own candle needs no line (`bar.close()` and the other `bar.*()` readers), and the first input is the bar grid. The sources, their fields and knobs: [Data sources](../core-concepts/data-sources.md). The pins: `symbol` with `exchange` for another market ([Multi-source](../core-concepts/multi-source.md)); `interval` with `view`, `views`, `offset` and `bars` for a coarser leg ([Multi-timeframe](../core-concepts/multi-timeframe.md)); `missing` for what a bar with no observation reads. `input(name, <class>.cells, { max_cells, ... })` declares a celled input, a block of tuples per bar. No input reads another indicator's outputs. ## output `output(name, plot?, panel?, options?)` declares a per-bar number, written in `onBar()` with `out_<name>(value)`; an output not written that bar stays `NaN` and draws nothing there. `plot` is `line`, `bar`, `area`, `histogram`, `candle`, `shape`, `scatter` or `none` (data-only: computed, never drawn); `panel` is `overlay` (the price pane) or `lower` (a pane below it), per output. The options are style keys and presentation keys: [Plotting](../presentation/plotting.md), [Styling](../presentation/styling.md). The styling round's words ride the same literal: the plot-kind looks (`step`, `smooth`, `gradient`, `split` with `up_color`, `down_color`, `split_level`, `split_fill` and `split_base`, `fill_color`, `fill_opacity`, `fill_gradient`, `gradient_mode`, `fill_color_by` plus `fill_colors`, `fill_color_packed_by`, `base`, `grading`, `stack`, `candle_style`, `border_colors`, `wick_colors`, `border_width`, `shape`, `location`, `char`, `font_family`, `fill`, `role`, `align`, `pill_style`, `font_size`, `axis_look` (a guide's axis tag: `pill`, `quiet` or `words`), each refused by name off the plot kinds that take it), `z` (-10..10, the paint order), `pane` (a declared pane's name or `"lower"`), `color_packed_by` (a packed rgba output per bar), `displacement_bars_by` (`{ param, scale?, offset? }`), and the presentation keys `decimals` (0..8) and `signed` (both need `format`, whose words are `price`, `%`, `si`, `int`, `0`, `0.0`, `0.00`, `0.000`, `usd` and `auto`; `unit` prints beside one) and `axis_name`; every one reaches the sheet only ([Plotting](../presentation/plotting.md#lines-areas-columns-dots-marks)). Four more ride the same way: `show_price_display` (the output's price-axis tag under `display({ price_display: "per_output" })`), `show_price_display_by` (an output whose value switches that tag per run), `omit_if_empty` (no legend row or tag when no bar drew) and `barcolor: true` on a `none` output (its value picks the candle tint from `colors`, or `color_packed_by` names it) ([Styling](../presentation/styling.md#tags-the-legend-and-the-candle-tint)). `output(...)` returns a handle; bind it with a top-level `const` when a `box`, `segment`, `hover` or `alert` needs to name it. ## string `string(name, { max_bytes, description? })` declares a text slot, written per bar in `onBar()` through `str_<name>(text)` or the `sb_*` builder and `str_<name>_sb()`; a slot not written that bar is absent. Slots feed renderers, drawings, blocks and the Console, never a plot ([Strings and text](../functions/text-formatting.md)). A slot named exactly `debug` is the indicator's debug log in the editor's Console ([Debugging](../faq/debugging.md)). ## render and draw `render.text`, `render.label`, `render.table`, `render.shape`, `render.stats_row`, `render.bgcolor` and `render.barcolor` place text, marks and tints over outputs and slots; `render.legend` adds a legend entry and `render.hud` a card. `draw.line`, `draw.box`, `draw.polyline` and `draw.label` with a name as the first argument each declare one drawing, placed from the newest bar. Numeric references name outputs; `text` and table `cells` name string slots. `render.table` also takes the look keys and per-cell `styles` ([Styled tables](../presentation/cards-frames-panels.md#styled-tables)), and `render.shape` takes `width`, the mark's size in pixels ([Mark size](../presentation/plotting.md#mark-size)). Renderers: [Plotting](../presentation/plotting.md); legend and cards: [Legend](../presentation/legend.md), [HUD and hover cards](../presentation/hud-and-hover-cards.md); drawings and handles: [Drawing objects](../presentation/drawing-objects.md). Since the styling round, `render.text` and `render.label` take `style` from eight words (`plain`, `price_label`, `pill`, `callout`, `badge`, `box`, `knockout`, `emblem`) and the look keys: `align` and `valign` on plain text; `label_position`, `background_color`, `border_color` and `corner_radius` on a tag (a tag key on plain text, or `align` on a tag, is refused); `font_weight`, `font_family`, `emblem_shape`, `emblem_color` and `size_by` on both; a text renderer's `background_color_by` plus `background_colors`, `color_by` plus `colors` or `color_packed_by`, and `panel`; a label's `padding`. A `render.label` pins to a corner with `position` (one of the nine anchors) and `offset` (`[x, y]`, each -200..200 px) instead of `x` and `y` (declaring both is refused; `price_label` and `callout` are refused there). `render.shape` adds `location` (`absolute`, `above_bar`, `below_bar`, `top`, `bottom`), `glow`, `char` (one character, with and only with `shape: "char"`), `font_family`, `fill`, `fill_opacity` and `tooltip`; `render.stats_row` adds `color`, `colors`, `color_by`, `color_packed_by` and `priority` (1..3); `render.bgcolor` adds `width` (0.5..10, a vertical line per gated bar) and `line_style`; `render.hud` takes its surface, type and look words. Every `draw.*` declaration takes its handle kind's look words in snake_case: `extend`, `arrow`, `glow`, `glow_color`, `sticky_right`, `axis_label`, `opacity` and `tooltip` on a line; `border_color`, `border_width`, `border_style`, `corner_radius`, `shape`, `gradient`, `gradient_direction`, `text` (a string slot), `text_color`, `font_size`, `font_weight`, `font_family`, `align`, `valign` and `padding` on a box, whose `color` is the fill; `fill_color`, `closed` and `smooth` on a polyline; `style`, `background_color`, `max_width`, `angle`, `emblem_shape` and `emblem_color` on a label. Every one is a presentation key, stripped before the compiler, and since the styling round every `render.text`, `render.label`, `render.shape` and `draw.*` declaration is erased whole ([Plotting](../presentation/plotting.md), [Drawing objects](../presentation/drawing-objects.md)). ## box, segment and range `box(name, { top, bottom, ... })` and `segment(name, { yFrom, yTo, ... })` declare per-bar shapes over output HANDLES; `range(upper, lower, options?)` declares a band between two rendered outputs (ranges never dedupe: repeat the declaration for several bands); its `edge_width` is 0..10 (`0` for no edge lines) and it also takes `legend` (false drops the band's legend row), `label`, `z`, `fill` (false draws the two edge lines with no interior), `show_price_display` (the band's tags) and `omit_if_empty` (no legend row or tag when no bar had both edges). `fill(a, b, options?)` shades the interior between two drawn outputs on one pane with no edge lines (`color`, `opacity` 0..1 with default 0.25, `color_by` plus `colors`, `color_packed_by`, `z`; only a top-level `fill(` statement is read, a `.fill(` method on a handle is something else), and `pane(name, options?)` declares a pane of the indicator's own, at most four (`title`, `place` `"below"` or `"price"`, `height_frac` 0.05..0.6, `scale` `"linear"`, `"log"`, `"percent"` or `"indexed"`, `invert`, `padding` `[top, bottom]`, `min`, `max`, `format`, `decimals`, `signed`, `unit`), joined by an output's `pane: "<name>"`. A box also takes `borderStyle`, `z` and the colour ladders `colorBy` plus `colors`, `colorPackedBy`, `borderColorBy` plus `borderColors` and `borderColorPackedBy` (output handles for the `By` keys; a ladder half without the other is refused). All of these are erased before the compiler. What the chart draws: [Drawing objects](../presentation/drawing-objects.md), [Styling](../presentation/styling.md). ## alert `alert(name, { when, message?, description?, text?, every_bar?, title? })` declares a signal the chart's alert dialog offers: `when` is the handle of the output whose false-to-true edge fires it (a data-only `none` output works, so no 0/1 line has to be drawn), `message` the fire text with placeholders such as `{{symbol}}`, `{{close}}` and `{{<output>}}` (a declared output's value on the fired bar), `description` the picker's sub-line, both at most 200 characters. `text` names a string slot: the words the file writes into it on the fired bar are the message, sent as one plain line of at most 200 characters. `every_bar: true` fires on every bar `when` holds, once per bar at most; the default fires on the false-to-true edge only ([Alerts](../functions/alerts.md#alert-words-and-every-bar)). `title` is the words the dialog, an armed alert and its notification show for the signal, any characters, 1 to 120 of them; the name keeps letters, digits, `.`, `_` and `-`. The declaration adds nothing to the module. A worked signal: [Alerts](../functions/alerts.md). ## Layout words `page(title)`, `section(title, { toggle?, collapsed?, when? })`, `divider()` and `note(text)` lay the settings dialog out in source order; `presets({ Name: { param: value } })` ships named settings sets; `legend({ title })` sets the legend's title template. Sheet-only, compiled to nothing: [Pages, sections, dividers, notes](../settings/layout.md), [Presets](../settings/presets.md), [Legend](../presentation/legend.md). `display({ axis?, price_display?, overlay?, mount_order? })`, at most once, sets the indicator's look on the chart as a whole: `axis: false` gives it no price axis of its own (an indicator on the price pane rides the chart's), `price_display: "per_output"` tags each plot on the price axis by its own `show_price_display`, `overlay: "offchart"` homes it in its own pane below the chart, and `mount_order: "first_value"` lists its plots in the order they first draw ([Styling](../presentation/styling.md#tags-the-legend-and-the-candle-tint)). ## Other words `hover(handle, [block.*])` is an output's hover card ([HUD and hover cards](../presentation/hud-and-hover-cards.md)); `handles.*` sets handle defaults ([Drawing objects](../presentation/drawing-objects.md)); `frame`, `panel.*`, `plot.levels`, `draw.ladder`, `draw.feed`, `draw.meter` and `out.inset` declare JSON snapshots and the panels and widgets drawn from them ([Cards, frames and panels](../presentation/cards-frames-panels.md)); `strategy({ ... })` places orders through the engine's broker ([Strategies overview](../strategies/overview.md)). `plot.heatmap`, `plot.footprint`, `plot.tpo`, `plot.profile` and `plot.matrix` declare the price canvases and `out.grid` a block of data-only outputs a heatmap reads ([Price canvases](../presentation/price-canvases.md)); `plot.marks`, `plot.spans` and `plot.rays` hold up to 64 records a bar on outputs the build adds, written through the generated `out_<name>_mark`, `out_<name>_span` and `out_<name>_ray` ([Marks, spans and rays](../presentation/marks-spans-rays.md)); `chart.contrast_guard(false)` and `chart.stack_handles(true)` are top-level flags with one boolean literal each (a binding is refused): the first keeps the author's colours as written on a light chart, the second stacks the indicator's corner-anchored handle groups below other indicators' groups ([Colors](../functions/colors-kit.md#theme-tokens)). ## A file that uses them Two settings, two inputs, three outputs and the debug slot, with the hooks that read and write them (the bar loop in full: [Execution model](../core-concepts/execution-model.md)): ```typescript // One output in its own pane (lower), labelled with a unit. param("period", 14, { min: 2, max: 200, description: "RSI Period" }); // An on/off setting is a 0/1 param. param("show_raw", 1, { min: 0, max: 1, description: "Write the raw RSI as well as the smoothed one" }); // The first input is the bar grid the funding input is aligned to; bar.close() reads through it. input("close", ohlcv.close); // A funding input, aligned to the close's rows; the chart serves it as a percent. input("funding", funding.rate_close, { description: "Funding rate in percent, as of the bar" }); output("rsi", line, lower, { unit: "%", color: "#7c3aed", width: 2, description: "RSI (14)" }); output("smoothed", line, lower, { unit: "%", color: "#38bdf8", width: 1, description: "RSI smoothed by a 5-bar EMA" }); output("funding_pct", line, overlay, { unit: "%", color: "#f59e0b", description: "Funding in percent, on the price pane" }); // The debug log: a string slot named debug, printed in the editor's Console. string("debug", { max_bytes: 32 }); let rsi = new Rsi(14); const ema = new Ema(5); let showRaw: bool = true; function onStart(): void { rsi = new Rsi(i32(p_period())); showRaw = p_show_raw() > 0.5; } function onBar(): void { const value = rsi.update(bar.close()); const fundingRate = in_funding(); if (isNaN(value)) return; const smoothed = ema.update(value); out_rsi(showRaw ? value : NaN); out_smoothed(smoothed); out_funding_pct(fundingRate); sb_clear(); sb_text("rsi "); sb_f64(value, 2); str_debug_sb(); } ``` A `0` in `show_raw` writes `NaN` to the raw line, which draws nothing: that is how a boolean toggle hides a plot. ## The declaration grammar A declaration is a top-level statement of your file: a call to one of the words above with a string-literal name, a literal default and a literal options object, nothing imported. The build reads them without running the code, derives the sheet, and generates the readers and writers (`p_*`, `pb_*`, `in_*`, `out_*`, `str_*`, `sb_*`, `fb_*`) from the same object, so the two cannot disagree. A file with `onBar()` and no `output(...)` is refused at Run. A file that exports `init`, `state`, `finalize` or `reset` is the four-function form; both forms derive the same sheet ([The four-function form](../core-concepts/execution-model.md#the-four-function-form)). ```typescript param("period", 14, { min: 2, max: 200, description: "Lookback window" }); param.bool("show_raw", true, { label: "Raw line" }); input("close", ohlcv.close); input("btc_close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES" }); output("value", line, lower, { unit: "score", label: "Score", format: "0.00" }); ``` ### Bindings `"@<param>"` as the value of `color`, an entry of `colors` or `line_style` on an output or a text, label or legend renderer binds that spot to a `param.color` (for `line_style`, a `param.choice` over `solid`, `dashed`, `dotted`); as `interval` or `symbol` on an input it binds the pin to a `param.timeframe` or a `param.symbol`; a `param.source` declares the input it reads. The build writes the setting's default in the reference's place before the compiler runs and records the binding on the sheet (`style_targets`, `interval_param`, `symbol_param`, `field_param`), so the module's bytes never depend on a setting ([The Style page](../settings/style-page.md), [Picks, lanes, the cap](../settings/picks-and-lanes.md)). The same reference works on a `range`, a `fill`, a `box` and a `segment` (their colours, palette entries, gradient stops and line or border styles), on an output's other colour words (`fill_color`, `fill_colors`, `fill_gradient`, `gradient`, `up_color`, `down_color`, `border_colors`, `wick_colors`), and on the style keys of a `plot.levels` profile, where a word key takes a `param.choice` over that key's words, a number key a `param.number` or `param.int` whose range lies inside the key's, and a boolean key a `param.bool`. A data-only output refuses a paint binding (a `barcolor` output, which paints the candles, takes one), and so do a `draw.*` object, a `handles.*` default, a panel series and a tile. Every colour reference also takes `"@<param>/<alpha>"`, a panel series colour excepted: the setting's default at that alpha (a decimal from 0 to 1, replacing the colour's own) lands in the reference's place, as `rgba(r, g, b, a)` where the colour takes `rgba()` (an output's `color` and `colors`, a renderer's colours but a stats row's, a legend entry, a range's colours and gradient, a fill's `color`, a box's `color` and `borderColor`, a segment's `color`, a mini-chart grid's colours) and as `#rrggbbaa` where it takes a colour word, and the binding records the alpha, so a recolour keeps the translucency. `ticks_per_bar: "@<param>"` on a `volume_profile.cells` input binds the profile's bucket size to a `param.int` within 1..500: the sheet carries its default and `ticks_per_bar_param`, and the chart fetches again when it changes. ### Sheet-only keys An output's presentation keys, a typed setting's and an output's `visible_by`, a renderer's `style`, `tooltip`, `hover` and `badges`, the plot-kind looks, `z` and `pane`, an input's `ticks_per_bar`, `currency` (`"Auto"` included), `needed_by`, `follow`, `when` and `when_bit`, a candles input's `chart_interval_below`, and a profile's `missing`, and the whole of `hover`, `range`, `fill`, `pane`, `box`, `segment`, `alert`, `display`, the chart flags, every `plot.*` canvas, the layout words, `render.legend`, `render.hud` and (since the styling round) every `render.text`, `render.label`, `render.shape` and `draw.*` declaration reach the sheet only: the build strips them before the compiler runs, so a declaration with them compiles to the same bytes as one without. A `const` bound to a `string(...)` or `output(...)` is a handle for naming, dropped the same way. ### Rules every declaration follows Each is a named build error on the declaration's line: - Names are string literals; defaults and option values are literals; the code never runs at build time. - Names may carry capitals. Params, inputs, string slots and frames are stored lowercase, with every option and `{{placeholder}}` that names one; outputs keep their spelling; each accessor also answers to the file's spelling. Two names of one family that differ only by case are refused; boxes, segments and alerts keep their spelling, so `Zone` and `zone` are two boxes. - Declarations are top-level statements; one anywhere else names the file and line. - Indexes follow declaration order: the first `input(...)` is slot 0, the primary input, and reordering declarations reorders slots while the accessors stay name-attached. A candle field read through `bar.<field>()` is served by a declared input of exactly that feed, else appended after the declared inputs under its own name, in the order `open`, `high`, `low`, `close`, `volume`, `bar_t`; a file with no `input(...)` line gets `close` as slot 0. - Box and segment coordinates, a section's `toggle` and `when`, a `hover` target and an alert's `when` are output handles bound by a top-level `const` (`let`, `var` and `export const` bind too); the sheet records the output's name, never the handle. A string literal where a handle goes, or an unbound handle, is refused. - `color_by`, `width_by` and `shape_where` name a DIFFERENT declared output; `colors` goes with `color_by` and `widths` with `width_by`, each half without the other refused. - A typed setting's options belong to its kind; `when` names a declared `param.bool`, `param.choice`, `param.int`, `param.number` or `param.multi` in one of five forms (`"name"`, `"!name"`, `"name=v"`, `"name!=v"`, `"name in a,b"`, each value one the setting holds: 0 or 1 for a toggle, an option index for a choice); a `"@<param>"` reference names a setting of the kind the spot needs; a preset sets sheet params only. A setting cannot take a name the chart keeps (`symbol`, `exchange`, `interval`, `transformations`, `ticksPerBar`, `currency`, `runMode`, `devViewerTier` and the overlay's own keys), start with `__style__`, or collide with a name another setting derives (`band_lo`, `rth_tz`, `offset_unit`, `market_tick_size`). - `visible_by` rides a typed setting and an `output(...)` only, as `{ size_unit: [codes] }` with codes 0 to 3, at least one and each once; a setting's derived rows carry it too. `currency: "Auto"` follows the market the indicator runs on, so an input pinned to another market names its unit. `needed_by` rides a secondary scalar feed `input(...)` or a secondary `tape.cells` input only, the same `{ size_unit: [codes] }`: its lane is fetched only on the markets listed, and elsewhere the input reads its fill (a tape zero prints); the first input, a `time.*` input, every other celled input and a metric composition refuse it. A typed setting's `visible_by` and a tape's `needed_by` may also name one `param.choice` beside `size_unit`, with its option indexes; the choice names the size unit alone in its own `visible_by`, and an undeclared name, a non-choice, an index it lacks, a second choice and the row itself are refused ([Size units](../settings/sessions-and-units.md#the-dialog-and-the-lanes)). A tape's `min_coins` names coin markets alone in its `needed_by`. - `follow: "coin"` rides a secondary `trades.*` input only, beside `exchange` and never beside `symbol` or a `"@<param>"` symbol: the chart picks that venue's market for the coin of the chart's market, and a venue that lists none reads the input's `missing` fill ([Multi-source](../core-concepts/multi-source.md#coin-legs-every-venue-follows-the-chart)). `when` names a `param.bool`, or a `param.multi` with `when_bit` naming the option's bit; it rides a secondary scalar feed input only, and while the setting is off the lane is not fetched and the input reads its fill. A `trades.*` input's `currency` may be `"@<param>"` naming a `param.choice` whose choices are the units (`"USD"`, `"Coin"`): the sheet keeps the default's word as `currency` and the setting as `currency_param`, and the chart reads the lane in the picked unit. - `chart_interval_below` rides a stream input only (`candles`, `oi_candles`, `volume_profile_candles`), as an interval word the sheet writes as the enum word (`"1h"` lands as `HOUR`), never on the first input or beside `view: "forming"` ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). - The expanded sheet holds at most 128 params (a `range` counts two, a `session` three, a `list` its `max` + 1, a `unit` list one more); every other cap is on [Limits](limits.md). - Names share one namespace across outputs, boxes, segments, renderers, drawings and alerts. - A celled input requires `max_cells` (`candles` and `oi_candles` get the larger of `bars` and 2 when it is left out; `volume_profile_candles` always names it, at least `bars`) and `book` requires `block_size`; scalar-feed knobs are refused on a celled input. `currency` on `oi.*` and `oi_candles.cells` is `"USD"` or `"Coin"` (`oi.*` defaults to dollars, `oi_candles.cells` to the venue's own units). ## The sheet Run derives When you press **Run**, the editor derives the sheet from the declarations, checks it against the schema, and compiles; a refusal prints in the Console on the declaration's line, and Run stops there. There is no hand-written sheet. Read it at the Console prompt (`sheet`) and in **Copy for LLM**; a published indicator carries it. The sheets on this page omit the provenance fields every derived sheet carries (`generated_from`, `source_digest`, and `wasm_sha256` once the module compiles). These declarations, in a tab titled "Context Skeleton": ```typescript param("period", 14, { min: 2, max: 200, description: "Lookback bars" }); input("close", ohlcv.close); input("btc_close", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", description: "Fixed BTC reference market" }); input("funding_rate", funding.rate_close); output("value", line, lower, { unit: "score" }); output("raw", none); output("lagging", line, lower, { displacement_bars: -26 }); ``` derive every top-level field a scalar sheet has: ```json { "id": "context-skeleton", "name": "Context Skeleton", "params": [ { "name": "period", "default": 14, "min": 2, "max": 200, "description": "Lookback bars" } ], "inputSources": { "close": { "source": "ohlcv", "field": "close" }, "btc_close": { "source": "ohlcv", "field": "close", "exchange": "BINANCE_FUTURES", "symbol": "BTCUSDT" }, "funding_rate": { "source": "funding", "field": "rate_close" } }, "inputs": [ { "index": 0, "name": "close" }, { "index": 1, "name": "btc_close", "description": "Fixed BTC reference market" }, { "index": 2, "name": "funding_rate" } ], "outputs": [ { "index": 0, "name": "value", "plot": "line", "panel": "lower", "unit": "score" }, { "index": 1, "name": "raw", "plot": "" }, { "index": 2, "name": "lagging", "plot": "line", "panel": "lower", "displacement_bars": -26 } ] } ``` | Field | What Run writes | | --- | --- | | `id`, `name` | from the editor tab's title (`Context Skeleton` derives `context-skeleton` and `Context Skeleton`); `name` is shown in lists, and publishing names the package `@yourname/<name>` ([Publishing](../functions/publishing.md)) | | `abi_version` | the runtime contract, picked from the declarations you use; ABSENT means `"wrun-1"` (below) | | `generated_from`, `source_digest` | `"declarations"`, and the sha256 of the source the sheet came from | | `wasm_sha256` | the compiled module's sha256, stamped when Run compiles it | | `history_independent` | `true` beside `wasm_sha256` when the compile proved that every bar's outputs depend on that bar's inputs alone, so the chart recomputes only the new bars on a pan-back ([Per-bar scripts](../core-concepts/per-bar-scripts.md)); derived by the compiler, never written by hand (a sheet that carries it builds with a warning and loses it), absent otherwise and never `false` | | `history_warmup` | `{ kind: "exact", windows: [{ terms: [{ param, multiplier }], plus, min }], plus }` beside `wasm_sha256` when the compile proved that the file's only memory is instances of kit classes with a finite window, so a fresh run started W bars early matches the run from the first bar bit for bit: W is each window's `max(ceil(sum of setting * multiplier + plus), min)`, summed, plus the top-level `plus`, and the chart recomputes only the new bars on a pan-back after that running start ([Per-bar scripts](../core-concepts/per-bar-scripts.md#rolling-math-that-settles-within-w)); a declared `warmup` or `warmup_bars` stays out of it, and the chart's running start is the larger of the two at the run's settings. A file that keeps a second mode behind one select, or behind several selects joined by `&&` (a mode guard), is proven on its guarded arm alone, and its stamp, the same shape, ends with one window holding a term per select, `{ terms: [{ param: "<select>", multiplier: 1000000000 }, ...], plus: 0, min: 0 }` (the kit's `WRUN_WARMUP_MODE_UNBOUNDED`): a conditional proof encoding, not a bound, so W is the arm's while every select reads 0 and past every chart's cap once any picks another option ([Per-bar scripts](../core-concepts/per-bar-scripts.md#one-setting-two-modes-the-mode-guard)); derived by the compiler, never written by hand (a sheet that carries it builds with a warning and loses it), never beside `history_independent` | | `params` | `{name, default, required?, min?, max?, description?}` with unique names, in declaration order; values reach the module positionally in that order | | `inputSources` | keyed BY INPUT NAME: the source, the field and the options the declaration set, an interval always as the long word (`FOUR_HOURS`) | | `inputs` | `{index, name, description?}`, indexes contiguous from 0 in declaration order; index 0 is the PRIMARY input, which follows the chart's market and interval (a pin on it is refused; an `odds` input is the exception); a `time` source cannot be primary | | `outputs` | `{index, name, description?, plot?, panel?, unit?, displacement_bars?, ...style, ...presentation}`, indexes contiguous from 0, unique names; `plot: ""` is a data-only output (declared `none`); `displacement_bars` draws the value written at bar i at bar `i + displacement_bars`, the module never shifting a row | The chart reads no warm-up field: the bars where `onBar()` writes nothing are the warm-up. The sheet is DERIVED state, serialized canonically (an unchanged source rewrites nothing): edit the declaration, never the sheet. ## Typed settings on the sheet A typed setting adds its `type` (`int`, `number`, `boolean`, `select`, `color`, `time`, `price`, `multi`, `symbol`, `text`) and the dialog's keys (`label`, `step`, `group`, `row`, `hint`, `when`, `hide`, `slider`, `confirm`; `options` and `option_labels` on a select, `multi_bits` on a multi, `unit` and `unit_default` beside a unit menu); a composite expands to its members (`range` / `range_end`, `list` / `list_index` / `list_end`, `session` / `session_end`, `unit_for`); a host-applied setting carries `host` and a symbol its `symbol_default`; a binding records `style_targets` (and `style_values` on a line-style choice); a `text` setting carries `max_bytes`, `multiline` and its words as `text_default` (its `default` is 0); `market.*` and `chart.*` carry `host_fill` and `hidden`. None of these change what reaches the module: one number per sheet param, a text setting's number being its words' byte count, with the words on the text channel. The declarations below, in a tab titled "Typed Skeleton": ```typescript page("Signal"); param.int("period", 14, { min: 2, max: 200, label: "Length" }); param.choice("kind", ["Simple", "Exponential"], "Simple"); const show = param.bool("show_band", true); section("Band", { toggle: show }); param.range("band_pct", [0.5, 2.0], { min: 0, max: 10, step: 0.1, label: "Band width %" }); param.color("band_color", "#94a3b8"); input("close", ohlcv.close); output("value", line, overlay, { label: "Average", format: "price" }); output("band_hi", line, overlay, { color: "@band_color", label: "Band", legend: false }); presets({ Tight: { band_pct_lo: 0.2, band_pct_hi: 1 } }); ``` derive six sheet params from five settings (the range is two), the color's default written onto the output it paints plus the binding on the param, the layout, and the preset: ```json { "id": "typed-skeleton", "name": "Typed Skeleton", "params": [ { "name": "period", "default": 14, "min": 2, "max": 200, "type": "int", "step": 1, "label": "Length" }, { "name": "kind", "default": 0, "type": "select", "options": [0, 1], "option_labels": ["Simple", "Exponential"] }, { "name": "show_band", "default": 1, "min": 0, "max": 1, "type": "boolean" }, { "name": "band_pct_lo", "default": 0.5, "min": 0, "max": 10, "type": "number", "step": 0.1, "label": "Band width %", "range": "band_pct", "range_end": "lo" }, { "name": "band_pct_hi", "default": 2, "min": 0, "max": 10, "type": "number", "step": 0.1, "label": "Band width %", "range": "band_pct", "range_end": "hi" }, { "name": "band_color", "default": 9975030760, "type": "color", "style_targets": [{ "output": "band_hi", "property": "color" }] } ], "inputSources": { "close": { "source": "ohlcv", "field": "close" } }, "inputs": [{ "index": 0, "name": "close" }], "outputs": [ { "index": 0, "name": "value", "plot": "line", "panel": "overlay", "label": "Average", "format": "price" }, { "index": 1, "name": "band_hi", "plot": "line", "panel": "overlay", "color": "#94a3b8", "label": "Band", "legend": false } ], "layout": [ { "kind": "page", "title": "Signal" }, { "kind": "param", "name": "period" }, { "kind": "param", "name": "kind" }, { "kind": "param", "name": "show_band" }, { "kind": "section", "title": "Band", "toggle": "show_band" }, { "kind": "param", "name": "band_pct_lo" }, { "kind": "param", "name": "band_color" } ], "presets": [ { "name": "Tight", "values": { "band_pct_lo": 0.2, "band_pct_hi": 1 } } ] } ``` Underneath, the module still receives six numbers in this order: the length, the choice's index, 1 or 0 for the toggle, the two ends of the range, and the packed color. ## Pins on the sheet A pin lands on the input's `inputSources` entry as declared; one the user can change carries the setting's default plus `interval_param` or `symbol_param`, a profile's bucket size `ticks_per_bar_param`, and a `param.source` input `field_param`. A volume profile declared `missing: "empty"` carries the word too, and so does a `trades` input's `currency`. The chart checks every pin before anything is fetched and refuses one it cannot serve by name. What each source may pin, and what a leg, a view, an offset or `bars` reads: [Multi-timeframe](../core-concepts/multi-timeframe.md); another market and the `missing` policy: [Multi-source](../core-concepts/multi-source.md). Liquidations first, read as 0 on quiet bars, with the close carried beside them (the schema refuses `missing: "carry"` on the first input): `input("liqs", liquidations.liquidations, { missing: "zero", description: "Total liquidations, 0 on quiet bars" })`, `input("close", ohlcv.close, { description: "Close, carried" })` and `output("liq_ratio", histogram, lower)`, in a tab titled "Dense Liquidations", derive: ```json { "id": "dense-liquidations", "name": "Dense Liquidations", "params": [], "inputSources": { "liqs": { "source": "liquidations", "field": "liquidations", "missing": "zero" }, "close": { "source": "ohlcv", "field": "close" } }, "inputs": [ { "index": 0, "name": "liqs", "description": "Total liquidations, 0 on quiet bars" }, { "index": 1, "name": "close", "description": "Close, carried" } ], "outputs": [ { "index": 0, "name": "liq_ratio", "plot": "histogram", "panel": "lower" } ] } ``` A fixed BTC reference on its own 4h candles, as of close: `input("btc_4h", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", interval: "4h", description: "BTC on its own 4h grid, as of close" })` beside `input("close", ohlcv.close)` and `output("ratio", line, lower)`, in a tab titled "BTC 4h Context", derive the sheet below, the interval spelled `FOUR_HOURS`. On a 4h chart the pin equals the chart's interval and reads BTC row by row; on a coarser chart it is finer than the chart, and Run refuses it. ```json { "id": "btc-4h-context", "name": "BTC 4h Context", "params": [], "inputSources": { "close": { "source": "ohlcv", "field": "close" }, "btc_4h": { "source": "ohlcv", "field": "close", "exchange": "BINANCE_FUTURES", "symbol": "BTCUSDT", "interval": "FOUR_HOURS" } }, "inputs": [ { "index": 0, "name": "close" }, { "index": 1, "name": "btc_4h", "description": "BTC on its own 4h grid, as of close" } ], "outputs": [{ "index": 0, "name": "ratio", "plot": "line", "panel": "lower" }] } ``` An `odds` input names its own Polymarket market by condition id (`0x` + 64 hex) in `symbol` and may be the first input ([Data sources](../core-concepts/data-sources.md)). This sample pins the placeholder market the chart's prediction starters ship, so Run refuses it until you paste your market's condition id into `symbol`: ```typescript param("period", 5, { min: 1, max: 200, description: "Momentum lookback, bars" }); // The market is its condition id (0x + 64 hex): paste yours over this placeholder. input("yes_odds", odds.close, { symbol: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", outcome: "YES", description: "Polymarket YES probability" }); output("momentum", line, lower, { description: "Rate of change of the YES probability" }); let roc = new Roc(5); function onStart(): void { roc = new Roc(i32(p_period())); } function onBar(): void { out_momentum(roc.update(in_yes_odds())); } ``` ## Boxes and segments (per-bar shapes) Two top-level arrays, derived from `box(...)` and `segment(...)`, legal on every contract: they add nothing to the module, and the chart evaluates them on EVERY bar row. The sheet records output NAMES under snake_case fields: `boxes` (at most 16), each `{name, top, bottom, x_from?, x_to?, when?, panel?, color?, border_color?, opacity?, border_width?, border_style?, z?, color_by?, colors?, color_packed_by?, border_color_by?, border_colors?, border_color_packed_by?}` (the `_by` keys name declared outputs whose per-bar value picks an entry of `colors` or `border_colors`, 1..64 colours each; the `_packed_by` keys an output carrying a packed colour per bar), and `segments` (at most 16), each `{name, y_from, y_to, x_from?, x_to?, when?, panel?, color?, width?, line_style?}`. The coordinates name declared outputs (data-only allowed); `x_from` / `x_to` are bar offsets, a literal (whole or fractional: a fraction places the edge inside its bar, at that share of the bar's interval) or the name of an output whose truncated per-bar value is the offset; `when` names a gate output (the bar is skipped unless its value is finite and nonzero). Every refusal names the field (`boxes.0.top`). The defaults and what the chart draws: [Drawing objects](../presentation/drawing-objects.md). ## Declared alerts `alerts` (at most 64), derived from `alert(name, { when, message?, description?, text?, every_bar?, title? })`, each `{name, when, message?, description?, text?, every_bar?, title?}`: `when` names a declared output (any plot, data-only `""` included), and the alert fires on the bar that output turns from false to true (true is finite and nonzero; a `NaN` row is false and re-arms it), or on every bar it holds when `every_bar` is `true`; `text` records the slot's name. Legal on every contract; nothing new reaches the module. The golden-cross declarations on [Alerts](../functions/alerts.md), in a tab titled "Golden Cross", derive: ```json { "id": "golden-cross", "name": "Golden Cross", "params": [ { "name": "fast", "default": 21, "min": 1, "max": 200, "description": "Fast EMA length" }, { "name": "slow", "default": 55, "min": 2, "max": 400, "description": "Slow EMA length" } ], "inputSources": { "close": { "source": "ohlcv", "field": "close" } }, "inputs": [{ "index": 0, "name": "close" }], "outputs": [ { "index": 0, "name": "fast", "description": "Fast EMA of the close", "plot": "line", "panel": "overlay", "color": "#2563eb" }, { "index": 1, "name": "slow", "description": "Slow EMA of the close", "plot": "line", "panel": "overlay", "color": "#f97316" }, { "index": 2, "name": "golden_cross", "plot": "" } ], "alerts": [ { "name": "golden_cross_up", "when": "golden_cross", "message": "{{symbol}} golden cross at {{close}}", "description": "Fast EMA crosses above slow EMA" } ] } ``` ## Settings layout, presets, presentation Four more top-level keys, written only when the file declares them and read by the chart alone: `layout`, `presets`, `legend_title` and `presentation`. Legal on every contract; none reaches the module. | Key | Shape | | --- | --- | | `layout` | the dialog in source order: `{kind: "page", title}`, `{kind: "section", title, toggle?, collapsed?, when?}`, `{kind: "divider"}`, `{kind: "note", text}`, `{kind: "param", name}` (a composite once, under its first member's name; a hidden `market.*` param takes no entry); absent when the file uses no layout word and no `group` option, and the dialog keeps one flat list | | `presets` | `[{name, values: {param: number | boolean | string}}]` as declared; the chart turns each value into the setting's own form when a preset is picked | | `legend_title` | the `legend({ title })` template | | `presentation` | `{legend?: [...], hud?: [...]}` from `render.legend` and `render.hud`, each entry with the keys of its declaration, the tiles in the block shape an output's `hover` uses | A `presentation.hud` entry carries its surface, type and look words as declared (`width`, `offset`, `z`, `background_color`, `corner_radius`, `font_family`, `look`, `accent_color`, `chrome`, `safe_area`, `mobile` and the rest). Two more top-level arrays and two flags travel the same way: `panes` (from `pane(...)`, each `{name, title?, place?, height_frac?, scale?, invert?, padding?, min?, max?, format?, decimals?, signed?, unit?}`, at most 4), `fills` (from `fill(...)`, each `{between: [a, b], color?, opacity?, color_by?, colors?, color_packed_by?, z?}`), `contrast_guard` (boolean, default true) and `stack_handles` (boolean, default false). What the dialog draws from each: [Pages, sections, dividers, notes](../settings/layout.md), [Presets](../settings/presets.md), [Legend](../presentation/legend.md), [HUD and hover cards](../presentation/hud-and-hover-cards.md); the Style page is derived from the outputs, with no key of its own ([The Style page](../settings/style-page.md)). ## ABI versions: the five contracts Run writes `abi_version` from the declarations you use, and the module is validated and run under that contract and no other. The first contract is FROZEN: published indicators on it keep running bit-identically. Each later contract is ADDITIVE over the one before, the same entry points and scalar block plus one channel family, and freezes in turn. `range`, `box`, `segment` and `alert` are contract-neutral: declaring one never flips the sheet; so are `fill`, `pane`, the chart flags, the cell-fed canvases (`plot.heatmap`, `plot.footprint`, `plot.tpo`, `plot.profile`), which ride whichever contract their input already needs, and `plot.marks`, `plot.spans` and `plot.rays`, whose records ride plain outputs. | Contract | Stamped by | Adds | | --- | --- | --- | | `"wrun-1"` (the field absent) | scalar-only declarations | params, inputs, outputs | | `"wrun-2"` | a celled input, a string slot, a renderer or a declared drawing | the cell and string channels, the renderer and drawing vocabulary (below) | | `"wrun-3"` | a handle, `strategy(...)` or a `bar.isLast()` call | the handle-keyed draw channel, the strategy channel, the last-bar flag ([Drawing objects](../presentation/drawing-objects.md), [Strategies overview](../strategies/overview.md)) | | `"wrun-4"` | a frame (`frame(...)`, `panel.*`, `plot.levels`, `plot.matrix`, a `draw.ladder` or `draw.feed` HUD) | the frame channel ([Cards, frames and panels](../presentation/cards-frames-panels.md)) | | `"wrun-5"` | a text setting (`param.text`, `param.text_area`) | the text channel (`wrun_param_len`, `wrun_param_bytes`): a text setting's words, handed over before the first bar ([Text settings](../settings/kinds.md#text-settings)) | | `"wrun-6"` | a `bar.count()` read | the bar count (`wrun_bar_count`): how many bars the run holds, so a bar can tell whether a later bar exists ([Execution model](../core-concepts/execution-model.md#how-many-bars-the-run-holds)) | The second contract's sheet additions, as Run derives them from `input("profile", volume_profile.cells, { max_cells: 256 })` and `input("book", book.cells, { max_cells: 1000, block_size: 10 })` in a tab titled "Orderflow Context": ```json { "id": "orderflow-context", "name": "Orderflow Context", "abi_version": "wrun-2", "params": [], "inputSources": { "close": { "source": "ohlcv", "field": "close" }, "profile": { "source": "volume_profile" }, "book": { "source": "book", "block_size": 10 } }, "inputs": [ { "index": 0, "name": "close" }, { "index": 1, "name": "profile", "cellType": "array", "max_cells": 256, "capacity": 256 }, { "index": 2, "name": "book", "cellType": "array", "max_cells": 1000, "capacity": 1000 } ], "outputs": [ { "index": 0, "name": "imbalance", "plot": "line", "panel": "lower" } ] } ``` `inputs[].cellType: "array"` marks a celled input, and `max_cells` beside it counts the class's TUPLES (the cap the chart enforces: an oversize bar refuses the run, never truncates); `capacity` beside that is the tuples the build gave the input's buffer, `max_cells` or, for a print read's union, `max_cells` plus `newest`, and the chart hands a bar's block to the indicator up to it (the build writes it, never you); `block_size` and `max_depth` are recorded, and the chart serves the book it has stored as it is. A celled input keeps its positional slot in the scalar block (reading `NaN`), can never be the primary input, and joins the chart's rows exactly: a bar with no observation is a PRESENT EMPTY block (`0` cells, not `-1`), never a carried value and never a withheld row. The classes and each block's rules: [Data sources](../core-concepts/data-sources.md#celled-sources), [Multi-timeframe](../core-concepts/multi-timeframe.md). ## String slots, renderers, drawings Outputs stay numbers; the second contract adds three top-level arrays, derived from `string(...)`, `render.*` and `draw.*`, that turn numbers and per-bar text into chart decorations. Numeric coordinates name declared OUTPUTS, text fields name declared STRING SLOTS, and the two namespaces never substitute for each other. | Array | Entries | | --- | --- | | `string_slots` (at most 64) | `{index, name, max_bytes, description?}`, indexes contiguous from 0, unique names; a slot not written that bar is ABSENT, distinct from a written empty string | | `renderers` (at most 64) | `{kind, name, ...}` with the keys of the matching `render.*` declaration, `kind` one of `text`, `label`, `table`, `shape`, `stats_row`, `bgcolor`, `barcolor` | | `stats_strip` (beside a `stats_row` renderer) | `{grading?, label_side?, theme?}`, the strip's look in its words ([Plotting](../presentation/plotting.md)); a `param.choice` paints a key it holds through `style_targets` and `style_values` | | `drawings` (at most 64) | `{kind, name, ...}` with the coordinate outputs of the matching `draw.*` declaration, `kind` one of `line`, `box`, `polyline`, `label`; x values are epoch SECONDS | What each renderer draws and which row wins: [Plotting](../presentation/plotting.md); a declared drawing is evaluated on the LAST row only: [Drawing objects](../presentation/drawing-objects.md). The expanded render selection must stay under 8 MiB per run, refused as `wrun_render_result_too_large`. A 2x2 session-stats table plus a box around the session's price range. The box's top and bottom are drawn as lines on the price pane: a package with a drawn `overlay` output is homed there, and a declared drawing follows the pane of its y output (`top` for a box), so the box frames the candles while `range_pct` keeps its own pane below. Data-only outputs never decide a pane, so the two x coordinates, bar times, stay `none`. The four cells are rewritten every bar so the table shows the last complete row: ```typescript output("range_pct", line, lower, { unit: "%", description: "Session range as a percent of its low" }); // The box's coordinates, read by name. Its top and bottom are drawn on the price pane: // a drawn overlay output homes the package there, and the box follows its `top` output's // pane, so it frames the candles rather than the percent line. The two times stay data-only. output("left", none); output("top", line, overlay, { color: "#f59e0b", width: 1, description: "Session high so far, the box top" }); output("right", none); output("bottom", line, overlay, { color: "#f59e0b", width: 1, description: "Session low so far, the box bottom" }); // The table's four cells: byte-capped string slots rewritten every bar. string("close_label", { max_bytes: 16 }); string("close_text", { max_bytes: 32 }); string("range_label", { max_bytes: 16 }); string("range_text", { max_bytes: 32 }); render.table("session_stats", { rows: 2, cols: 2, cells: ["close_label", "close_text", "range_label", "range_text"], position: "top_right" }); draw.box("session_zone", { left: "left", top: "top", right: "right", bottom: "bottom", color: "#f59e0b" }); let high: f64 = NaN; let low: f64 = NaN; let left: f64 = NaN; let right: f64 = NaN; function onBar(): void { const close = bar.close(); if (isNaN(high) || close > high) high = close; if (isNaN(low) || close < low) low = close; const t = bar.time(); if (isNaN(left)) left = t; right = t; if (isNaN(low) || low <= 0.0) return; const range = (100.0 * (high - low)) / low; out_range_pct(range); out_left(left); out_top(high); out_right(right); out_bottom(low); str_close_label("close"); sb_clear(); sb_f64(close, 2); str_close_text_sb(); str_range_label("range"); sb_clear(); sb_f64(range, 2); sb_text("%"); str_range_text_sb(); } ``` Because every coordinate output is finite on the last bar, the box exists with `createdBar` = that bar; a module that wants a drawing REMOVED writes `NaN` to a coordinate output on the newest bar. Decorations never change the numbers the outputs carry. ## Validation, in one list When Run checks the derived sheet, the schema refuses, naming the path (the Console puts a param, input, output or string-slot refusal on the declaration it came from). The caps, each with its message, are on [Limits](limits.md); the messages with their fixes are in [Common errors](../faq/common-errors.md). Beyond the caps and the rules above, the schema refuses: | Family | Refused | | --- | --- | | Params | duplicate names; a `type` outside the nine words; a composite with a member missing or doubled; `hide` without `when`; `unit_default` outside `unit`; a `multi` default past its bits; a `when` or `unit_for` naming no param; a `style_targets` output that is not drawn; `unset_at_default` on a target of a setting that is not a `param.color`, or on a non-colour target; a `stats_strip` target the strip does not hold, or painted by anything but a choice over the key's words; a preset or presentation name used twice | | Inputs | non-contiguous or duplicate indexes and names; an input without a source entry, or the reverse; a `time` primary; a lone pin half; `outcome` or `binding` outside odds; a condition id that is not `0x` + 64 hex; a required knob missing (`tenor`, `side`, `token`, `fund`, `publisher`, `series`, a feed's `ref`) or a knob on a source that does not take it; a `series` primary input; a `delta` other than 5, 15, 25 or 35; `fund: "all"` on `etf_premium`; a `missing` value outside `carry`, `nan` and `zero`, `missing: "carry"` on the primary input, or any `missing` on a celled or `time` source; unknown fields per source | | Celled inputs | `cellType` without the second contract or without `max_cells`; `max_cells` without `cellType`; a `capacity` without `cellType`, below `max_cells` or above what the read can hold; a celled class under a scalar input, as the primary input, or with a `field` or an `interval` pin (`intrabar` and the streams `candles`, `oi_candles` and `volume_profile_candles` excepted); `block_size` or `max_depth` anywhere but `book` | | Outputs and ranges | non-contiguous or duplicate indexes and names; a `format` outside the ten, `decimals` or `signed` without `format`; a `line_style` or `edge_line_style` outside solid, dashed and dotted; a block whose output or slot does not exist; an output badging itself; a style reference to an output that does not exist; range sides equal or not rendered; a range `color_by` without `colors` (bare `colors` is legal: the band sign palette) | | Boxes, segments, alerts | a coordinate, offset or `when` gate naming no declared output; a `panel` outside overlay and lower | | String slots, renderers, drawings | any of the three under the first contract; non-contiguous or duplicate slot indexes and names; a reference to an output or string slot that does not exist; a bgcolor, barcolor or shape ladder half without the other; a bgcolor or barcolor `where` naming no declared output; a text or label `style` outside the eight, a tag key on plain text or `align` on a tag, a corner label with `x` and `y` beside `offset`; a HUD `position` outside the nine anchors or its `columns` outside 1 and 2, a HUD `look`, `chrome` or tile `draw` outside its list | | Styling words | a `theme.` word outside the seven; a `unit` past 8 characters beside a `format` on a pane, panel, level, card, ladder or canvas (an output's `unit` stays unbounded); a `corner_radius` outside 0..32, a `font_weight` or `font_family` outside their words; a look word on a plot kind that does not take it (`step` on a bar, `gradient` beside `color_by`, `split` without both colours, `stack` beside `base`, `char` without `shape: "char"`); a `pane` naming no declared pane, a declared pane with nothing drawn in it or more than 4, a `fill` whose sides sit on two panes, a `z` outside -10..10; a box or fill ladder half without the other, or a packed key beside its `_by` key | <!-- source: https://openmarket.xyz/wrun/reference/limits --> # Limits reference Every ceiling a wrun indicator runs under on the chart, in one place: the declaration caps Run checks when it derives the sheet, the runtime ceilings the browser sandbox enforces on every run, the data bounds, and the publish bounds. Each row gives the exact number, what it protects, the shape that hits it, and the message it produces. Most of them are counts of declarations, because a wrun indicator declares almost everything once. ## Plans Free and Plus differ in how much you keep on your charts and in your account: | | Free | Plus | | --- | --- | --- | | Indicators | 3 across your charts | 10 per chart | | Indicator alerts | 5 | 50 | | Saved scripts | 100 | 500 | At the saved-script limit, saving a new script stops with "Saved-script limit reached (100 on your plan). Delete a script or upgrade to save new ones." ## Declaration caps Checked by Run in your browser when it derives the sheet from your declarations, before anything reaches the chart. A declaration over a cap is refused in the editor's Console, anchored on the declaration that breaks it and naming the field (`boxes.0.top`, `renderers.2.size`). | Limit | Value | What it caps | When you hit it | Refusal | | --- | ---: | --- | --- | --- | | Boxes | 16 per indicator | `box(...)` declarations, each drawn once per bar | one declaration per occurrence instead of one gated declaration | `boxes must declare at most 16 entries` | | Segments | 16 per indicator | `segment(...)` declarations, each drawn once per bar | the same shape | `segments must declare at most 16 entries` | | Renderers | 64 per indicator | `render.text`, `render.label`, `render.table`, `render.shape`, `render.stats_row`, `render.bgcolor`, `render.barcolor` | a footprint-style file with a text tile per price level | `renderers must declare at most 64 entries` | | Drawings | 64 per indicator | `draw.line`, `draw.box`, `draw.polyline`, `draw.label` and the widgets, placed from the newest bar | many run-level objects; a growing list is handles instead | `drawings must declare at most 64 entries` | | Polyline points | 64 pairs | `points` on one declared `draw.polyline` (a polyline handle takes 100,000) | a curve traced point by point in a declaration | `polyline points must be <= 64 pairs` | | Declared alerts | 64 per indicator; `message` and `description` at most 200 characters each; `title` 1 to 120 characters on one line, without control or invisible characters; `text` names a declared string slot, whose words are cut at 200 characters when the alert fires | `alert(...)` declarations | a signal per level instead of one gate output | `alerts must declare at most 64 entries`, `message must be at most 200 characters`, `alert 'cross' title is 121 characters; it takes at most 120`, `alert 'cross' text names 'ghost', which is not a declared string slot` | | Handle defaults | `width` 0.5..20, `border_width` 0..10, `opacity` 0..1, `size` and `font_size` 6..64, `line_style` and `border_style` solid/dashed/dotted, `extend` none/left/right/both, `align` left/center/right, `valign` top/middle/bottom, `padding` 0..64, `corner_radius` 0..32, `glow` 0..32, `max_width` 0..2000 (0 = no wrap), `angle` -90..90, `gradient` 2..8 colours, `arrow` none/start/end/both, `axis_label` none/price (text on a label), `panel` overlay/lower; the legacy `borderWidth`, `borderColor` and `lineStyle` spellings still read, never beside their snake_case twins | the defaults one `handles.<kind>(...)` declaration sets for `line`, `box`, `label` or `polyline`, and the same keys on a declared `draw.line`, `draw.box`, `draw.polyline` or `draw.label` | a label handle no longer needs a string slot: `.mark()` draws an emblem with no text | `handles.line.width: width must be <= 20`, `a line has no text; use price` | | Table geometry | 32 rows x 32 cols | one `render.table`; `cells` must list exactly `rows * cols` slot names; `rows_by` paints the first rows only (a data-only output's value on the table's bar, clamped to 0..`rows`) | a dashboard dump | `table rows must be <= 32`, `table cols must be <= 32`, `table 'stats' declares 2x2 = 4 cells but lists 3`, `render.table 'stats' rows_by names 'v', which is a drawn output; rows_by takes a data-only output (plot none) holding how many rows paint` | | Table look | `width` and each of `column_widths` 0..4096 px (0 = measured, one per column), `cell_padding` 0..64, `offset` within [-200, 200], `border_width` and `grid_width` 0..10, `corner_radius` 0..32, `font_size` 6..64, `opacity` 0..1, a gradient 2..8 colours, `header_rows` at most `rows`, a `colspan` or `rowspan` inside the grid at every cell carrying the slot, every colour ladder in a pair (`<key>_by` + `<key>s`, or `<key>_packed_by`, never both) | the look keys and `styles` entries on one `render.table` ([Styled tables](../presentation/cards-frames-panels.md#styled-tables)) | a span past the last column, a widths list shorter than the columns | `table 'board' lists 1 column widths for 2 columns`, `table 'board' cell 'b' spans 2 columns from column 2 of 2`, `table 'board' declares text_color_by without text_colors (both or neither)` | | String slots | 64 per indicator | `string(...)` declarations | one slot per table cell on a big table | `string_slots must declare at most 64 slots` | | Slot bytes | 1..4096 per slot | `max_bytes` on one slot | a long per-bar readout | `max_bytes must be <= 4096 (the per-slot byte cap)` | | Frames | 8 per indicator, each at most 96 KiB (98,304 bytes) | `frame(...)` declarations and their `max_bytes` | a snapshot per widget instead of one frame per payload | named by field | | Mini-chart grid | 1..12 panels of 0..100 candles; labels 1..24 characters, the title at most 40 | the frame of one `draw.minicharts` | a grid of more than 12 markets or timeframes | `a grid holds at most 12 panels`, `a panel holds at most 100 candles` | | Mini-chart look | `columns` 1..4, `panel_width` 72..320, `panel_height` 48..220, `gap` 0..48, `x` and `y` -2000..2000, `ma_width` 0.5..5 | the options of one `draw.minicharts` | | `columns must be within 1..4` | | Docked profiles | 4 per indicator; a frame of 1..512 rows; `width_frac` 0.05..0.5 or `width_px` 16..600 (never both); `offset` x 0..4096; `thickness_px` 2..40; `opacity`, `outside_opacity` 0..1; `series` 1..8 with unique names; `gradient` 2..8 colours; `border_width`, `value_area_width`, `poc_width` 0..10 (the POC at least 1); `font_size` 6..64; `step`, `scale_max` above 0; `labels_text` 0..24 characters a row, `tooltips` 0..64, `poc_label_text` 1..24 | `plot.levels(...)` and its frame ([Docked profiles](../presentation/cards-frames-panels.md#docked-profiles)) | a level `beside` itself or on the other dock, a `behind_candles` profile on the lower pane, a `scale: "fixed"` with no `scale_max` | `width_px is refused beside width_frac`, `scale_max needs scale 'fixed'`, `wrun_frame_invalid` for a frame whose series count or shape disagrees with the declaration | | Level spans | 64 spans per frame, 1..512 prices each, 4096 rows across every span; a span's own `labels_text` (0..24 characters a row), `series` (one array per declared series, each the span's row count, on every span or on none), `value_area`, `poc_price` and `poc_label_text` (1..24) under the pane frame's caps | a `plot.levels` frame under `span: "time"` | one span per bar instead of one per session; a span's `colors` beside its `series` | `wrun_frame_invalid: <frame>.spans`, `unknown span key '<key>'`, `colors and series do not mix: a segmented row takes its series colours`, `every span carries series or none does` | | Panels | 8 per indicator; `series` 1..8 (a table 1..12); frame rows 2000 (a table 128, a pie or tiles 24); `markers` and `guides` 0..8; `summary` 0..5 rows; `height_frac` 0.05..0.9; `title` 1..40, `caption` 1..64; `x_title`, `y_title` 1..40; `width` 0..4096, `column_widths` 0..4096 each (one per column), `cell_padding` 0..64, `offset` -200..200, `font_size` 6..64, `border_width` and `grid_width` 0..10, `background_gradient` 2..8, `palette` 2..8, `bins` 2..200, `columns` 1..8, `slice_gap` 0..8, `trail_width` 0.5..6, a series `width` 0.5..20, marker and guide `width` 0.5..4, labels 1..24 | `panel.<kind>(...)` and its frame ([Frames, panels and compact widgets](../presentation/cards-frames-panels.md#frames-panels-and-compact-widgets)) | a 9th marker, a word on a kind that does not take it, a rich-line word on a boxed line | `markers allows at most 8`, `table allows at most 128 rows`, `series allows at most 12 columns on a table`, `<word> is only valid for <kinds>`, `<word> needs chrome 'hairlines', 'grid' or 'none' on a line, not 'box'` | | Side strip | `width_px` 160..480, `height_px` 80..800, both with `place: "side"` only; the strip takes at most 40% of the chart and folds away under 480 px | a panel placed beside the chart or a matrix with `dock: "side"` | a side panel on a narrow layout | `width_px is only valid with place: 'side'` | | Heatmaps | 4 per indicator; `palette` 2..8 colours; `auto_quantile` 0.5..1; `cell_gap` 0..4; `opacity` 0..1; `tooltip` 1..200 characters, `label` 1..40; `out.grid` rows 2..128, and the grid's outputs count toward the 256 | `plot.heatmap(...)` and `out.grid(...)` ([Price canvases](../presentation/price-canvases.md)) | a grid with a row per tick, `cells` beside `grid` | `heatmaps must declare at most 4 entries`, `out.grid 'heat' rows must be between 2 and 128`, `heatmap 'h' takes cells or grid, not both` | | Profiles | 4 per indicator across footprints, TPOs and time-anchored profiles; `imbalance_ratio` 1.1..20; `stacked_imbalances` 0..10; `value_area` 0.5..0.95; `poc_width` 1..10; `letter_minutes` 1..240; a TPO `palette` 2..26; `width_frac` 0.05..1; `outside_va_opacity`, `background_opacity` 0..1 | `plot.footprint(...)`, `plot.tpo(...)`, `plot.profile(...)` | a footprint over book cells, a TPO colour mode that needs profile cells | `footprint 'fp' does not take period`, `tpo 't' color_mode 'volume' needs cells from a volume_profile input`, `profile 'p' behind_candles needs span 'session' and a filled mode` | | Marks, spans and rays | 4 sections of each kind per indicator; `slots` 1..64, each slot 3 outputs (marks), 4 (spans, rays) or 5 (timed spans and rays) that count toward the 256; marks `colors` 2..4, spans and rays 1..8; `words` up to 16 of 1..32 characters; `tooltip` 1..200; `size.scale` 1..10, `opacity_pct` 10..80, `look` 0..3, `text.mode` 0..2, `text.min_px` 0..64, `x` 0..1; a span `border.width` 0..4; a ray `width` 0.5..8 | `plot.marks(...)`, `plot.spans(...)`, `plot.rays(...)` ([Marks, spans and rays](../presentation/marks-spans-rays.md)) | a mark per trade past 64 a bar, 64 slots on several sections at once | `marks must declare at most 4 entries`, `plot.marks 'm' slots must be an integer from 1 to 64 (the records it holds a bar)`, `plot.marks 'm2' derives 66 outputs (22 slots x 3 fields), which takes the sheet to 259 outputs; a row carries at most 256, so declare fewer slots or fewer outputs`, `plot.spans 'z' is written by both out_z_span() (line 5, a run of bars) and out_z_span_at() (line 6, two timestamps); a section holds one record layout, so call one of the two writers` | | Matrices | 4 per indicator, `wrun-4` only; a frame of 1..128 prices, 1..12 columns and at most 1536 cells; cell text and column labels 1..16 characters; `column_width` 24..160; `row_max_px` 8..64; `cell_padding` 0..12; `tooltip` 1..200, `label` 1..40 | `plot.matrix(...)` and its frame | a matrix on a `wrun-3` sheet, a 13th column | `matrices needs abi_version "wrun-4" (wrun-3 has no frame channel)`, `wrun_frame_invalid: <frame>.cells` | | Widgets | 8 cards per indicator and 32 cards, feeds and meters per pane; a card's `rows` 1..12 (0..12 with a headline); `title` 1..40 (80 with a template), a row `label` 1..24 (64 with a template), a literal value 0..64; `offset` -4096..4096; `width` 80..1200; `corner_radius` 0..32; `padding` 0..24; `border_width` 0..10; `font_size` and `title_font_size` 6..64; `background_gradient` 2..8; `state_colors` exactly 4; a ladder frame 1..256 rows, `width_frac` 0.02..0.5, `offset` x 0..4096 with y 0; a feed 1..50 lines of 1..80 characters; a meter `ramp` 2..5, `bar_height` 2..40 | `draw.card`, `draw.feed`, `draw.meter`, `draw.ladder` ([Status cards](../presentation/cards-frames-panels.md#status-cards)) | a card with neither rows nor a headline, `accent_color` beside `state_colors` | `card 'x' needs a row or a headline`, `title takes 1 to 40 characters, 80 with a {{template}}`, `offset entries must be integers from -4096 to 4096`, `accent_color and state_colors are exclusive` | | HUD cards | `width` 80..1200 (300, or 180 at one column); `offset` -4096..4096; `corner_radius` 0..32; `padding` 0..24; `border_width` 0..10; `text_glow` 0..8; `accent_colors` 2..8; one headline tile per card; `rings` 1..3; a tile `font_size` 6..64, a tile `height` 16..120 | `render.hud(...)` and its tiles ([HUD cards](../presentation/hud-and-hover-cards.md#hud-cards)) | two headline tiles, a fourth ring | `a HUD takes at most one headline tile`, `look must be one of 'default', 'glass', ...` | | Number format | `decimals` 0..8; `unit` at most 8 characters on panes, panels, levels, cards, ladders and canvases; `decimals` and `signed` only beside `format` (an output's `unit` stays unbounded with or without `format`, as it always was; without `format` it is never printed) | every `format` word (outputs, panes, panels, levels, cards, ladders, canvases) | a unit longer than 8 characters on a pane, panel, level, card, ladder or canvas | `decimals must be an integer from 0 to 8`, `unit takes at most 8 characters`, `decimals needs format` | | Text size | 6..64 px | `size` on `text` and `label` renderers, and every `font_size` | | `size must be >= 6`, `size must be <= 64`, `font_size must be an integer from 6 to 64` | | Type words | `font_family` ui/mono/serif/rounded, `font_weight` normal/medium/bold, `valign` top/middle/bottom, `gradient_direction` vertical/horizontal, `corner_radius` 0..32 | every surface that takes them (panels, levels, cards, feeds, meters, ladders, HUDs, handles, drawings, renderers, canvases) | a CSS family name, a numeric weight | `font_family must be one of 'ui', 'mono', 'serif', 'rounded'`, `font_weight must be one of 'normal', 'medium', 'bold'`, `corner_radius must be between 0 and 32` | | Display offset | -500..500 bars, integer | `displacement_bars` on an output | a lagging span longer than 500 bars | `displacement_bars must be >= -500`, `displacement_bars must be <= 500`, `displacement_bars must be an integer count of bars` | | Shape offset | -500..500 bars, a whole or fractional literal | `from` / `to` on a box or segment | a zone anchored further back than 500 bars | `a literal bar offset must be within -500..500 bars of the current bar` | | Width ladder | 1..10 entries, each 0.5..20 (0.05..20 on bar and histogram) | `widths` beside `width_by` | | `widths must list at most 10 entries`, `widths entries must be <= 20` | | Line width | 0.5..20 | `width` on an output or a segment | | `width must be <= 20` | | Border width | 0..10 | `borderWidth` on a box | | `border_width must be <= 10` | | Edge width | 1..10, integer | `edge_width` on a range | | `edge_width must be <= 10` | | Gradients | 2..8 colors | `gradient` on a range, a line or a docked profile, `fill_gradient` on an area, `background_gradient` on a widget, a HUD or a table, a box's `gradient` | | named by field, `<key> must list 2 to 8 colours` | | Opacity | 0..1 | `opacity` on an output or a box (box default 0.2) | | named by field | | Color string | 1..64 chars, or a theme token | any `color` on a box, segment, renderer, or drawing; `theme.up`, `theme.down`, `theme.text`, `theme.muted`, `theme.bg`, `theme.grid` and `theme.accent` pass everywhere a colour goes (a colour param's default and presets excepted), and any other `theme.` word is refused | a `theme.` word outside the seven | `color must be a non-empty string of at most 64 chars`, `colour token must be one of theme.up, theme.down, theme.text, theme.muted, theme.bg, theme.grid, theme.accent`, `a colour param takes #rrggbb or #rrggbbaa; put the token on the colour key` | | Colour word | `#rrggbb`, `#rrggbbaa` or a theme token | every colour key this round added (panels, levels, cards, feeds, meters, ladders, HUDs, canvases, and the frames they read) | `rgba(...)` or a named colour on a panel series | `a colour must be #rrggbb, #rrggbbaa or one of theme.up, theme.down, theme.text, theme.muted, theme.bg, theme.grid, theme.accent` | | Box fill color | hex, `rgb()`, `hsl()` or a theme token | a box's and a box handle's `color` (the fill takes the opacity: a token fills at it) | a named color such as `"red"` | `color must be a hex, rgb() or hsl() color (the fill takes the opacity)` | | Palette | at least 2 entries | `colors` beside `color_by` | | `color_by needs 'colors' with at least 2 entries` | | Celled cap | required, positive integer, counts TUPLES | `max_cells` on a celled input | a celled input declared without it | `celled input 'profile' needs max_cells, e.g. input("profile", volume_profile.cells, { max_cells: 512 }) ...` | | Bucket size from a setting | a `param.int` whose `min..max` lies inside 1..500 | `ticks_per_bar: "@<param>"` on a `volume_profile.cells` input | an open-ended setting, or one that reaches past 500 | `input 'profile' ticks_per_bar references "@ticks", whose min..max (open..open) must lie inside ticks_per_bar's range 1..500` | | Colour alpha | a decimal from 0 to 1 after the setting's name, `"@<param>/0.4"` | every colour bound to a setting: the default lands as `rgba()` where the colour takes it, as `#rrggbbaa` where it takes a colour word | a panel series colour, which binds without an alpha | `whose alpha is not a decimal from 0 to 1 ("@bull/0.4")`, `a panel series colour binds without an alpha` | | Outputs | 1..256 | output declarations; the sandbox tracks 256 output slots per run (a file whose visuals are all frames may declare none) | a file past 256 outputs, or a raw write past the tracked slots | `WRUN output index 300 out of bounds for 256 tracked outputs` | | Settings | 128 per indicator, after expansion: most kinds count 1, a `unit` list on a number 1 more, a `range` 2, a `session` 3, a `list` its `max` + 1, a `draw.minicharts` grid that binds no setting 9 to 16 (its look's own settings) | `param.<kind>` declarations and each hidden `market.*` setting; OpenMarket's cloud accepts at most 128 settings per indicator, so the build refuses the declaration that crosses the line ([Picks, lanes, the cap](../settings/picks-and-lanes.md)) | a list whose `max` alone crosses 128 (a list's max counts its slots and the count, so `max` is at most 127), or many composites | `the sheet would carry 129 params after expansion (a range derives two, a list max + 1, a session three, a unit list one more); hosted lanes cap params at 128` | | Text settings | `max_bytes` 1..4096 UTF-8 bytes per setting, 256 when left out; the default within it and free of invisible and control characters | `param.text` / `param.text_area` declarations ([Setting kinds](../settings/kinds.md)) | a default longer than its cap, a pasted name carrying a bidi control | `param.text 'label' default is 12 UTF-8 bytes, over its max_bytes 4`, `param.text 'label' default carries a newline, a control or an invisible character` | ## What the chart trims when it draws These limits never refuse a run. The chart applies them when it draws, so one indicator can't bury another, hide the chart's own buttons, or draw more rows than a screen can show. | Limit | Value | What happens past it | | --- | --- | --- | | Drawing and label text | 256 characters | the text is cut and ends with an ellipsis | | Drawing order | `zorder` -100..100 | a higher value draws as 100, a lower one as -100 | | Drawings per run | 2,000, counting every bar a segment draws, every declared drawing and every live handle | the newest 2,000 are drawn and the oldest are left out; the indicator's legend row says "Drawings capped", and its card says how many of the total were drawn | | Widgets | 16 cards, feeds, meters and ladders per indicator per pane | the ones past 16 are not drawn | | Legend entries | 32 per indicator, each 64 characters | entries past 32 are not shown; longer text ends with an ellipsis | | HUD cards | inside the price pane: below the symbol row and the legend, left of the price axis | an `offset` that would move a card out is clamped; a card under 0.15 opacity lets clicks through | | Card controls | `controls: "none"` | the glyphs stay hidden at rest; hovering always shows hide and collapse | | TPO rows per period | 512 per day, week or month | the chart doubles the row height until every period fits, at most 6 times, for `"auto"` and a number alike; every run says so with a warning row in the Console and the warning on the legend chip: `tpo 'tpo': row_height 1 coarsened to 8 (512 rows per day is the chart's limit)` ([Row height](../presentation/price-canvases.md#row-height)) | | TPO rows on screen | 3 px | thinner rows merge on the price grid: a merged row's letters are the union of its rows' letters, its counts and volumes add up, and the POC and the value area are computed on the merged rows | | TPO blocks | 262,144 per TPO | the blocks past it are not drawn, and the Console says so | | Heatmap cells per indicator | the chart's budget, across all of an indicator's heatmaps, the loaded history and the live bars together (one cell per book level, grid row or profile bucket on each bar) | the oldest bars are dropped and the newest are drawn whole; the indicator's legend row says "Cells capped", and its card says how many bars are drawn | Names share one namespace across outputs, boxes, segments, renderers, and drawings; `color_by`, `width_by`, and `shape_where` cannot name their own output; each ladder half without the other is refused by name. The full validation list is at the end of [Declarations and the sheet](declarations.md#validation-in-one-list). ## Runtime ceilings Enforced on every run by the sandbox your browser runs the module in. A breach refuses the WHOLE run by name and the editor's Console says why; nothing is truncated, clamped, or silently dropped. An indicator that already drew keeps its last good render, and its legend offers a retry. | Limit | Value | What it protects | When you hit it | Refusal | | --- | ---: | --- | --- | --- | | Module memory | 4 MiB (4,194,304 bytes), fixed | the linear memory a module uses | a buffer sized far past any param's `max` | `WRUN memory 8388608 bytes exceeds limit 4194304 bytes` | | No growth after `onStart()` | 0 bytes of growth | flat per-bar memory across a long history and the forming bar's replays | memory you keep growing: a history pushed onto on every bar, a map that gains a key per bar; in a file with the four functions, any allocation per bar | "The Indicator allocated memory after init() (65536 to 131072 bytes): the sandbox forbids growth once the bars start." | | Per-bar scratch | 256 KiB, reserved once `onStart()` returns; none when the module already holds more than 2 MiB then, and none in a file with the four functions | the temporaries `onBar()` makes and drops (an array, a string, an object): the module sweeps them once about 32 KiB of them have piled up, whatever it keeps, and serves new ones from the freed room | one bar's temporaries alive at the same moment, plus the 32 KiB that pile up before a sweep, past the 256 KiB (past 2 MiB with no scratch, past the room start-up left) | the no-growth refusal above | | Output values | finite or NaN | a chart and an alert that mean something | a division by zero written as `Infinity` | `WRUN output 0 is Infinity; guard the calculation and emit NaN when the value is undefined` | | Run deadline | 20 s per run (the compile has its own 15 s) | one runaway module never holds the sandbox: the worker is stopped and replaced | unbounded loops, deep recursion | "The run did not finish within 20 s." | | Cell block | `max_cells` tuples per bar, per celled input | the one buffer of `max_cells` tuples the build allocates per celled input when the module starts; each bar's block is read into it once, and `in_<input>_view()` reads it in place | a deeper book than the cap; a profile with more price buckets than the cap | `... input 1 bar at ts 1725580800000 has 1200 cells; max_cells is 1000, so the evaluation is refused (a block is never truncated)`; a volume profile declared `missing: "empty"` is not refused: that bar reads an empty block (`in_<input>_cells()` is `0`) and the run goes on | | TPO rows per bar | 4,096 | the rows one bar expands into at a TPO's row height | a declared `row_height` far below one bar's range (`"auto"` stays under it) | `tpo 'tpo': row_height 0.05 expands one bar into 5001 price rows, above the 4096-row limit (declare a larger row_height)` | | Cell read bounds | inside exported memory | a copy that would overrun the module's memory | a pointer outside the preallocated buffer | `WRUN wrun_arg_bytes(1, 65536): 1536 bytes do not fit the module's exported memory of 65536 bytes; reserve max_cells * 8 bytes per celled input and pass a pointer inside that buffer` | | Cell phase | `onBar()` | the cell readers answer for the bar being evaluated; before the first bar (in `onStart()`, at module start) the count reads `-1` and there is no block | the host's cell import called in another phase, which the generated readers never do | `WRUN wrun_arg_len is callable during state() only (called during finalize); read cell blocks inside state() and carry what finalize() needs in module state` | | String phase | `onBar()` | slots belong to the row being committed | a string sent outside `onBar()` | `WRUN wrun_output_str is callable during finalize() only (called during state); ...` | | String slot bytes | `max_bytes` per slot (at most 4096) | the buffer reserved per slot | a line longer than the slot | `WRUN string slot 0 write of 40 bytes exceeds the slot's max_bytes 32; strings are never truncated; ...` | | String bytes per row | 65,536 (64 KiB) | one bar's text across all slots | many slots near their cap on one bar | `WRUN string writes for one row total 70000 bytes, over the per-row limit 65536; emit less text per bar` | | Strings and frames per run | 2,097,152 (2 MiB), together; a live session counts as one run | one run's text and frame snapshots across all bars | long readouts on every bar of a long history | `WRUN string and frame writes for this run total 2100000 bytes, over the per-run limit 2097152; emit less text or fewer rows` | | UTF-8 | valid sequences only | a slot never carries a replacement character silently | raw bytes sent through the host import | `WRUN string slot 0 write of 5 bytes is not valid UTF-8; wrun_output_str carries UTF-8 text only (encode before writing)` | | Expanded render result | 8 MiB (8,388,608 bytes) | the selection the chart receives after the run: 16 bytes per selected entry, 8 per carried number, the UTF-8 bytes of every carried string (table cells charge 8 more per cell; handles and a strategy's result count too) | many renderers over a long history with long strings; hundreds of live polylines | `WRUN render result exceeds 8388608 bytes expanded (wrun_render_result_too_large): fewer rows, shorter strings, or fewer renderers/drawings` | | Live handles per kind | 1000 | the handles of one kind alive at once, counted on every creation | a zone tracker that never deletes | `wrun_draw_kind_limit`: `1000 live box handles already exist; the cap is 1000 per kind ...` | | Live handles in total | 1500 | every kind together | the same shape across kinds | `wrun_draw_total_limit`: `1500 live handles already exist; the cap is 1500 in total ...` | | Polyline handle points | 1..100,000 per call | the points one `setPoints` sends; the buffer must fit the module's memory | a path that never trims its oldest points | `wrun_draw_polyline_too_large`, `wrun_draw_polyline_empty`, `wrun_draw_polyline_out_of_bounds` | | Polyline points per run | 524,288 across the live polylines | the points every live polyline holds, checked on each `setPoints`: a re-sent path gives its old points back first and a deleted one frees its own | hundreds of long paths kept alive at once | `wrun_draw_polyline_budget` | | Draw calls per bar | 4096 | every handle call on one bar | re-sending every live handle on every bar | `wrun_draw_calls_per_row`: `more than 4096 draw calls on one row ...` | | Draw phase | `onBar()` | handle ops belong to the row being committed | a handle operation outside `onBar()` | `wrun_draw_phase` | | Handle identity | ids `>= 0`, one space across kinds, kind declared in `handles`, coordinates finite | the ledger the chart mirrors, kind by kind | a negative id; a label on a box's id; a kind the file does not declare; a `NaN` corner; a setter on an id nobody holds | `wrun_draw_id_negative`, `wrun_draw_kind_mismatch`, `wrun_draw_kind_undeclared`, `wrun_draw_non_finite`, `wrun_draw_handle_missing` | | Handle style values | the prop's range, integer where required, legal on the kind | the same setter table the engine enforces | `size` on a line; `width` of 30; `style` of `7` | `wrun_draw_prop_unsupported`, `wrun_draw_style_out_of_range`, `wrun_draw_prop_unknown` | | Handle label text | a declared slot, written on the bar of the draw call | the text a label carries is the slot's bytes at call time | `text(...)` before the slot's sender ran that bar | `wrun_draw_label_slot_absent`, `wrun_draw_label_slot_undeclared` | The module contract is checked by Run before any of this: the four engine functions the build adds around `onBar()` with exact signatures (a file that exports them itself is checked the same way, [The four-function form](../core-concepts/execution-model.md#the-four-function-form)), exported `memory` when the cell, string, or polyline channel is imported, every present draw import with its exact signature, and an import set limited to the contract's allowlist. Before a module runs, the chart checks its bytes against the sheet's `wasm_sha256` and refuses a mismatch. Those messages are in [Common errors](../faq/common-errors.md). ## Data bounds | Limit | Value | Where | | --- | ---: | --- | | History | the bars the chart has loaded | every source is fetched over the chart's loaded window, and a pan back runs again over the extended window; warm-up is the file's decision: an output `onBar()` leaves unwritten is NaN and draws nothing | | Live updates | the forming bar, about once a second at most | ticks in between are coalesced and the last one is never dropped; only the forming bar is replayed; a live gap wider than 250 bars rebuilds the run | | Source deadline | 45 s per source | a source that does not answer in time fails the run with its name | | Empty source | refused | a required source that answers empty fails the run: "<Label> data is unavailable for '<title>' (the <type> source lane answered empty or was declined), so the indicator cannot compute." | | Coarse pins | as of the coarser candle's close | a pinned `interval` contributes to a row only once its candle has closed; that market's candles are fetched from two leg spans before the chart's first bar | | Pinned intervals | coarser than the chart's and a whole multiple of it (`WEEK` counts 7 days) | any other interval pin is refused by name before any fetch | | Pinned venues | crypto, `POLYGON`, `FX_OTC` | stocks and ETFs on `POLYGON`, forex, gold and silver on `FX_OTC` are served like a crypto pin; an index pin (`POLYGON_INDICES`) reads its `missing` fill with a warning row; a CME Group pin is refused by name ([Multi-source](../core-concepts/multi-source.md#stocks-forex-and-gold)) | | Multi-day pins on session venues | `3d` refused | a `3d` candle on a stock, forex or gold market groups trading days, so the pin is refused before any fetch (`wrun_pin_session_interval_unserved`); pin `1d` or `1w` | | Intrabar | finer than the chart's interval and dividing it evenly, `1m` at the finest | so the chart must be 2 minutes or coarser; `max_cells` at least the finer bars in one chart bar; closed finer bars only | | Book depth | at most 500 levels each side | the chart's own order book at its own grouping, whatever `block_size` and `max_depth` say, so `max_cells: 1000` covers any bar | | Options chain | the live row only | the chain arrives on the last row; size `max_cells` for the chain (a BTC chain is about 1,550 contracts) | | Cell memory, per celled input | `max_cells` x tuple width x 8 bytes | 4 f64 per `volume_profile` tuple, 3 per `book` tuple, 6 per `intrabar` bar, 10 per `options_chain` contract, 12 per `option_strikes` row, all inside the 4 MiB of module memory; the build allocates this buffer once per celled input when the module starts, reads each bar's block into it once, and `in_<input>_view()` reads it in place (a copy through `in_<input>_read(ptr)` holds the block twice) | | Alerts | 600 bars of the chart's interval, at most | the window is the larger of the file's `warmup()` and its largest setting maximum (up to 500); an indicator that reads a coarser pin gets all 600 unless it also reads `book` or `volume_profile` cells, and those bars hold 600 / (leg / chart) candles of the pin (a 4h pin: 150 on 1h, 37 on 15m, 12 on 5m), so a longer higher-timeframe average arms but stays empty; another market's candles on a secondary `ohlcv` input and a coarser `1m` to `1w` pin that is a whole multiple of the chart's interval are served; a pin on the first input, a finer pin, a custom timeframe and a source alerts cannot evaluate are refused when you save the alert ([Alerts](../functions/alerts.md)) | | Alert checks | once a second for each indicator, at most | every price tick of the chart's market wakes a check of the forming bar, and the ticks inside the second fold into it (its high and low keep every extreme, its close is the latest), so a wick is seen on the next check and a value that crosses a level and comes back inside the second is not; every bar's close is checked; an indicator whose runs keep failing on the server has its alerts paused (`paused_runtime`) and is tried again by itself ([When an alert checks and fires](../functions/alerts.md#when-an-alert-checks-and-fires)) | | Strategy order ids | 64 distinct per run (`closeAll` counts as one) | the 65th distinct id refuses the run (`wrun_strategy_id_limit`); an id is a slot, re-issuing one replaces its pending order | | Strategy id text | 64 bytes of UTF-8 per id, `from` name or OCA name | longer text refuses by name (`wrun_strategy_id_too_long`), never truncated; invalid UTF-8 refuses (`wrun_strategy_id_invalid_utf8`) | | Strategy calls per bar | 4096 order calls and getter reads per bar | over it refuses (`wrun_strategy_calls_per_row`); an infinite price refuses (`wrun_strategy_non_finite`), NaN is absent | | Closed trades per run | 10000 | the 10001st closed trade refuses on the bar it closes (`wrun_strategy_trade_limit`); every engine rejection (pyramiding, legs, sizing, margin, the forming bar) is counted in `rejectedOrders`, never a refusal | | Strategy result bytes | inside the 8 MiB expanded render result | the trades, orders and equity together with the drawings (`wrun_render_result_too_large`) | | Strategy feed | the price input reads `ohlcv` on the chart's own market, no symbol or exchange pin | refused by name (`wrun_strategy_feed_not_ohlcv`); `slippageModel: "bookEstimate"` refused (`wrun_strategy_slippage_model_unsupported`); `strategy.position` and `strategy.equity` are reserved output names (`wrun_strategy_reserved_output`) | ## Publish bounds | Limit | Value | | --- | ---: | | Open source code | 256 KB ("The source is {size} KB; the limit is {limit} KB.") | | What changed | one line of up to 280 characters, from the second version | | Name | lowercase letters, digits, and dashes after your `@yourname/` scope; fixed after the first publish | | Inputs | 32 per indicator | | Fills | 32 per indicator | | Colours on one output | 32 | | Names and words | 256 characters: the indicator's name, a setting's, an input's, a box's, a segment's, a string slot's, a frame's, a level's and a panel's name, a market pin, an output's unit and description | | Colour words | 64 characters | Publishing refuses a sheet past one of these in the registry's words (`inputs cap is 32`), and so does building the package, so a package never builds only to be refused at publish. A draft from Run still runs past them. The module runs sandboxed: no filesystem, no network, no order capability. Each wrun indicator on a chart, a draft from Run included, counts against the chart's indicator limit. [Publishing](../functions/publishing.md) has the dialog. ## Paint verdict After a version is published, OpenMarket measures how much its price canvases draw and records the result on the version as its paint verdict. Every `plot.tpo`, `plot.footprint`, `plot.profile` and grid `plot.heatmap` the indicator declares is built the way the chart builds it, on one reference chart: BTCUSDC on Binance Futures, 15-minute bars, 1,500 bars (about 16 days). For each canvas the verdict records: | Canvas | Rows | Cells | | --- | --- | --- | | `plot.tpo` | the most price rows one period draws | the most letter blocks one period draws | | `plot.footprint` | the most price rows one bar's column draws | the same as its rows | | `plot.profile` | the most price rows one session spans | the same as its rows | | `plot.heatmap` over an `out.grid` | the grid's rows | rows x 400 bars, one screen of the reference chart | It also records whether the chart had to coarsen a TPO's rows to keep a period at 512 rows (the coarsening the Console reports with a warning row). A heatmap over book or volume profile cells, a profile anchored in time and a strike matrix are not counted: the reference chart's candles cannot build them. A version is **heavy** when any of its canvases is: a TPO, footprint or profile that draws more than 512 rows or more than 8,192 cells, or had its rows coarsened; a grid heatmap that draws more than 25,600 cells on one screen, so a 64-row grid fits and a 128-row grid is heavy. Nothing about a heavy indicator is refused, and its values are the same. The Indicators picker shows a **Heavy** chip beside its name, whose hover says what was measured, and the chart starts it lean: coarser rows and fewer letters and labels, with its legend saying so. To clear the verdict, publish a version that draws less; each version is measured on its own: - leave `row_height` at `"auto"`, or declare one large enough that a period holds at most 512 rows; at its auto rows the TPO letters template draws 88 rows a day on the reference chart ([Row height](../presentation/price-canvases.md#row-height)); - give a footprint or a profile a coarser `row_height` when one bar or one session spans more than 512 rows; - declare an `out.grid` of at most 64 rows. The verdict counts rows and cells, not paint time: it is taken once per version, without drawing anything. How long a canvas takes to draw depends on the device, and the chart measures that as it runs, leaning or pausing an indicator that is slow there. ## Other bounds Bounds that are not a number in the tables above. | Shape | In wrun | | --- | --- | | Sources per indicator | No per-indicator source budget. On the chart, a wrun indicator counts against your plan's per-chart indicator limit once per distinct source it reads ([Data sources](../core-concepts/data-sources.md)). Each source is fetched once per run over the chart's loaded bars, however many inputs read it; a pinned market or interval on `ohlcv` adds its own fetch, a `funding` or `oi` interval pin adds none. | | Output objects per run | No object count. Every output is one number per bar, in at most 256 slots; decorations are declared once. Every bar emits a row, with NaN in each output `onBar()` did not write, so the leading NaN rows of a warm-up count toward the per-run budgets above. What reaches the chart is capped by the 8 MiB expanded render result, and past 2,000 drawings in a run the chart draws the newest 2,000. | | Table cells | 32 x 32 = 1,024 cells per table renderer, each a string slot; 64 slots per indicator. A `panel.table` over a frame takes 128 rows by 12 columns instead, and a `plot.matrix` 128 prices by 12 columns within 1536 cells. | | Collection size | No element cap. Collections live inside the 4 MiB module memory: one you keep across bars is allocated before the first bar, at module start or in `onStart()`; one that `onBar()` makes and drops is freed again. | | Nesting and recursion depth | The compiler's own rules apply; the module's stack lives inside its memory, and the 20-second run deadline stops runaway recursion. | | Backtest bars and runs per day | No grant to spend: the chart's Strategy Tester runs a wrun strategy in your browser over the bars the chart has loaded and recomputes as you pan ("This strategy runs locally over the chart window and recomputes as you pan."), [Reading the Strategy Tester](../strategies/reading-the-tester.md). | | Strategy declaration bounds (`leverage`, fees, funding) | Checked by Run with the engine's rules: `initialCapital` and `leverage` more than 0, `pyramiding` an integer of at least 1, `maintenanceMarginPercent` at least 0 and under 100, the fee and slippage rates at least 0, enum fields the engine's literals. A setting linked to a param is checked once before the first bar and falls back to the default when out of range, reported. [Writing strategies](../strategies/writing-strategies.md) has the table. | ## Notes that save debugging time - **`max_cells` is a contract, not a hint.** The build sizes one buffer per celled input from it (`in_<input>_capacity` f64s, tuples x width) when the module starts, and `in_<input>_view()` reads it in place; size a `book` input for the chart's depth: at most 500 levels a side, so 1000 tuples. - **Strings never truncate.** Pick `max_bytes` for the longest line the slot will ever carry; the generated builder counts the bytes a line REQUIRES, so an oversize line refuses by name instead of clipping. - **Most caps are counts of declarations.** You meet them when you press **Run**, in the editor's Console, anchored on the declaration. A repeating shape is one declaration gated per bar with `when`, never one declaration per occurrence. - **Segments count as drawings.** A segment drawn on every bar of a long window is the shape that reaches 2,000 drawings per run; gate it with `when` or narrow its span. - **The render cap counts expanded bytes.** Sixty-four text renderers over a long history with long strings is the shape that reaches 8 MiB; leave slots unwritten on quiet bars so those rows select nothing. - **Delete what you no longer draw.** A handle stays alive until `delete()`; the per-kind cap is met by the tracker that creates a zone on every pivot and never frees one. Keep a bounded pool of ids and delete the oldest before reusing its id, and re-send only the handles that changed on a bar (the calls-per-bar cap counts every setter). - **Keep what lasts bounded.** Buffers that live across bars are sized at module start or in `onStart()` from a param's `max`. A temporary per bar is freed in a file with `onBar()`, but a kept array that grows on every bar both slows a long history and trips the no-growth rule, and a file with the four functions trips it with any per-bar allocation. ## Example: the caps as contracts A book-imbalance indicator that sizes everything from what the chart delivers: the chart's order book carries at most 500 levels a side, so `max_cells` is 1000; the cell buffer is the build's own, sized from that cap and read in place; and the readout slot is sized for its longest line: ```typescript input("close", ohlcv.close); // The chart's order book carries at most 500 levels a side, so a bar never holds more than 1000 tuples: // max_cells is a contract, and a bigger block would refuse the whole run. // block_size is required by the declaration; the chart keeps its own price grouping. input("book", book.cells, { max_cells: 1000, block_size: 10 }); output("imbalance", line, lower, { unit: "ratio" }); // The longest line is "500 bids / 500 asks" (19 bytes); 32 leaves room and stays under the 4096 cap. string("depth", { max_bytes: 32 }); render.text("depth_mark", { y: "imbalance", text: "depth", size: 10 }); function onBar(): void { const n = in_book_cells(); if (n <= 0) return; // The build's own buffer, sized once at module start: max_cells x 3 cells per [price, size, side] tuple. const cells = in_book_view(); let bidSize = 0.0; let askSize = 0.0; let bids: i32 = 0; let asks: i32 = 0; for (let i = 0; i + 2 < n; i += 3) { if (cells[i + 2] > 0.0) { bidSize += cells[i + 1]; bids += 1; } else { askSize += cells[i + 1]; asks += 1; } } const total = bidSize + askSize; const imbalance = total > 0.0 ? (bidSize - askSize) / total : NaN; if (isNaN(imbalance)) return; out_imbalance(imbalance); sb_clear(); sb_int(bids); sb_text(" bids / "); sb_int(asks); sb_text(" asks"); str_depth_sb(); } ``` The scan branches on each tuple's `side`, never on its position: the chart lists the bids best first, then the asks from the farthest to the best. <!-- source: https://openmarket.xyz/wrun/reference/limitations --> # Limitations What a wrun indicator does not do in the chart, and where to find the numbers. An indicator is a sandboxed, declared computation over market data; a few things are deliberately out of scope, and knowing them up front saves you from designing around a feature that is not there. ## Not supported today <!-- wrun:cards --> **Numbers only in outputs.** Every output is a 64-bit float, and `NaN` is the one "nothing here" value. Text reaches the chart only through string slots and renderers (the second runtime contract, which **Run** derives for you when you declare one). Decisions are numbers too: `1` or `0` in a data-only output, turned into a look by a declaration (`shape_where`, `color_by`, a box's `when`). **Settings are typed, text included.** A setting is `param.<kind>(...)`: a whole number, a number, a toggle, a menu, a color, a time or a price picked on the chart, a range, a multi-select, a list, a price field, a timeframe, a market, a session or words, each drawn by the overlay's settings dialog as its own control and laid out in pages and sections ([The settings dialog](../settings/overview.md)). A `param.text` or `param.text_area` takes plain words within its `max_bytes` ([Setting kinds](../settings/kinds.md#text-settings)). A sheet holds at most 128 settings after a range (2), a session (3), a list (`max` + 1) and a unit menu (1 more) expand. A source, timeframe or symbol pick is applied by the chart when the Indicator runs in the browser; an Indicator that runs on OpenMarket's servers keeps the declared default for those three, and an alert refuses to arm while one is off its default. Changing a setting runs the module again over the loaded bars without recompiling. **Pins are served with restrictions.** An unpinned input follows the chart's own market and interval. The chart checks every pin before it fetches anything and refuses the ones it cannot serve by name: - a market pin (`symbol` and `exchange` together) only on a secondary `ohlcv` or `trades` input, or on an `intrabar` input or a stream (`candles`, `oi_candles`, `volume_profile_candles`); every other source and every other celled input follows the chart's own market, except `odds`, which names its Polymarket market by condition id; - an interval pin only coarser than the chart and a whole multiple of it, on a secondary `ohlcv` input, an `odds` input, or `funding` and `oi`; - no market or interval pin on the first input: it follows the chart (an `odds` input may come first and still names its market); - a `forming` view up to `WEEK`, and never a view without an interval pin. Pins on stocks and ETFs (`POLYGON`), forex, gold and silver (`FX_OTC`) are served like crypto pins, on any chart. An index pin reads `NaN` with a warning row, and a CME Group pin or a `3d` pin on a stock, forex or gold market is refused by name. [Multi-timeframe](../core-concepts/multi-timeframe.md) and [Multi-source](../core-concepts/multi-source.md) have the rules in full. **No market picker.** The chart has no picker for a market chosen per use: an `odds` input declared with `binding` is refused ("the chart has no market picker yet; pin the market's condition id (0x…) in the input's symbol"). Pin the Polymarket market by its condition id instead. **Tape history is large prints only.** `tape` history comes from the large-print lane: prints of $10,000 or more on markets quoted in USD or a dollar stablecoin, and the contracts floor on CME Group futures (10 ES, 5 NQ, 20 CL, 10 GC). A `min_value` or `min_size` floor below the lane's reads history at the lane's floor, a market quoted outside dollars has no large-print history and no dollar value for a `min_value` floor, `history` reaches back 30 days at most, and a one-second chart or a calendar interval refuses the input ([Data sources](../core-concepts/data-sources.md#large-prints-tape)). Side-split volume per bar is the `trades` source with `side: "BUY"` or `"SELL"`, and the split by trade size is `trade_volume_by_size`. **No other indicator's output on the chart.** The editor has no declaration for another indicator's output, and the chart serves none; a package whose `wrun/metadata.json` declares one as a `metric` input reads it on your OpenMarket runner only. A published feed is a source of its own: `input(name, series.value, { ref: "@scope/name" })` reads it ([Feeds as inputs](../core-concepts/feeds-as-inputs.md)). **Some feeds are the chart's alone.** The option summaries beyond implied volatility and skew (`volatility_index`, `options_oi`, `options_volume`), `long_short_ratio`, the ETF feeds, `ethena_positions`, `bitfinex_funding`, `treasury_balance` and `economic` are served when the indicator runs in the browser, like `etf_flow`. An alert on an indicator that reads one is refused. **The options chain is the live row's only.** `options_chain` fills the newest row with the current chain (a 30-second snapshot, polled live) and leaves every history row an empty block, so a gamma map over past chains has no form on it; the `option_strikes` source carries every bar's own strike snapshot instead, on crypto, CME and US stock charts ([Option strikes](../core-concepts/data-sources.md#option-strikes)). `venue` picks the chain: `auto` (the chart's own options venue, the CME chain of a CME future or the OPRA chain of a US stock or ETF, each at your own tier, else the coin's Deribit chain), or one venue's (`deribit`, `cme`, `binance`, `okx`, `bybit`, `bullish`, `derive`), refused by name on a chart that venue cannot serve; no venue word reads OPRA. **The order book is the chart's.** `book` cells come from the book the chart loads for its own market, up to 500 price levels a side, so a full book is up to 1,000 tuples; size `max_cells` for that. The declaration requires `block_size`, but the chart does not read it or `max_depth`, so neither changes what it fetches ([Order flow](../functions/order-flow-kit.md)). **Drawings have fixed budgets.** Boxes and segments are declared once and evaluated on every bar, 16 of each. Drawing handles (line, box, label, and polyline) are objects the module creates, moves, and deletes across bars, capped at 1,000 live handles per kind, 1,500 live handles in all, 100,000 points per polyline and 524,288 points across the live polylines, and 4,096 draw calls per row; there is no table handle (a table is `render.table`). One run draws at most 2,000 drawings on the chart; past that the chart draws the newest 2,000, says "Drawings capped" on the indicator's legend row, and its card says how many were drawn ([Drawing objects](../presentation/drawing-objects.md)). **No history array.** `onBar()` sees one bar, which is also why an indicator cannot look ahead by accident ([Execution model](../core-concepts/execution-model.md)). There is no `[]` operator on a series, and `History` from `./sdk/stats` keeps the window for you: `push()` the value once per bar and `ago(n)` reads it `n` bars back ([Stats, history and lists](../functions/stats-history-lists.md)). **No persistence across runs.** Module state lives for one run over the loaded bars. Nothing survives a reload, a new **Run**, or a pan that loads older bars (the chart runs the module again over the wider window); anything you need is recomputed from the loaded history. A draft's overlay lasts for the session and is not saved with the layout: **Run** it from the editor again to bring it back. **No cross-indicator communication.** Each overlay runs its own module. Two wrun indicators on the same chart share no state, and one cannot read another's outputs; combine the logic into one file. **No orders from the file.** The module has no filesystem, no network, no clock, and no order capability. A strategy's orders fill only in the Strategy Tester's simulated broker, against the chart's own candles; nothing reaches an exchange ([Strategies overview](../strategies/overview.md)). **One file per indicator.** Helpers, classes, and constants live in the one editor tab beside `onBar()`. The kit and the accessors generated from your declarations are the only names there are, so there are no library imports, and a `//@file=` line is refused ([Publishing](../functions/publishing.md)): ```text One file per indicator for now. Move the code from <file> into this tab and remove the //@file line. ``` **History is what the chart loaded.** The module sees exactly the candles the chart has loaded, and every source is fetched over that window; there is no separate warm-up fetch, so a long lookback needs the chart to load more bars. The exceptions reach back by their own `bars`: an interval pin, and the streams (`candles`, `oi_candles`, `volume_profile_candles`), whose first bar carries as many closed candles as `bars` asks ([Multi-timeframe](../core-concepts/multi-timeframe.md#history-the-candles-stream)). An indicator runs at any chart interval from 1s to 1Y, but on a 1s chart the sources not served at 1s are declined, prediction-market odds need a one-minute chart or coarser, and `intrabar` cells come from bars no finer than 1m, so they need a chart of 2m or coarser. **Alerts read pins within 600 bars.** An alert needs a published version and runs in OpenMarket's cloud on the chart's market and interval with the overlay's settings, over at most 600 bars of that interval. It serves another market's candles on a secondary `ohlcv` input and a coarser pin that is a whole multiple of the chart's interval, read once its candle has closed; 600 chart bars hold 600 / (leg / chart) candles of a pin, so a higher-timeframe average longer than that arms but stays empty, and belongs on a coarser chart. It refuses a pin on the first input, a finer pin, a custom timeframe, a source alerts cannot evaluate yet (the feeds above and the `oi_candles` and `volume_profile_candles` streams among them), and a source, timeframe or symbol setting off its default. An indicator that builds a higher timeframe from the chart's own bars must declare `warmup()`, or its alert can arm and stay empty. A data-only output is not offered as a condition target ([Alerts](../functions/alerts.md)). **CME data stays on the chart.** On a CME market an indicator runs in your browser once you are signed in and have accepted the CME market data terms. It reads CME data at your own tier: real time on a real-time CME account, else delayed 10 minutes. Its results show on that chart only: the legend, the hover values and the editor console. A console copy leaves out the values it printed, an agent's chart read withholds them, a CSV export refuses them, and a chart that carries CME data cannot be shared as a clip. A Protected indicator does not run there (**Cloud** is not offered), a strategy does not backtest there, and only price alerts are available. **The CME option chain is read on a CME futures chart only.** On a CME futures chart (ES1!, NQ1!, CL1!, GC1!, 6E1!, ...) an indicator that runs in your browser reads the chart's CME option chain as it reads the chart's candles, on the same terms. That holds for your drafts, the indicators you publish to run in the browser and the ones you add from the community. It reads `options_chain` with `venue: "auto"` or `"cme"`, `options_flow` and the chain sources below (`option_strikes`, `option_surface`, `option_daily`, `option_stats_10m`, `option_prints`, `option_contract_state`, `option_contract_flow`, ...). `underlying` reads another CME root's chain there, such as the ES chain on an NQ chart. An indicator on any other chart (a stock, a coin, an index) reads no CME chain. A CME root named by `underlying` there is refused by name: "Indicators you write or add from the community read a CME option chain on a CME futures chart only." **US options data is served at your own tier.** On a US stock or ETF chart every indicator reads the stock's listed options (OPRA): `options_chain` with `venue: "auto"` and the other chain sources when the indicator runs in the browser, and `options_chain` on OpenMarket's servers too (Run on Cloud, a Protected package), each at the viewer's own tier: real time on a real-time US options account, else delayed 15 minutes, and the legend says so ("OPRA data delayed 15 minutes"). The delayed chain is the newest snapshot 15 minutes behind the live bar, and a live-bar read repeats it until the next one lands. On a US option contract chart a draft or a community indicator runs in the browser at your own tier; a Cloud (Protected) indicator does not run there yet. US options data stays on the chart: an agent's chart read withholds it and a CSV export refuses it. Alerts on a US option contract are coming for real-time US options accounts, on the contract's own candles; until the alert server serves them, an alert on US options is refused. **The chain sources read one chain and one book.** `option_strikes`, `option_contract_state`, `option_surface`, `option_daily`, `option_stats_10m`, `option_prints`, `option_contract_flow` and `option_prints_v2` are served when the indicator runs in the browser, on crypto, CME and US stock charts: each input reads the chain its `venue` word picks and one book of it (`book`), the inputs of one indicator read one chain across all eight, and a CME or US stock chart's chain follows the chain's rules above. An alert and a Protected indicator on OpenMarket's servers refuse each by name (`wrun_option_surface_unsupported`, `wrun_option_daily_unsupported`, `wrun_option_prints_v2_unsupported`, ...). The surface keeps five-minute samples for 30 days and a daily sample after that ([Data sources](../core-concepts/data-sources.md#option-surface)). Sizes are in the chain's own size (the coin on a crypto chain, contracts on US listed options and CME), and the statistics' premium is served on US listed options only until crypto and CME prints are. **The flow and print sources.** `options_flow`, `option_prints`, `option_prints_v2` and `option_contract_flow` read the options of the chart's underlying on crypto, CME and US stock charts (and an option contract chart), the CME and US listed options under their rules above; `options_flow` reads its scopes per market, and a scope the market does not serve reads the input's fill. A crypto or CME print carries the taker's side and no quote, so its mid, none and outside-the-quote values read 0. An alert and a Protected indicator on OpenMarket's servers refuse each by name. The `market.earnings_*` facts are declared in the kit ahead of the chart lane that will fill them. A cell is never `NaN`: a value the data does not carry reads `0` with its `present` bit clear, and bit 14 marks a bar cut short by `max_cells` or older than the kept history. `option_prints` history reaches 3 days for every print and 90 days for the large ones, and multi-report earnings history is not served ([Data sources](../core-concepts/data-sources.md#us-listed-options-opra)). **Where it runs is fixed at the first publish.** A name first published as Compiled or Open source runs in each reader's browser, and one first published as Protected runs on OpenMarket's servers; a later version cannot switch sides. The Publish dialog has no price, and paid indicators cannot be added from the chart yet ([Publishing](../functions/publishing.md)). ## What AssemblyScript and the sandbox leave out The file is AssemblyScript: TypeScript syntax over fixed-width numbers, compiled in your browser. The editor's compile hints link here when you reach for something it does not have: <!-- wrun:cards --> | You wrote | Write instead | | --- | --- | | a closure over a local variable | keep the value at module scope, or pass it as a parameter | | a union type | one concrete type (`f64`, `i32`, `string`), or a nullable class | | `any` | the concrete type: `f64`, `i32`, `string`, or a class | | a bare object literal | a class with those fields, built with `new` | | the spread operator | a counting loop, or `Array.slice()` | | destructuring | read the fields or indexes one at a time (`const a = pair[0]`) | | optional chaining (`?.`) or nullish coalescing (`??`) | test for `null` with `if` or a ternary | | `for...of` | a counting `for` loop over the indexes | | the `in` operator | `Map.has()`, or read the field directly | | a regular expression | the string methods: `includes`, `startsWith`, `indexOf`, `split` | | `try` / `catch` | test the condition before the call; a throw ends the run | | `async` / `await` | nothing: an indicator runs synchronously, one bar at a time | | `console.log(...)` | the debug log: `string("debug", { max_bytes: 256 })` and `str_debug(text)` in `onBar()` ([Debugging](../faq/debugging.md)) | | `Date.now()` or `new Date()` | `bar.time()`, the bar's open time in epoch seconds | | `Math.random()` | a variation derived from the bar data: a run is reproducible bar for bar | | `performance.now()` | nothing: the sandbox has no clock | ## Named refusals Each gap above is refused by name, never worked around silently, and the message names the way out: [Common errors](../faq/common-errors.md) lists every refusal with its cause and fix. ## Sandbox limits Every wrun indicator runs under fixed ceilings (declaration caps, text and frame budgets, memory, and a deadline per run) so one module cannot exhaust the chart; every number is in the [Limits reference](limits.md). The caps quoted on this page come from one table in the kit, which says where each one is enforced. The table itself enforces nothing: the sandbox, the chart and OpenMarket's servers each check their own. ## Build and runtime errors For the messages you meet while writing an indicator (a coordinate passed as a string instead of a handle, a param option that does not exist, a missing cast, a sheet field out of range, an `onBar()` written with the wrong signature, a run that drew nothing), see [Common errors](../faq/common-errors.md). Each one is listed by its exact text with a cause and a fix. <!-- source: https://openmarket.xyz/wrun/reference/symbol-format --> # Exchange and symbol format The exchange ids and the venue-native symbol spellings a wrun indicator uses where the file names a market: a pinned input's `symbol` and `exchange`. The vocabulary is the chart's own: an exchange id in uppercase, and the symbol as that venue spells it. ## Where the vocabulary is used A market is the pair `exchange` + `symbol`, and in the file the two travel together: - **Pinned inputs.** `input("btc", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES" })`. The chart passes both as written, in its own ids, and serves a market pin on a secondary `ohlcv` input: it fetches that market's candles at the chart's interval (or at a coarser pinned `interval`) and joins them to the chart's bars by timestamp. A lone `symbol` or a lone `exchange` is refused at the sheet check, because half a pin names a market that does not exist. - **Polymarket odds.** An `odds` input names its market by condition id in `symbol` alone; the exchange is implied, and writing one is refused. - **Everything else follows the chart.** An unpinned input reads the chart's own market, and the module never sees a market name: the chart supplies it. Trades, funding, open interest, liquidations, order books, and volume profiles always read the chart's own market. ## Example: one market on three venues Three pinned closes of the same asset, spelled the way each venue spells it, and two spreads between them. The first input stays unpinned, so the indicator follows whatever market the chart shows: ```typescript input("close", ohlcv.close); // Every pin names the venue's own spelling of the market, and symbol and exchange always pin together. input("binance_spot", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE", description: "Binance spot, joined form" }); input("binance_perp", ohlcv.close, { symbol: "BTCUSDT", exchange: "BINANCE_FUTURES", description: "Binance perpetual, joined form" }); input("coinbase", ohlcv.close, { symbol: "BTC-USD", exchange: "COINBASE", description: "Coinbase spot, hyphen form" }); output("basis_pct", line, lower, { unit: "%", description: "Binance perp premium over Binance spot" }); output("coinbase_gap_pct", line, lower, { unit: "%", description: "Coinbase spot over Binance spot" }); function onBar(): void { const spot = in_binance_spot(); if (isNaN(spot) || spot <= 0.0) return; out_basis_pct(((in_binance_perp() - spot) / spot) * 100.0); out_coinbase_gap_pct(((in_coinbase() - spot) / spot) * 100.0); } ``` The unpinned `close` is never read by the code; it is the grid every pinned input aligns to. To try it, press **New indicator** in the editor's Explorer, keep the `//@lang=wrun-ts` line, replace the starter under it with this file, and press **Run**: the two spreads draw in their own pane below the chart, at the chart's interval, on a crypto chart (a stock or forex chart's session bars open at other times: [Stocks, forex and gold](../core-concepts/multi-source.md#stocks-forex-and-gold)). An alert evaluates the pinned markets too ([Alerts](../functions/alerts.md)). ## Exchange reference table Exchange ids are the chart's own spelling, always uppercase. Symbols are venue-native: each venue's own separator, or none. The format column shows the venue's convention with an example market. | Exchange | Category | Symbol format | Example | | --- | --- | --- | --- | | `BINANCE` | SPOT | `BTCUSDT` | Bitcoin to Tether (spot) | | `BINANCE_FUTURES` | PERPETUAL | `BTCUSDT` | BTC/USDT perpetual | | `BINANCE_DELIVERY` | dated futures | venue-native | BTC dated contracts | | `BITFINEX` | SPOT | `BTCUST` or `BTC:USD` | Bitcoin to USD (spot) | | `BITFINEX_DERIVATIVES` | PERPETUAL | `BTCF0:USTF0` | BTC perpetual | | `BITGET` | PERPETUAL | `BTCUSDT` | BTC/USDT perpetual | | `BITMEX` | PERPETUAL | `XBTUSD` | Bitcoin to USD | | `BITSTAMP` | SPOT | `BTCUSD` | Bitcoin to USD (spot) | | `BYBIT` | PERPETUAL | `BTCUSDT` | BTC/USDT perpetual | | `BYBIT_SPOT` | SPOT | `BTCUSDT` | Bitcoin to USDT (spot) | | `COINBASE` | SPOT | `BTC-USD` | Bitcoin to USD (spot) | | `DERIBIT` | PERPETUAL | `BTC-PERPETUAL`, `BTC_USDC-PERPETUAL` | BTC/USD and BTC/USDC perpetuals | | `GATE_IO` | SPOT | `BTC_USDC` | Bitcoin to USDC (spot) | | `GATE_IO_FUTURES` | PERPETUAL | `BTC_USDT` | BTC/USDT perpetual | | `HUOBI` | SPOT | venue-native | spot markets | | `HUOBI_DM_SWAP`, `HUOBI_DM_LINEAR_SWAP` | PERPETUAL | venue-native | coin- and USDT-margined swaps | | `HYPERLIQUID` | SPOT | `HYPE-USDC` | HYPE to USDC (spot) | | `HYPERLIQUID_FUTURES` | PERPETUAL | `BTC` | BTC perpetual (the bare base asset) | | `HYPERLIQUID_HIP3` | PERPETUAL | venue-native | HIP-3 perpetuals | | `OKEX` | SPOT | `BTC-USDT` | Bitcoin to USDT (spot) | | `OKEX_FUTURES` | dated futures | `BTC-USDT-251226` | BTC future (Dec 26, 2025) | | `OKEX_SWAP` | PERPETUAL | `BTC-USDT-SWAP` | BTC/USDT perpetual swap | | `UPBIT` | SPOT | `KRW-USDT` | Korean won to USDT | | `CME` | dated futures | venue-native | listed futures; an indicator reads CME data once the viewer has accepted the CME market data terms, and no script may pin a CME Group market (`CME`, `CBOT`, `NYMEX`, `COMEX`, `GLOBEX`) as another market's input: the pin is refused by name | | `POLYGON` | US stocks and ETFs | `AAPL/USD`, `SPY/USD` | a stock or ETF pinned as a reference market | | `FX_OTC` | forex, gold and silver | `EUR/USD`, `XAU/USD`, `XAG/USD` | quote candles, `volume` 0; served on the chart and in alerts | | `LBMA`, `LME`, `ICE`, `PLATTS` | retired | none | no longer served: pin gold and silver on `FX_OTC` (`XAU/USD`, `XAG/USD`) | | `POLYMARKET` | prediction markets | the 66-character condition id | never written in a pin: an `odds` input's `symbol` is the condition id, and the exchange is implied | A venue with both a spot book and a derivatives book has two ids (`BINANCE` and `BINANCE_FUTURES`, `BYBIT_SPOT` and `BYBIT`, `OKEX` and `OKEX_SWAP`, `GATE_IO` and `GATE_IO_FUTURES`, `HYPERLIQUID` and `HYPERLIQUID_FUTURES`), and the same symbol can exist on both: pin the id of the book you mean. ## A misspelled pin is refused A guessed id is a pin that reads nothing, and the chart does not draw a flat line in its place: it asks for the market as written, and when nothing comes back it refuses the run and names the market it could not load, in a toast and on the overlay's **Could not load** chip: ```text Pinned market candle (BINANCE_FUTURES/BTCUSDTT) data is unavailable for 'Venue spreads' (the ohlcv source lane answered empty or was declined), so the indicator cannot compute. ``` Check the spelling against the table: the exchange id in uppercase, and the symbol the way that venue writes it. ## Notes **Case sensitivity.** Exchange ids are uppercase (`BINANCE`, never `binance`), and symbols are matched as the venue spells them. An interval pin takes the vocabulary's words or their short forms, and nothing else: `MINUTE`, `FIVE_MINUTES`, `FIFTEEN_MINUTES`, `THIRTY_MINUTES`, `HOUR`, `FOUR_HOURS`, `DAY`, `WEEK`, or `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w`, and on the chart only its custom timeframes, `TWO_MINUTES` to `THREE_DAYS` or `2m`, `3m`, `10m`, `45m`, `2h`, `6h`, `8h`, `12h`, `3d` ([The chart's custom timeframes](../core-concepts/multi-timeframe.md#the-charts-custom-timeframes)). **Separators vary.** Hyphens (`BTC-USD`), underscores (`BTC_USDT`), colons (`BTC:USD`), or nothing (`BTCUSDT`), per venue. The same asset is a different string on every venue, so an indicator that pins several venues carries one spelling per pin; there is no normalized symbol in a pin. **Data availability.** Not every source exists for every venue and symbol: funding, open interest, and liquidations are perpetual-venue feeds, and the implied volatility and skew tenors are Deribit's. On the chart those sources always read the chart's own market. When that market does not serve one, the volume profile, implied volatility, skew, the options chain, ETF flows, and funding (unless its input declares `missing: "nan"` or `"zero"`) refuse the run by name, while open interest, liquidations, and trades read their missing fill. **Dated futures and options.** Use the format the venue publishes; `YYMMDD` in an OKX future is the expiry. **Polymarket.** An `odds` input names one outcome market by its condition id (`0x` plus 64 hex characters), never the market slug or the event, with `outcome` `YES` or `NO`; the exchange is implicit and refused if written. The chart has no market picker, so the condition id in `symbol` is the only way to name the market ([Data sources](../core-concepts/data-sources.md)). **CME.** An indicator reads CME data in the browser once you are signed in and have accepted the CME market data terms; its results stay on that chart, and a Protected indicator does not run there ([Limitations](limitations.md)). <!-- source: https://openmarket.xyz/wrun/reference/versions --> # Versions and contracts How a wrun indicator changes over time for someone who writes it in the chart: the contract a package runs under, the compiler the editor pins, and what a new version of your indicator does and does not change. A wrun indicator has no language versions, only a contract that each published package carries and the versions you publish. ## What moves, and what never does ```text The contract abi_version in the sheet Run derives from your declarations Your versions 0.1.0 on the first publish, then Patch, Minor or Major The compiler AssemblyScript 0.27.37, loaded by the editor's Run ``` <!-- wrun:cards --> | Contract | What it adds | Your file is on it when it declares | | --- | --- | --- | | `wrun-1` | the first contract, frozen forever | nothing the rows below name | | `wrun-2` | celled inputs, text slots, renderers and declared drawings | a celled input, a text slot, a renderer or a declared drawing | | `wrun-3` | drawing handles, strategies and the last-bar flag | a handle, a `strategy(...)` or `bar.isLast()` | | `wrun-4` | frames: level profiles, panels and widgets | a frame | | `wrun-5` | text settings: the typed words, read by the file | a text setting | | `wrun-6` | the bar count: how many bars the run holds | a `bar.count()` read | - **The contract.** You never pick it: Run derives it from what your declarations use (reading `bar.count()` makes the sheet `wrun-6`; a text setting makes it `wrun-5`; a frame makes it `wrun-4`; a handle, a `strategy(...)` or `bar.isLast()` makes it `wrun-3`; a celled input, a text slot, a renderer or a declared drawing makes it `wrun-2`; anything else stays on `wrun-1`). The first contract is frozen: its behavior never changes, and every package written under it keeps computing bit-identically. Each later contract adds to the one before and freezes in turn, so an indicator written today keeps computing the same way. - **Your versions.** The first publish is 0.1.0, and every later publish is a new version you pick as **Patch**, **Minor** or **Major**, with a one-line "What changed" ([Publishing](../functions/publishing.md)). A published version never changes. A chart that added your indicator keeps the exact version it added and reloads that version, so a new release reaches a chart when its owner adds the new version. Where an indicator runs (the browser, or OpenMarket's servers for Protected code) is fixed by its first version. - **The compiler.** Run compiles in your browser with the AssemblyScript version the kit pins, so the same source always builds the same module. ## When the chart updates The chart's editor and OpenMarket's alerts engine ship on their own schedule, and an update can let the editor accept new declarations, draw new kinds of shapes, serve new sources, or accept a new file shape (a file with `onBar()` beside the four-function form). It never rewrites a published version: the module a chart loads is the one you published, under its frozen contract, and a package that does not use a new feature is unaffected by it. ## What we publish | Page | Purpose | | --- | --- | | [What is wrun](../getting-started/introduction.md) | What wrun is, how a file runs and where, in one read. | | [Publishing](../functions/publishing.md) | Versions, sharing and where a published indicator runs. |