# 0xArchive Terminal scripts The 0xArchive Terminal (a web charting and trading terminal for Hyperliquid and Lighter, with 0xArchive as its data layer) runs indicator scripts written in TypeScript. This file is the complete reference for writing one: the guides, the diagnostic codes, the API (script-api.d.ts), and every example and built-in indicator. It is generated from those files, the same ones the pages at https://docs.0xarchive.io/terminal are built from, so it matches the engine exactly. ## Terminal scripting Scripts run in the [0xArchive Terminal](https://terminal.0xarchive.io), on every market it charts. Beside the chart's bars, a script reads everything 0xArchive records: every trade with its change in open interest, liquidations with the wallet liquidated, where open positions would be liquidated, the full-depth order book, funding, open interest and market breadth. ```ts indicator('Opening flow'); const chart = bars(); const tape = trades(); const opened = tally(); const flow = plot.histogram('New longs less new shorts $'); tape.onTrade((t) => { if (t.oiDelta > 0) opened.add(t.side === 'buy' ? t.notional : -t.notional); }); chart.onBar(() => { flow.set(opened.value, opened.value >= 0 ? color.up : color.down); }); ``` This script splits out the trades that opened positions, using each trade's own change in open interest, and plots new longs less new shorts in USD on every bar. ### What a script is A script is one TypeScript file with no imports. The top level runs once and declares everything: the script's name, its settings, the data it reads, its plots and its state. Handlers then run on every bar of history, oldest first, and on every live update, with the values of that moment. There is no lookahead: history only sees what was known at the time, so a script draws the same values live as it does on history. Scripts run in the browser, in a worker of their own with no network access, and give the same result on every machine. ### Where scripts live The scripts you write are kept in your browser, under the names you give them, and any chart can add them from the Indicators dialog. A script runs on whatever market and interval its chart shows, so one script works on BTC, a HIP-3 stock or a Lighter market alike. Its alerts fire in the browser while the chart is open. The terminal's own studies, from RSI to Supertrend, are scripts too, and so is every example on these pages: open one, copy it into the editor, and change it. ### Start here - [Your first script](https://docs.0xarchive.io/terminal/guides/first-script) writes one step by step and puts it on a chart. - [How a script runs](https://docs.0xarchive.io/terminal/guides/how-scripts-run) gives the rules every script follows. - [Examples](https://docs.0xarchive.io/terminal/examples) shows complete scripts with their chart output, each a click away from a chart. - [Reference](https://docs.0xarchive.io/terminal/reference) lists every function and field. ## Your first script Write a script that draws a 20-period EMA, shades it by trend, and can alert when the price crosses it. Each step adds one idea. ### Open the editor In the [terminal](https://terminal.0xarchive.io), open the chart's menu and choose **New script**, or press `/` for the Indicators dialog and choose **New script**. The editor checks the script as you type and lists its problems underneath; **Add to chart** runs it on the chart, and **Save** keeps it in this browser under its name. ### Name it and read the bars Every script starts with `indicator(name, options)`. `overlay: true` draws on the price pane; without it, the script gets a pane of its own below. ```ts indicator('My EMA', { overlay: true }); const chart = bars(); ``` `bars()` with no options is the chart's own bars. It is a stream: a source of data with a handler that runs on each bar. ### Calculate on every bar Indicators such as `ta.ema` are created once at the top, then updated in a handler. The handler runs once for every bar of history, and again on every update of the bar still forming. ```ts indicator('My EMA', { overlay: true }); const chart = bars(); const ema = ta.ema(20); const line = plot.line('EMA'); chart.onBar(() => { line.set(ema.update(chart.close)); }); ``` Update an indicator on every bar, before any early `return`: it only advances on the bars it is updated on. ### Add a setting `input.*` declares a setting the chart's settings panel shows. Changing it runs the script again from the first bar. ```ts const length = input.int('Length', 20, { min: 1 }); const ema = ta.ema(length); ``` ### Colour by trend A plot's `set` takes an optional colour for that bar. `color.up` and `color.down` are the theme's own, so they follow the reader's theme. ```ts chart.onBar(() => { const value = ema.update(chart.close); line.set(value, chart.close >= value ? color.up : color.down); }); ``` ### Alert on a cross `alert(name)` declares an alert, which the reader arms on the chart. `fire` fires it when the condition is true, at most once per bar, and only on live data. ```ts indicator('My EMA', { overlay: true }); const length = input.int('Length', 20, { min: 1 }); const chart = bars(); const ema = ta.ema(length); const crossUp = ta.crossover(); const line = plot.line('EMA', { width: 2 }); const crossed = alert('Close crossed above the EMA'); chart.onBar(() => { const value = ema.update(chart.close); line.set(value, chart.close >= value ? color.up : color.down); crossed.fire(crossUp.update(chart.close, value), `Close ${fmt.price(chart.close)} crossed the EMA`); }); ``` ## How a script runs Know what may go where in a script and the order its handlers run in. The editor enforces these rules as you type, each with a [diagnostic code](https://docs.0xarchive.io/terminal/reference/diagnostics). ### The shape of a script A script is one TypeScript file with no imports. Its globals are the [API](https://docs.0xarchive.io/terminal/reference). The top level runs once, when the script loads (setup). It may contain only: - `indicator(name, options)`, first; - `const` declarations whose values come from the API's constructors (`input.*`, `bars()`, `trades()` and the other streams, `state.*`, `series`, `tally`, `tallyBy`, `ta.*`, `plot.*`, `alert`, `draw.table`), from literals, or from other constants and helper functions; - `plot.level(...)` calls; - function declarations: pure helpers, or factories called at setup; - handler registrations: `stream.onBar(fn)`, `stream.onClose(fn)`, `trades.onTrade(fn)`, `liquidations.onLiquidation(fn)`, `book.onUpdate(fn)`. Handlers hold the logic and run per bar or per event. A local variable in a handler starts fresh on every run. Anything that persists is declared [state](https://docs.0xarchive.io/terminal/guides/state). ### What the compiler enforces - Constructors only at the top level; handlers registered only at the top level, unconditionally. - Each state object, series and indicator belongs to the one stream whose handler updates it. - Event handlers (`onTrade`, `onOrder`, `onLiquidation`, `onUpdate`) may change only tallies and live state. - Tallies are filled only by event handlers. - Plots, markers and drawings are set only in the chart's own `bars()` handlers. - No `import` or `export`, `eval`, `with`, `async`, generators, classes, top-level `let` or `var`, top-level collections that change, dynamic indexing of API objects, `Date`, timers, `fetch` or other globals. - `Math` is the engine's own: `exp`, `log`, `pow`, the trigonometric functions and the rest give the same bits in every browser, which can differ in the last bit from a browser console. There is no `Math.random`: use `random(seed)`. ### The order things run in For chart bar `i`, in history: 1. Everything that happened before the bar closed, merged by time: trades and liquidations with a time before its close, and other bar streams' bars that close at or before it (their `onBar` with `confirmed` true, `onClose`, then their commit). At equal times a bar close comes first, and a longer interval before a shorter one. 2. The chart's `onBar`, with `confirmed` true, then its `onClose`. 3. The commit. Tallies empty for the next bar. Live, the forming bar runs again from the last commit on every update, with `confirmed` false. Only the latest update matters, so updates can be skipped without changing the result. > Another stream read from a handler gives its last closed value, "as of" that moment: there is no lookahead. `.forming` on a stream reads its developing bar live, which repaints; on history it is the last closed bar. See [data and timeframes](https://docs.0xarchive.io/terminal/guides/data). An indicator advances only when `update` runs, so update it on every bar. Missing numbers are `na`: arithmetic with `na` is `na`, and comparisons with it are false. See [missing values](https://docs.0xarchive.io/terminal/guides/missing-values). ### When a script runs again The script runs again from setup, over the whole history, when older history is loaded, the market or interval changes, or an input changes. That takes a few tens of milliseconds per 100,000 bars for a typical script. Values near the oldest loaded bar may change, as on TradingView. ## State and indicators Keep a value from one bar to the next. A local variable in a handler starts fresh on every run, so anything that must persist is declared at the top, with a lifetime that says what happens to it while the newest bar is still forming. ### State | Declared with | Kept | |---|---| | A local in a handler | Never: fresh on every run | | `state.bar(x)`, `state.list(n)`, `state.map(n)`, `state.mat(rows, cols)`, `series(n)`, every `ta.*`, `stats.*` and `ml.*` instance | Across bars; rolled back before each update of the forming bar, like Pine's `var` | | `state.live(x)`, `state.list(n, 'live')`, `state.map(n, 'live')` | Across bars and across updates of the forming bar, like Pine's `varip` | | `tally()`, `tallyBy(n)` | Within one bar: empty on each new chart bar, and each event is applied once | A cell holds one value, read and written through `.value`: ```ts const highest = state.bar(na); chart.onBar(() => { if (isNa(highest.value) || chart.high > highest.value) highest.value = chart.high; }); ``` Because `state.bar` is rolled back before every update of the forming bar, the update always starts from the last closed bar and nothing is counted twice. Use `state.live` only for something that should count every update, such as how many updates a bar received. ### Lists and maps `state.list(capacity)` and `state.map(capacity)` hold numbers, booleans, strings or `null`, up to 100,000 entries. A map is keyed by strings. Size them for what they will hold: adding past the capacity stops the script with `OX2004`, so `shift` a list's oldest entry before it fills. ```ts const seen = state.map(10_000, 'live'); liq.onLiquidation((l) => { if (l.user !== null) seen.set(l.user, (seen.get(l.user) ?? 0) + l.notional); }); ``` An event handler may change only live state and tallies, which is why this map is `'live'`. ### Series `series(lookback)` is a number with history: `set` the current bar's value, then read `value`, or `ago(n)` for `n` bars back, up to the declared lookback (at most 5,000). ```ts const range = series(20); chart.onBar(() => { range.set(chart.high - chart.low); const widest = Math.max(range.value, range.ago(1), range.ago(2)); }); ``` The bars themselves have history too: `chart.ago(n)` is the bar `n` bars ago. ### Tallies A tally sums what event handlers add during one bar: `add` in `onTrade`, `onLiquidation` or another event handler, read `value` (and `count`) in the chart's handlers. It empties on each new bar and never rolls back, so each trade counts once even while the bar is forming. ```ts const tape = trades(); const delta = tally(); const deltaBars = plot.histogram('Delta $'); tape.onTrade((t) => delta.add(t.side === 'buy' ? t.notional : -t.notional)); chart.onBar(() => { deltaBars.set(delta.value); }); ``` `tallyBy(capacity)` keeps a sum per key, such as per taker order or per wallet, up to 10,000 keys; read it with `get(key)` or `entries()`. Keys past its capacity are dropped for the rest of the bar. ### Indicators `ta.*` creates an indicator instance at the top; `update` feeds it a value and returns the result. Values match TradingView's built-ins, including their seeds and how they treat `na`. ```ts const rsi = ta.rsi(14); const atr = ta.atr(14); chart.onBar(() => { const r = rsi.update(chart.close); const a = atr.update(chart); }); ``` - **Update on every bar.** An instance advances only when `update` runs, so updating it inside an `if` gives a different result. This is Pine's rule that every call keeps its own history, made visible. - **One instance per use.** Two RSIs of different sources are two instances. - **`value`** is the result of the latest update in this run; **`confirmed`** is the value as of the stream's last closed bar, for reading from another stream's handler. Updated twice in one run, an instance starts the second update again from the bar's start: the last update of the bar wins. Instances can sit in a list when a script needs many alike: `const rsis = [7, 14, 28].map((n) => ta.rsi(n))`, then `rsis.map((rsi) => rsi.update(chart.close))` on every bar. `stats.*` and `ml.*` are instances too, with the same rules: see [statistics and machine learning](https://docs.0xarchive.io/terminal/guides/machine-learning). ## Statistics and machine learning Build signals the way a quant does, inside the script: rolling statistics, models that learn one bar at a time, principal components, and matrices. Each model is an instance, like an indicator: create it at the top, update it on every bar, and it rolls back with the forming bar. ### Statistics `stats.*` are rolling statistics that match pandas, so a number checked in a notebook is the number on the chart. Variance divides by n − 1, as pandas does; `ta.stdev` keeps TradingView's n. ```ts const z = stats.zscore(100); const corr = stats.corr(50); const vol = stats.vol(30, 'yangZhang', { annualize: true }); chart.onBar(() => { const reading = z.update(chart.close); const together = corr.update(chart.close, other.close); const annual = vol.update(chart); }); ``` `zscore`, `corr`, `cov`, `beta`, `skew`, `kurt`, `quantile`, `median` and `autocorr` work over the last `length` values. `ewmVar`, `ewmCov` and `ewmCorr` weigh by a half-life. `vol` estimates volatility from each bar's prices: from closes, or with Parkinson, Garman-Klass, Rogers-Satchell or Yang-Zhang, which use the high, the low and the gap from the previous close. > A bar with `na` in an input returns `na` and leaves the window as it was, so a window is the last `length` bars that had values. pandas would count the missing bar inside the window instead. ### Regression `ml.ols(length, inputs)` fits a least-squares line over the last `length` bars; `ml.rls(inputs)` learns from every bar so far, each older bar weighing `forget` times less. Each update takes this bar's `y` and its list of `x`, and returns the coefficients, R², t-statistics and two honest numbers: `fitted`, the estimate of this bar's `y` from what the model knew before it, and `residual`, the miss. ```ts const fit = ml.rls(2, { forget: 0.995, ridge: 1 }); chart.onBar(() => { const r = fit.update(chart.close, [other.close, third.close]); const ahead = fit.predict([other.close, third.close]); }); ``` `ridge` keeps the fit steady when inputs move together; it leaves the intercept alone, as scikit-learn's Ridge does. Give the inputs similar scales (z-scores, say) when you use it, so it weighs them alike. > The t-statistics assume each bar's error is independent. Labels that overlap, such as 12-bar forward returns sampled every bar, share 11 bars each, and the t-statistics overstate how significant a coefficient is. ### Labels a model cannot see early To learn what came *after* a reading, a model needs the return that followed it, which does not exist until later. `ml.forward(horizon, inputs)` holds each bar's inputs and hands them back with the log return since, `horizon` bars later and never sooner. Train on what it returns, and the model cannot learn from the future. ```ts const labels = ml.forward(12, 3); const model = ml.rls(3, { forget: 0.998 }); chart.onClose(() => { const x = [a.value, b.value, c.value]; const done = labels.update(x, chart.close); model.update(done === null ? na : done.ret, done === null ? x : done.x); forecast.set(model.predict(x)); }); ``` A model updated with `na` as `y` learns nothing that bar, so it can be updated on every bar as the rules ask, even before the first label. ### Scoring a forecast `ml.score(horizons)` grades a forecast against what followed it. Pass each bar's forecast and price; every forecast is scored once its return exists. ```ts const score = ml.score([1, 6, 24]); chart.onClose(() => { const s = score.update(forecast, chart.close); const skill = s.ic(6); // correlation with the 6-bar return that followed const sure = s.t(6); // its t-statistic, allowing for overlap }); ``` `ic` is the information coefficient, the correlation between forecast and return; `hit` the share of pairs with the same sign; `t` the t-statistic of the return's slope on the forecast; `n` the pairs scored. A 6-bar return sampled every bar shares 5 bars with the next, so an ordinary t-statistic overstates how sure the score is by about √6. `t` uses Newey-West with `h − 1` lags and doesn't. A [strategy](https://docs.0xarchive.io/terminal/guides/strategies) shows its first `ml.score` in its report. ### Kalman filters `ml.kalman` smooths a value that moves as a random walk and is seen with noise: it returns the level, its uncertainty, and each bar's surprise. `ml.kalmanBeta` estimates `y = α + βx` with α and β drifting, the hedge ratio of a pairs trade, and returns the spread and its z-score. See [Kalman pairs spread](https://docs.0xarchive.io/terminal/examples/kalman-pairs). ### Principal components `ml.pca(inputs)` finds the ways a list of numbers moves together over a window: RSI at many lengths, or many markets' returns. Each bar it returns the `scores` (where the inputs sit on each component, what a model learns from), the share each component explains, the `loadings`, and each input's `residual`, the part the components don't explain. ```ts const rsis = [4, 8, 12, 16, 20, 24, 28, 32].map((n) => ta.rsi(n)); const pca = ml.pca(8, { window: 500, components: 3, standardize: true }); chart.onClose(() => { const p = pca.update(rsis.map((rsi) => rsi.update(chart.close))); const first = p.scores[0]; }); ``` The components are computed exactly, from the window's covariance (or its correlations, with `standardize`), on closed bars. They are recomputed every `refit` bars and held in between, so a model fed the scores doesn't have its inputs shift under it every bar. `refit: 'auto'`, the default, recomputes every bar up to 20 inputs, then every 4 bars at 30 inputs, every 8 at 40 and every 16 at 50, to keep the cost near 20 inputs'. Each component's largest loading is positive, so a component never flips sign from one refit to the next. ### Forecasting from components, walk-forward A model that keeps learning from `ml.pca` scores has the components move under it at every refit. When two smaller components swap places, its coefficients suddenly apply to the wrong one until it learns again. `ml.pcr(inputs)` avoids that. It fits the components and the regression on them together, on the same window, then freezes both, centre and scale included, until the next refit. That is a walk-forward test: each stretch is forecast by a fit that only saw the bars before it. ```ts const rsis = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24].map((n) => ta.rsi(n)); const labels = ml.forward(6, 12); const model = ml.pcr(12, { window: 500, components: 3, refit: 100, quantiles: [0.01, 0.99] }); chart.onClose(() => { const x = rsis.map((rsi) => rsi.update(chart.close)); const done = labels.update(x, chart.close); const fit = model.update(done === null ? na : done.ret, done === null ? x : done.x); const guess = model.predict(x); const [low, high] = fit.quantiles; }); ``` Feed it the pairs `ml.forward` returns. Once `window` pairs are in, it fits on closed bars every `refit` pairs, and `fit.refitted` is true on that bar. `quantiles` gives thresholds from the fit's own in-sample forecasts, so "above the 99th percentile" means unusually strong by that fit's standard. `predict` and `scores` use the frozen fit, and return `na` before the first. See [RSI PCA forecast](https://docs.0xarchive.io/terminal/examples/rsi-pca-forecast). ### Matrices `linalg` has matrices for scripts that build their own models: products, `solve`, `inv`, and the Cholesky, QR, symmetric eigen and singular value decompositions. A matrix made in a handler is a plain value; `state.mat(rows, cols)` keeps one across bars and rolls it back with the forming bar. ```ts const a = linalg.mat(2, 2, [4, 1, 1, 3]); const { values, vectors } = linalg.eigSym(a); const x = linalg.solve(a, [1, 2]); ``` A singular `solve` or `inv`, or a `cholesky` of a matrix that is not positive definite, returns `na` throughout rather than stopping the script. Results are the same bits in every browser. A decomposition counts about n³ steps against the [step budget](https://docs.0xarchive.io/terminal/guides/limits). ## Strategies Turn a signal into a strategy and see what it would have made after it paid to trade. Declare `strategy()` in place of `indicator()`, say on each closed bar what position you want, and the engine fills it, charges what the venue would have charged, and keeps the account. ```ts strategy('MA cross', { capital: 10_000, from: '2025-03-01' }); const chart = bars(); const fast = ta.sma(20); const slow = ta.sma(50); chart.onClose(() => { const f = fast.update(chart.close); const s = slow.update(chart.close); // Long above the slow average, flat below it: a strategy trades only the sides it asks for. if (!isNa(s)) strategy.target(f > s ? 1 : 0); }); ``` The chart shows each fill as an arrow on the price and the equity curve in a pane of its own, beside buy-and-hold. **Report** in the legend opens the Strategy report. ### Targets `strategy.target(fraction)` is the position you want as a fraction of equity: 1 fully long, −1 fully short, 0 flat. `strategy.targetUsd(usd)` takes a notional instead, and `strategy.targetSize(coins)` a size in coins. All are held to `leverage` times equity. Nothing makes a strategy trade both ways: one that only ever asks for 0 to 1 is long only, and one that asks for −1 to 0 is short only. - A target applies on closed bars only. By default it fills at the next bar's open, so a script never trades on a close it hasn't seen. `fill: 'close'` fills at the signal bar's own close, the shortcut many testers take. - The same target again holds the position as it is: calling `strategy.target(1)` every bar doesn't trade as equity moves. A new value trades to it. - An order under $10 is not sent, as the venue would refuse it. `strategy.position`, `strategy.equity`, `strategy.cash`, `strategy.closedTrades` and `strategy.costs` read the account back in a handler, marked at the bar's close. `strategy.position.entries` counts the fills that opened or added to the position, and `entryBar` and `entryTime` say when it opened. ### Stops, limits and exits A target with a `stop` or a `limit` rests until price reaches it, rather than filling at the next open. An exit closes the position at a stop or a limit, whichever price reaches first. ```ts strategy('Breakout', { capital: 10_000 }); const chart = bars(); const high20 = ta.highest(20); const atr = ta.atr(14); chart.onClose(() => { const level = high20.update(chart.high); const range = atr.update(chart); if (isNa(level) || isNa(range)) return; // Buy a break above the last 20 bars' high; out 2 ATR below the entry or 4 above it. strategy.target(1, { stop: level, id: 'breakout' }); strategy.exit({ loss: 2 * range, profit: 4 * range }); }); ``` - A **stop** fills once price trades through it (above for a buy, below for a sell), at its price, or at the open when a bar opens past it. It pays the taker fee and the slippage. - A **limit** fills once price trades at it, at its price or a better open. It pays the maker fee and no slippage. - Inside a bar, price is taken to go from the open to the nearer of the high and the low, then to the other, then to the close. Each order fills where that path first reaches it. An exit placed with its entry can fill in the bar the entry opens. - `strategy.exit({ stop, limit })` takes prices. `{ loss, profit }` takes distances from the entry price, placed once the position is open. Both can be given; the one reached first fills. `side: 'long'` or `'short'` keeps an exit to one side. - An order placed on a bar's close can fill from the next bar on. It stays until it fills, another with its `id` replaces it, `strategy.cancel(id)` removes it, or, for an exit, the position it closes is closed. A strategy holds at most 16. ### What it pays Each cost is charged on its own and listed in the report, so you can see what took the edge. - **Fees**: the venue's base tier (Hyperliquid's rates, twice them on HIP-3, Lighter's). A market or stop fill pays the taker rate, a limit fill the maker rate. `fees: { takerBps, makerBps }` sets your own; `makerBps` defaults to `takerBps`. - **Slippage**: what a market order of the fill's size paid against the order book at the signal bar's close, the book the next open trades into. The archive records what $10k, $100k and $1M cost on each bar it holds (Hyperliquid and HIP-3); sizes between are interpolated, smaller ones run down to half the spread, and larger ones carry the last stretch on (the report counts them). On a bar the archive has no reading for, a fill costs `fallbackBps` (2). The report says how many fills the book priced and from when. `slippage: { bps }` uses a flat cost throughout. - **Funding**: every hour a position is open it pays or collects that hour's rate on its notional, as the venue settles it, from 2025-03-01. A 4h or 1d bar charges each hour inside it. Funding needs a time chart of 1m or longer; on other charts pass `funding: false`. - **Liquidation**: with `leverage` above 1, a position whose equity at the bar's worst price falls below maintenance margin is closed where it would have been (half the initial margin at the market's highest leverage). An account never goes below zero; the report says what the venue's backstop took. > A backtest is one path through history. A strategy tuned until it looks good on that path has learned the path. Check it on a stretch it was not tuned on, and score its forecast with `ml.score` (see [statistics and machine learning](https://docs.0xarchive.io/terminal/guides/machine-learning)), before you trust it. ### History `from: '2025-03-01'` loads the chart's history back to that date before the run, so the report covers more than the bars on screen. The run takes longer on more history; the legend says how far it has got. ### The Strategy report The report opens in a panel of its own, from **Report** in the legend or the legend's menu. A backtest on 0xArchive's server, from Backtests in the Strategies bar, shows the same report in its row. - **Overview**: the net result against buy-and-hold, max drawdown, Sharpe, profit factor, trades, win rate and exposure; the equity curve with its drawdown underneath; what each cost took from the gross; and the forecast's score when the script declares an `ml.score`. Its data line says which run it is (**Loaded bars** on the chart, **Up to a year** on the server), what the script's rules read (bars only, or trades and the book as well) and how it filled. - **Trades**: every round trip with its costs. Click one to bring it into view on the chart. - **Export**, at the end of the tabs, saves the trades: **CSV** for a spreadsheet, one row per trade with its entry and exit, size, prices, costs, net and return; or **JSON** for a script or an AI, the same rows with the run's script, inputs, market, span, capital and cost model. An algo's **On history** and a server backtest's card have it too. - **Assumptions**: every rule and source the run used: fills, fees, slippage, where the order book and funding start, leverage and maintenance, and how stops and limits fill when the script places them. Every fill is simulated, in the browser or on the server, and nothing reaches an exchange. The same bars and settings give the same trades on every run. ### Running it on an account A one-market strategy runs on Paper or Live from **Strategies**: it's listed under **Yours** in the library, with **Backtest**, **Paper** and **Live** on its row (Live once trading is set up in Live). Start it, then arm it from its row in **Running**, as you would any strategy: it starts **Watching**, with nothing traded until you set its bias and shots and press **Arm**, and those gate its entries. **New strategy** starts one from a template: On bar close, On order flow (each bar's order flow from the archive, backtested on the server over up to a year), Live tape (the live trades and book only, so it has no history to backtest), Semi-auto or Blank. Its live run follows its own backtest's trades. On each closed bar it runs as it does in the backtest, and what its simulated account does becomes orders: - **A trade it opens** is an entry on that side, sized from its target: a share of equity is that share of the account's equity, a notional is that notional, a size is that size at the bar's close. Its stop goes in first, then the entry. - **Its stop and target** come from `strategy.exit`: a price, or a distance from the entry. An entry without one gets the run's **Stop if none**, in basis points. Every trade has a stop. - **A trade it closes** is closed live too, with a reduce-only order. A partial close (a smaller target) closes the same share of the live position. - **A flip** closes the live trade, then enters the other side once the account is flat. - **One trade at a time.** A strategy that adds to its position doesn't add live: its row's journal says it would have. Its run has four settings of its own: - **Starts**: *When flat* (the default) takes no position its history holds at the start, and trades from its next entry. *Adopt* takes a position you hold, on the side its history holds, as its trade, so its exit closes it. - **Fill**: *Market*, the backtest's fill at the next bar's open, or *Chase*, which rests at the touch and follows the price. - **Worst price**: how far from the bar's close an order may fill, in basis points. Empty, a market order takes the book. - **Stop if none**: the stop, in basis points from the entry, for an entry its `strategy.exit` gives none. > Some things differ from the backtest. A stop or limit entry (`strategy.target(1, { stop })`) fills inside the bar in the backtest, but live it's entered at the close of the bar it filled in. A stop the script moves after the entry is followed at the close of the bar it's hit in, since the run's stop rests where it was first placed. A strategy() script runs in your tab. Portfolio strategies run in Backtests. ### Portfolios `strategy(name, { portfolio: true })` trades many markets in one account: shared cash, cross margin, every Hyperliquid perp. Set one market's weight with `strategy.target(0.2, { market: 'ETH' })`, or the whole book with `strategy.targets({ ETH: 0.2, SOL: 0.2 })`, where a market left out goes to 0. A weight is a fraction of equity, as one market's target is, and fills at the open of that market's next bar. ```ts strategy('Momentum', { portfolio: true, capital: 100_000, from: '2025-06-01' }); const pool = universe.topN(25); const chart = bars(); chart.onClose(() => { if (clock.parts(chart.time).dayOfWeek !== 0) return; const scores: Record = {}; for (const m of pool.current) scores[m] = pool.ret(m, 7) / pool.volatility(m, 30); strategy.targets(portfolio.longShort(scores, { quantile: 0.2 })); }); ``` - **Picking and trading read different data.** Picking a universe reads the universe history, one row a day for every perp. Trading reads each market's own bars at the chart's interval, the same bars its chart shows: fills, marks, liquidation and the pool's price reads. On 1D they come in the universe history's monthly files, which hold exactly the daily bars a chart shows, so a daily run loads in seconds. Intraday each picked market's bars load on their own: quick over weeks, slower over many months of hourly bars. - **The universe is picked point in time.** `universe.topN(n)` holds the `n` perps with the most dollar volume over the last 30 days, among those with 60 days of prices, re-picked every 30 days. `universe.rule(select)` runs a rule of your own: `select(view)` reads any market's days before the pick (`markets`, `listed`, `closes`, `volume`, `openInterest`, `funding`, `volatility`, `historyDays`) and returns the members. Both pick from every perp that traded then, delisted ones included, so a run never holds a coin for what it later became. `pool.view` reads the same days as of now. - **The pool's price reads use the members' bars.** `pool.close(m)`, `closes`, `ret`, `volatility`, `beta`, `resid` (the move a reference such as BTC does not explain) and `volume` count bars of the pool's interval, the chart's by default; `universe.topN(25, { interval: '1d' })` reads daily bars on an intraday chart. A bar is read once it has closed. Intraday a market's bars load the first time it is picked; until they land its reads are `na` and the report says it is loading. - **It runs on any time chart from 1m to 1W.** On a 4h chart it trades every 4 hours; the universe is still re-picked on the days `every` sets. The chart shows its own market's fills, its sleeve of the book, and the whole account's equity. An intraday run covers the history the chart holds, as any script does: scroll back for more. - **The costs.** Each fill pays the taker fee and a flat 2 bps of slippage (`slippage: { bps }` sets your own): the archive's book readings start on 6 Sep 2026, too late for most of a portfolio's history. Every hour a position is held it pays or collects that day's mean hourly funding rate. The book is held to `leverage` at every rebalance; below the sum of its maintenance margins at the bar's worst prices, the whole account is liquidated. The Strategy report adds **Markets**, what each market made after its costs, and **Book**, the weights after each rebalance beside the universe's picks. ## Algos An algo is a script that places real orders. It declares `algo()` in place of `indicator()`, reads its settings and whatever data it needs, and says in `algo.onArm` which orders to place. When you press **Arm**, the script runs that function once, and the orders it makes are placed: in this tab on Paper or Live, or on 0xArchive's server. ```ts algo('Chase', { role: 'entry', overlay: true }); const side = input.side('Side', 'buy'); const size = input.size('Size', { usd: 1000 }); const worst = input.price('Worst price', null, { drag: true }); algo.onArm(() => { order.chase({ side, size, limitPx: worst }); }); ``` Every built-in algo in the Algo picker (Chase, Fast stop, Time stop, Take profit, OCO) is a script like this one, and so are its two [strategies](#strategies), Book lean and Flush absorbed. **Edit a copy** opens it in the editor, and your edited copy is an algo of your own, which runs the same way. ### Runs as orders An algo **runs as orders** when every `order.*` call sits inside the function you give `algo.onArm`. Arming then places fixed orders: a chase with its prices, a stop at its price, a condition with its test. These are the same order types the server runs, so an algo that runs as orders can run on the server with your tab closed, edited or not. An `order.*` call anywhere else, in `chart.onBar` or a book's `onUpdate`, makes the algo decide later, on live events. The picker tags it **Script**. A Script algo arms in this tab, on Paper or Trade. The server trades a strategy's triggers and plans, nothing else: a Script algo that is not a strategy is not offered Server, and a strategy's own order calls are not sent there. [Live logic](#live-logic) below says how it runs. The picker and the settings show which it is before you arm anything. The compiler decides from the source: keep order calls lexically inside `onArm`'s function. A helper function declared at the top level and called from `onArm` counts as outside, so declare the helper inside `onArm` if it places orders. ### The order types | Call | What it places | |---|---| | `order.chase({ side, size, limitPx, ... })` | A post-only order at the best price that follows it until it fills, never past `limitPx` | | `order.fastStop({ px, source, size, ... })` | Closes the position you hold when the mark, the best bid or ask, or the last trade reaches `px` | | `order.timeStop({ after, size, ... })` or `({ at })` | Closes the position you hold after a hold, or at a time | | `order.oco(a, b)` | Two resting limits: the first to fill cancels the other | | `order.when(trigger, () => order.X(...))` | When the trigger's test holds, the one order the callback makes: `order.reduce`, `order.close`, `order.limit` or `order.market` | Each call is checked against the order type's own ranges when the algo plans. A value out of range is refused with the same words the server uses, before anything is sent. `trigger.mark`, `trigger.book` (the mid), `trigger.trade`, `trigger.funding` and `trigger.oiUsd` are the prices the server watches itself. Their tests are `'above'`, `'below'`, `'crossesAbove'` and `'crossesBelow'`. A trigger outside this list, such as a book lean, needs code to watch it, which is live logic. ### Sizes A size is one of `{ usd }`, `{ coins }`, `{ pctOfPosition }`, `{ pctOfEquity }`, or `{ riskUsd, stop }`. The last is the size that loses `riskUsd` if the price reaches `stop`, counted from the order's price. An exit sized in dollars or as a share of equity is turned into coins at the mark, rounded down to the market's size step. ### Reading the account `account()` gives the account as it stands when the algo plans: `position` (its side, size in coins, entry price and notional), `equity` and `mark`. Read it inside `algo.onArm`; elsewhere it reads flat. A stop protects the position the account holds at that moment, in whichever direction it faces: ```ts algo('ATR stop, half at 2R', { role: 'protect', overlay: true }); const mult = input.float('ATR multiple', 1.5, { step: 0.25 }); const chart = bars(); const atr = ta.atr(14); const acct = account(); chart.onBar(() => { atr.update(chart); }); algo.onArm(() => { const p = acct.position; const long = p.side === 'long'; const stop = long ? p.entryPrice - mult * atr.value : p.entryPrice + mult * atr.value; const target = p.entryPrice + 2 * (p.entryPrice - stop); order.fastStop({ px: stop }); order.when(trigger.mark(long ? 'crossesAbove' : 'crossesBelow', target), () => order.reduce({ pctOfPosition: 50 })); }); ``` The script runs over the market's history first, as an indicator does, so `atr.value` is warm by the time you arm it. ### Roles `role: 'protect'` promises the algo only reduces your position: every order it makes must be an exit or reduce-only, or arming is refused. `'entry'` may add to the position, and `'both'` does either. On Trade, an entry obeys the account's kill switch; a protective algo keeps working under it. ### Settings for trading `input.price`, `input.size`, `input.side`, `input.percent` and `input.duration` draw the fields a trader expects: a price, an amount with its unit, buy or sell, a percent, and a time written as `'30s'`, `'5m'` or `'4h'` (read in seconds). Group the ones most people leave alone with `group: 'More'`, and the settings fold them. `algo.describe(() => '...')` gives the sentence the settings lead with. Without it, the settings word the orders themselves. ### What the host adds Every algo's settings carry rows the script can't change: the **market**, where it **runs** (this tab or the server), the **account** (Paper or Trade; the server is always Trade), and when it **ends**. Below them, the settings list in words the orders arming will place, from the account as it is now. **Arm** plans once more at the press, so the orders sent are the account's at that moment. On the server, **Preview** asks the server to check them first. Several orders from one `onArm` are placed one after another. If the server refuses one, those before it stay armed, and the settings say how many. ### Live logic A Script algo keeps running after you arm it. Each order call it makes on a live event, a closed bar or a book update or a trade after the arm, is a request, and the tab checks it before anything is placed: - **Stop first.** An entry needs a working stop from the same algo on that market: an `order.fastStop`, an `order.timeStop`, or an `order.when` that closes or reduces. Place it in `algo.onArm`. - **Entries.** The settings' **Entries** row says how many times it may open or add to a position on one arm. One by default. - **Entry caps.** At most 10 entries a minute and 200 a day on the account, across every algo. - **The kill switch** stops entries on Trade while server trading is signed in. - **`trades.maxPositionUsd`**, when the script declares it, caps the position an entry may take it to. Exits and reduce-only orders skip these: a stop is never held back. A plain `order.market`, `order.limit`, `order.reduce` or `order.close` places at once. In history, or before you arm it, an order call sends nothing. Its ref says which: `'sent'` on a live event, `'none'` otherwise. Count what you sent from the ref, so the history run doesn't use it up: ```ts algo('Lean entry', { role: 'both' }); const ob = book({ levels: 10 }); const acct = account(); const sent = state.live(false); algo.onArm(() => { order.fastStop({ px: acct.mark * 0.98, tag: 'stop' }); }); ob.onUpdate((b) => { if (sent.value) return; const bid = b.bids.reduce((s, l) => s + l.size, 0); const ask = b.asks.reduce((s, l) => s + l.size, 0); if (bid / (bid + ask) < 0.65) return; const ref = order.chase({ side: 'buy', size: { usd: 1000 }, tag: 'entry' }); if (ref.state === 'sent') sent.value = true; }); acct.onOrder((o) => { if (o.state === 'refused') log.warn(o.tag + ' refused: ' + o.words); }); ``` `account()` reads the account as the tab last saw it while the algo is armed. `acct.onOrder` hears each answer and change to the algo's orders, refusals included, and `acct.onFill` each fill; both run on live events only. `order.cancel('entry')` cancels the working orders made with that tag. **Disarm** stops the script and cancels its working entries; its stops keep protecting the position. It also ends at its end time, when its script fails, or once its entries are used and its orders have ended. A reload ends it. ### Quoting `order.quote({ bidPx, askPx, size })` quotes both sides: a post-only bid and ask rest in the account, each of `size` (`{ usd }` or `{ coins }`). Call it from a live handler as often as you like. Each call moves the quotes to its prices, and `null` pulls that side. A quote whose price moved less than half a basis point stays where it is, keeping its place in the queue; a moved one goes to the back of its new level. The tab applies at most four calls a second, the newest. ```ts algo('Quote the spread', { role: 'both', trades: { maxPositionUsd: 3000 } }); const ob = book({ levels: 10 }); ob.onUpdate((b) => { const mid = (b.bids[0].price + b.asks[0].price) / 2; order.quote({ bidPx: mid * (1 - 8 / 10_000), askPx: mid * (1 + 8 / 10_000), size: { usd: 1000 } }); }); ``` A quoting algo needs `trades: { maxPositionUsd }`: the position, valued at the mark, never passes it. The side that would take it past is pulled, and the other side keeps quoting, which works the position back. Quotes are not entries: the entry caps and the stop-first rule above do not apply to them, the cap does. **Disarm** pulls its quotes and leaves the position; **Flatten** pulls them and closes the position at market. Quoting runs on Paper. The built-in **Quote the spread** leans its quotes against what it holds. A fill pulls at once whatever the cap no longer allows; nothing is placed again until the script's next call says where. Quoting combines with exits: the built-in **Fade the extremes** rests its bid and ask at the edges of the 1-minute Bollinger band, and once a side fills it places `order.fastStop` and `order.timeStop` for that position, quotes only the take profit (`{ coins }` of the whole position, at the band's middle), and cancels its exits with `order.cancel` when the position is flat again. ### Strategies A **strategy** is an algo that stays on: `algo(name, { lifetime: 'standing' })`. Its script finds the moments to trade (`algo.trigger`), and you steer it while it runs. Each trigger trades only when all of these hold: - you have armed it; - the bias allows that side; - its price is inside one of the strategy's zones, if it has any; - the governor has room for the day; - no cooldown is running. Any other trigger goes in its journal as **would have traded**, with the reason. ```ts algo('Book lean', { lifetime: 'standing', trades: { maxPositionUsd: 20000 } }); const risk = control.number('Risk per trade', 50, { min: 1, max: 500, step: 1, unit: 'usd', history: 50 }); const stopBps = control.number('Stop', 40, { min: 10, max: 200, step: 5, unit: 'bps', history: 40 }); algo.bias({ owner: 'trader', initial: 'both' }); algo.governor({ dailyLossUsd: 150, maxTrades: 4 }); const ob = book({ levels: 10 }); ob.onUpdate((b) => { // ...when the book tips to the bids: algo.zones([{ lo: b.bids[b.bids.length - 1].price, hi: b.asks[0].price, side: 'long', label: 'Bid stack' }]); algo.trigger({ side: 'long', price: b.asks[0].price, why: 'Bids 79% of the top 10' }); }); algo.plan(() => ({ entry: { how: 'cross', worstBps: 20 }, size: { riskUsd: risk.value }, stop: { bps: stopBps.value }, targets: [{ r: 2, pct: 100 }], timeStop: '60m', })); ``` **Controls** are how you steer it now. `control.number`, `choice`, `toggle`, `price` and `button`, at most 16, declared at the top level like inputs. A change is an event the script reads from its next handler: it never re-runs the script, and the journal records it. A `control.price` is a line on the chart you drag. In history a control reads its `history` value, and a button never fires. **The plan** turns a trigger into a trade, in your terms. It sets the entry (`cross`, or `chase` with a worst price) and the size (`riskUsd`, `notionalUsd` or `equityPct`). It must set a stop: `bps`, a `price`, or `beyondZone`. Targets in R and a time stop are optional. When a trigger trades, its **stop goes in first**, protecting the side the entry will open, and then the entry. Once the entry fills, the stop **rests on the exchange** as a reduce-only stop market for what filled, and each target as a reduce-only take-profit market, so they protect the position when the tab closes. The tab watches the stop only until the exchange lists it, or for the whole trade if the exchange refuses it. The time stop runs in the tab. Every order goes through the admission and caps in [Live logic](#live-logic). A strategy places entries only through its plan: an entry its handlers place directly is refused. **Start on Paper** or **Start on Trade** in its settings starts it **Watching**, on that account: bias Off and no shots, so nothing trades until you arm it. Trade places real orders with your trading key, each through the same checks. A strategy never trades a market where you hold a position it didn't open. Its row in Running is where you drive it, and its state is one word at the row's start: **Watching**, **Armed** with its shots and bias ("Armed 2 · Long"), **In trade**, **Paused** or **Stopped**. - **Bias:** Long, Short, Both or Off. Off always wins, even when the script sets the bias with `algo.bias.set`. - **Shots** and **Arm**: pick how many trades it may open (1, 2, 3, 5, or **Auto** for no limit) and press **Arm**. Each trade it opens takes one; at none it watches again. While it's armed, Shots says what is left and the button is **Disarm**. On Live, Arm asks a second time, naming the account. - **Armed for** and **Each trade**, in its details: how many minutes an arm lasts, and **Confirm** or **At once**. Confirm comes first on Trade. With Confirm, each accepted trigger waits on a card showing the trade it will place. **Trade** places it. **Skip**, or 30 seconds passing, places nothing and keeps the shot. - **The menu** (⋯) holds what ends something, each asking again on the row. **Flatten & disarm** turns entries off, cancels its entry and its resting stop and targets, and closes the position its trade opened. **Stop** ends the strategy: its resting stop and targets stay on the exchange and keep protecting the position. Its row in History says what still rests. - **The state and the next trade**, and the governor's day: "Day P&L −$40 of −$150 · 1 of 4 trades". The day counts every trade on the account: on Trade, today's closed P&L less fees from the account's fills, plus what is open. While it can't be read, it takes no entries. At the loss limit it **halts** until the next UTC day. **Reset** lifts the halt and turns the day's loss limit off until tomorrow. - **Its controls,** live. - `panel.checklist` and `panel.log`, if the script writes them: what it waits for, and its own notes. - **The journal:** the last 30 events. Its zones are bands on its market's charts while its settings are open or it runs. #### On history A strategy replays its history with fills, and its settings show the result under **On history**: trades, win rate, net, drawdown and costs, from the strategy() account's fees, book slippage and funding. The replay assumes what you would own live: armed for every trigger and its declared bias, unless `algo({ backtest: { capital, assume: { bias, armed } } })` says otherwise. The governor counts the simulated day. When it halts the strategy, the replay arms it again at the next UTC day, when the halt lifts, as you would. With `armed: 'script'`, only the script's own `algo.arm` arms it. It trades at the bar tier: - the entry fills at the next bar's open; - the stop and the first target rest as one exit; - the time stop counts from the fill: its exit goes in at the first bar close past it and fills at the next bar's open, so a one-bar time stop goes out at the open after the bar it filled in. In this tab only a trigger on a closed chart bar is replayed: a strategy that reads the live book or the trade stream has no history here, so On history has nothing to show for Book lean. Flush absorbed decides on closed bars from 0xArchive's open interest, so its history and its live run are the same signal. A backtest on 0xArchive's server also replays a trigger in a `book()` handler, against the archive's book every 5 seconds ([Data](https://docs.0xarchive.io/terminal/guides/data)), at the book tier: - the entry meets the next update, never the one that fired it, and walks the opposite side up to the plan's worst price, each level giving at most 96% of its size; what is left does not fill, and a lost book before it cancels the entry; - a resting entry fills at its price only when a later update's best or a later bar trades through it, never at a touch; - the stop is seen on the first update at or past it and fills walking that book, never better than the stop; a time stop closes on the first update past it; - a target fills at its price only when the book or a bar trades through it; when the stop and a target are reached in one update, the stop wins. Its report says so: `assumptions.fills` is `'book 5s'`, and `replay.bookTier` counts the triggers, fills, stops, targets and time stops, with the largest share of the book any fill took. Trade and liquidation triggers are still not replayed, and are counted in `replay.notReplayed`. ## Data and timeframes Read more than the chart's own bars. Every kind of data 0xArchive records is a stream a script declares at the top, and every stream reads as of the bar being run, so history never sees the future. ### Streams | Stream | What it gives, and how far back | |---|---| | `bars()` | Bars of any market and interval: the chart's own as loaded, another from 300 of its bars before the chart's first, at most 5,000 | | `trades()` | Every trade with its side, size, order and change in open interest; back to the chart's first bar, at most 7 UTC days | | `orderFlow()` | Per bar of the chart's interval, what takers bought and sold at each price, with the bar's delta, its running delta's low and high, liquidations and busiest second; Hyperliquid perps from 22 Mar 2025 and HIP-3 from 22 Dec 2025 at the earliest, as far back as the chart, a year in a backtest | | `intentFlow()` | Per bar of the chart's interval, the trades summed by what each side did to its position (opened, took profit, stopped out, flipped), with each category's volume, notional, VWAP and count; Hyperliquid perps from 25 May 2025 14:24 UTC and HIP-3 from 22 Dec 2025 at the earliest, through the archive's last closed hour, a year in a backtest | | `liquidations()` | Every liquidation with its side and the account liquidated: a wallet on Hyperliquid; the last 7 days | | `liquidationLevels()` | Where open positions would be liquidated, 40 levels over 10% either side of the mark, about every 5 minutes; Hyperliquid, the last 7 days | | `orderBook()` | The full-depth book over each bar: mid, spread, size and USD within 0.1% to 10%, imbalance, slippage; Hyperliquid and HIP-3 from 2026-09-06 | | `book()` | The live order book level by level, ungrouped, up to 400 levels a side, with every change; in a server backtest, the archive's book every 5 seconds from 2026-09-06, at most 31 days | | `depth()` | Resting size within bands of the live book the page shows; live only | | `openInterest()` | Open interest over each bar, open, high, low and close; Hyperliquid from 2025-03-01, HIP-3 and Lighter from their starts | | `funding()` | The funding rate over each bar; time bars of 1m or longer | | `derivatives()` | Open interest, funding, mark, oracle and premium from 5-minute samples; the last 14 days | | `breadth()` | The share of a venue's markets above their session VWAP; perps from 24 Aug 2026, HIP-3 from 28 Aug 2026 | | `optionTrades()` | Every BTC option print, with every field the exchange sends; on any chart, the last 7 days | | `optionOrders()` | BTC option orders joined from their prints: blocks, screen combos and sweeps; the last 7 days | | `dealerExposure()` | Option dealers' gamma, charm and vanna at BTC's price, the gamma flip and each strike's position, every 5 minutes; the last 7 days | Anything a stream does not have reads `na`, `null` or `available: false`, never a guess. Each stream's fields are in the [reference](https://docs.0xarchive.io/terminal/reference/streams). ### Other markets and intervals `bars({ market, interval, venue })` reads another market, another interval, or both. Give it a handler of its own when there is something to calculate on its bars: ```ts indicator('4h EMA', { overlay: true }); const chart = bars(); const h4 = bars({ interval: '4h' }); const ema = ta.ema(20); const line = plot.line('4h EMA', { width: 2 }); h4.onBar(() => { ema.update(h4.close); }); chart.onBar(() => { line.set(ema.confirmed); }); ``` `ema.confirmed` is the EMA as of the last closed 4-hour bar, so the line steps once per 4 hours and draws the same on history as it did live. Intervals are `1m` to `1w`, calendar months `1M` to `12M` (capital M; `1m` is a minute), and bars that close on trades: seconds (`s15`), trade counts (`t500`), volume (`v1000000`), delta, range, renko and reversal. Weeks open on Monday 00:00 UTC. ### As of: no lookahead Inside a handler, every stream other than the handler's own reads its last confirmed value at or before the current moment: just before the bar's close in history, and the newest data live. A 4-hour bar that closes with the last 1-hour bar of its span is visible on that 1-hour bar, as Pine's `request.security` with lookahead off shows it. The one way to read a bar still forming is to ask for it by name, `.forming`: ```ts chart.onBar(() => { const developing = h4.forming.close; }); ``` Live, `forming` is the developing bar, which changes until it closes: it repaints. On history it is the last closed bar, so history still never looks ahead. ### The forming bar The chart's newest bar runs again on every update, each time from the last commit: `confirmed` is false, every `state.bar` value is back where the last closed bar left it, and only the latest run's output is drawn. When the bar closes, `onBar` runs once more with `confirmed` true, then `onClose`. Do something once per bar in `onClose`; do something that should follow the price live in `onBar`. ### Events: trades and liquidations `trades()`, `takerOrders()`, `liquidations()`, `optionTrades()` and `optionOrders()` deliver events to `onTrade`, `onOrder` and `onLiquidation`, in execution order, before the `onBar` of the bar they fall in. Sum them into [tallies](https://docs.0xarchive.io/terminal/guides/state#tallies) and read the tallies in the chart's handlers; see [order flow](https://docs.0xarchive.io/terminal/guides/order-flow), [liquidations](https://docs.0xarchive.io/terminal/guides/liquidations) and [BTC options](https://docs.0xarchive.io/terminal/guides/options). `available` says whether the stream covers the current bar completely: older bars than its history have none. ### The live book `book()` is the order book as it is now, level by level: `bids` and `asks` best first, each with `price`, `size` and `notional`, `bestBid`, `bestAsk`, `mid`, `spread`, and `size(side, price)` for one price. It holds the nearest 100 levels a side, ungrouped; `book({ levels: 400 })` holds more. `onUpdate` runs once per book the page receives, about one per block of the venue's, in time order with trades and before the `onBar` of the bar it falls in, and `changes` lists the levels it changed with the size each had before: ```ts const b = book(); const pulled = tally(); b.onUpdate((u) => { for (const c of u.changes) if (c.size < c.previous) pulled.add((c.previous - c.size) * c.price); }); ``` Like events, an update's handler may change only tallies and live state. Read anywhere else, the book is as of that moment: at a bar's close in history, the newest live. On a chart in the browser the book is live only. 0xArchive's full-depth archive is served per bar there, as [`orderBook()`](https://docs.0xarchive.io/terminal/reference/streams#orderbook), not level by level, so `book()` starts when the page does: older bars read `available` false and empty lists. A dropped feed is an update too, with `available` false until the book is back, and the first book after it replaces the book whole (`snapshot`). A re-run (new settings, an edit) reads the book from as far back as its changes are kept: the last 200,000 to 400,000 rows, one to two hours of BTC's 100 levels a side and 20 to 70 minutes of its 400 (measured on 2026-10-16). What was drawn before keeps until then. On a server backtest, `book()` is the archive's order book every 5 seconds of block time, for Hyperliquid from 6 September 2026. Days the archive has not built read as unavailable. There is one update per 5-second column whose nearest `levels` changed, stamped at the column's last millisecond, so a bar sees the book as of its own close and never later. Sizes are rounded to within about 4%. Where the archive does not know the book, `available` is false until the next update replaces it whole. A trigger in its handler is replayed against the book: [Algos](https://docs.0xarchive.io/terminal/guides/algos#on-history) says how it fills. Nothing inside a 5-second column is seen: quotes that came and went, the order of changes, or your place in a queue. A backtest reads at most 31 days of the book, or 14 days at 400 levels; the backtest form says so before it runs a longer span. ### Sample streams `orderBook()`, `openInterest()`, `funding()`, `derivatives()`, `breadth()`, `depth()` and `liquidationLevels()` have no handlers. Read them in any handler; each gives its value as of that moment, or `na` with `available: false` when there is none. ```ts const oi = openInterest(); chart.onBar(() => { if (!oi.available) return; oiChange.set(oi.change({ usd: true })); }); ``` ## Read order flow in terminal scripts Build order flow from the tape: every taker fill on the market, with what 0xArchive records about it. `trades()` reaches back to the chart's first bar, at most 7 UTC days, from 0xArchive's history, and continues live from the chart's tape. The last three UTC days come in first, so a script draws its newest bars at once; the older days stream in after, and the script's lines extend back when they are all in. ### A trade | Field | What it is | |---|---| | `time`, `price`, `size`, `notional` | When, at what price, how much in the market's coin, and in USD | | `side` | The taker's side, `'buy'` or `'sell'` | | `oiDelta` | The trade's change in open interest: positive where it opened positions, negative where it closed them | | `takerWhy`, `makerWhy` | What each side did to its position: opened, took profit, stopped out, flipped (below) | | `sameOrder` | Whether the same taker order filled the trade before it | | `takerOrderId`, `tradeId` | Ids, on live trades; `null` in history | | `liquidation` | Whether the taker was being liquidated | | `taker`, `maker` | Wallets, where the source carries them; `null` in the terminal today | ### Sum the tape per bar Add each trade to a [tally](https://docs.0xarchive.io/terminal/guides/state#tallies) in `onTrade`, and read it in the chart's `onBar`. This is volume delta, in USD: ```ts indicator('Volume delta'); const chart = bars(); const tape = trades(); const delta = tally(); const deltaBars = plot.histogram('Delta $'); tape.onTrade((t) => delta.add(t.side === 'buy' ? t.notional : -t.notional)); chart.onBar(() => { if (!tape.available) return; deltaBars.set(delta.value, delta.value >= 0 ? color.up : color.down); }); ``` `minSize` and `minNotional` filter the stream, so `trades({ minNotional: 100_000 })` delivers only trades of $100k or more. ### Opening and closing trades 0xArchive records each trade's change in open interest (`oiDelta`), in the market's coin. With the taker's side it says what the trade did: | Taker trade | What happened | |---|---| | Buy, `oiDelta` above 0 | A new long | | Buy, `oiDelta` below 0 | A short bought back | | Sell, `oiDelta` above 0 | A new short | | Sell, `oiDelta` below 0 | A long sold out | An `oiDelta` of 0 means one side opened while the other closed. Hyperliquid and HIP-3 count both sides of open interest, Lighter longs only, as each venue's own open interest does. [Opening and closing flow](https://docs.0xarchive.io/terminal/examples/opening-closing-flow) and [Squeeze or new positions](https://docs.0xarchive.io/terminal/examples/squeeze-or-new-positions) are built on it. ### Why each side traded `oiDelta` says what a trade did to open interest; it cannot say which side did what. `takerWhy` and `makerWhy` can: each side's own position, before and after, as 0xArchive's who's-trading series buckets it. | Value | That side | |---|---| | `open_long`, `open_short` | Opened or added to a long (short) | | `tp_long`, `tp_short` | Reduced or closed a long (short) in profit | | `stop_long`, `stop_short` | Reduced or closed a long (short) at a loss, or was forced out by a liquidation or auto-deleveraging | | `flip_ls`, `flip_sl` | Went from long to short (short to long) in the one fill | | `settlement` | A settlement, which is no trade decision | So a taker buy with `takerWhy` `stop_short` is a short stopped out, and the same buy with `tp_short` is one taking profit, which `oiDelta` alone reads the same. Market makers' sides are tagged too. Either is `null` where 0xArchive could not vouch for the position, on Lighter, and from a server that does not send them yet. ```ts const stops = tally(); tape.onTrade((t) => { if (t.takerWhy === 'stop_long' || t.takerWhy === 'stop_short') stops.add(t.side === 'buy' ? t.notional : -t.notional); }); ``` ### Taker orders One market order fills against many resting orders, and each fill is a trade. `takerOrders()` joins the fills back into the orders that made them and calls `onOrder` once per order, once all its fills are in: ```ts const orders = takerOrders({ minNotional: 250_000 }); const sweeps = tally(); orders.onOrder((o) => { if (o.levels >= 3) sweeps.add(o.side === 'buy' ? o.notional : -o.notional); }); ``` | Field | What it is | |---|---| | `time`, `side` | Its fills' time and the taker's side: one taker order fills within one millisecond | | `size`, `notional`, `avgPrice` | The fills summed, in coin and USD, and the average price | | `fills`, `levels` | How many fills it took, and at how many prices | | `firstPrice`, `lastPrice` | Where it started and where it stopped: how far it walked the book | | `oiDelta` | Its fills' change in open interest summed, `na` if any fill's is unknown | | `liquidation` | Whether the taker was being liquidated | | `takerOrderId`, `taker` | The order id and wallet, on live trades; `null` in history | `minNotional` counts the whole order, so `takerOrders({ minNotional: 1_000_000 })` delivers $1M orders however many fills they took. A forming bar never sees part of an order, and history and live join the same way, by `sameOrder`. Lighter names no orders, so there every fill is an order of one. The reach is the trades': the chart's first bar, at most 7 UTC days back. To join fills yourself, a new order starts wherever a trade's `sameOrder` is false. [Large taker orders](https://docs.0xarchive.io/terminal/examples/large-takers) draws the ones of $2M or more as levels until price trades back, and [Opening sweeps](https://docs.0xarchive.io/terminal/examples/opening-sweeps) the orders that walked the book to open positions. ### Volume by price `volumeProfile()` sums the tape by price: what takers bought and sold at each price, over the current bar (`bar()`), the last few bars (`last(n)`), or since a time (`since(time)`), such as the session's start. Each span gives a profile with its totals, its `rows({ rowSize })`, its point of control (`poc()`) and its value area (`valueArea(70)`, by TradingView's rule): ```ts const profile = volumeProfile(); chart.onBar(() => { const session = profile.since(clock.startOf(chart.time, 'day')); const area = session.valueArea(70, { rowSize: 10 }); if (area !== null) poc.set(area.poc); }); ``` A row size puts rows on whole multiples of it, so a row is the same row on every bar; without one, each traded price is its own row. A profile is read in the run that asked for it. A span older than the trades (the chart's first bar, at most 7 UTC days back) reads [order flow by bar](#order-flow-by-bar-over-a-year) up to the trades and the trades from there, so it starts at the first whole bar at or after its start; where neither covers it, it reads `available: false`. [Footprint cells](https://docs.0xarchive.io/terminal/examples/footprint-cells) draws each bar's rows inside it, and [Session volume profile](https://docs.0xarchive.io/terminal/examples/session-volume-profile) the session's developing value area. #### Footprint rows `chart.rowSize` is the row size the chart's footprint draws: the reader's own, or what Auto picks at the chart's zoom. Pass it as the row size, and the rows a script marks sit on the footprint's rows, its point of control is the footprint's, and its imbalances are the ones the footprint shades: ```ts chart.onBar(() => { const poc = profile.bar().poc({ rowSize: chart.rowSize }); if (poc !== null && chart.close >= poc.high) marks.add({ low: poc.low, high: poc.high }); }); ``` A script that reads it runs again from its first bar when the size changes: when the reader picks another, or Auto steps to another as the chart zooms. Without a footprint on the chart it is the reader's size for the market, or one near a 5,000th of the price ($20 rows for BTC at 81,000), the same for the whole run. To bin trades by row yourself, as the flow setups below do, use `Math.floor(t.price / chart.rowSize)`. #### Flow setups A footprint shows where takers bought and sold. Each fill's `takerWhy` adds who they were, so a setup can ask what no footprint can: [Stacked imbalances above PoC](https://docs.0xarchive.io/terminal/examples/stacked-above-poc) marks buyers holding above the bar's busiest price; [Trapped traders](https://docs.0xarchive.io/terminal/examples/trapped-traders), new positions opened on the wrong side of it; [Stopped out at the extreme](https://docs.0xarchive.io/terminal/examples/stopped-at-extreme), stacks made by traders closing at a loss; and [Breakout with new money](https://docs.0xarchive.io/terminal/examples/breakout-new-money), whether a move out of the previous day's value area opened positions or closed them. ### Order flow by bar, over a year `orderFlow()` reads 0xArchive's order flow archive at the chart's interval: for each bar, what takers bought and sold at each price, and the bar's totals. It reaches as far back as the chart does (a year in a backtest), where `trades()` reaches 7 days, so a footprint, delta or CVD strategy can be backtested over a year: ```ts indicator('Delta and CVD'); const chart = bars(); const flow = orderFlow(); const delta = plot.histogram('Delta'); const cvd = plot.line('Session CVD'); chart.onBar(() => { const bar = flow.bar(); if (bar === null || !bar.available) return; delta.set(bar.delta); cvd.set(flow.cvd()); }); ``` | Read | What it gives | |---|---| | `bar()` | The newest bar closed as of the handler: in a bar's own handler, that bar. Its `rows` (price, `buyVolume`, `sellVolume`, `delta`, counts, notional), its totals, `minDelta` and `maxDelta` (the running delta's low and high after each trade, from 0 at the open), `liquidatedBuy` and `liquidatedSell`, `offBookVolume` and `peakSecond` (trades in its busiest second) | | `last(n)` | The newest `n` closed bars, oldest first, up to 2,000 | | `since(time)` | Rows summed from the first whole bar at or after `time`, with the span counted (`from`, `to`) | | `cvd()` | Cumulative delta in the market's coin: from 00:00 UTC of the bar's day by default, or `cvd('start')` from the first bar the order flow covers | Each bar holds every trade that filled against the book, as the venue's candles count them, so its volume and trade count equal the candle's. Backstop liquidations and auto-deleveraging did not trade against the book: they are counted beside the bar (`offBookVolume`, `offBookCount`), never in its rows. `orderFlow({ rowSize })` puts the rows on whole multiples of a row size (a whole multiple of the market's price step); without one each traded price is its own row. A bar is read once it has closed and never before, so a backtest never sees a bar early. The forming bar is not in it: live, read it from `trades()` or `volumeProfile().bar()`. Order flow starts on 22 March 2025 12:00 UTC for Hyperliquid perps and 22 December 2025 for HIP-3 at the earliest. On a chart, the bars after the archive's last closed hour come from the live trades as they close; there `offBookVolume` reads `na`, since the live tape does not tell those trades apart. A bar neither knows (a day not built yet) reads `available: false` with `na` values, never zeros, and `cvd()` reads `na` from the anchor through such a bar: the session's CVD comes back the next day, the start's does not. Rows are kept for the last 2,000 bars or 500,000 rows, whichever is fewer, and a bar older than that reads `available: false` with its totals. ### Intent flow by bar, over a year `intentFlow()` reads 0xArchive's intent flow archive at the chart's interval: for each bar, the trades summed by what each side did to its position, in the categories `takerWhy` and `makerWhy` name. Each category gives its volume, notional, VWAP and trade count, so a strategy on who opened, who took profit and who was stopped out can be backtested over a year, where `trades()` reaches 7 days: ```ts indicator('Stopped-out VWAP'); const chart = bars(); const intent = intentFlow(); const longsOut = plot.line('Longs stopped out, VWAP'); const shortsOut = plot.line('Shorts stopped out, VWAP'); const opened = plot.histogram('Opened, share of taker volume'); chart.onBar(() => { const bar = intent.bar(); if (bar === null || !bar.available) return; const t = bar.taker; longsOut.set(t.stop_long.vwap); shortsOut.set(t.stop_short.vwap); opened.set((t.open_long.volume + t.open_short.volume) / t.total.volume); }); ``` | Read | What it gives | |---|---| | `bar()` | The newest bar closed as of the handler: in a bar's own handler, that bar. Its `taker`, `maker` and `all` sides, each with a cell per category and `total` | | `last(n)` | The newest `n` closed bars, oldest first, up to 2,000 | | `available` | Whether `bar()` is a whole bar the archive knows | Each cell is `{ volume, notional, vwap, count }`: the size traded in the market's coin, the USD at the traded prices, their ratio, and the trades. A category with no trade in the bar reads 0, and its `vwap` reads `na`. | Category | That side | |---|---| | `open_long`, `open_short` | Opened or added to a long (short) | | `tp_long`, `tp_short` | Reduced or closed a long (short) in profit | | `stop_long`, `stop_short` | Reduced or closed a long (short) at a loss or flat, or was forced out by a liquidation or auto-deleveraging | | `flip_ls`, `flip_sl` | Went from long to short (short to long) in the one fill | | `settlement` | A settlement, which is no trade decision | | `unknown` | 0xArchive could not vouch for the position | | `total` | Every trade of the bar, whatever its category, `unknown` included | The categories come from each fill's position before and after it and its closed profit, not from the order that made it: "stop" is an exit at a loss or a forced one, not a stop order. A stop order that closes in profit is `tp_long` or `tp_short`. Each side counts every trade once, so `taker.total` and `maker.total` are both the bar's volume and trade count: every trade that filled against the book, as the venue's candles count them. `taker` is the aggressors, the side that moved price; `maker` is the resting orders they filled; `all` adds the two, every trade twice, so `all.open_long` is every long opened in the bar, by takers and makers alike. Sizes add in whole units of the market's size step, so a sum over many bars does not drift. A bar is read once it has closed and never before. Intent flow starts on 25 May 2025 14:24 UTC for Hyperliquid perps, the first minute in which every fill carries what its category is read from, and on 22 December 2025 for HIP-3, at the earliest. The archive holds closed hours: the forming bar, every bar after the archive's last closed hour, a day it has not built, and everything before its start read `available: false` with `na` values, never zeros. A bar it holds only the first part of reads `available: false` with `partial: true` and its sums so far. For the newest bars, sum `trades()` by `takerWhy` as [above](#why-each-side-traded). Every chart interval of a minute or more; seconds bars and bars that close on trades read `available: false`. ### Order flow by bar, without events Bars that close on trades (`t500`, `v1000000` and the rest) carry `buyVolume` and `sellVolume` on each bar. On time bars, read `orderFlow()` above, or sum `trades()`. ## Read liquidations in terminal scripts Follow liquidations two ways: the ones that happened, with the account liquidated, and the ones waiting, as the price levels where open positions would be liquidated. ### Liquidations that happened `liquidations()` delivers each liquidation to `onLiquidation`: `time`, `price`, `size`, `notional`, `side` (the side of the position liquidated, `'long'` or `'short'`) and `user`, the account. On Hyperliquid `user` is the wallet, lower-case; on Lighter it is an account index. Liquidations reach back 7 days. ```ts indicator('Liquidations', { precision: 0 }); const chart = bars(); const liq = liquidations({ minNotional: 10_000 }); const longs = tally(); const shorts = tally(); const longBars = plot.histogram('Longs liquidated $'); const shortBars = plot.histogram('Shorts liquidated $'); liq.onLiquidation((l) => (l.side === 'long' ? longs : shorts).add(l.notional)); chart.onBar(() => { if (!liq.available) return; longBars.set(-longs.value, color.down); shortBars.set(shorts.value, color.up); }); ``` ### When a bar is complete `available` is true once the bar's liquidations are all in. It says the bar is complete, not that the feed is healthy: liquidations arrive a little after the trades that caused them, so a closed bar waits for its own before it runs. Bars older than the 7 days of history read false, and the forming bar reads true once everything before it is in. - On the chart's own market, liquidations are complete to about 2 seconds before now, and a closed bar waits that long. The live feed opens with the last few minutes of liquidations, so once it has joined the history this holds within moments of the chart loading, reconnecting or switching market. When the live server holds fewer minutes (just after it restarts, or after a loss in its own feed), the stream reads `delayed` until the history reaches them, a few minutes at most. - A market other than the chart's has no live feed: its liquidations are complete only as far as the history has reached, a few minutes behind. A closed bar waits for that too, for up to 10 minutes. - Past the wait (3 minutes with the live feed joined), a bar runs with `available` false. Once its liquidations arrive, the script runs again from its first bar, so that bar and everything after it update. Alerts fire only on bars run live, not on that re-run. `liq.coveredTo` is the time the liquidations are complete to, and `liq.state` how the stream stands: | `state` | Meaning | | --- | --- | | `'loading'` | Nothing has arrived yet | | `'live'` | Complete to within seconds of now | | `'delayed'` | Complete to a few minutes behind: normal for a market other than the chart's, for a moment while the chart's live feed starts or reconnects, and for a few minutes when the live server holds fewer minutes than that | | `'retrying'` | A read failed and is asked again, and the coverage is not keeping up meanwhile | | `'unavailable'` | The market has no liquidations | Both describe the stream now, not as of the bar being run, so read them on the newest bar. A covered bar with no liquidations reads `available` true and an empty tally, so write `na` rather than 0 while a bar is pending: ```ts indicator('Net liquidations', { precision: 0 }); const chart = bars(); const liq = liquidations(); const longs = tally(); const shorts = tally(); const net = plot.line('Shorts minus longs liquidated $'); liq.onLiquidation((l) => (l.side === 'long' ? longs : shorts).add(l.notional)); chart.onBar(() => { if (!chart.confirmed) return; net.set(liq.available ? shorts.value - longs.value : na); if (chart.isLast && liq.state === 'retrying') log.warn('liquidations retrying, complete to', liq.coveredTo); }); ``` ### Follow wallets `input.addresses` gives the settings panel a wallet list, which keeps only valid addresses, lower-case. Skip the others in the handler: ```ts const wallets = input.addresses('Only these wallets', []); liq.onLiquidation((l) => { if (wallets.length > 0 && !(l.user !== null && wallets.includes(l.user.toLowerCase()))) return; (l.side === 'long' ? longs : shorts).add(l.notional); }); ``` Lighter names an account index rather than a wallet, which no address matches. One position is often liquidated in several fills a moment apart. To count liquidations rather than fills, treat a wallet's fills within a minute as one, as [Most-liquidated wallets](https://docs.0xarchive.io/terminal/examples/liquidated-wallets) does. ### Where liquidations would happen next `liquidationLevels()` is 0xArchive's estimate of where open positions would be liquidated: 40 levels over 10% either side of the mark, each with the USD of longs and of shorts liquidated there, about every 5 minutes. Read it in any handler; `levels()` is the snapshot as of that bar, sorted by price. ```ts const map = liquidationLevels(); chart.onBar(() => { if (!map.available) return; let shortsAbove = 0; for (const level of map.levels()) if (level.price > chart.close) shortsAbove += level.shortUsd; }); ``` Levels are Hyperliquid's, from 27 July 2026, kept for 7 days, and never interpolated between snapshots: a bar between two snapshots reads the earlier one. Levels far from the price stretch the price scale and squash the candles; plot them with `autoscale: false` so they are drawn where they fall without moving the scale. [Liquidation levels ahead](https://docs.0xarchive.io/terminal/examples/liquidation-levels-ahead) and [Liquidation clusters](https://docs.0xarchive.io/terminal/examples/liquidation-clusters) draw them. ## BTC options Read BTC options on any chart: every print, the orders they join into (blocks, screen combos and sweeps), and the dealers' exposure that the Dealer exposure panel draws. The options are always BTC's, whatever market the chart shows. ### Every print `optionTrades()` delivers each print to `onTrade`: `time`, `price` (the option's price in BTC), `size` (BTC of options), `notional` (the premium in USD), `side` (the taker's), `strike`, `expiry`, `type` (`'call'` or `'put'`), `iv` in percent, `markPrice`, `indexPrice`, and every field the exchange sends, such as `instrument`, `tradeId`, `blockTradeId` and `comboTradeId`. `block` is true for a leg of a block trade. Prints reach back 7 days, and new ones arrive live, about a second after they print. ```ts indicator('Call premium bought', { precision: 0 }); const chart = bars(); const prints = optionTrades({ minNotional: 10_000 }); const bought = tally(); const hist = plot.histogram('Calls bought $'); prints.onTrade((p) => { if (p.type === 'call' && p.side === 'buy') bought.add(p.notional); }); chart.onBar(() => { if (prints.available) hist.set(bought.value, color.up); }); ``` ### Orders: blocks, combos and sweeps `optionOrders()` joins prints into orders and delivers each one to `onOrder` once all its prints are in. An order is a block trade (`kind: 'block'`), a screen combo (`'combo'`), or one taker order in one millisecond (`'taker'`); a taker order of several prints is a sweep. Each carries `size`, `buySize` and `sellSize`, `callSize` and `putSize`, `premium` in USD and `premiumBtc`, `fills`, `strikes` and `expiries` (how many it took), `lowStrike`, `highStrike` and `side`, which is `'mixed'` when the legs went both ways, as in a spread. ```ts const orders = optionOrders({ minNotional: 250_000 }); const sweeps = tally(); orders.onOrder((o) => { if (o.kind === 'taker' && o.fills > 1 && o.callSize > o.putSize && o.side === 'buy') sweeps.add(o.premium); }); ``` ### Dealer exposure `dealerExposure()` is the Dealer exposure panel's model, a snapshot every 5 minutes: `spot`, dealers' totals at it (`gamma`, `charm`, `vanna`), the gamma `flip`, and `strikes()`, each strike's net dealer `position` and what it adds. Read it in any handler; it is the last snapshot at or before that bar. - **Gamma**, BTC of delta per $1,000 of price: positive, dealers sell rises and buy dips; negative, they chase moves. - **Charm**, BTC of delta per hour as time passes: positive, dealers sell; negative, they buy. - **Vanna**, BTC of delta per vol point of IV: positive, dealers sell as IV rises; negative, they buy. Dealer positions come from block trades by default, where the taker asked for the quote, so the dealer holds the other side. `dealerExposure({ model: 'all' })` counts every trade. Only the nearest expiry counts by default, as the panel opens; `expiries: 'all'` counts every one. Snapshots reach back 7 days, and start on 25 September 2026. ```ts const dealers = dealerExposure(); const flip = plot.line('Gamma flip'); chart.onBar(() => { if (dealers.available) flip.set(dealers.flip, dealers.gamma >= 0 ? color.up : color.down); }); ``` ## Outputs Show what a script found. Plots are declared at the top and set in the chart's handlers; drawings and tables are objects a handler creates and changes. ### Plots | Plot | What it draws | |---|---| | `plot.line` | A line, solid, dashed or dotted, or a staircase with `step` | | `plot.histogram` | Columns from a base, 0 by default, or bars `width` pixels wide | | `plot.area` | A line with its area filled, to a `base` or fading to the foot of the pane | | `plot.points` | Dots or crosses, joined by a line with `join: true` | | `plot.candles` | Candles of the script's own, or OHLC bars with `bars: true` | | `plot.arrows` | Arrows up or down, as tall as their value is large | | `plot.fill` | A shade between two plots or levels | | `plot.level` | A horizontal line across the pane, such as 70 on an RSI | | `plot.background` | A shade behind the whole height of the pane | | `plot.barColor` | The chart's own candles, recoloured | | `plot.cells` | Bands of price inside each bar, such as a footprint, and levels across each bar, such as its value area | `set(value, color)` sets the current bar; a plot not set on a bar is `na` there, and a line breaks across it unless it says `join: true`. A colour left out, or `null`, follows the theme's study palette. A line takes `glow` and a fill a `gradient` (see [Gradients and glow](#gradients-and-glow)). Up to 64 plots. ```ts const basis = plot.line('Basis', { width: 2 }); const upper = plot.line('Upper', { color: color.withAlpha(color.study(3), 0.6) }); const lower = plot.line('Lower', { color: color.withAlpha(color.study(3), 0.6) }); const band = plot.fill('Band', upper, lower, { color: color.withAlpha(color.study(3), 0.08) }); ``` ### Panes and scales An overlay script (`indicator(name, { overlay: true })`) draws on the price pane; any other draws in a pane of its own. A plot can choose with `pane`: `'price'`, `'own'`, or a name, which gives the script another pane. - `autoscale: false` draws a plot at its values without stretching the scale, for levels far from the price. - `range: { min: 0, max: 100 }` fixes the scale, as an RSI's. - `band: { top: 0.84, bottom: 0 }` draws the plot on a hidden scale in a slice of the pane, such as volume at its foot. - `offset` shifts a plot by whole bars, -500 to 500: positive draws into the space past the newest bar, like Ichimoku's leading spans. - `showLast: 50` draws only the newest 50 bars of a plot. - `indicator(name, { overlay: true, scale: 'own' })` draws the script's price-pane plots on one hidden scale of their own, over the candles without moving the price scale. ### Shapes and markers `plot.shape` draws a shape, a label or a character on the bars where `set(condition)` is true, at a fixed `location`. `plot.markers` adds any number of markers to a bar, each with its own position, shape, text and colour: ```ts const marks = plot.markers('Big orders'); chart.onClose(() => { if (buyUsd.value > 1_000_000) marks.add({ position: 'below', shape: 'circle', text: fmt.usd(buyUsd.value), color: color.up }); }); ``` ### Cells inside bars `plot.cells` draws bands of price inside each bar, each with a width, a colour and a number, as a footprint chart does. `add({ low, high, weight, value })` adds one to the current bar; every run of a bar starts with none, so add all the cells the bar should show. - `columns` (1 to 4) splits each bar side by side, two for sold × bought; a cell picks one with `column`. - `weight` sets the width. With `scale: 'bar'` (the default) the bar's largest weight fills its column; `'visible'` scales to the bars in view, and `'unit'` reads weights from 0 to 1. - `align` grows a cell from the column's `'left'` (the default), `'right'` or `'center'`, and lines its number up there. - `value` is the number written in the cell. A cell too small for it drops decimals, then shortens it (3.21K), then writes none; a bar's numbers step down together so they line up. `format` is `'compact'`, `'fixed'` or `'percent'`. - `candles` sets how the candle shows with the cells, with the footprint chart's Candle modes, drawn as the footprint draws them. `'overlay'` (the default) leaves the chart's own candles behind the cells. - `'body'`: the candle as a spine. Two columns hang either side of it in the middle of the bar; other counts sit to its right, the spine on the left edge. - `'backdrop'`: the body's rows shaded behind the cells and edged in the candle's colour, and the range from high to low framed by a hairline. The cells take the whole bar. - `'ticks'`: a line from high to low with the open's tick on its left and the close's on its right, where the spine would be. - `'off'`: no candle. The cells take the whole bar. With `'body'` and `'backdrop'`, bars 12 px apart or closer are plain candles, as on the footprint chart. A bar with no cells keeps a slim candle, or its ticks. The older `'side'` and `'hidden'` still work: they are `'body'` and `'off'`. To let the trader pick, pass an input: `candles: input.choice('Candle', 'body', ['body', 'backdrop', 'ticks', 'off'])`. ```ts const profile = volumeProfile(); const cells = plot.cells('Sold × bought', { columns: 2, candles: 'body' }); chart.onBar(() => { for (const row of profile.bar().rows({ rowSize: 10 }) ?? []) { cells.add({ low: row.low, high: row.high, weight: row.sell, value: row.sell, color: color.withAlpha(color.down, 0.3), column: 0, align: 'right' }); cells.add({ low: row.low, high: row.high, weight: row.buy, value: row.buy, color: color.withAlpha(color.up, 0.3), column: 1 }); } }); ``` Cells are bands of price, so they need bars wide enough to read: zoom in. A bar holds up to 1,024 cells and a plot 250,000. [Footprint cells](https://docs.0xarchive.io/terminal/examples/footprint-cells) is the whole script. #### Levels inside bars A cell with one `price` in place of `low` and `high` is a level: a line across its column at that price, in the same box as the bar's cells. On a footprint it spans the bar's cell column edge to edge, as the footprint's own value area lines do, so it lines up with the footprint's rows and columns; over candles it stops a few pixels short of each edge, so it never meets the next bar's. A dashed or dotted level starts and ends on a dash. Use it for a price that belongs to one bar, such as its value area high and low or its point of control. - `line` is `'solid'` (the default), `'dashed'` or `'dotted'`. - `text` is a short label on the line, up to 16 characters, in the line's colour unless `textColor` says otherwise. Without `text`, a level writes its `value` in the plot's format, if it has one. - `column`, `align` and `weight` work as they do for a band: `weight` makes the line part of the column's width, grown from `align`, and the label sits at that edge. - A label shows only where it fits: it needs room on its bar with some line left beside it, inside the pane, clear of the bar's other labels, its numbers and the candle behind it. Otherwise the line is drawn alone, so zoom in to read the labels. ```ts const profile = volumeProfile(); const levels = plot.cells('Value area', { color: color.neutral }); chart.onBar(() => { const area = profile.bar().valueArea(70, { rowSize: chart.rowSize }); if (area === null) return; levels.add({ price: area.high, line: 'dashed', text: 'VAH' }); levels.add({ price: area.low, line: 'dashed', text: 'VAL' }); }); ``` Levels count with the plot's cells, 1,024 a bar and 250,000 in all, so every bar of the history keeps its own; a drawing (`draw.line`) is for a line that spans bars. [Bar value area](https://docs.0xarchive.io/terminal/examples/bar-value-area) draws the same pair on every bar, without the labels. ### Footprints `plot.footprint` is a footprint of the script's own, drawn by the footprint chart type. A script adds amounts by price into up to 4 named **lanes**, and the chart offers it as a **Script** choice under **Data**, beside Bid × Ask. Everything the footprint does then applies to it: rows that follow the zoom, the shapes, the colours, the candle, the scales, the value area and POC, the statistics rows and the row readout. Five come with the chart: **Opens and closes**, **Stopped out**, **Stopped vs profit**, **Open interest** and **Makers opening** are under **Positions** in the chart-type menu, below Data. Picking one runs the example of the same name on the chart, without adding it to your scripts; any other Data choice stops it. They read who opened and who closed, which only Hyperliquid's fills carry, so on Lighter they are greyed. To change one, add its example as a script and edit it: yours is a **Script** choice. ```ts const tape = trades(); const fp = plot.footprint('Stopped out', { lanes: [ { id: 'longsStopped', label: 'Longs stopped', side: 'left', color: color.down }, { id: 'shortsStopped', label: 'Shorts stopped', side: 'right', color: color.up }, ], }); tape.onTrade((t) => { if (t.takerWhy === 'stop_long') fp.add('longsStopped', t.price, t.size); else if (t.takerWhy === 'stop_short') fp.add('shortsStopped', t.price, t.size); }); ``` - **Lanes** sit left or right of the candle, at most 2 a side; on each side the first declared sits nearest the candle. Each has its own colour, shaded by size, and `measure: 'count'` for amounts that are not sizes. - **`fp.add(lane, price, amount)`** is called from an event handler, such as `onTrade`, as a tally is (`OX1111`, `OX2108`): a forming bar's `onBar` runs again, and would count its trades twice. Prices snap to the market's step; `0` and `na` are left out, and an amount below 0 is an error, so a signed value goes into two lanes. - **An empty lane draws nothing**: no 0 and no dot. - **Shapes**, under **Shape** in the chart-type menu: **Cells** print each lane's number in its own column; **Profile** draws each lane as a bar in its column, as long as its amount; **Stacked** draws each price as one bar, as long as its total and split into the lanes' colours in the cells' order, with the total at its end. Every footprint example shows Cells and Stacked. - **Imbalances** are marked only between the pairs in `opposed`, a left lane against a right one, at the same price (`compare: 'row'`) or one row apart as Bid × Ask does (`'diagonal'`). With none, the footprint's Imbalances choices are off for this data. - **Statistics rows**: `stats` lists the rows offered first under the bars, each lane summed over the bar or `{ net: [a, b], label }`, one lane less another. The chart's own rows (volume, delta) stay in the picker. - A bar the script's trades do not wholly cover draws as a bar still loading. On a candle chart nothing is drawn, and the legend offers **Switch** to the footprint chart. [Opens and closes footprint](https://docs.0xarchive.io/terminal/examples/opens-closes-footprint), on the same bars in each shape: ![Opens and closes footprint as Cells: each lane's number in its own column](/images/terminal/examples/opens-closes-footprint.webp) ![Opens and closes footprint as Profile: each lane a bar in its column](/images/terminal/examples/opens-closes-footprint-profile.webp) ![Opens and closes footprint as Stacked: each price one bar, split into the lanes' colours](/images/terminal/examples/opens-closes-footprint-stacked.webp) A script draws one footprint; switch between views with an input. A bar keeps up to 4,096 prices and a plot 1,000,000 values, the oldest bars losing theirs first. [Opens and closes footprint](https://docs.0xarchive.io/terminal/examples/opens-closes-footprint) uses all four lanes. ### Heats `plot.heat` is a heat of the script's own: amounts by time and price, drawn behind the candles by the order book heatmap's painter. A column is a bar, rows group the market's step as you zoom, and the tone is the view's own scale, so it reads on a quiet market as on a busy one. ```ts const tape = trades(); const heat = plot.heat('Tape speed', { label: 'Prints', measure: 'count' }); tape.onTrade((t) => heat.add(t.price, 1)); ``` - **Carry.** A bar's own trades sit inside its range, behind its candle, so the chart carries each value into later bars. `carry: { fade: n }` halves a value every `n` bars (1 to 200, 10 by default), so a level glows and cools. `'hold'` keeps it whole until a later bar's range covers its price, as levels price never went back to. `'none'` draws each bar's own values only. It is the heat's default; the trader picks another in the heat's settings, and nothing reruns. - **One side or two.** One side takes a `label` and, optionally, a `color`: without one it draws on the order book heatmap's blue-to-gold ramp. Two take `sides`, each `{ id, label, color }`, and `heat.add(side, price, amount)`. `combine: 'net'` (the default) nets a row's sides, so a balanced row is quiet; `'larger'` draws the row's total in its larger side's colour. The first side is the negative one. A script's own colours that land close in a theme are turned apart; the theme's up and down stay. - **`heat.add`** is called from an event handler, as `fp.add` is (`OX1111`, `OX2108`). Prices snap to the market's step and amounts at one price add up; `0` and `na` are left out, and an amount below 0 is an error. - **`measure`**: `'size'` (the default) reads out in USD or coin, as the footprint's unit is set; `'count'` as counted. - The **legend** shows the carry in use and the scale's ends; the heat's settings (the script's **Heat** tab) hold **Carry**, **Opacity**, the newest bar at the right edge, and **Details on hover**: each side's value under the pointer, made in that bar or carried, and from when. - It draws on bars a fixed time apart up to a week, over the order book and liquidation heatmaps when they are on, under the candles and drawings. Not on trade, volume or range bars. A script draws one heat, with the footprint's limits: a bar keeps up to 4,096 prices and a heat 1,000,000 values. [Tape speed heat](https://docs.0xarchive.io/terminal/examples/tape-speed-heat), [Stopped-out heat](https://docs.0xarchive.io/terminal/examples/stopped-out-heat), [Makers opening heat](https://docs.0xarchive.io/terminal/examples/makers-opening-heat) and [Open interest heat](https://docs.0xarchive.io/terminal/examples/open-interest-heat) are the examples. ### Drawings `draw.line`, `draw.box`, `draw.label`, `draw.polyline` and `draw.linefill` place objects at times or bar numbers and prices, up to 500 bars into the future. A bar number may have a fraction: a bar's middle is its number, so `bar: chart.index - 0.5` is its left edge and `chart.index + 0.5` its right. They are made in the chart's handlers, and a drawing made while the forming bar updates is rolled back with it. Each kind is capped, 50 by default and at most 500 (`maxLines` and the others in `indicator`'s options), with the oldest removed first. A box with `border: null` draws no border. A common pattern draws only on the newest bar, with the cap set to what one bar draws, so each bar's drawings replace the last's: ```ts indicator('Range lines', { overlay: true, maxLines: 2 }); const chart = bars(); const high = ta.highest(50); const low = ta.lowest(50); chart.onBar(() => { const top = high.update(chart.high); const bottom = low.update(chart.low); if (!chart.isLast) return; draw.line({ from: { bar: chart.index - 50, price: top }, to: { bar: chart.index, price: top }, extend: 'right' }); draw.line({ from: { bar: chart.index - 50, price: bottom }, to: { bar: chart.index, price: bottom }, extend: 'right' }); }); ``` #### Pane and layer A drawing goes to its script's pane: the price pane for an overlay, else the script's first pane of its own. `pane` sends it elsewhere, with the choice a plot has: `'price'`, `'own'` or the name of a pane a plot of the script draws in. It is placed by that pane's scale, so an RSI script can mark its divergences on the candles at the candles' prices. A pane the script has no plot in is an error, never a drawing put somewhere else. A linefill is in its two lines' pane, which must be one pane. `layer: 'behind'` paints a drawing under the pane's series, the candles on the price pane, so an order block or a gap shades the bars it marks without hiding them; `'above'` paints it over them. `indicator(name, { layer: 'behind' })` sets it for the script's lines, boxes, polylines and linefills, as Pine's `behind_chart`. Labels stay above unless one says otherwise, so their text reads, and tables always show over the chart. ```ts indicator('RSI divergences', { maxLines: 40, maxLabels: 20 }); const chart = bars(); const rsi = ta.rsi(14); const lows = ta.pivotLow(5, 5); const highs = ta.pivotHigh(5, 5); const history = series(6); const line = plot.line('RSI'); // The last swing low and high: their bar, price and RSI. const lowBar = state.bar(-1); const lowPrice = state.bar(0); const lowRsi = state.bar(0); const highBar = state.bar(-1); const highPrice = state.bar(0); const highRsi = state.bar(0); // A divergence from one swing to the next: on the candles (pane: 'price') and on the RSI, its own pane. function mark(from: number, to: number, prices: [number, number], values: [number, number], bull: boolean) { const color = bull ? 'theme:up' : 'theme:down'; draw.line({ from: { bar: from, price: prices[0] }, to: { bar: to, price: prices[1] }, color, width: 2, pane: 'price' }); draw.label({ at: { bar: to, price: prices[1] }, text: bull ? 'Bull' : 'Bear', style: bull ? 'up' : 'down', color, size: 'small', pane: 'price' }); draw.line({ from: { bar: from, price: values[0] }, to: { bar: to, price: values[1] }, color, width: 2 }); } chart.onBar(() => { const value = rsi.update(chart.close); history.set(value); line.set(value); const swingLow = lows.update(chart.low); const swingHigh = highs.update(chart.high); // A swing is known 5 bars after it. const at = chart.index - 5; const then = history.ago(5); if (!isNa(swingLow)) { // A lower low in price on a higher low in RSI. if (lowBar.value >= 0 && swingLow < lowPrice.value && then > lowRsi.value) mark(lowBar.value, at, [lowPrice.value, swingLow], [lowRsi.value, then], true); lowBar.value = at; lowPrice.value = swingLow; lowRsi.value = then; } if (!isNa(swingHigh)) { // A higher high in price on a lower high in RSI. if (highBar.value >= 0 && swingHigh > highPrice.value && then < highRsi.value) mark(highBar.value, at, [highPrice.value, swingHigh], [highRsi.value, then], false); highBar.value = at; highPrice.value = swingHigh; highRsi.value = then; } }); ``` ### How drawings look A line, a polyline and a border are 1 to 20 pixels wide (`width`), and a dashed or dotted one keeps its dashes as it widens. `arrow: 'start'`, `'end'` or `'both'` puts an open arrowhead on a line's ends, or an open polyline's. A vertical line with `extend` runs to the pane's top and foot. A box with `extend: 'right'` (or `'left'`, `'both'`) runs to the pane's edge and keeps its top and bottom, as a zone that holds until price trades through it does. Its `text` may have several lines (`\n`), and takes: - `textSize`: a size, `'small'` by default, or `'auto'` for the largest that fits the box. - `textAlign` (`'left'`, `'center'`, `'right'`) and `textValign` (`'top'`, `'middle'`, `'bottom'`): together they put a tag in any corner, or on any side. - `textWrap: true` to break long lines at spaces, at the box's width. - `textBold`, `textItalic` and `textFont: 'mono'`. The text stays 4px inside the box, clear of its border, and is cut there: it never draws outside the box. A label with `location: 'above'` sits over its bar's high, and `'below'` under its low, a few pixels clear at any zoom, as a `plot.shape` there does; its point's price is not read, so `na` is fine. Give it style `'down'` above the bar and `'up'` below it, so its pointer points at the bar. Labels also take `italic`, `font: 'mono'` and `textAlign` for the lines of a label with several, and table cells take `italic` and `font`. A polyline with `curved: true` is a smooth curve through every point. ```ts indicator('Order blocks', { overlay: true, maxBoxes: 3, maxLabels: 2, maxLines: 1, maxPolylines: 1 }); const chart = bars(); const high = ta.highest(30); const low = ta.lowest(30); chart.onBar(() => { const top = high.update(chart.high); const bottom = low.update(chart.low); if (!chart.isLast) return; const mid = (top + bottom) / 2; // A zone that holds until price trades through it, with its tag in the top-left corner. draw.box({ from: { bar: chart.index - 24, price: top }, to: { bar: chart.index - 20, price: mid + (top - mid) * 0.6 }, extend: 'right', fill: color.withAlpha(color.down, 0.12), border: { color: color.down }, text: 'OB 1h', textAlign: 'left', textValign: 'top', textColor: color.down, textBold: true, }); draw.label({ at: { bar: chart.index - 20, price: na }, text: 'HH', location: 'above', style: 'down', color: color.down }); draw.label({ at: { bar: chart.index - 8, price: na }, text: 'LL', location: 'below', style: 'up', color: color.up }); draw.line({ from: { bar: chart.index - 8, price: bottom }, to: { bar: chart.index, price: mid }, color: color.up, width: 2, arrow: 'end' }); draw.polyline({ points: [{ bar: chart.index - 24, price: top }, { bar: chart.index - 14, price: mid }, { bar: chart.index - 8, price: bottom }], curved: true, color: color.neutral, style: 'dotted' }); }); ``` ### Tooltips and axis tags A label, a box, a shape, a marker or a cell can carry a `tooltip`: resting the pointer on it shows the text in the chart's readout card, beside it, as a Pine label's tooltip shows. Split lines with `\n`; the first is the card's heading, and a line written `Name: value` reads as a name and its value. Where several overlap, the one drawn on top reads. A shape plot takes one `tooltip` for every bar, and `set(true, { tooltip })` gives a bar its own. ```ts indicator('Pivots', { overlay: true, maxLabels: 50 }); const chart = bars(); const pivot = ta.pivotHigh(5, 5); chart.onClose(() => { const high = pivot.update(chart.high); if (!Number.isFinite(high)) return; draw.label({ at: { bar: chart.index - 5, price: high }, text: 'PH', style: 'down', tooltip: `Pivot high\nPrice: ${fmt.price(high)}\nBars each side: 5` }); }); ``` `axisLabel: true` on a horizontal `draw.line` (both ends at one price) or on a `plot.level` shows its price as a tag on the price axis, styled as a plot's last-value tag, so key levels such as the prior day's high and low read off the scale. The axis spreads overlapping tags apart, as it does the plots'. ```ts draw.line({ from: { bar: chart.index - 20, price: dayHigh }, to: { bar: chart.index, price: dayHigh }, extend: 'right', axisLabel: true }); ``` ### Gradients and glow A box's or polyline's `fill`, a linefill's `color` and a `plot.fill`'s `gradient` take a gradient as well as a colour: `{ top, bottom }` runs down the shape, `{ left, right }` across it, and an end left out fades the other end's colour to nothing. `glow` on a line, a polyline, a box's or label's `border`, or a `plot.line` draws a soft glow in the line's own colour under it: `true` for 8px, or 1 to 24. Labels also take `bold`, `padding` (0 to 16px, 6 by default) and a `border`. A fill's `setGradient(top, bottom, topColor, bottomColor)` shades one bar from a colour at one price to another at a second price, as a TradingView gradient fill does. ```ts indicator('Glow box', { overlay: true, maxBoxes: 2, maxLines: 2, maxLabels: 1 }); const chart = bars(); const high = ta.highest(20); const low = ta.lowest(20); const violet = '#A78BFA'; chart.onBar(() => { const top = high.update(chart.high); const bottom = low.update(chart.low); if (!chart.isLast) return; const mid = (top + bottom) / 2; const from = chart.index - 20; // Two halves, each brightest at its edge, and edges that glow. draw.box({ from: { bar: from, price: top }, to: { bar: chart.index, price: mid }, border: null, fill: { top: color.withAlpha(violet, 0.25), bottom: color.withAlpha(violet, 0.03) } }); draw.box({ from: { bar: from, price: mid }, to: { bar: chart.index, price: bottom }, border: null, fill: { top: color.withAlpha(violet, 0.03), bottom: color.withAlpha(violet, 0.25) } }); for (const price of [top, bottom]) draw.line({ from: { bar: from, price }, to: { bar: chart.index, price }, color: violet, glow: 6 }); draw.label({ at: { bar: from, price: top }, text: 'RANGE', style: 'lowerLeft', color: color.none, textColor: violet, bold: true }); }); ``` ### Tables `draw.table({ position, columns, rows })` puts a table in one of nine positions of the script's pane, or of the pane its `pane` names, clear of the legend and the price axis; it may be made at the top. `cell(column, row, text, options)` writes a cell, with colours, size, alignment, a tooltip, `bold` text and a `meter`, a rounded bar after the text filled to a `value` from 0 to 1; `merge` spans cells. Write the cells on the newest bar only (`chart.isLast`). Text is shown as text: no markup, links or images, at most 500 characters. Up to 9 tables. ### Canvas `draw.canvas()` is for what no other output draws: a profile docked to the right edge, a glyph of your own, a readout that stays in a corner. It is the place a study that paints its own pictures, such as one ported from an `OnRender` method, does its painting. A script never sees pixels, so where such a study would ask the chart for a bar's x and a price's y and paint there, a canvas says where each point is and the chart works out the pixels on every frame: - across, a `bar` (fractions allowed) or a `time`, or `left` or `right` pixels in from that edge of the pane; - down, a `price`, or `top` or `bottom` pixels in; - then `dx` and `dy` move it by pixels. So `{ price: p, right: 40 }` is 40px in from the right edge at price `p`, and `{ left: 8, top: 8 }` stays in the top-left corner however the chart scrolls. Because the chart places the points, a canvas follows a pan, a zoom, a resize and a scale move without the script running again. `canvas.set(shapes)` replaces what it draws: `rect` (a fill, a gradient, a `border`, a `radius`), `line`, `path` (`closed`, filled or outlined), `text` (`align`, `valign`, `size`, `bold`, `mono`, up to 200 characters) and `arc` (a circle, or `start` to `end` degrees). Every shape takes `alpha`, and colours are the theme's tokens or your own, as everywhere else. Shapes paint in order, later ones on top, above the candles with the other drawings, or under them with `draw.canvas({ layer: 'behind' })`. A canvas holds up to 2,000 shapes and 10,000 points; a script up to 8 canvases. Set it on the newest bar (`chart.isLast`), as an `OnRender` paints the picture of now: ```ts indicator('Last close tag', { overlay: true }); const chart = bars(); const tag = draw.canvas(); chart.onBar(() => { if (!chart.isLast) return; // A tag 8px in from the right edge at the close, whatever the zoom. tag.set([ { type: 'rect', from: { price: chart.close, right: 88, dy: -10 }, to: { price: chart.close, right: 8, dy: 10 }, fill: color.panel, border: { color: color.neutral }, radius: 4 }, { type: 'text', at: { price: chart.close, right: 48 }, text: fmt.price(chart.close), align: 'center', mono: true }, ]); }); ``` The [Docked session profile](https://docs.0xarchive.io/terminal/examples/docked-profile) example draws a whole profile this way. ### Graphs Some reads have no place on a time axis: volume by hour of the day, the return after each RSI reading, venues side by side. `graph(title, { axis })` makes a chart with an axis of its own, which shows in a **Script panel** of the workspace. The script's legend on the chart opens it, from its **Graphs** button or its menu. | Axis | Keys | |---|---| | `'category'` | Names, such as `'14:00'` or `'Asia'`, in the order first set | | `'number'` (the default) | Numbers, spaced by value, such as an RSI of 30 | | `'time'` | Times, spaced by time | Each graph holds up to 8 series, `bars`, `line` or `points`, set by key from the chart's handlers. Setting a key again replaces its value, and a set made while the forming bar updates is rolled back with it, as a plot's is. ```ts const byHour = graph('Average volume by UTC hour', { axis: 'category' }); const volume = byHour.bars('Volume'); const sums = state.map(24); const counts = state.map(24); chart.onBar(() => { const hour = `${clock.parts(chart.time).hour}:00`; const n = (counts.get(hour) ?? 0) + 1; counts.set(hour, n); sums.set(hour, (sums.get(hour) ?? 0) + chart.volume * chart.close); volume.set(hour, sums.get(hour)! / n); }); ``` `format: 'percent'` writes values with a % sign (set them in percent) and `precision` fixes their decimals. A value's own colour, `set(key, value, color.up)`, overrides the series'. `stack: true` stacks a graph's bars, each key's series on top of the one before, as shares of a whole are. Up to 8 graphs per script and 1,000 keys per series. [Volume by hour](https://docs.0xarchive.io/terminal/examples/volume-by-hour) and [Return after RSI](https://docs.0xarchive.io/terminal/examples/rsi-forward-returns) are whole scripts. ### Panels Some reads are not about one chart at all: twenty markets side by side, a ranking, where each market sits on a map. A **panel script** runs in a Script panel of its own instead of on a chart. `indicator('Market Read', { panel: { market: 'BTC', interval: '1h' } })` names the market whose bars clock it and their interval; the panel's settings change both. Adding one from a chart's **Indicators** opens a Script panel, and the panel's own menu picks any script that has panel blocks. A panel shows the script's blocks in the order they were made, one or two columns wide: | Block | Holds | |---|---| | `panel.stats(title)` | Stat tiles: a row of large values, each set by label, with a note | | `panel.table(title, { columns })` | Rows set by key, sortable by any column; a `market` column's names show that market on the linked charts | | `panel.scatter(title, { x, y, quadrants })` | Points set by key, each with an optional label, note and `tail` of earlier positions | | `graph(title)` | A graph, as above | Blocks are made at the top level and set from the clock's handlers, like plots; a set made while the forming bar updates is rolled back with it. Set them on the newest bar (`chart.isLast`) unless every bar's value matters. ```ts indicator('Three majors', { panel: { market: 'BTC', interval: '1h' } }); const names = ['BTC', 'ETH', 'SOL']; const legs = names.map((m) => bars({ market: m })); const chart = bars(); const table = panel.table('Markets', { columns: [{ title: 'Market', format: 'market' }, { title: 'Change', format: 'percent', precision: 2, signed: true }], sort: 'Change', }); chart.onBar(() => { if (!chart.isLast) return; names.forEach((m, i) => table.row(m, [m, (legs[i].close / legs[i].open - 1) * 100])); }); ``` A scatter's `quadrants` names the four corners about zero, top left, top right, bottom left, bottom right, each a label or `{ label, color }`. Its axes are fitted to the points; `scale: 'sqrt'` spreads a cluster near zero. A point's `tail` is up to 30 earlier `[x, y]` positions, oldest first, drawn fading behind it, as a relative rotation graph draws them. Up to 16 blocks per script, 1,000 rows each. [Market Read](https://docs.0xarchive.io/terminal/examples/market-read) is a whole panel script. ### In lists The watchlist and In play can show any script that reads only bars as a column: one value per market, which sorts like any other column. The reader picks the script from the Columns menu, then its plot, its timeframe and its inputs. A cell reads the last bar that closed; the watchlist also offers Live, the forming bar. A plot on the price scale shows how far price is from it ("vs EMA 200", -4.92%), since a price cannot be compared across markets; a plot in a pane of its own shows its value. A script can keep a reading just for lists: a plot that is `hidden` and has `legend: false` is never drawn and never in the legend, and a column starts on it. Supertrend's Direction counts the bars of the current trend, + up and - down, so a list sorts by how long each market has trended: ```ts const direction = plot.line('Direction', { hidden: true, legend: false, precision: 0 }); const streak = state.bar(0); chart.onBar(() => { const value = trend.update(chart); if (value.direction === 1 || value.direction === -1) { streak.value = Math.sign(streak.value) === value.direction ? streak.value + value.direction : value.direction; direction.set(streak.value, value.direction > 0 ? color.up : color.down); } }); ``` A cell takes its colour from the bar's: `color.up` and `color.down` colour it, any other colour leaves it plain. A head reads the script's short name and its first two number inputs ("Supertrend 10 3"), so a `shortName` keeps it short. A script that reads trades, the book, open interest or any other stream is not offered as a column yet. ### Text and colour - `fmt.price(x)` writes a price to the market's precision; `fmt.usd(x)` writes `$1.2M`; `fmt.pct(0.0123)` writes `1.23%`; `fmt.num` and `fmt.compact` the rest. - `color.up`, `color.down`, `color.neutral` and `color.panel` are the theme's, and `color.study(i)` its study palette, so a script follows the reader's theme. `color.withAlpha(c, a)`, `color.mix(a, b, t)` and `color.rgb` make others. - A plot's colour in the settings' Style tab, and a colour input's, has an opacity slider: a reader can make any plot translucent, kept as `#rrggbbaa`. - `color.none` draws nothing, on the whole plot or on one bar. A plot declared with it, such as a fill's edge, stays out of the settings' Style tab. A value only for the legend is a plot set each bar in a clear colour, `color.withAlpha(color.up, 0)`: the legend names it in that colour, opaque, and nothing is drawn. - A plot on the price chart shows its legend value as a price unless it sets `precision`; with one, it reads as a number with its `unit`, such as a lean of `-12%`. - `format` says how values print in the legend, on the axis and in list columns: `'volume'` compact (1.2K, 3.4M, 5.6B), `'price'` as the market prints prices, `'mintick'` rounded to the market's tick, `'percent'` with a % sign (set the values in percent). On `indicator()` it applies to every plot off the price pane's own scale; on a plot, to that plot wherever it draws. A cumulative delta reads `1.89B` with `plot.line('CVD', { format: 'volume' })`. With `precision` too, volume keeps that many decimals in its unit (`1.886B` at 3) and a price that many places. ### Alerts `alert(name, { message })` declares an alert at the top, which the reader arms on the chart; `fire(condition, message)` fires it from a handler. An alert fires at most once per bar, only on live data, and by default only when a bar closes; `onForming: true` also fires on the forming bar, which repaints. Alerts fire in the browser while the chart is open. ## Add script inputs Let the reader tune a script without editing it. Each `input.*` at the top declares a setting in the chart's settings panel and returns its value. Changing one runs the script again from its first bar. | Input | The setting | |---|---| | `input.int`, `input.float` | A number, with `min`, `max`, `step` and a `unit` (`'usd'` or `'bps'`) its field shows | | `input.bool` | A switch | | `input.string` | Text | | `input.choice` | One of a list of strings | | `input.source` | A bar value such as `close` or `hl2`, read with `chart.source(name)` | | `input.color` | A colour; `null` follows the theme | | `input.time` | A moment picked by clicking the chart, `null` until picked | | `input.price` | A price, typed or picked by clicking the chart, and with `drag: true` a line to drag | | `input.interval` | An interval; `'chart'` is the chart's own | | `input.market` | A market such as `ETH` or `xyz:GOLD`; `null` is the chart's | | `input.addresses` | A list of wallet addresses, lower-case | | `input.markets` | A list of markets, such as a basket, at most 50 | ```ts const length = input.int('Length', 20, { min: 1, max: 500 }); const source = input.source('Source', 'close'); const against = input.market('Against', 'ETH'); const corner = input.choice('Position', 'top-right', ['top-left', 'top-right'], { legend: false }); ``` - `group` puts inputs under a heading, `inline: true` on the row of the one before, and `tooltip` explains one. - The legend names a script with its numbers, sources, choices and intervals, as in "RSI 14 close". `legend: false` keeps an input out of it, for a setting that says where something draws rather than what it computes, and `indicator(name, { legendInputs: false })` keeps all of them out, so the legend reads the script's name alone. ### What changing an input does Every input is read once, at setup, so its value is a plain constant everywhere in the script: use it to size an indicator (`ta.ema(length)`), to pick a market for a stream, or in any handler. Changing it in the settings panel runs the script again from its first bar with the new value, so the whole history is drawn as if it had always been set that way. - An `input.time` starts `null`, and the settings panel offers **Pick on chart**: the reader clicks a bar, and the script reads its time. Draw nothing until one is picked, or start from the first bar. - An `input.price` is a field the reader types in, with **Pick** beside it: the reader clicks the chart at a price, and the field takes it to the market's decimals. With `drag: true` the price is also a line on the chart, labelled with the input's name, and dragging it sets the input, as an entry or a stop is set on a risk and reward tool. A `null` default leaves it empty, reading `null` until set; any value is above 0. - `confirm: true` on an `input.price` or `input.time` asks for it as soon as the script is added: the chart says which input it wants and takes the next click, one input at a time, as Pine's `confirm = true` does. Escape skips the rest; the settings keep every input editable. - An `input.interval` set to `'chart'` follows the chart: the script reads the chart's own code, such as `'15m'`, and `bars({ interval })` with it is the chart's own stream. - An `input.market` left `null` follows the chart's market, so `bars(against === null ? {} : { market: against })` reads the chart itself. - `input.addresses` takes pasted addresses; the script receives only the valid ones, lower-case. - `input.markets` lists markets as chips, each added with the market picker. Open a stream per market with `markets.map((m) => bars({ market: m }))`. ## Missing values Handle data that is not there. A missing number is `na`, a float NaN, as in Pine; missing strings, colours and objects are `null`. - Arithmetic with `na` gives `na`, and every comparison with it is false, including `na === na`. - `isNa(x)` tests for it; `nz(x, replacement)` replaces it, with 0 by default. - A plot set to `na` draws nothing on that bar: a line breaks there unless it says `join: true`. - An indicator updated with `na` follows TradingView's rule for that indicator. Because comparisons with `na` are false, test for the condition you want rather than its opposite: ```ts // Draws nothing until the EMA has a value, then colours each bar. const value = ema.update(chart.close); if (!isNa(value)) line.set(value, chart.close > value ? color.up : color.down); ``` ### Missing strings, colours and objects Anything that is not a number is `null` when it is missing: a market input left on the chart's own, a colour input that follows the theme, the wallet on a Lighter liquidation. Check before using one, as for any nullable value in TypeScript: ```ts liq.onLiquidation((l) => { if (l.user === null) return; seen.set(l.user, (seen.get(l.user) ?? 0) + l.notional); }); ``` A colour of `null` passed to a plot's `set` means the plot's own colour, not none; use `color.none` to draw nothing on that bar. ### In state and history A series bar that was never set reads `na`, and so does `ago(n)` before the first bar. A `state.bar(na)` cell is a common way to mean "not known yet": the first bar that knows the value writes it, and every bar after reads it. ```ts const firstClose = state.bar(na); chart.onBar(() => { if (isNa(firstClose.value)) firstClose.value = chart.close; change.set(chart.close / firstClose.value - 1); }); ``` ### Where data starts Each stream has a start: trades the chart's first bar or 7 UTC days back, whichever is later, liquidations 7 days back, the order book 2026-09-06, order flow by bar 22 March 2025 (Hyperliquid perps) and 22 December 2025 (HIP-3) at the earliest. Before it, a stream's `available` is false and its values are `na`. Check `available` before using a stream, so older bars stay empty instead of showing zeros: ```ts chart.onBar(() => { if (!tape.available) return; deltaBars.set(delta.value); }); ``` ## Pine Script Bring an indicator or a strategy from TradingView. Paste a Pine Script® v5 or v6 `indicator()` or `strategy()` script into the script editor and it is translated into a TypeScript script when it loads, with any problems reported against your Pine line numbers. **Show as TypeScript** in the editor shows what it became, to read or keep editing. Pine Script is a registered trademark of TradingView, Inc. ### How Pine maps to a script | Pine | Here | |---|---| | A plain variable | A local inside the chart's `onBar` | | `var x = ...` | `const x = state.bar(...)` at the top | | `varip x = ...` | `const x = state.live(...)` | | `x[n]` | A `series` read with `.ago(n)` | | `ta.ema(src, 20)` | An instance per call, `ta.ema(20)`, updated where the call was | | `request.security(syminfo.tickerid, tf, expr)` | A second `bars({ interval })` stream, read closed only | | `request.security` on another ticker | A stream on that market, for Binance, Bybit and OKX crypto tickers | | `request.footprint`, `footprint.*` | Built from `trades()`, where the trade history reaches | | `plot`, `plotshape`, `plotarrow`, `plotcandle`, `plotbar`, `fill`, `bgcolor`, `barcolor`, `hline` | `plot.line` and the other plots, with their styles, widths, `show_last` and `display` | | `line.*`, `label.*`, `box.*`, `polyline.*`, `table.*` | `draw.*`, drawn as Pine scripts expect: arrow styles, widths to 20, extended boxes, box text with its size, alignment and wrapping, `yloc.abovebar` and `belowbar`, curved polylines, and monospace, bold and italic text | | `force_overlay = true` on `line.new`, `label.new`, `box.new`, `polyline.new`, `table.new` | `pane: 'price'` on the drawing | | `behind_chart` (true by default) | `layer: 'behind'` on an overlay's lines, boxes, polylines and linefills; labels and tables stay over the candles | | `alertcondition` | `alert` | | `strategy(...)` | `strategy(...)`, with the capital, the leverage its margins allow and `process_orders_on_close` | | `strategy.entry`, `strategy.order`, `strategy.close`, `strategy.close_all` | Targets that fill at the next open, or at a stop or limit price | | `strategy.exit` | `strategy.exit`: a stop and a limit that cancel each other, with `loss` and `profit` in ticks from the entry | | `strategy.position_size`, `position_avg_price`, `equity`, `opentrades`, `closedtrades`, `netprofit`, `openprofit` | `strategy.position` and the account | `request.security` reads what the other timeframe had closed, which is Pine's behaviour with lookahead off; the public API has no way to look ahead. ### Strategies A pasted strategy runs as a [strategy](https://docs.0xarchive.io/terminal/guides/strategies) here: an equity curve beside buy-and-hold, its fills on the chart and the Strategy report. Its orders keep Pine's rules. An entry the other way reverses the position. One the same way adds only while the entries are under `pyramiding`. An entry's size is its `qty` in coins, or the declaration's default: coins, USD or a percent of equity. Fills follow TradingView's strategy tester. A market order placed on a bar's close fills at the next open. A stop or limit fills where price first reaches it inside a bar: from the open to the nearer of the high and low, then the other, then the close. Costs are not the script's. It pays the market's own fees (a maker fee for limit fills), the order book's slippage and funding, so `commission_value` and `slippage` are left out with a note. The result is what the trades would have cost here, and it will not match TradingView's number when the script assumed no costs. Not supported, each refused with a message on its line: trailing stops (`trail_points`, `trail_offset`, `trail_price`), partial exits (`qty_percent` under 100), `oca_name` groups, stop-limit orders (`limit` and `stop` together), per-trade reads past the first open trade (`strategy.closedtrades.*`), and `strategy.risk.*` other than `allow_entry_in`. A plot option the chart cannot draw, such as a `format` on one plot or `fillgaps`, is named in a `PN2020` note when the script loads rather than left out without a word. ### What it refuses Each with a message saying what to do: - Pine v4 and older: TradingView's Pine Editor converts a script to a newer version. - `import` of libraries. - Data only TradingView has: `request.financial`, `request.economic`, `request.earnings`, `request.dividends`, `request.splits`, `request.seed` and `request.quandl`, and macro tickers such as `TVC:DXY`. Diagnostics from the translation start with `PN`: `PN1xxx` parsing, `PN2xxx` types and meaning, `PN3xxx` not supported. ### Credits The numeric rules of the `ta` library (seeds, the order of operations, `na` handling) follow TradingView's built-ins as PyneCore records them. Powered by PyneSys ([pynesys.io](https://pynesys.io)). ## Limits and determinism Know the limits a script runs within. They are the same on every device and every plan. | Limit | Value | |---|---| | Steps (loop iterations and function calls) | 10 million for setup, per batch of 512 bars, and per live update | | Plots | 64 | | Series lookback | 5,000 bars | | `tallyBy` keys | 10,000 | | State lists and maps | 100,000 entries | | Drawings | 50 per kind by default, 500 at most | | Tables | 9 | | Cells | 1,024 per bar, 250,000 per plot | | Graphs | 8 per script, 8 series each, 1,000 keys per series | | Labels and table cells | 500 characters | | A slice of a run | 5 seconds | | A run, over all its slices | 60 seconds | Past the step budget a script stops with `OX2200`, naming the line of the loop or call, and keeps what it had drawn. Counting steps rather than time makes the limit behave the same on a phone and a desktop. A model's refit or a matrix decomposition counts too, about n³ steps for n inputs, so `ml.pca` refitting 30 inputs on every bar runs out where `refit: 'auto'` does not. ### Long runs A run replays every loaded bar, and every chart's scripts share one worker. So a run hands the worker back about every 50 ms, between batches of 512 bars, and picks up where it stopped: other scripts keep updating while a heavy one works, and its legend says how far it has got ("Calculating 40%"). The chart keeps the run before until the new one has finished, and the result is the same wherever the pauses fall. - A slice that takes more than 5 seconds is stopped, and the same script with the same settings is not loaded again on the page until you change it. - A run that works more than 60 seconds over all its slices stops with `OX2201`. Do less per bar: refit less often, use fewer inputs or a shorter window, or load less history. ### Keeping a script fast - Work per bar, not per bar times history: keep running totals in [state](https://docs.0xarchive.io/terminal/guides/state) rather than looping back over old bars. - Draw only on the newest bar (`chart.isLast`) when only the newest bar's drawing matters. - Sum events into tallies in their handlers; do the per-bar work once in `onBar` or `onClose`. ### The same result everywhere A script gives the same output for the same data in every browser: - no clock, timers or `Math.random`: `random(seed)` gives the same numbers for the same seed; - `Math` is the engine's own, a port of fdlibm, so `exp`, `log`, `pow` and the trigonometric functions give the same bits in Chrome, Safari and Firefox; - `ta.*` follow TradingView's formulas, seeds and running sums. Scripts run in a worker of their own, served with a policy that allows no network access, and output is checked against the script's declaration before it is drawn. ## Tools for agents Have an AI write scripts for you. The whole reference comes as one text file, and every problem the editor reports has a stable code a model can act on. ### The reference for an AI [scripting/llms.txt](https://terminal.0xarchive.io/scripting/llms.txt) indexes the whole scripting reference: these guides, each section of the API's TypeScript declarations, every diagnostic code, every example and every built-in indicator, each a file of its own with its size, so a model reads only what the script needs. [llms-full.txt](https://terminal.0xarchive.io/llms-full.txt) is all of it in one file, about 140,000 tokens, for a model with room to read it whole. Both are built from the same sources as these pages and the engine, so they match what the terminal runs. Give a model the index with your request, then paste the script into the editor. ### What to ask for A model writes a better script when the request says what it should read and draw. Name: - the data: the chart's bars, another interval or market, the tape, liquidations, liquidation levels, the order book, open interest, funding or breadth; - what to plot and where: on the price pane, in a pane of its own, as a line, bars, markers or a table; - the settings the reader should be able to change; - what should happen on the bar still forming: follow the price live, or wait for the bar to close. For example: "Using the 0xArchive scripting reference, write a script that plots, in its own pane, the USD of long liquidations less short liquidations on each bar, with a setting for the smallest liquidation to count, and marks bars where more than $5M of longs were liquidated." The rules a model most often breaks are in [how a script runs](https://docs.0xarchive.io/terminal/guides/how-scripts-run): constructors only at the top, persistent values as declared state, and indicators updated on every bar. ### Fixing what it wrote The editor checks a script as you type and lists each problem with its line and a code, such as `OX1003` for a top-level `let`. Give the model the list: each code's entry in [diagnostics](https://docs.0xarchive.io/terminal/reference/diagnostics) says what is wrong and what to do. Codes never change meaning, so a fix-up loop can key on them. `OX9xxx` codes are the engine's own failures, never the script's. ## Diagnostic codes | Code | Severity | What | What to do | |---|---|---|---| | OX1000 | error | The source does not parse. | Fix the syntax at the line shown. | | OX1001 | error | The script must start with indicator(...), strategy(...) or algo(...). | Make `indicator(name, options)`, or `strategy(name, options)` for a strategy, or `algo(name, options)` for an algo, the first statement. | | OX1002 | error | This statement cannot run at the top level. | The top level may hold only indicator(), const declarations, plot.level(), function declarations, handler registrations and an algo's algo.onArm() and algo.describe(). Move logic into a handler such as `chart.onBar(() => { ... })`. | | OX1003 | error | Top-level let and var are not allowed. | Persistent values are declared state: use `const x = state.bar(0)` and write `x.value` in a handler. | | OX1004 | error | A top-level collection is changed after setup. | Top-level arrays, objects, Maps and Sets are constants. Use `state.list(n)` or `state.map(n)` for data that changes. | | OX1006 | error | indicator(...) or strategy(...) may be called only once, at the top level. | Keep one `indicator(...)` or `strategy(...)` call, as the first statement. | | OX1010 | error | Scripts have no imports or exports. | A script is one file. Everything it can use is a global of the script API. | | OX1011 | error | eval and the Function constructor are not available. | Write the code directly. | | OX1012 | error | The with statement is not allowed. | Name the object explicitly. | | OX1013 | error | async and await are not available. | Handlers run synchronously per bar or event; data arrives through streams. | | OX1014 | error | Generators are not available. | Use a loop or an array. | | OX1015 | error | Classes are not available. | Use plain objects and functions; persistent values are declared state. | | OX1016 | error | `this` is not available at the top level. | Name the value you mean. | | OX1017 | error | finally blocks are not allowed. | A finally block can swallow the step limit. Use try/catch without finally. | | OX1018 | error | debugger statements are not allowed. | Use `log.info(...)` to inspect values. | | OX1019 | error | This TypeScript construct is not supported. | Scripts use erasable TypeScript only: no enum, namespace, decorators or parameter properties. Use a union of string literals instead of an enum. | | OX1020 | error | This global is not available in scripts. | Scripts see only the script API and plain JavaScript values (Math, Number, String, Array, Object, JSON, Map, Set). | | OX1021 | error | Math.random is not available. | Use `random(seed)`, which gives the same numbers everywhere. | | OX1022 | error | constructor, prototype and __proto__ are not accessible. | Work with the values directly. | | OX1023 | error | Globals and API objects cannot be assigned to. | Declare your own value, or write a state cell’s `.value`. | | OX1024 | error | **= works on a plain variable only. | Write `a.b = a.b ** c`. | | OX1025 | error | Names starting with __ are reserved for the engine. | Rename the variable. | | OX1026 | error | A catch clause takes a plain name. | Write `catch (e)`, then destructure `e` inside the block. | | OX1101 | error | This constructor can be called only at the top level (setup). | Create inputs, streams, state, indicators, plots and alerts once at the top level; update them in handlers. | | OX1103 | error | Handlers must be registered at the top level, unconditionally. | Write `stream.onBar(...)` as its own top-level statement. | | OX1104 | error | API objects cannot be indexed dynamically. | Name the member: `chart.close`, or read a bar value by name with `chart.source(name)`. | | OX1105 | error | This state is updated from two streams’ handlers. | Each state object, series and indicator belongs to one stream. Give each stream its own, and read the other stream’s value instead of writing it. | | OX1106 | error | Event handlers may change only tallies and live state. | Events are never replayed, so they cannot change state that rolls back. Add to a `tally()` or `tallyBy(n)`, or use `state.live(...)`, and use the result in the chart’s onBar. | | OX1107 | error | Tallies are filled by event handlers. | Call `tally.add(...)` in `trades.onTrade`, `takerOrders.onOrder`, `liquidations.onLiquidation` or `book.onUpdate`. In a bar handler, use a local or `state.bar(...)`. | | OX1108 | error | Plots, markers and drawings are set from the chart’s handlers. | Set them in the onBar or onClose of the chart’s own `bars()` stream, reading the other stream there. | | OX1109 | error | This stream has no such handler. | Bar streams have onBar and onClose, trades() has onTrade, takerOrders() has onOrder, liquidations() has onLiquidation, book() has onUpdate. Sample streams have no handlers: read them in a bar handler. | | OX1110 | error | A handler must be a function. | Pass an arrow function, or the name of a top-level function. | | OX1111 | error | A footprint or heat is filled by event handlers. | Call `footprint.add(...)` or `heat.add(...)` in `trades.onTrade`, `takerOrders.onOrder` or `liquidations.onLiquidation`. A forming bar’s onBar runs again, so it would count the same trades twice. | | OX1901 | warning | This indicator is updated inside a condition. | An indicator advances only when update runs, so it skips the bars where the condition is false (Pine’s call-site rule). Update it on every bar and use the value conditionally, unless that is what you mean. | | OX2001 | error | A constructor was called inside a handler. | Create it once at the top level and update it in the handler. | | OX2002 | error | This can be called only inside a handler. | Indicators update and handlers register at fixed points in a run, set out in the scripting guide. | | OX2003 | error | This state cell holds numbers. | Its initial value was a number. Declare `state.bar(null)` or similar for a cell that can hold other values. | | OX2004 | error | A state list, map or tally is full. | Raise its capacity (up to the limit) or remove old entries. | | OX2005 | error | A size is over the limit. | Series keep at most 5,000 bars, tallyBy 10,000 keys, lists and maps 100,000 entries, drawings 500 per kind. | | OX2006 | error | A series was read further back than its lookback. | Declare a larger lookback: `series(n)`. | | OX2007 | error | More than 64 plots. | Combine plots, or split the script. | | OX2008 | error | An input is declared wrongly. | Check the default value and the options. | | OX2009 | error | Plots, markers and drawings can be set only from the chart’s handlers. | Set them in the chart stream’s onBar or onClose. | | OX2010 | error | An argument is not valid. | Check the value named in the message. | | OX2011 | error | Unknown time zone. | Use an IANA name such as `America/New_York`, or `UTC`. | | OX2012 | error | More than 9 tables. | Reuse a table: clear it and write new cells. | | OX2013 | error | A list index is out of range, or the list is empty. | Check `list.length` first. | | OX2014 | error | An order or trigger is not valid. | Check the value named in the message against the order type in the Algos reference. | | OX2100 | error | The script threw an error. | Read the message and the line. | | OX2105 | error | This state is updated from two streams’ handlers. | Each state object, series and indicator belongs to the stream whose handler first updated it. | | OX2106 | error | An event handler changed state that rolls back. | Event handlers may change only tallies and live state. | | OX2107 | error | A tally was added to outside an event handler. | Fill tallies in onTrade, onOrder, onLiquidation or onUpdate. | | OX2108 | error | A footprint or heat was added to outside an event handler. | Fill it in onTrade, onOrder or onLiquidation. | | OX2201 | error | A run took longer than 60 seconds. | A run replays every loaded bar and pauses every 50 ms so other scripts keep running, but works 60 seconds at most. Do less per bar: refit a model less often, use fewer inputs or a shorter window, or load less history. | | OX2200 | error | The step limit ran out. | A script gets 10 million steps (loop iterations and function calls) for setup, per batch of 512 bars and per live update. Look for a loop that does not end, or work that can move out of the loop. | | OX9001 | error | The engine failed on this script, which is our bug, not yours. | Please report the script. Simplifying what the message names (a very deeply nested expression, say) may get past it meanwhile. | | OX9002 | error | The engine could not read the data this script reads, which is our bug, not yours. | Please report it. Reloading the page starts the data over. | ## The API: script-api.d.ts ```ts /** * The oxterminal script API: every global a script can use. * * This file is the contract between script authors (people, AI agents and the Pine front end) * and the engine. The rules it relies on are in the scripting guide. It is ambient on purpose: * scripts have no imports. Only script sources and the engine's own checks include it; app code * must never import it, or these names would leak into the app's global scope. * * Writing style for the doc comments: they are the editor's autocomplete and the AI's reference, * so each says what the thing does, when it may be called, and what it returns when data is missing. */ // --------------------------------------------------------------------------------------------- // Basic types // --------------------------------------------------------------------------------------------- /** Milliseconds since the Unix epoch, UTC. */ type Time = number; /** * A colour: `#rrggbb`, `#rrggbbaa`, or a theme token from `color.*` (`theme:up`, `theme:down`, * `theme:neutral`, `theme:panel`, `theme:none`, `theme:study:<0-15>`, each with an optional alpha suffix such as * `theme:up@0.3`). `null` means "the theme's colour for this output", which is what a plot uses * when no colour is given. */ type Color = string; /** A price-derived value of the bar a source input can pick. */ type SourceName = 'open' | 'high' | 'low' | 'close' | 'hl2' | 'hlc3' | 'ohlc4' | 'hlcc4' | 'volume'; /** Which venue a market trades on. Defaults to the chart's venue. */ type Venue = 'hl' | 'hip3' | 'lighter'; /** * An interval code. Time: `1m` `3m` `5m` `15m` `30m` `1h` `2h` `4h` `8h` `12h` `1d` `1w`, and calendar * months `1M` `2M` `3M` `4M` `6M` `12M` (capital M; `1m` is a minute). Weeks open on Monday * 00:00 UTC and months on the 1st, from January. Bars that close on trades: `s15` seconds, `t500` trades, * `v1000000` volume, `d250000` delta, `r10` range, `k10` renko, `x10-0` reversal. */ type IntervalCode = string; /** Where a value is drawn: the price pane, the script's own pane (`'own'`), or a named pane of this script. */ type PaneName = 'price' | 'own' | (string & {}); type LineStyle = 'solid' | 'dashed' | 'dotted'; /** * A line's width in whole pixels, 1 to 20. Wider than 20 a stroke covers more than a candle body * and reads as a band, which `plot.fill`, a box or a background draws better. */ type LineWidth = number; /** A typeface for drawn text: the chart's own (`'sans'`, the default) or monospace (`'mono'`), whose figures line up in columns. */ type FontName = 'sans' | 'mono'; /** * A shape to mark a bar with. `labelUp` and `labelDown` are labels with a pointer: `labelUp` * sits below its point and points up at it, `labelDown` sits above and points down; their * `text` is written inside. */ type ShapeName = 'circle' | 'square' | 'diamond' | 'cross' | 'xcross' | 'triangleUp' | 'triangleDown' | 'arrowUp' | 'arrowDown' | 'flag' | 'labelUp' | 'labelDown'; type ShapeLocation = 'above' | 'below' | 'top' | 'bottom' | 'absolute'; type Size = 'tiny' | 'small' | 'normal' | 'large' | 'huge'; /** * `na` is the missing number, a float NaN: arithmetic with it gives `na`, and every comparison * with it is false, as in Pine. Missing strings, colours and objects are `null`. */ declare const na: number; /** `x`, or `replacement` (default 0) when `x` is `na`. */ declare function nz(x: number, replacement?: number): number; /** Whether `x` is `na` (for numbers) or `null`. */ declare function isNa(x: unknown): boolean; // --------------------------------------------------------------------------------------------- // The declaration. Call once, first. // --------------------------------------------------------------------------------------------- /** * How a value prints: * - `'volume'`: compact, 1.2K, 3.4M, 5.6B; with `precision`, that many decimals in the unit. * - `'price'`: as the market prints its prices; with `precision`, that many decimals. * - `'mintick'`: as the market prints its prices, rounded to its tick, whatever the precision. * - `'percent'`: a % sign after the value. Set the values in percent: 12.5 prints 12.5%. */ type ValueFormat = 'volume' | 'price' | 'mintick' | 'percent'; interface IndicatorOptions { /** Draw on the price pane (true) or in the script's own pane below it (false, the default). */ overlay?: boolean; /** A short name for the legend. */ shortName?: string; /** Decimal places for values; defaults to the market's price precision on the price pane. */ precision?: number; /** * How the script's values print in the legend, on the axis and in list columns, for every plot * that is not on the price pane's own scale (a pane of its own, `scale: 'own'`, a `band`), as * Pine's `format`. Leave it out for plain numbers: compact (12.3M), or `precision` decimals. * A plot's own `format` wins. */ format?: ValueFormat; /** * `false` keeps every input's value out of the script's name in the legend ("Bands" * rather than "Bands 20 2"). Default true. An input's own `legend: false` keeps one out. */ legendInputs?: boolean; /** * `'own'`: the plots on the price pane share a hidden scale of their own, drawn over the * candles without moving the price scale, as Pine's `scale.none`. Default `'price'`. */ scale?: 'price' | 'own'; /** * Where the script's lines, boxes, polylines and linefills paint: `'above'` the pane's series * (the candles, on the price pane), the default, or `'behind'` them, as Pine's `behind_chart`. * Labels and tables stay above, so their text reads. A drawing's own `layer` wins. */ layer?: DrawingLayer; /** Caps on drawing objects, oldest removed first. Default 50 each, at most 500. */ maxLines?: number; maxLabels?: number; maxBoxes?: number; maxPolylines?: number; maxLinefills?: number; /** * A panel script: it runs in a script panel of its own rather than on a chart, on the market and * interval named here, or the panel's choice where they are left out. `bars()` is that market's * bars, which clock the script; its `panel` blocks and graphs fill the panel. Plots are not drawn. * A market-wide read (20 markets' positioning, a cross-market table) is a panel script. */ panel?: true | { market?: string; interval?: IntervalCode }; } /** Names the script and says where it draws. Must be the first statement. */ declare function indicator(name: string, options?: IndicatorOptions): void; /** A strategy's display options are an indicator's (`overlay: true` draws its plots over the candles); it runs on a chart, never in a panel. */ interface StrategyOptions extends Omit { /** Starting equity in USD. Default 10,000. */ capital?: number; /** * Where the account starts trading, with history loaded back to it: a date such as `'2025-03-01'` (or an ISO time, * UTC unless it names a zone), a time in ms, or * a span back from the run's end, `'90d'`, `'4w'` or `'1y'` (a whole number of days, weeks or 365-day years, * lowercase, at most ten years). A span back is counted from the close of the newest bar the run has (a backtest's * end on our server), so a template can say "a year back" and still give the same result on the same bars. By default * what the chart holds. */ from?: string | number; /** * `'nextOpen'` (the default): a target set on a bar's close fills at the next bar's open, so a * script never trades on a close it hasn't seen. `'close'`: at the signal bar's own close. */ fill?: 'nextOpen' | 'close'; /** * `'venue'` (the default): the venue's base tier, a market or stop fill paying the taker rate and * a limit fill the maker rate. Or rates of your own; `makerBps` defaults to `takerBps`. */ fees?: 'venue' | { takerBps: number; makerBps?: number }; /** * `'book'` (the default): what a market order of the fill's size paid against the archived book * at the signal bar's close (Hyperliquid and HIP-3), `fallbackBps` where it has no reading. Or a * flat cost. */ slippage?: 'book' | { bps: number }; /** The cost where the book has no reading, in basis points. Default 2. */ fallbackBps?: number; /** Charge funding while a position is open, every hour as the venue settles it. Default true; time charts of 1m and up only. */ funding?: boolean; /** The most a target may ask for, as a multiple of equity. Default 1. Above 1 a position can be liquidated. */ leverage?: number; /** * A portfolio: one account, shared cash and cross margin, across every Hyperliquid perp, set with * `strategy.target(weight, { market })` or `strategy.targets({...})`. It runs on any time chart * from 1m to 1W: each market fills at the open of its own next bar at the chart's interval, is * marked at its closes and liquidated at its bars' worst prices, from the same bars its chart * shows (on 1D every market's from the universe history's months, which hold exactly those * bars; intraday each market's own stream). The chart shows its own market's fills and the whole account's equity. Funding is * charged every hour at the day's mean hourly rate. `history` is how many days of the universe * history (for picking markets) load before the chart's first bar (default 180). Slippage is a * flat cost (`slippage: { bps }`, default `fallbackBps`, 2): the archive's book readings start on * 2026-09-06. */ portfolio?: true | { history?: number }; } /** One market of a portfolio's book. */ interface PortfolioPosition extends StrategyPosition { readonly market: string; /** Notional over equity, signed: 0.2 is a fifth of equity long. */ readonly weight: number; } interface StrategyPosition { /** Coins held: positive long, negative short. */ readonly size: number; readonly side: 'long' | 'short' | 'flat'; /** The average entry; `na` when flat. */ readonly entryPrice: number; readonly unrealized: number; readonly notional: number; /** Fills that opened or added to the position since it was last flat; 0 when flat. A portfolio's open sleeve counts one. */ readonly entries: number; /** The chart bar (`chart.index`) and the time of the fill that opened the position; `na` when flat, and in a portfolio. */ readonly entryBar: number; readonly entryTime: Time; } /** * A resting order: it waits until price reaches it rather than filling at the next open. A stop * fills when price trades through it, at its price (or the open, when a bar opens past it), as a * taker; a limit fills when price trades at it, at its price or a better open, as a maker with no * slippage. An order placed on a bar's close can fill from the next bar on, and stays until it * fills, is replaced by another with its id, or is cancelled. */ interface RestingOrderOptions { /** Fill once price trades at or through this price: above for a buy, below for a sell. */ stop?: number; /** Fill once price trades at this price or better: below for a buy, above for a sell. */ limit?: number; /** * Names the order: another with this id replaces it, `strategy.cancel(id)` removes it. Default * `'entry'`. A target with an id and no price is a market target that cancels the resting one. */ id?: string; } interface ExitOptions { /** Close the position when price trades through this price. */ stop?: number; /** Close the position when price trades at this price. */ limit?: number; /** A stop this far from the entry price, in price units, placed once the position is open. */ loss?: number; /** A limit this far from the entry price, in price units, placed once the position is open. */ profit?: number; /** Close only a long or only a short. Default: the position open now, or else the next one opened. */ side?: 'long' | 'short'; /** Another exit with this id replaces it. Default `'exit'`. */ id?: string; } /** * A strategy: an indicator whose target position the engine trades, charging what the venue would * have (fees, slippage from the order book, funding), with an equity curve, fills on the chart and * a Strategy report. Must be the first statement, in place of `indicator()`. */ declare const strategy: { (name: string, options?: StrategyOptions): void; /** * The position wanted from this bar's close, as a fraction of equity: 1 fully long, −1 fully * short, 0 flat, held to the leverage. Applies on closed bars only. The same value again holds * the position as it is; a new value trades to it. */ target(fraction: number): void; /** The same position wanted once price reaches a stop or a limit, resting until then. */ target(fraction: number, order: RestingOrderOptions): void; /** * A portfolio's weight wanted in one market from this bar's close, as a fraction of equity, * filled at that market's next daily open. Markets not set keep what they hold. The book is held * to `leverage` at the fill: the markets traded give way, those left alone do not. */ target(fraction: number, options: { market: string }): void; /** The position wanted as a notional in USD: positive long, negative short. One market only. */ targetUsd(usd: number, order?: RestingOrderOptions): void; /** The position wanted in coins: positive long, negative short, held to the leverage. One market only. */ targetSize(coins: number, order?: RestingOrderOptions): void; /** * Close the position when price reaches a stop or a limit, whichever it reaches first; the other * is then cancelled. It rests until it fills or the position it closes is closed. One market only. */ exit(options: ExitOptions): void; /** Cancel the resting order or exit with this id, or every one. */ cancel(id?: string): void; /** A portfolio's whole book from this bar's close, market to weight: a market left out goes to 0. */ targets(weights: Readonly>): void; /** The chart's market's position; in a portfolio, its sleeve. */ readonly position: StrategyPosition; /** A portfolio's open positions, largest first. */ readonly positions: readonly PortfolioPosition[]; /** Cash plus the open position marked at the last price. */ readonly equity: number; readonly cash: number; /** Round trips closed so far: a position opened and closed, or flipped. One market only. */ readonly closedTrades: number; /** What trading has cost so far, in USD: funding positive when received. */ readonly costs: { readonly fees: number; readonly slippage: number; readonly funding: number }; }; // --------------------------------------------------------------------------------------------- // Algos: scripts that trade an account through the fixed order types, armed in the tab or on 0xArchive's server. // --------------------------------------------------------------------------------------------- /** An algo's display options are an indicator's; it runs on a market, never in a panel. */ interface AlgoOptions extends Omit { /** What its orders do to risk: `'protect'` may only reduce a position, `'entry'` may add. Default `'entry'`. */ role?: 'entry' | 'protect' | 'both'; /** `'once'` (the default) ends when its orders have; `'standing'` stays armed and runs as a script (later). */ lifetime?: 'once' | 'standing'; /** What it may trade, shown when it is armed: the chart's market or a list, and a cap on the position. */ trades?: { markets?: 'chart' | readonly string[]; maxPositionUsd?: number }; /** * A standing algo's replay on history (its settings' On history): the capital it starts with, where its history * starts trading (`from`, as `strategy({ from })` takes it: a date such as `'2025-11-09'`, a time in ms, or a span * back from the run's end such as `'1y'` or `'90d'`; the settings open On history on it, cut to the archive's first * bar), and what it assumes of the trader's bias and arming. */ backtest?: { capital?: number; from?: string | number; assume?: { bias?: 'long' | 'short' | 'both' | 'off'; armed?: 'always' | 'script' } }; } type Side = 'buy' | 'sell'; /** An order's size. `pctOfPosition` sizes an exit; `riskUsd` is the size that loses that much if `stop` is hit. */ type OrderSize = { usd: number } | { coins: number } | { pctOfPosition: number } | { pctOfEquity: number } | { riskUsd: number; stop: number }; /** Seconds, or text such as `'30s'`, `'5m'`, `'4h'`, `'2d'`. */ type Duration = number | string; /** * An order an algo made. In a plan it reads `'planned'`. Armed, a call on a live event reads `'sent'`: a request the * tab admits or refuses, whose answer and fills arrive on `account().onOrder` and `onFill`, by `tag`. In history, or * before the algo is armed, it reads `'none'`: nothing was sent. */ interface OrderRef { readonly id: string; readonly tag: string | null; readonly state: 'none' | 'planned' | 'sent'; readonly filled: number; readonly avgPx: number; } /** A resting order: an OCO's leg, or a limit. */ interface Leg { side: Side; size: OrderSize; /** The limit price. `null` (an empty price input) is refused at arm. */ px: number | null; /** Post only: refused rather than taking. */ postOnly?: boolean; /** How long a condition's limit rests. */ restFor?: Duration; tag?: string; } /** A test of one of the execution service's own prices, for `order.when`. Made by `trigger.*`. */ interface Trigger { readonly input: 'mark' | 'book' | 'trade' | 'funding' | 'oiUsd'; readonly test: TriggerTest; readonly value: number | null; } type TriggerTest = 'above' | 'below' | 'crossesAbove' | 'crossesBelow'; interface TriggerOptions { /** How long the test must hold before it fires. */ confirm?: Duration; /** Another market's price; the algo's own by default. */ market?: string; } /** * An algo: a script that trades an account through the fixed order types (`order.*`). Must be the first * statement, in place of `indicator()`. It runs as orders when every `order.*` call sits in `algo.onArm`: * arming runs that function once and places the orders it makes, fixed numbers that the tab or 0xArchive's * server runs. An order call anywhere else is live logic (later). */ declare const algo: { (name: string, options?: AlgoOptions): void; /** Runs once when the trader arms the algo, after setup and history: the orders it makes are what arming places. */ onArm(fn: () => void): void; /** The sentence the algo's settings lead with ("Chase buy $1,000, never past 61,290"). */ describe(fn: () => string): void; /** * A strategy's arm (`lifetime: 'standing'`): how many trades it may take, until when, on which sides, and the wait * after each. From a button's `onPress`, or at the top level to arm it from the start (full auto, `shots: Infinity`). */ arm(o?: { shots?: number; expires?: Duration; sides?: 'long' | 'short' | 'both'; cooldown?: Duration }): void; /** Who sets the direction allowed: the trader (the strip's Long, Short, Both, Off) or the script, with `algo.bias.set`. Top level. */ bias: ((o?: { owner?: 'trader' | 'code'; initial?: 'long' | 'short' | 'both' | 'off' }) => void) & { /** The script's bias, when it owns it. The trader's Off still wins. */ set(dir: 'long' | 'short' | 'both' | 'off'): void; }; /** The day's limits, from the account's real fills (manual trades count): a breach halts entries. Top level. Every strategy has one. */ governor(o: { dailyLossUsd: number; dailyProfitUsd?: number; maxTrades?: number }): void; /** Where the strategy may engage: a trigger outside every zone for its side is journaled, not traded. */ zones(list: readonly { lo: number; hi: number; side?: 'long' | 'short'; label?: string }[]): void; /** * The moment the strategy would trade. The tab trades it when armed, the bias allows its side, its price is in a * zone (when there are zones), and the governor has room; otherwise it is journaled as "would have traded". Live * events only: whether it was sent. */ trigger(o: { side: 'long' | 'short'; price: number; why: string; strength?: number }): boolean; /** The trade a trigger makes, in trader terms. The stop goes in before the entry, the targets once it fills. Top level. */ plan(fn: (trigger: { side: 'long' | 'short'; price: number; why: string; strength: number | null }) => StrategyPlan): void; }; /** A trade in trader terms. `r` targets count from the entry to the stop. */ interface StrategyPlan { entry?: { how?: 'cross' | 'chase'; worstBps?: number }; size: { riskUsd: number } | { notionalUsd: number } | { equityPct: number }; stop: { bps: number } | { price: number } | { beyondZone: true; padBps?: number }; targets?: { r: number; pct: number }[]; timeStop?: Duration; } /** * A strategy's controls: how the trader drives it now. Declared at the top level, at most 16. A change is an event, * never a re-run. In history a control reads its `history` value, and a button never fires. */ declare const control: { number(label: string, value: number, o?: { min?: number; max?: number; step?: number; unit?: 'usd' | 'bps'; history?: number }): { readonly value: number }; choice(label: string, value: T, choices: readonly T[], o?: { history?: T }): { readonly value: T }; toggle(label: string, value: boolean, o?: { history?: boolean }): { readonly value: boolean }; /** A price the trader types or drags. Empty in history: a level set today gets no credit for last month. */ price(label: string, o?: { value?: number }): { readonly value: number | null }; button(label: string): { onPress(fn: () => void): void }; }; /** The order types an algo places. Each call is one order of that type, checked against its ranges at arm. */ declare const order: { /** Rest at the best price and follow it until filled, never past `limitPx`. `maxTime` gives up; `onEnd: 'cross'` takes the rest. */ chase(o: { side: Side; size: OrderSize; limitPx?: number | null; peg?: 'touch' | 'inside'; maxReprices?: number; maxTime?: Duration; onEnd?: 'cancel' | 'cross'; reduceOnly?: boolean; tag?: string }): OrderRef; /** * Close the position held at arm (or `size` of it) when the price reaches `px`: the mark, the best bid or ask * (`'book'`), or the last trade. Watched by the runner, not resting on the venue. Exits in reduce-only rounds * within `bandPct` of the mark, at most `attempts` times. */ fastStop(o: { px: number | null; source?: 'mark' | 'book' | 'trade'; size?: OrderSize; confirm?: Duration; bandPct?: number; attempts?: number; tag?: string }): OrderRef; /** Close the position held at arm (or `size` of it) after a hold, or at a time. */ timeStop(o: { after?: Duration; at?: number; size?: OrderSize; bandPct?: number; attempts?: number; tag?: string }): OrderRef; /** Two resting orders: the first to fill cancels the other. */ oco(a: Leg, b: Leg, o?: { tag?: string }): OrderRef; /** When the trigger's test holds, make the one order `then` makes: `order.reduce`, `order.close`, `order.limit` or `order.market`. */ when(trigger: Trigger, then: () => OrderRef, o?: { tag?: string }): OrderRef; /** A reduce-only order at market within the band, as a condition's action. */ reduce(size: OrderSize, o?: { bandPct?: number; tag?: string }): OrderRef; /** Close the whole position at market within the band, as a condition's action. */ close(o?: { bandPct?: number; tag?: string }): OrderRef; /** A resting limit, as a condition's action. */ limit(o: Leg & { reduceOnly?: boolean }): OrderRef; /** An order at market within the band, as a condition's action. */ market(o: { side: Side; size: OrderSize; bandPct?: number; reduceOnly?: boolean; tag?: string }): OrderRef; /** Live logic: cancel the working orders made with this tag (or this ref's tag). Not in `algo.onArm`. */ cancel(target: OrderRef | string): void; /** * Live logic: quote both sides. A post-only bid at `bidPx` and ask at `askPx`, each of `size`, rest in the account; * each call moves them (a moved quote goes to the back of its new level), and `null` pulls that side. The host keeps * the position inside `algo({ trades: { maxPositionUsd } })`: the side that would pass it is pulled. Quoting runs on the Paper account. */ quote(o: { bidPx: number | null; askPx: number | null; size: { usd: number } | { coins: number }; tag?: string }): OrderRef; /** Not available: use the ticket's TP/SL, or `order.fastStop` with `order.when`. */ bracket(o: { entry: Leg; stop: number; takeProfit?: number; tag?: string }): OrderRef; /** Not available. */ trailing(o: { distance: { pct: number } | { price: number }; size?: OrderSize; tag?: string }): OrderRef; }; /** The prices `order.when` can test, as the execution service reads them. A `null` value (an empty price input) is refused at arm. */ declare const trigger: { mark(test: TriggerTest, value: number | null, options?: TriggerOptions): Trigger; /** The book's mid. */ book(test: TriggerTest, value: number | null, options?: TriggerOptions): Trigger; /** The last trade. */ trade(test: TriggerTest, value: number | null, options?: TriggerOptions): Trigger; /** The funding rate per hour, as a fraction. */ funding(test: TriggerTest, value: number | null, options?: TriggerOptions): Trigger; /** Open interest in USD. */ oiUsd(test: TriggerTest, value: number | null, options?: TriggerOptions): Trigger; }; /** What became of one of an algo's orders: the tab's answer to it, or a change in what it placed. */ interface OrderEvent { readonly tag: string | null; /** `'refused'` with `code` (`needs_stop`, `shots_used`, `entry_rate_limited`, ...) and `words` when the tab did not place it. */ readonly state: 'working' | 'filled' | 'ended' | 'refused'; readonly code: string | null; readonly words: string | null; /** Filled so far, in coins, and its average price (`NaN` with nothing filled). */ readonly filled: number; readonly avgPx: number; } /** * The account the algo trades. In `algo.onArm`, as it stands at the arm. Armed, as the tab last read it, for live * logic. Otherwise it reads flat. */ interface AlgoAccount { /** The position in the algo's market: `size` in coins, `entryPrice` the average entry. */ readonly position: { readonly side: 'long' | 'short' | 'flat'; readonly size: number; readonly entryPrice: number; readonly notionalUsd: number }; /** The account's equity in USD. */ readonly equity: number; /** The market's mark price. */ readonly mark: number; /** Each answer and change to the algo's orders, on live events only, never in history. Registered at the top level. */ onOrder(fn: (order: OrderEvent) => void): void; /** When one of the algo's orders fills more. Registered at the top level. */ onFill(fn: (order: OrderEvent) => void): void; } /** The account the algo trades. Declared at the top level, once. */ declare function account(): AlgoAccount; // --------------------------------------------------------------------------------------------- // Inputs: settings the user changes in the settings panel. Declared at the top level only. // Changing an input re-runs the script from its first bar. // --------------------------------------------------------------------------------------------- interface InputOptions { group?: string; tooltip?: string; /** Show the input on the same row as the previous one. */ inline?: boolean; /** * `false` keeps the input's value out of the script's name in the legend, which otherwise * carries its numbers, sources, choices and intervals ("RSI 14 close"). For a setting that * says where something draws rather than what it computes, such as a table's corner. */ legend?: boolean; } interface NumberInputOptions extends InputOptions { min?: number; max?: number; step?: number; /** For `int` and `float`: what the number counts, written in its field (`'usd'` dollars, `'bps'` basis points). */ unit?: 'usd' | 'bps'; } declare const input: { int(label: string, defaultValue: number, options?: NumberInputOptions): number; float(label: string, defaultValue: number, options?: NumberInputOptions): number; bool(label: string, defaultValue: boolean, options?: InputOptions): boolean; string(label: string, defaultValue: string, options?: InputOptions): string; /** * One of a fixed list of strings. `labels` names values for the settings panel and the legend, * such as `{ lastHour: 'Last hour' }`, so the values can stay stable while the words change. */ choice(label: string, defaultValue: T, choices: readonly T[], options?: InputOptions & { labels?: Partial> }): T; /** Which bar value to read, such as `close` or `hl2`. Read it with `bars().source(name)`. */ source(label: string, defaultValue: SourceName, options?: InputOptions): SourceName; /** A colour; `null` follows the theme. */ color(label: string, defaultValue: Color | null, options?: InputOptions): Color | null; /** * A moment the user picks by clicking the chart, such as an anchored VWAP's start. `null` until picked. * `confirm: true` asks for it by a click on a bar as soon as the script is added, as Pine's `confirm`. */ time(label: string, defaultValue: Time | null, options?: InputOptions & { confirm?: boolean }): Time | null; /** * An interval code. `'chart'` stands for the chart's own interval, as a default and as the * user's choice: the script then reads the chart's code (`'15m'` on a 15-minute chart), and a * `bars({ interval })` stream with it is the chart's own stream. */ interval(label: string, defaultValue: IntervalCode | 'chart', options?: InputOptions): IntervalCode; /** A market symbol such as `BTC` or `xyz:GOLD`; `null` means the chart's market. */ market(label: string, defaultValue: string | null, options?: InputOptions): string | null; /** A list of wallet addresses, lower-case hex. */ addresses(label: string, defaultValue: readonly string[], options?: InputOptions): readonly string[]; /** * A list of market symbols, such as a basket for `ml.pca`: at most 50, trimmed, without repeats. * Open one stream per market with `markets.map((m) => bars({ market: m }))`. */ markets(label: string, defaultValue: readonly string[], options?: InputOptions): readonly string[]; /** * A price: a number field the user types in, or sets with Pick by clicking the chart at a price (an * indicator's entry, stop or a fixed level). With `drag: true` it is also a line on the chart that a * drag moves, as the ticket's TP/SL; in an algo it is one on every chart of its market. `confirm: true` * asks for it by a click on the chart as soon as the script is added, as Pine's `confirm`. Values are * above 0 and kept to the market's decimals. A `null` default is an empty field, for an optional * price; it reads `null` until set. */ price(label: string, defaultValue: number | null, options?: InputOptions & { drag?: boolean; confirm?: boolean }): number | null; /** An algo's size: an amount and its unit ($, coins, % of the position, % of equity), as the ticket's size. */ size(label: string, defaultValue: OrderSize, options?: InputOptions): OrderSize; /** Buy or sell. */ side(label: string, defaultValue: Side, options?: InputOptions): Side; /** A percent, such as a price band. */ percent(label: string, defaultValue: number, options?: NumberInputOptions): number; /** A length of time written as the trader writes it (`'30s'`, `'5m'`, `'4h'`, `'2d'`), read in seconds. */ duration(label: string, defaultValue: Duration, options?: InputOptions): number; }; // --------------------------------------------------------------------------------------------- // Streams: the data a script reads. Declared at the top level only. // // Inside a handler of stream S, S's fields describe the bar or event being run. Every other // stream reads "as of" that moment: its last confirmed value at or before the current bar's // time. That is the no-lookahead rule, for every kind of data. // --------------------------------------------------------------------------------------------- interface MarketInfo { readonly symbol: string; readonly venue: Venue; /** The smallest price step at the current price. Hyperliquid's step changes with price. */ readonly tickSize: number; readonly sizeDecimals: number; } interface IntervalInfo { readonly code: IntervalCode; /** Length in milliseconds for time bars (for months, the average month); `na` for bars that close on trades. */ readonly ms: number; readonly isTime: boolean; } /** One bar. Values the source does not provide are `na`. */ interface BarView { readonly time: Time; /** When the bar ends (exclusive). For time bars, `time + interval.ms`; for months, the next month's open. */ readonly closeTime: Time; readonly open: number; readonly high: number; readonly low: number; readonly close: number; /** Base volume. */ readonly volume: number; /** Quote (USD) volume. */ readonly quoteVolume: number; readonly tradeCount: number; /** Taker buy and sell base volume, when the host has them. */ readonly buyVolume: number; readonly sellVolume: number; /** A bar value by name, such as `source('hl2')`. */ source(name: SourceName): number; } interface BarsOptions { /** A market other than the chart's, such as `ETH`. */ market?: string; venue?: Venue; /** An interval other than the chart's, such as `4h`. */ interval?: IntervalCode; } interface Bars extends BarView { readonly market: MarketInfo; readonly interval: IntervalInfo; /** Bar number on this stream, from 0 at the first loaded bar. */ readonly index: number; /** True when this run is for a closed bar; false for an update of the forming bar. */ readonly confirmed: boolean; /** True on the first run of a bar. */ readonly isNew: boolean; /** True on the newest bar the chart has. */ readonly isLast: boolean; /** * The index of this stream's newest bar, known on every bar of history (Pine's * `last_bar_index`). It grows as new bars arrive; bars already run keep the value they saw. */ readonly lastIndex: number; /** The open time of this stream's newest bar, known on every bar (Pine's `last_bar_time`). */ readonly lastTime: Time; /** True once the run has reached live data. */ readonly isRealtime: boolean; /** * The footprint's row size on the chart, in price: the reader's own, or what Auto draws at the * chart's zoom, so rows a script marks sit on the footprint's rows. Pass it to a profile, as * `profile.bar().rows({ rowSize: chart.rowSize })`. A script that reads it runs again from its * first bar when the size changes. Without a footprint, the reader's size for the market, or one * near a 5,000th of the price ($20 rows for BTC at 81,000). On the chart's own bars only; * `na` on another market's or interval's. */ readonly rowSize: number; /** The bar `n` bars ago on this stream; `ago(0)` is the current one. Fields are `na` before the first bar. */ ago(n: number): BarView; /** * The developing bar of this stream, read from another stream's handler. It changes until the * bar closes (it repaints), which is why it has to be asked for by name. */ readonly forming: BarView; /** Runs for every bar of history, once, and again on every update of the forming bar. */ onBar(handler: () => void): void; /** Runs once when a bar closes, after its last `onBar`. */ onClose(handler: () => void): void; } /** The chart's bars by default, or another market or interval. */ declare function bars(options?: BarsOptions): Bars; /** One trade (a taker fill), with the identities 0xArchive records. */ interface Trade { readonly time: Time; readonly price: number; readonly size: number; /** price × size, in USD. */ readonly notional: number; /** The taker's side. */ readonly side: 'buy' | 'sell'; readonly tradeId: string | null; /** The taker's order id: fills with the same id are one order. */ readonly takerOrderId: string | null; /** Wallet addresses, lower-case hex, when the source carries them. */ readonly taker: string | null; readonly maker: string | null; /** True when the taker was being liquidated. */ readonly liquidation: boolean; /** * True when the same taker order filled the trade before this one on the stream (time order, * execution order within a millisecond), filters such as `minSize` aside. False where the * source does not say. Join fills into orders with it when `takerOrderId` is null. */ readonly sameOrder: boolean; /** * The trade's change in the venue's open interest, in the market's base unit, from both sides' * positions before it: positive where it opened positions, negative where it closed them, 0 where * one side opened and the other closed. Hyperliquid and HIP-3 count both sides of open interest, * Lighter longs only, as each venue's own open interest does. `na` where the venue does not know. */ readonly oiDelta: number; /** * Why the taker's side of the trade traded, from the position it changed: see `Intent`. `null` * where it is unknown (a position 0xArchive could not vouch for), on Lighter, and from a server * that does not send it. */ readonly takerWhy: Intent | null; /** Why the maker's side traded, as `takerWhy`. Market makers' legs are tagged too. */ readonly makerWhy: Intent | null; } /** * What one side of a trade did to its position, as 0xArchive's who's-trading series buckets it: * - `open_long`, `open_short`: opened or added to a long (short); * - `tp_long`, `tp_short`: reduced or closed a long (short) in profit, not forced; * - `stop_long`, `stop_short`: reduced or closed a long (short) at a loss, or forced out by a * liquidation or auto-deleveraging; * - `flip_ls`, `flip_sl`: went from long to short (short to long) in the one fill; * - `settlement`: a settlement, which is no trade decision. * New values are only ever added. */ type Intent = 'open_long' | 'open_short' | 'tp_long' | 'tp_short' | 'stop_long' | 'stop_short' | 'flip_ls' | 'flip_sl' | 'settlement'; interface TradesOptions { market?: string; venue?: Venue; /** Skip trades smaller than this, in base units or in USD. */ minSize?: number; minNotional?: number; } interface Trades { /** Runs once per trade, in execution order, before the `onBar` of the bar it falls in. */ onTrade(handler: (trade: Trade) => void): void; /** Whether trades cover the current bar completely. Trade history is limited, so older bars have none. */ readonly available: boolean; } declare function trades(options?: TradesOptions): Trades; /** * One taker order, joined from its fills: a trade with `sameOrder` false and the trades after it * with `sameOrder` true. */ interface TakerOrder { /** Its fills' time: one taker order fills within one millisecond. */ readonly time: Time; readonly side: 'buy' | 'sell'; /** The fills' sizes summed, in base units. */ readonly size: number; /** The fills' price × size summed, in USD. */ readonly notional: number; /** notional / size: the order's average fill price. */ readonly avgPrice: number; /** How many fills it took. Lighter names no orders, so there every fill is an order of one. */ readonly fills: number; /** The price of its first fill and of its last: how far it walked the book. */ readonly firstPrice: number; readonly lastPrice: number; /** How many prices it filled at, in turn. */ readonly levels: number; /** Its fills' changes in open interest summed (see `Trade.oiDelta`); `na` if any fill's is. */ readonly oiDelta: number; /** True when the taker was being liquidated. */ readonly liquidation: boolean; /** As on its first fill: the order id and the taker's wallet where the source names them. */ readonly takerOrderId: string | null; readonly taker: string | null; } interface TakerOrdersOptions { market?: string; venue?: Venue; /** Skip orders smaller than this, in USD, counting the whole order. */ minNotional?: number; } interface TakerOrders { /** * Runs once per taker order, once all its fills are in, in time order with other events and * before the `onBar` of the bar it falls in. A forming bar never sees part of an order. */ onOrder(handler: (order: TakerOrder) => void): void; /** Whether trades cover the current bar completely, as `trades().available`. */ readonly available: boolean; } /** Taker orders joined from the market's trades: the same history and live feed as `trades()`. */ declare function takerOrders(options?: TakerOrdersOptions): TakerOrders; interface Liquidation { readonly time: Time; readonly price: number; readonly size: number; readonly notional: number; /** The side of the position that was liquidated. */ readonly side: 'long' | 'short'; readonly user: string | null; } interface Liquidations { onLiquidation(handler: (liquidation: Liquidation) => void): void; /** * Whether the current bar's liquidations are all in. It says the bar is complete, not that the * feed is healthy. False on bars older than the 7 days of history. A closed bar waits for its * liquidations (about 2 seconds on the chart's own market, a few minutes on another market, * which has no live feed) and reads false only past that wait; the script then runs again from * its first bar once they arrive. The forming bar reads true once everything before it is in. */ readonly available: boolean; /** The time the liquidations are complete to, now, whichever bar runs; `na` before the first read. */ readonly coveredTo: Time; /** * How the stream stands now, whichever bar runs: `'loading'` (nothing yet), `'live'` (complete * to within seconds of now), `'delayed'` (complete to a few minutes behind: normal for a market * other than the chart's, for a moment while the chart's live feed starts or reconnects, and for * a few minutes when the live server holds fewer minutes than that, as just after it restarts), * `'retrying'` (a read failed and is asked again, and the coverage is not keeping up meanwhile) * or `'unavailable'` (the market has none). */ readonly state: 'loading' | 'live' | 'delayed' | 'retrying' | 'unavailable'; } declare function liquidations(options?: { market?: string; venue?: Venue; minNotional?: number }): Liquidations; /** Perp state as of the current bar: the last sample at or before it. `na` when unknown. */ interface Derivatives { /** When the sample read was taken; `na` when there is none. */ readonly time: Time; readonly openInterest: number; readonly openInterestUsd: number; /** The funding rate for one hour, as a fraction (0.0001 is 0.01%). */ readonly funding: number; readonly markPrice: number; readonly oraclePrice: number; readonly premium: number; readonly available: boolean; } declare function derivatives(options?: { market?: string; venue?: Venue }): Derivatives; /** The share of a venue's markets trading above their session VWAP, as of the current bar. */ interface Breadth { /** Percent, 0 to 100. */ readonly value: number; readonly eligible: number; /** How complete the sample is: the percent of the venue's markets that had data for it, 0 to 100. */ readonly coverage: number; /** When the sample read was calculated; `na` when there is none. */ readonly time: Time; readonly available: boolean; } declare function breadth(options?: { venue?: 'hl' | 'hip3' }): Breadth; /** * The universe history's reads, for picking markets: every Hyperliquid perp's daily * rows, listed and delisted, as of the current moment, so a day is read once it has closed and never * before. Days and counts are UTC days; returns are daily log returns except `ret`. A rule's * `select(view)` and `pool.view` read these; a pool's own price reads use its members' bars. */ interface UniverseReads { /** Markets with a close on the day read. */ readonly markets: readonly string[]; /** Whether the market has a close on the day read: listed then, and not yet delisted. */ listed(market: string): boolean; /** The close `ago` days back (0, the default, is the last day read). */ close(market: string, ago?: number): number; /** The last `n` closes, oldest first, `na` where a day has none. */ closes(market: string, n: number): readonly number[]; /** The simple return over the last `n` days. */ ret(market: string, n: number): number; /** The standard deviation of the last `n` daily log returns, not annualised. */ volatility(market: string, n: number): number; /** The least-squares beta of the last `n` daily log returns on `to`'s. */ beta(market: string, to: string, n: number): number; /** The sum over the last `n` days of each return less `to`'s times the beta fitted over the last `fit` days. */ resid(market: string, to: string, n: number, fit: number): number; /** Dollar volume over the last `n` days. */ volume(market: string, n: number): number; /** Open interest in dollars at the day's last mark. */ openInterest(market: string): number; /** The mean hourly funding rate over the last `n` days (1 by default); a day's funding is about 24 times it. */ funding(market: string, n?: number): number; /** Days of prices the market has in the universe history up to the day read. */ historyDays(market: string): number; } /** What a `universe.rule` select reads: the days before its pick. */ interface PickView extends UniverseReads { /** The pick's boundary. */ readonly at: Time; } /** * A universe: its members, picked point in time from the universe history, and reads of any * market's own bars at the pool's interval (the chart's unless `interval` names another), the bars * a portfolio trades on. Counts are bars of that interval; a bar is read once it has closed. A * market's bars load the first time it is picked or read; until then its reads are `na`. */ interface Pool { /** The members in force, best first: at most 50. */ readonly current: readonly string[]; /** The boundary of the pick in force; `na` for `universe.all()`. */ readonly pickedAt: Time; readonly available: boolean; /** The universe history's reads as of now, as a rule's `select(view)` gets them: `markets`, `listed`, `openInterest`, `funding`, `historyDays`... */ readonly view: UniverseReads; /** The close `ago` bars back (0, the default, is the last closed bar). */ close(market: string, ago?: number): number; /** The last `n` closes, oldest first, `na` where a bar is missing. */ closes(market: string, n: number): readonly number[]; /** The simple return over the last `n` bars. */ ret(market: string, n: number): number; /** The standard deviation of the last `n` log returns, per bar, not annualised. */ volatility(market: string, n: number): number; /** The least-squares beta of the last `n` log returns on `to`'s over the same bars. */ beta(market: string, to: string, n: number): number; /** The sum over the last `n` bars of each return less `to`'s times the beta fitted over the last `fit` bars. */ resid(market: string, to: string, n: number, fit: number): number; /** Dollar volume over the last `n` bars. */ volume(market: string, n: number): number; } interface UniverseOptions { /** Days of the universe history loaded before the chart's first bar (default 180, or what the first universe or portfolio asked for). */ history?: number; /** The interval of the pool's price reads, such as `'1h'` or `'1d'`, from 1m to 1W. Default the chart's. */ interval?: string; } /** * Universes picked point in time from every Hyperliquid perp, delisted ones included while they * traded, so a backtest never trades a market for what it later became. */ declare const universe: { /** * The `n` (at most 50) markets with the most dollar volume over the trailing `window` days (or * the most open interest on the last day, `by: 'openInterest'`), among those with `minHistory` * days of prices, re-picked every `every` days from `anchor`. Defaults: 30, 60, 30 and * 2025-03-22, signal-lab's rule; fewer than half the places filled is no universe. */ topN(n: number, options?: UniverseOptions & { by?: 'volume' | 'openInterest'; window?: number; minHistory?: number; every?: number; anchor?: string | number }): Pool; /** A rule of your own: `select(view)` returns the members best first (at most 50), or null to keep the last pick, every `every` days. */ rule(select: (view: PickView) => readonly string[] | null, options?: UniverseOptions & { every?: number; anchor?: string | number }): Pool; /** Every market listed on the day read. */ all(options?: UniverseOptions): Pool; }; /** Turning scores into a portfolio's weights. Scores and weights are objects of market to number. */ declare const portfolio: { /** The markets by score, best first; `na` scores left out. */ rank(scores: Readonly>): readonly string[]; /** * Long the top `quantile` (default 0.2) of the markets scored and short the bottom one, or one * side only (`sides`), each side's weights summing to its share of `gross` (default 1), equal or * in proportion to `by` (such as `1 / vol`). */ longShort(scores: Readonly>, options?: { quantile?: number; sides?: 'both' | 'long' | 'short'; gross?: number; by?: Readonly> }): Readonly>; /** Each weight over its market's volatility, rescaled to the same gross. */ inverseVol(weights: Readonly>, vols: Readonly>): Readonly>; }; /** Resting size in the book near the price, as of the current update. */ interface Depth { /** Total resting bid and ask size within `bandPct` percent of the mid. `bandPct` must be one of the declared bands. */ bid(bandPct: number): number; ask(bandPct: number): number; readonly bestBid: number; readonly bestAsk: number; readonly mid: number; readonly spread: number; /** When the sample read was taken; `na` when there is none. */ readonly time: Time; /** Book views have no history until the terminal serves one; before that only live bars have them. */ readonly available: boolean; } declare function depth(options: { bandsPct: readonly number[]; market?: string; venue?: Venue }): Depth; /** One price level of the live book. */ interface BookLevel { readonly price: number; /** Resting size, in the market's base unit. */ readonly size: number; /** price × size, in USD. */ readonly notional: number; } /** A level an update changed. */ interface BookChange { readonly side: 'bid' | 'ask'; readonly price: number; /** The size after the update: 0 where the level went. */ readonly size: number; /** The size before it: 0 where the level is new. */ readonly previous: number; } /** * The live order book, level by level and ungrouped, as of the current moment: built from every * update before it, as trades are delivered before it. Live only: before the page's book arrived * (every bar older than the page) it reads `available` false and empty lists. */ interface LiveBook { /** * Runs once per update of the book, in time order with trades and other events and before the * `onBar` of the bar it falls in. An update is one book the page received: about one per block * of the venue's, coalesced to at most one per frame. */ onUpdate(handler: (book: LiveBook) => void): void; /** Bids, best (highest) first; at most `levels` of them. */ readonly bids: readonly BookLevel[]; /** Asks, best (lowest) first; at most `levels` of them. */ readonly asks: readonly BookLevel[]; readonly bestBid: number; readonly bestAsk: number; readonly mid: number; readonly spread: number; /** * The size resting at `price` on a side: 0 where no level rests there, `na` past the deepest * level held on that side, where the book is not known. */ size(side: 'bid' | 'ask', price: number): number; /** * The levels the last update changed; in `onUpdate`, the update running. A level that only came * into the levels held, or left them, as the book moved is not a change: the book holds only its * nearest `levels` a side. */ readonly changes: readonly BookChange[]; /** The last update replaced the book whole: its first, or the first after the feed dropped. */ readonly snapshot: boolean; /** When the book read was taken (its last update); `na` before the first. */ readonly time: Time; /** The book is known: it has arrived, and has not been lost since. */ readonly available: boolean; } /** * The live order book of a market, level by level: the nearest `levels` a side (100 by default), * ungrouped, from 0xArchive's live book. Live only; history level by level is not served. */ declare function book(options?: { market?: string; venue?: Venue; levels?: 10 | 20 | 50 | 100 | 400 }): LiveBook; /** A band around the mid, in basis points: 10 is 0.1%, 1000 is 10%. */ type BookBand = 10 | 25 | 50 | 100 | 250 | 500 | 1000; /** `avg`, the default: the time-weighted mean over the bar. `close`: the book at the bar's end. */ type BookStat = 'avg' | 'close'; /** * The full-depth order book over each of the chart's bars (Hyperliquid and HIP-3, from 2026-09-06): * from 0xArchive's book archive, and for the newest hour from the page's live book. A bar the book * was not known for reads `na`, never 0. Live, the page holds up to 400 levels a side, so a band * that reaches past them reads `na` until the archive has the hour. */ interface OrderBook { /** Mid price. */ mid(options?: { stat?: BookStat }): number; /** Best ask less best bid over the mid, in basis points. */ spreadBps(options?: { stat?: BookStat }): number; /** Size resting at the best bid and the best ask (the best queues), in contracts. */ bestBidSize(options?: { stat?: BookStat }): number; bestAskSize(options?: { stat?: BookStat }): number; /** Resting size within `band` of the mid on one side: in contracts, or in USD with `usd: true`. */ bid(band: BookBand, options?: { usd?: boolean; stat?: BookStat }): number; ask(band: BookBand, options?: { usd?: boolean; stat?: BookStat }): number; /** Bids less asks over their sum, in USD within `band`: -1 (all asks) to 1 (all bids). */ imbalance(band: BookBand, options?: { stat?: BookStat }): number; /** What a market order of `usd` pays against the mid at the bar's end, in basis points; `na` when the book cannot fill it. */ slippageBuy(usd: 10000 | 100000 | 1000000): number; slippageSell(usd: 10000 | 100000 | 1000000): number; /** Price levels on each side at the bar's end; `na` live. */ readonly bidLevels: number; readonly askLevels: number; /** The share of the bar the book was known, 0 to 1. */ readonly coverage: number; /** True when any of the bar came from the live book rather than the archive. */ readonly live: boolean; /** The bar's open time; `na` when there is no reading. */ readonly time: Time; readonly available: boolean; } declare function orderBook(options?: { market?: string; venue?: Venue }): OrderBook; /** * Open interest over each of the chart's bars, from 0xArchive's one-minute open interest * (Hyperliquid from 2025-03-01, HIP-3 and Lighter from their own starts). A bar opens at the close * of the minute before it, so `close - open` is its whole change; its high and low are over its * minutes. In the market's base unit, or USD with `{ usd: true }` (each minute's open interest times * its mark). * * The newest bars are built from the trades instead: each trade's change in open interest * (`Trade.oiDelta`), summed and anchored to the one-minute open interest, so the forming bar moves * with every trade and each bar closes where its last trade left it. On time bars of a minute or * more that is every bar since the hour before the chart opened; on seconds bars and bars that close * on trades (tick, volume, range and the rest) it is every bar, as far back as those bars reach * (today and the two UTC days before). USD there is each level times the price of the * trade that set it. */ interface OpenInterest { open(options?: { usd?: boolean }): number; high(options?: { usd?: boolean }): number; low(options?: { usd?: boolean }): number; close(options?: { usd?: boolean }): number; /** * The bar's change, close less open. In USD it is the change in coins at the bar's closing mark, * so it counts positions opened and closed, not the price moving the ones already open. */ change(options?: { usd?: boolean }): number; /** The bar's open time; `na` when there is no reading. */ readonly time: Time; readonly available: boolean; } declare function openInterest(options?: { market?: string; venue?: Venue }): OpenInterest; /** * The funding rate over each of the chart's bars, from 0xArchive's one-minute funding readings * (Hyperliquid from 2025-03-01, HIP-3 and Lighter from their own starts). A bar's rate is the * venue's rate at its last minute: on Hyperliquid the predicted rate for the hour then running, * which is what settles at the hour's end, so a 1h bar holds the rate its hour paid. Positive: * longs pay shorts. The forming bar moves as each minute closes, about 1 to 4 minutes behind. Only * time charts of whole minutes, 1m or longer, have it: on seconds, tick, volume and range bars * every value is `na`. */ interface Funding { /** The rate as a fraction per hour, as the venues pay it, or per `hours` hours (8 for an eight-hour rate, 8760 for a year's). */ rate(options?: { hours?: number }): number; /** The premium at the bar's last minute, the mark's distance from the oracle the rate is built from; `na` on Lighter. */ readonly premium: number; /** The bar's open time; `na` when there is no reading. */ readonly time: Time; readonly available: boolean; } declare function funding(options?: { market?: string; venue?: Venue }): Funding; /** A price level with resting size on each side, such as a liquidation or stop cluster. */ interface Level { readonly price: number; /** USD notional that would trade if price reached the level: long and short positions, or buy and sell orders. */ readonly longUsd: number; readonly shortUsd: number; } interface Levels { /** The levels as of the current bar, sorted by price. Empty when unknown. */ levels(): readonly Level[]; /** When the snapshot read was taken; `na` when there is none. */ readonly time: Time; readonly available: boolean; } /** Where open positions would be liquidated, from 0xArchive's liquidation levels. */ declare function liquidationLevels(options?: { market?: string; venue?: Venue }): Levels; /** Resting stop and trigger orders by price, where the data exists. */ declare function triggers(options?: { market?: string; venue?: Venue }): Levels; /** One strike's dealers at a `dealerExposure()` snapshot. */ interface StrikeExposure { readonly strike: number; /** Dealers' net position in BTC of options at this strike, calls and puts together: + long, − short. */ readonly position: number; /** What this strike adds to the totals at the snapshot's price, in the same units. */ readonly gamma: number; readonly charm: number; readonly vanna: number; } interface DealerExposure { /** The snapshot as of the current bar: when it was taken, and the BTC index then (the options' underlying). */ readonly time: Time; readonly spot: number; /** Where dealers' total gamma changes sign nearest spot, within 6%; `na` when it keeps one sign. */ readonly flip: number; /** * Dealers' totals at spot. Gamma: BTC of delta per $1,000 of price; + dealers lean against moves * (sell rises, buy dips), − they chase them. Charm: BTC of delta per hour as time passes; + dealers * sell, − they buy. Vanna: BTC of delta per vol point of implied volatility; + dealers sell as IV * rises, − they buy. */ readonly gamma: number; readonly charm: number; readonly vanna: number; /** Every strike with a dealer position, sorted by strike. */ strikes(): readonly StrikeExposure[]; readonly available: boolean; } interface DealerExposureOptions { /** * How dealer positions are inferred from the options' trades. 'block' (the default): dealers hold the * other side of block trades, where the taker asked for the quote. 'all': every trade, which counts * a dealer who lays a block off on screen twice. */ model?: 'block' | 'all'; /** * Which options count. 'next' (the default): the nearest expiry still to come at each snapshot, * as the Dealer exposure panel opens; it dominates gamma near spot. 'all': every expiry. */ expiries?: 'next' | 'all'; } /** * BTC option dealers, every 5 minutes, whatever the chart's market: their gamma, charm and * vanna at BTC's price, the gamma flip, and each strike's net position. The last 7 days. */ declare function dealerExposure(options?: DealerExposureOptions): DealerExposure; /** One BTC option print, with every field the exchange sends. */ interface OptionTrade { readonly time: Time; /** The option's price in BTC, and the size in BTC of options. */ readonly price: number; readonly size: number; /** The premium in USD: price × size × the index. */ readonly notional: number; /** The taker's side. On a block the taker is the one who asked for the quote. */ readonly side: 'buy' | 'sell'; readonly strike: number; /** When it expires: 08:00 UTC on its date. */ readonly expiry: Time; readonly type: 'call' | 'put'; /** Implied volatility of the print, in percent. */ readonly iv: number; readonly markPrice: number; readonly indexPrice: number; readonly contracts: number; readonly tradeSeq: number; readonly tickDirection: number; readonly liquidation: boolean; /** True for a leg of a block trade. */ readonly block: boolean; readonly blockLegs: number; readonly tradeId: string | null; /** The instrument's name, such as `BTC-6NOV26-82000-C`. */ readonly instrument: string | null; /** The order it belongs to: a block's id, `COMBO-…` for a screen combo, or `TAKER-{time}-{side}`. */ readonly group: string | null; readonly blockTradeId: string | null; readonly blockRfqId: string | null; readonly comboId: string | null; readonly comboTradeId: string | null; /** Which side was liquidated, as the exchange writes it ('M', 'T' or 'MT'), or null. */ readonly liquidationSide: string | null; readonly starbaseMatchId: string | null; readonly starbaseTimestamp: string | null; /** Any field the exchange added that has no name here yet, as JSON text, or null. */ readonly extra: string | null; } interface OptionTradesOptions { /** Skip prints smaller than this, in BTC of options. */ minSize?: number; /** Skip prints whose premium is under this, in USD. */ minNotional?: number; } interface OptionTrades { /** Runs once per print, in time order with other events and before the `onBar` of the bar it falls in. */ onTrade(handler: (trade: OptionTrade) => void): void; /** Whether the prints cover the current bar completely. */ readonly available: boolean; } /** Every BTC option print, whatever the chart's market: history back to the chart's first bar, at most 7 days, then live. */ declare function optionTrades(options?: OptionTradesOptions): OptionTrades; /** * One option order, joined from its prints: a block, a screen combo, or one taker order that took * several prices or strikes in the same millisecond (a sweep). */ interface OptionOrder { readonly time: Time; readonly kind: 'block' | 'combo' | 'taker'; /** The taker's side, or 'mixed' when the legs went both ways (a spread). */ readonly side: 'buy' | 'sell' | 'mixed'; /** The legs' sizes summed, in BTC of options, and split by side and by type. */ readonly size: number; readonly buySize: number; readonly sellSize: number; readonly callSize: number; readonly putSize: number; /** The premium in USD, and in BTC. `notional` is the premium in USD too. */ readonly premium: number; readonly premiumBtc: number; readonly notional: number; /** How many prints, strikes and expiries it took, its first print's strike, and its lowest and highest. */ readonly fills: number; readonly strikes: number; readonly expiries: number; readonly strike: number; readonly lowStrike: number; readonly highStrike: number; readonly liquidation: boolean; readonly group: string | null; } interface OptionOrders { /** Runs once per order, once all its prints are in. */ onOrder(handler: (order: OptionOrder) => void): void; readonly available: boolean; } /** BTC option orders joined from their prints: the same history and live feed as `optionTrades()`. */ declare function optionOrders(options?: OptionTradesOptions): OptionOrders; /** * One row of a volume profile: what takers bought and sold between `low` and `high`, in the * market's base unit. */ interface ProfileRow { /** Where the row starts: a whole multiple of the row size, or the traded price itself without one. */ readonly low: number; /** Where the next row starts; equal to `low` for a row that is one traded price. */ readonly high: number; /** The middle of the row, where a line through it is drawn. */ readonly price: number; /** Taker buying. */ readonly buy: number; /** Taker selling. */ readonly sell: number; /** buy + sell. */ readonly total: number; /** buy − sell. */ readonly delta: number; } /** The rows around the point of control holding a share of a profile's volume. */ interface ValueArea { /** The value area's low (VAL): the bottom of its lowest row. */ readonly low: number; /** The value area's high (VAH): the top of its highest row. */ readonly high: number; /** The middle of the point of control's row. */ readonly poc: number; /** The volume inside the area. */ readonly volume: number; } interface ProfileOptions { /** * The height of each row in price, such as 10 for $10 rows on BTC. Rows sit on whole multiples * of it, so a row is the same row on every bar and in every profile. Defaults to the stream's * `rowSize`; without either, each traded price is its own row. */ rowSize?: number; } /** * Volume by price over a span of trades, as of the moment the handler runs. Read it in the run * that asked for it: asking the stream again for the same span gives the newer profile. */ interface Profile { /** Whether the trades cover the whole span. A span older than the trade history is missing its start. */ readonly available: boolean; /** Taker buying, taker selling, both, and buying less selling, over the span. */ readonly buy: number; readonly sell: number; readonly total: number; readonly delta: number; /** The highest and lowest traded price in the span; `na` with no trades. */ readonly high: number; readonly low: number; /** * The rows, lowest price first. With a row size, every row from the lowest to the highest * traded one, empty rows included; without, each traded price. `null` past 4,096 rows: use a * larger row size. */ rows(options?: ProfileOptions): readonly ProfileRow[] | null; /** The point of control: the row with the most volume (the higher one on a tie); `null` with no trades. */ poc(options?: ProfileOptions): ProfileRow | null; /** * The value area holding `percent` (default 70) of the volume, by TradingView's rule, the one the * footprint chart uses: from the point of control, add whichever neighbouring row holds more, * while the area stays at or under the share. `null` with no trades. */ valueArea(percent?: number, options?: ProfileOptions): ValueArea | null; } /** * Volume by price from the market's trades (`trades()`): what takers bought and sold at each * price, over the current chart bar, the last few bars, or since a time such as the session's * start. Trades reach back to the chart's first bar, at most 7 UTC days. Before that, a span reads * the archive's order flow by bar (`orderFlow()`) at the same row size, so it starts at the first * whole bar at or after its start; where neither covers it, it reads `available: false`. */ interface VolumeProfile { /** Whether trades cover the current chart bar completely, as `trades().available`. */ readonly available: boolean; /** The current chart bar's trades so far: a footprint's rows. */ bar(): Profile; /** The current chart bar and the `bars - 1` before it, 1 to 5,000. */ last(bars: number): Profile; /** Every trade from `time` to now, such as the session so far: `since(clock.startOf(chart.time, 'day'))`. */ since(time: Time): Profile; } declare function volumeProfile(options?: { market?: string; venue?: Venue; rowSize?: number }): VolumeProfile; /** One price row of a bar's order flow: what takers bought and sold at that price. Sizes in the market's base unit. */ interface FlowRow { /** The traded price, or with a row size the row's low edge (a whole multiple of it). */ readonly price: number; readonly buyVolume: number; readonly sellVolume: number; /** `buyVolume - sellVolume`. */ readonly delta: number; readonly buyCount: number; readonly sellCount: number; /** USD at the traded prices. */ readonly buyNotional: number; readonly sellNotional: number; } /** * One bar's order flow: every trade that filled against the book in it, as the venue's candles count them, so its * volume and trade count equal the bar's. Backstop liquidations and auto-deleveraging are counted beside it * (`offBookVolume`), never in it. Sizes in the market's base unit. */ interface FlowBar { /** The bar's open. */ readonly time: Time; /** Whether the bar is whole and its rows are held. False for a bar the archive does not know, holds only part of (`partial`), or past the rows kept. */ readonly available: boolean; /** The bar's rows, lowest price first; empty when not held. */ readonly rows: readonly FlowRow[]; readonly buyVolume: number; readonly sellVolume: number; /** `buyVolume - sellVolume`. */ readonly delta: number; readonly buyCount: number; readonly sellCount: number; readonly buyNotional: number; readonly sellNotional: number; /** The running delta's low and high after each trade, from 0 at the bar's open, never clamped at 0; `na` with no trade. */ readonly minDelta: number; readonly maxDelta: number; /** Book liquidations, by the taker's side: a liquidated long sells. */ readonly liquidatedBuy: number; readonly liquidatedSell: number; /** Trades that did not fill against the book (backstop liquidations, auto-deleveraging), not in the rows or totals; `na` on a bar from the live trades. */ readonly offBookVolume: number; readonly offBookCount: number; /** Trades in the bar's busiest clock second. */ readonly peakSecond: number; /** The order of trades within a millisecond was inferred somewhere in the bar, so `minDelta`/`maxDelta` may be approximate there. */ readonly orderHeuristic: boolean; /** Only the bar's first part is known (the archive ends inside it). */ readonly partial: boolean; } /** Order flow rows summed over a run of whole bars. */ interface FlowProfile { /** The span counted: the first bar's open and the last bar's close (`na` when no bar is in it). */ readonly from: Time; readonly to: Time; /** Whether every bar in it is known whole and its rows are held. */ readonly available: boolean; /** Rows by price, lowest first. Read in the run that asked for it. */ readonly rows: readonly FlowRow[]; readonly buyVolume: number; readonly sellVolume: number; readonly delta: number; } /** * Order flow by bar at the chart's interval, from 0xArchive's order flow archive: per bar and price, what takers * bought and sold, with the bar's delta, its running delta's extremes, liquidations and busiest second. Built from * every trade that filled against the book and checked minute by minute against the candles, so a bar's volume and * trade count equal the candle's. Hyperliquid perps from 22 Mar 2025 12:00 UTC and HIP-3 from 22 Dec 2025 at the * earliest; it reaches as far back as the chart, a year in a backtest, where `trades()` reaches 7 days. * * A bar is read once it has closed, never before: in a bar's own handler `bar()` is that bar. The forming bar is not * in it: live, its order flow is `trades()` or `volumeProfile().bar()`. On a chart, bars after the archive's last closed hour * are folded from the live trades as they close (their `offBookVolume` is `na`: the live tape does not tell those * trades apart). What neither knows (before the archive's start, a day it has not built) reads `available: false` and * `na`, never 0. Rows are kept for the last * 2,000 bars or 500,000 rows, whichever is fewer; totals for the whole run. */ interface OrderFlow { /** Whether `bar()` is a whole bar the archive knows. */ readonly available: boolean; /** The newest bar closed as of the handler (in a bar's handler, that bar); `null` before any. */ bar(): FlowBar | null; /** The newest `bars` closed bars, oldest first, 1 to 2,000. */ last(bars: number): readonly FlowBar[]; /** Rows summed from the first whole bar at or after `time` to the newest closed bar. */ since(time: Time): FlowProfile; /** * Cumulative delta in base units to the newest closed bar: `'session'` (the default) from 00:00 UTC of its day, * `'start'` from the first bar the order flow covers. `na` when any bar from the anchor on is not known whole. */ cvd(anchor?: 'session' | 'start'): number; } /** * Order flow by bar (`OrderFlow`). `rowSize` puts the rows on whole multiples of it, `floor(price / rowSize)` as * `volumeProfile()` places them, and must be a whole multiple of the market's price step; without it each traded price * is its own row, so a run never depends on the price when it ran. Every chart interval of a minute or more; seconds * bars and bars that close on trades read `available: false`. */ declare function orderFlow(options?: { market?: string; venue?: Venue; rowSize?: number }): OrderFlow; /** * What one side of a trade did to its position, as `takerWhy` and `makerWhy` name it, or `unknown` where 0xArchive * could not vouch for the position. */ type IntentCategory = Intent | 'unknown'; /** One category of a bar's intent flow: the trades in it summed. Sizes in the market's base unit. */ interface IntentCell { /** Size traded. */ readonly volume: number; /** USD at the traded prices. */ readonly notional: number; /** `notional / volume`: the category's volume-weighted price; `na` with no trade in it. */ readonly vwap: number; /** Trades. */ readonly count: number; } /** A side's categories, and `total`: every trade of the bar, whatever its category, `unknown` included. */ type IntentSide = { readonly [category in IntentCategory | 'total']: IntentCell }; /** * One bar's intent flow: every trade that filled against the book in it, as the venue's candles count them, by what * each side did to its position. Each side counts every trade once, so `taker.total` and `maker.total` are the bar's * volume and trade count; `all` adds the two, every trade twice. */ interface IntentBar { /** The bar's open. */ readonly time: Time; /** Whether the archive knows the whole bar. False for a bar it does not know (every number `na`) or knows only the first part of (`partial`). */ readonly available: boolean; /** Only the bar's first part is known (the archive ends inside it): its sums so far. */ readonly partial: boolean; /** The aggressors: `taker.stop_long` is longs that sold out at a loss or were forced out, into the book. */ readonly taker: IntentSide; /** The resting orders they filled: `maker.open_short` is shorts opened by resting sells that takers bought from. */ readonly maker: IntentSide; /** Taker and maker added: `all.open_long` is every long opened, by either side. */ readonly all: IntentSide; } /** * Intent flow by bar at the chart's interval, from 0xArchive's intent flow archive: per bar, the book trades summed by * what each side did to its position (`open_long`, `tp_short`, `stop_long` and the rest, as `takerWhy` and `makerWhy` * name it), with each category's volume, notional, VWAP and count. "stop" is a losing or forced exit (closed at a loss, * liquidated or auto-deleveraged), not a stop order. Hyperliquid perps from 25 May 2025 14:24 UTC and HIP-3 from * 22 Dec 2025 at the earliest; it reaches as far back as the chart, a year in a backtest, where `trades()` reaches 7 days. * * A bar is read once it has closed, never before: in a bar's own handler `bar()` is that bar. The forming bar is not in * it, and neither is any bar after the archive's last closed hour: those read `available: false` and `na`, never 0, as * does a day the archive has not built and everything before its start. Live, sum `trades()` by `takerWhy` instead. */ interface IntentFlow { /** Whether `bar()` is a whole bar the archive knows. */ readonly available: boolean; /** The newest bar closed as of the handler (in a bar's handler, that bar); `null` before any. */ bar(): IntentBar | null; /** The newest `bars` closed bars, oldest first, 1 to 2,000. */ last(bars: number): readonly IntentBar[]; } /** * Intent flow by bar (`IntentFlow`) for the chart's market, or `market`. Every chart interval of a minute or more; * seconds bars and bars that close on trades read `available: false`. */ declare function intentFlow(options?: { market?: string; venue?: Venue }): IntentFlow; /** Exchange session calendars for HIP-3 stock and commodity perps. */ declare const sessions: { /** The calendar id for a market, such as `nyse`, or `null` for markets that trade around the clock. */ calendarOf(market: string): string | null; /** * Whether `calendar` is in session at `time` (regular or extended hours), with that session's * bounds; when closed, `start` is the last close and `end` the next open. `regular` says whether * the session is the regular one. Holidays and early closes included. */ at(calendar: string, time: Time): { readonly open: boolean; readonly regular: boolean; readonly start: Time; readonly end: Time }; }; // --------------------------------------------------------------------------------------------- // State: values that persist between runs. Declared at the top level only. // // A local variable inside a handler starts fresh on every run. Anything that must persist is // declared here, with its lifetime, so the engine can roll it back correctly. // --------------------------------------------------------------------------------------------- type StateValue = number | boolean | string | null; interface Cell { value: T; } /** A number with history, made with `series(lookback)`. */ interface Series { /** Sets the value for the current bar. Unset bars are `na`. */ set(value: number): void; /** The current bar's value. */ readonly value: number; /** The value `n` bars ago, `n` at most the declared lookback. */ ago(n: number): number; } interface Tally { add(amount: number): void; /** The sum so far in the current bar. */ readonly value: number; /** How many amounts were added in the current bar. */ readonly count: number; } interface TallyBy { /** Add to `key`'s sum for this bar. A new key past the capacity is dropped for the rest of the bar. */ add(key: string, amount: number): void; /** `key`'s sum so far in this bar, 0 when it has none. */ get(key: string): number; /** How many keys have a sum this bar. */ readonly size: number; /** Every key with its sum, in the order the keys were first added. */ entries(): IterableIterator<[string, number]>; } interface StateList { readonly length: number; /** The value at `index`, from 0 at the oldest. */ get(index: number): T; set(index: number, value: T): void; /** Add at the end. Past the capacity the script stops (OX2004): `shift` the oldest first. */ push(value: T): void; /** Take from the end. */ pop(): T; /** Take from the start, the oldest. */ shift(): T; /** Add at the start. */ unshift(value: T): void; clear(): void; /** A copy as a plain array, oldest first. */ toArray(): T[]; } interface StateMap { readonly size: number; /** The value for `key`, or `undefined` when there is none. */ get(key: string): T | undefined; /** Set the value for `key`. A new key past the capacity stops the script (OX2004). */ set(key: string, value: T): void; /** Remove `key`; true when it was there. */ delete(key: string): boolean; has(key: string): boolean; clear(): void; entries(): IterableIterator<[string, T]>; } type Lifetime = 'bar' | 'live'; declare const state: { /** Kept across bars; rolled back before each update of the forming bar (Pine's `var`). */ bar(initial: T): Cell; /** Kept across bars and across updates of the forming bar (Pine's `varip`). */ live(initial: T): Cell; /** A list of at most `capacity` values with a lifetime, default `'bar'`. */ list(capacity: number, lifetime?: Lifetime): StateList; map(capacity: number, lifetime?: Lifetime): StateMap; /** A matrix kept across bars and rolled back with the forming bar, all zeros at first. */ mat(rows: number, cols: number): StateMat; }; /** A number with history: `lookback` bars kept, at most 5,000. */ declare function series(lookback: number): Series; /** A sum of what event handlers add during a bar. Starts at 0 on each new bar; never rolled back. */ declare function tally(): Tally; /** A sum per key (such as a taker order id) during a bar, at most `capacity` keys. Empty on each new bar. */ declare function tallyBy(capacity: number): TallyBy; // --------------------------------------------------------------------------------------------- // Indicators: instances with their own state. Create at the top level, update in a handler. // // Update an instance once per run, on every bar: an instance only advances when `update` runs, // so updating inside an `if` gives a different result (Pine's call-site rule, made visible). // Values match TradingView's built-ins, including their seeds and how they treat `na`. // --------------------------------------------------------------------------------------------- interface Indicator { update(...values: In): Out; /** The value after the latest update in this run. */ readonly value: Out; /** The value as of this stream's last closed bar. Read it from other streams' handlers. */ readonly confirmed: Out; } type Average = Indicator<[value: number], number>; interface MacdValue { readonly macd: number; readonly signal: number; readonly histogram: number } interface BandsValue { readonly basis: number; readonly upper: number; readonly lower: number } interface DmiValue { readonly plus: number; readonly minus: number; readonly adx: number } interface SupertrendValue { readonly line: number; /** 1 up, -1 down */ readonly direction: number } type VwapAnchor = 'session' | 'week' | 'month' | 'quarter' | 'year' | Time; declare const ta: { /** Simple moving average of the last `length` values. */ sma(length: number): Average; /** Seeded with the simple average of the first `length` values, as TradingView's `ta.ema`. */ ema(length: number): Average; /** Wilder's average, seeded like `ema`. */ rma(length: number): Average; /** Linearly weighted moving average: the newest value weighs `length`, the oldest 1. */ wma(length: number): Average; /** Hull moving average, a weighted average of weighted averages that lags less. */ hma(length: number): Average; /** Volume-weighted moving average of the last `length` values. */ vwma(length: number): Indicator<[value: number, volume: number], number>; /** Standard deviation of the last `length` values, over `length` as TradingView divides (not `length - 1`). */ stdev(length: number): Average; /** Variance of the last `length` values, the square of `stdev`. */ variance(length: number): Average; /** The highest of the last `length` values, the current one included. */ highest(length: number): Average; /** The lowest of the last `length` values, the current one included. */ lowest(length: number): Average; /** Bars since the highest or lowest value in the window, as a negative offset like TradingView's. */ highestBars(length: number): Average; lowestBars(length: number): Average; /** value − value `length` bars ago. */ change(length?: number): Average; /** Momentum: the value less the value `length` bars ago. */ mom(length: number): Average; /** Rate of change: the percent change from the value `length` bars ago. */ roc(length: number): Average; /** Relative strength index, 0 to 100, on Wilder's averages. */ rsi(length: number): Average; /** Commodity channel index: the distance from the `length`-bar average in units of mean deviation, over 0.015. */ cci(length: number): Average; /** The least-squares line through the last `length` values, read `offset` bars back from its end (0, the default, is the current bar). */ linreg(length: number, offset?: number): Average; /** The percent of the previous `length` values that are at or below the current one. */ percentRank(length: number): Average; /** The running sum of every value since the first bar. */ cum(): Average; /** True when the value has risen on each of the last `length` bars (a step within 1e-10 does not count). */ rising(length: number): Indicator<[value: number], boolean>; /** True when the value has fallen on each of the last `length` bars. */ falling(length: number): Indicator<[value: number], boolean>; /** True on the bar where `a` goes from at or below `b` to above it. */ crossover(): Indicator<[a: number, b: number], boolean>; /** True on the bar where `a` goes from at or above `b` to below it. */ crossunder(): Indicator<[a: number, b: number], boolean>; /** True on the bar where `a` crosses `b` either way. */ cross(): Indicator<[a: number, b: number], boolean>; /** Bars since `condition` was last true: 0 on a bar where it is, `na` until the first time. */ barsSince(): Indicator<[condition: boolean], number>; /** `value` on the bar where `condition` was true, the `occurrence`-th time back (0, the default, is the latest). */ valueWhen(occurrence?: number): Indicator<[condition: boolean, value: number], number>; /** * A pivot high: a value higher than the `left` before it and the `right` after it. It is known * only `right` bars later, so it is returned on that bar, `na` on every other. */ pivotHigh(left: number, right: number): Indicator<[value: number], number>; /** A pivot low, as `pivotHigh`: returned `right` bars after the low, `na` on every other bar. */ pivotLow(left: number, right: number): Indicator<[value: number], number>; /** MACD: the fast EMA less the slow EMA, its `signal`-bar EMA, and the difference of the two as the histogram. */ macd(fast: number, slow: number, signal: number): Indicator<[value: number], MacdValue>; /** Bollinger Bands: the `length`-bar SMA, and bands `mult` standard deviations either side. */ bb(length: number, mult: number): Indicator<[value: number], BandsValue>; /** Keltner Channels: the `length`-bar EMA of the close, and bands `mult` times the `length`-bar EMA of the true range (or of the bar's range) either side. */ kc(length: number, mult: number, useTrueRange?: boolean): Indicator<[bar: BarView], BandsValue>; /** Stochastic: where the close sits in the `length`-bar range of highs and lows, 0 to 100. Smooth it with `ta.sma` for %K and %D. */ stoch(length: number): Indicator<[close: number, high: number, low: number], number>; /** Money flow index, 0 to 100: an RSI of the typical price weighted by volume. */ mfi(length: number): Indicator<[bar: BarView], number>; /** On-balance volume: the running sum of volume, added on up closes and taken away on down closes. */ obv(): Indicator<[bar: BarView], number>; /** True range. `handleNa` as TradingView: on the first bar, high − low. */ tr(handleNa?: boolean): Indicator<[bar: BarView], number>; /** Average true range: Wilder's average of the true range over `length` bars. */ atr(length: number): Indicator<[bar: BarView], number>; /** Directional movement: +DI, -DI and the ADX, which measures trend strength whatever its direction. */ dmi(diLength: number, adxSmoothing: number): Indicator<[bar: BarView], DmiValue>; /** Supertrend: a trailing line `factor` ATRs from the price that flips side when the close crosses it, with its direction. */ supertrend(factor: number, atrLength: number): Indicator<[bar: BarView], SupertrendValue>; /** Volume-weighted average price from quote and base volume, reset at each anchor (UTC). */ vwap(anchor?: VwapAnchor): Indicator<[bar: BarView], number>; }; // --------------------------------------------------------------------------------------------- // Statistics and machine learning. Instances like `ta.*`: create at the top level, update once per bar, // and they roll back with the forming bar. A bar with `na` in an input returns `na` and // leaves the window or model as it was. The oracle is pandas, numpy and statsmodels, so variance // divides by n − 1 (pandas' default), where `ta.stdev` divides by n as TradingView does. // --------------------------------------------------------------------------------------------- type VolEstimator = 'close' | 'parkinson' | 'garmanKlass' | 'rogersSatchell' | 'yangZhang'; declare const stats: { /** (value − mean) / standard deviation over the last `length` values; `clip` caps it either way. */ zscore(length: number, options?: { clip?: number }): Average; /** Pearson correlation of `a` and `b` over the last `length` pairs, −1 to 1. */ corr(length: number): Indicator<[a: number, b: number], number>; /** Sample covariance (n − 1) of `a` and `b` over the last `length` pairs. */ cov(length: number): Indicator<[a: number, b: number], number>; /** Slope of `y` on `x` over the window: cov(y, x) / var(x). */ beta(length: number): Indicator<[y: number, x: number], number>; /** Skew, pandas' adjusted Fisher-Pearson: 0 for a symmetric window. */ skew(length: number): Average; /** Excess kurtosis, pandas' unbiased: 0 for a normal distribution. */ kurt(length: number): Average; /** The `q` quantile (0 to 1) of the window, interpolated linearly as pandas does. */ quantile(length: number, q: number): Average; median(length: number): Average; /** Correlation of the window with itself `lag` values back (default 1), as pandas' `Series.autocorr`. */ autocorr(length: number, lag?: number): Average; /** Exponentially weighted variance by half-life in bars, as pandas' `ewm(halflife).var()`. */ ewmVar(halfLife: number): Average; ewmCov(halfLife: number): Indicator<[a: number, b: number], number>; ewmCorr(halfLife: number): Indicator<[a: number, b: number], number>; /** * Volatility per bar over `length` bars from each bar's prices: `close` (log returns, the * default), `parkinson` (high and low), `garmanKlass`, `rogersSatchell` or `yangZhang` (with * the gap from the previous close). `annualize` scales by the bars in a 365-day year. */ vol(length: number, estimator?: VolEstimator, options?: { annualize?: boolean }): Indicator<[bar: BarView], number>; }; interface RegressionValue { readonly coef: readonly number[]; /** `na` for a model made with `intercept: false`. */ readonly intercept: number; readonly r2: number; /** The estimate of y from this bar's x, by what the model had learned before this bar. */ readonly fitted: number; /** y less `fitted`: an out-of-sample error. */ readonly residual: number; /** * t-statistics of the coefficients, assuming independent errors. They overstate significance * when labels overlap, such as 12-bar forward returns sampled every bar. */ readonly t: readonly number[]; /** Bars learned: the window's count for `ols`, every bar so far for `rls`. */ readonly n: number; } interface Regression extends Indicator<[y: number, x: readonly number[]], RegressionValue> { /** The estimate of y for `x` from what the model has learned so far. Doesn't learn. */ predict(x: readonly number[]): number; } interface LevelValue { readonly level: number; readonly variance: number; /** This bar's value less the level before it. */ readonly innovation: number; /** The innovation in standard deviations. */ readonly z: number; } interface HedgeValue { readonly alpha: number; readonly beta: number; /** y less α + βx, by the estimates before this bar: the spread a pairs trade watches. */ readonly spread: number; readonly spreadZ: number; } interface ForwardValue { /** The inputs from `horizon` bars ago. */ readonly x: readonly number[]; /** The log return of `price` since then. */ readonly ret: number; } interface PcaValue { /** Share of variance each component explains, largest first. */ readonly explained: readonly number[]; /** This bar's input on each component, by the components as of the last refit. What a model learns from. */ readonly scores: readonly number[]; /** Loadings of component `c` (0 is the first), one per input; each component's largest loading is positive. */ loadings(c: number): readonly number[]; /** The part of input `i` this bar the components don't explain, in the units PCA works in (standardised with `standardize`). */ residual(i: number): number; /** The residual over its standard deviation in the window, as of the last refit. */ residualZ(i: number): number; } interface PcrValue { readonly coef: readonly number[]; /** The mean of y in the window; `na` for a model made with `intercept: false`. */ readonly intercept: number; /** In-sample R² of the last fit. */ readonly r2: number; /** Share of the inputs' variance each component explains, largest first. */ readonly explained: readonly number[]; /** The `quantiles` asked for, of the last fit's predictions over its own window: thresholds the forecast is judged against. */ readonly quantiles: readonly number[]; /** Pairs in the last fit. */ readonly n: number; /** True on the bar the model refit. */ readonly refitted: boolean; /** Loadings of component `c` (0 is the first), one per input; each component's largest loading is positive. */ loadings(c: number): readonly number[]; } interface PcaRegression extends Indicator<[y: number, x: readonly number[]], PcrValue> { /** The estimate of y for `x` from the last fit; `na` before the first. Doesn't learn. */ predict(x: readonly number[]): number; /** `x` on each component of the last fit, centred and scaled as the fit was. */ scores(x: readonly number[]): readonly number[]; } interface ScoreValue { /** The information coefficient at horizon `h`: the correlation of the forecast with the `h`-bar log return that followed it, over every pair so far. */ ic(h: number): number; /** The share of pairs whose forecast and return had the same sign (zeros left out). */ hit(h: number): number; /** * The t-statistic of the slope of the return on the forecast, Newey-West with `h − 1` lags * (statsmodels' HAC without its small-sample correction). Overlapping returns share bars, and a * plain t-statistic overstates significance by about √h; this one doesn't. */ t(h: number): number; /** Pairs scored at horizon `h`. */ n(h: number): number; } declare const ml: { /** * Least squares over the last `length` bars, from `inputs` x values per bar. `ridge` penalises * the coefficients (not the intercept) to keep the fit stable when inputs move together. */ ols(length: number, inputs: number, options?: { intercept?: boolean; ridge?: number }): Regression; /** * Recursive least squares: every bar so far, each older bar weighted `forget` times less (1, the * default, weighs all alike). The same estimates as the closed-form weighted ridge solution. */ rls(inputs: number, options?: { forget?: number; intercept?: boolean; ridge?: number }): Regression; /** * A Kalman local-level filter: a smoothed value with its uncertainty. Only the ratio of the two * variances moves the level; set `noiseVar` to the noise in the data to read `variance` in its units. */ kalman(options?: { processVar?: number; noiseVar?: number }): Indicator<[z: number], LevelValue>; /** A hedge ratio that drifts with time, y = α + βx: the standard pairs-trading filter, by default `delta` 1e-4 and `noiseVar` 1e-3. */ kalmanBeta(options?: { delta?: number; noiseVar?: number }): Indicator<[y: number, x: number], HedgeValue>; /** * Inputs held `horizon` bars and handed back with the log return of `price` since, once it * exists; `null` until then. Train on what it returns, and a model never sees the future. */ forward(horizon: number, inputs: number): Indicator<[x: readonly number[], price: number], ForwardValue | null>; /** * Principal components of the last `window` (default 500) lists of `inputs` numbers, exact, * recomputed every `refit` closed bars and held in between. `'auto'`, the default, refits every * bar up to 20 inputs and less often above, to keep the cost near 20 inputs'. `components` * defaults to 3; `standardize` works on correlations instead of covariances. */ pca(inputs: number, options?: { window?: number; components?: number; standardize?: boolean; refit?: number | 'auto' }): Indicator<[x: readonly number[]], PcaValue>; /** * Principal component regression, walk-forward: every `refit` labelled pairs on closed bars, * once `window` (default 500) are in, the components of x and the regression of y on them are * fitted together on the window, then frozen until the next refit, centre and scale included. * Feed it pairs from `ml.forward`. `quantiles` (up to 8, 0 to 1) asks for quantiles of the fit's * in-sample predictions. Other options as `ml.pca` and `ml.ols`. */ pcr(inputs: number, options?: { window?: number; components?: number; standardize?: boolean; refit?: number | 'auto'; intercept?: boolean; quantiles?: readonly number[] }): PcaRegression; /** * Scores a forecast against what followed, at up to 8 `horizons` in bars (each 1 to 200): pass * each bar's forecast and price, and every forecast is scored once its return exists. */ score(horizons: readonly number[]): Indicator<[forecast: number, price: number], ScoreValue>; }; // --------------------------------------------------------------------------------------------- // Matrices. Results are the same bits in every browser; a decomposition takes steps from the // budget in proportion to its work (about n³). Eigenvectors and right singular vectors have their // largest entry positive, so they don't flip between bars. // --------------------------------------------------------------------------------------------- /** A matrix: rows × columns of numbers. */ interface Mat { readonly rows: number; readonly cols: number; get(row: number, col: number): number; set(row: number, col: number, value: number): void; row(index: number): readonly number[]; col(index: number): readonly number[]; toArray(): number[][]; } /** A matrix kept across bars (`state.mat`). */ interface StateMat extends Mat { /** Copy every entry of a matrix of the same shape. */ assign(source: Mat): void; fill(value: number): void; } declare const linalg: { /** A matrix of zeros, or of `values` given row by row (flat, or as a list of rows). At most 512 rows or columns. */ mat(rows: number, cols: number, values?: readonly number[] | readonly (readonly number[])[]): Mat; identity(n: number): Mat; mul(a: Mat, b: Mat): Mat; /** A matrix times a vector. */ mul(a: Mat, x: readonly number[]): readonly number[]; transpose(a: Mat): Mat; add(a: Mat, b: Mat): Mat; sub(a: Mat, b: Mat): Mat; scale(a: Mat, k: number): Mat; /** x with a·x = b, by LU with pivoting; `na` throughout when `a` is singular. */ solve(a: Mat, b: Mat): Mat; solve(a: Mat, b: readonly number[]): readonly number[]; /** The inverse; `na` throughout when `a` is singular. */ inv(a: Mat): Mat; /** The lower factor L of a = L·Lᵀ; `na` throughout when `a` is not positive definite. */ cholesky(a: Mat): Mat; /** Reduced QR: q is rows × k and r is k × cols, k the smaller of the two, with a non-negative diagonal in r. */ qr(a: Mat): { readonly q: Mat; readonly r: Mat }; /** Symmetric matrices only: eigenvalues largest first, unit eigenvectors as the columns of `vectors`. */ eigSym(a: Mat): { readonly values: readonly number[]; readonly vectors: Mat }; /** Reduced SVD, a = u · diag(s) · vᵀ, singular values largest first. */ svd(a: Mat): { readonly u: Mat; readonly s: readonly number[]; readonly v: Mat }; }; // --------------------------------------------------------------------------------------------- // Outputs. Declared at the top level only, at most 64 plots, set in handlers. // A plot not set on a bar is `na` there: a line or an area breaks (a gap), and a plot that says // `join: true` is drawn straight across the bars it has no value on. Histograms and points draw // nothing on such a bar. // --------------------------------------------------------------------------------------------- interface PlotOptions { color?: Color | null; pane?: PaneName; /** * How this plot's values print in the legend, on its axis tag and in list columns, wherever it * draws: a cumulative delta in `'volume'` (1.89B), a spread in `'price'`. Default: the script's * `format` off the price scale, and the market's price on it. */ format?: ValueFormat; /** * Hide from the chart, and from the legend's values. With `legend: false` too, a reading kept * for list columns (the watchlist, In play): never drawn, and a column starts on it. */ hidden?: boolean; precision?: number; /** * Show the last value as a tag on the price axis, without the line across the chart that * `trackPrice` adds. Default: false on the price pane, true in the script's own pane. */ axisLabel?: boolean; /** The scale margins of the scale this plot sits on, as fractions of the pane, such as `{ top: 0.2, bottom: 0.28 }`. */ margins?: { top: number; bottom: number }; /** * Draw on a hidden scale of its own inside the pane, between these fractions from the top and * the bottom, such as volume at the foot of the price pane: `{ top: 0.84, bottom: 0 }`. */ band?: { top: number; bottom: number }; /** A fixed scale from `min` to `max` instead of autoscaling, such as `{ min: 0, max: 100 }`. */ range?: { min: number; max: number }; /** * `false`: the plot is drawn at its values but does not stretch its scale, which fits the rest * of the pane (the candles, on the price pane). For levels far from price, such as liquidation * clusters, that would otherwise squash the candles into a line; parts outside the view are * simply not seen. Default true. */ autoscale?: boolean; /** * A short name the legend writes before this plot's value, such as `'Sell'`, at most 24 * characters. Without one the value stands alone, as the built-in studies' values do. Narrow * charts leave the names out and keep the values. `false` draws the plot with no value in the * legend, for a column whose value other plots name. */ legend?: string | false; /** A unit the legend writes after this plot's value, such as `'/s'` or `'×'`, at most 8 characters. */ unit?: string; /** Draw only the newest this many bars, a whole number from 1, as Pine's `show_last`. Default: every bar. */ showLast?: number; /** * Draw the plot shifted by this many bars, a whole number from -500 to 500. The value set on * bar `i` is drawn on bar `i + offset`: a positive offset shifts the plot right, and its last * values are drawn past the newest bar, in the empty space to its right (Ichimoku's leading * spans); a negative one shifts it left (the lagging span). The legend reads the value drawn * at the bar under the crosshair. Default 0. */ offset?: number; } interface JoinOptions { /** * Draw the line (and the area's fill) across bars where the plot is `na`, from the last value * to the next. Default false: the plot breaks there, as Pine's `plot.style_linebr` and * `style_areabr` do. Pine's `style_line`, `style_stepline` and `style_area` join, and the * translation of a pasted Pine script says so. */ join?: boolean; } /** * A gradient in place of a colour: `{ top, bottom }` runs down the shape it fills, `{ left, * right }` across it. Leave one end out to fade the other end's colour to nothing. */ type Gradient = { top?: Color | null; bottom?: Color | null } | { left?: Color | null; right?: Color | null }; /** A colour, or a gradient between two. */ type Fill = Color | Gradient; interface LinePlotOptions extends PlotOptions, JoinOptions { width?: LineWidth; style?: LineStyle; /** * A soft glow in the line's own colour, drawn under it: `true` for 8px of blur, or 1 to 24px. * It follows the line's colours bar by bar and breaks where the line does. */ glow?: boolean | number; /** Show the last value as a line across the chart and a tag on the price axis. */ trackPrice?: boolean; /** * A staircase: flat from each value to the next bar's, then straight up or down, as Pine's * `plot.style_stepline`. `'diamonds'` also marks each change of value with a diamond. */ step?: boolean | 'diamonds'; } interface HistogramPlotOptions extends PlotOptions { /** The value the bars grow from. Default 0. */ base?: number; /** * Bars this many pixels wide, as Pine's `plot.style_histogram`. Leave it out for columns as * wide as the bar, as `plot.style_columns`. */ width?: LineWidth; } interface AreaPlotOptions extends PlotOptions, JoinOptions { width?: LineWidth; style?: LineStyle; /** * Fill from the line to this value, as Pine's area fills to its `histbase`. Leave it out for a * wash that fades to the foot of the pane. */ base?: number; } interface PointsPlotOptions extends PlotOptions { shape?: 'circle' | 'cross'; /** The dots' size: 1 is the smallest. */ width?: LineWidth; /** Join the points with a line, as Pine's `join = true`. */ join?: boolean; } interface CandlePlotOptions extends PlotOptions { /** OHLC bars, a tick left for the open and right for the close, as Pine's `plotbar`. Default: candles. */ bars?: boolean; /** The wicks' colour, and the bodies' outline; `null` draws none. Default: the body's colour. */ wickColor?: Color | null; borderColor?: Color | null; } interface ArrowsOptions { /** The colours of arrows up (values above 0) and down. Default `color.up` and `color.down`. */ up?: Color | null; down?: Color | null; /** The shortest and tallest arrow in pixels, 1 to 200. Default 5 and 100. */ minHeight?: number; maxHeight?: number; pane?: PaneName; hidden?: boolean; /** Shift the arrows this many bars, as `PlotOptions.offset`. */ offset?: number; showLast?: number; } interface Plot { /** The value for the current bar, optionally with this bar's colour. */ set(value: number, color?: Color | null): void; } /** * A horizontal line across the whole pane (`plot.level`). It can be one side of a `plot.fill`. * `set` moves it: the line is drawn at the price in effect on the newest bar, across every bar. */ interface LevelPlot { set(price: number): void; } interface ShapePlot { /** * Draw the shape on the current bar when `condition` is true. `price` is used with * `location: 'absolute'`; `text` and `color` replace the plot's own for this bar. */ set(condition: boolean, options?: { price?: number; text?: string; color?: Color | null; textColor?: Color | null; tooltip?: string }): void; } interface ShapeOptions { /** The shape to draw. Give `char` instead to draw a character (Pine's `plotchar`). */ shape?: ShapeName; /** One character drawn in place of a shape, such as `'▲'` or `'•'`. */ char?: string; location: ShapeLocation; color?: Color | null; size?: Size; /** Written beside the shape, or inside a `labelUp` / `labelDown` label. */ text?: string; /** The text's colour. Default: the shape's colour; inside a label, black or white, whichever reads on it. */ textColor?: Color | null; /** * Shown when the pointer rests on a shape or its text. Text only, like a label's; lines split on * `\n`, and a line written `Name: value` reads as a name and its value. `set` can give a bar * its own. */ tooltip?: string; pane?: PaneName; /** Kept in the declaration but not drawn, like a plot's `hidden`. */ hidden?: boolean; /** Shift the shapes this many bars, as `PlotOptions.offset`. */ offset?: number; /** Draw only the newest this many bars, as `PlotOptions.showLast`. */ showLast?: number; } interface Marker { position: 'above' | 'below' | 'at'; shape: ShapeName; price?: number; text?: string; color?: Color | null; /** Shown when the pointer rests on the marker, as a label's `tooltip`. */ tooltip?: string; } interface MarkersPlot { /** Add a marker to the current bar. Several per bar are allowed. */ add(marker: Marker): void; } interface ColorPlot { /** The colour for the current bar; `null` for none. */ set(color: Color | null): void; } interface FillPlot extends ColorPlot { /** * Shade this bar with a gradient of its own, as Pine's gradient `fill`: `topColor` at the price * `top` and `bottomColor` at `bottom`, each colour held past its price. `null` fades that end * to nothing. */ setGradient(top: number, bottom: number, topColor: Color | null, bottomColor: Color | null): void; } interface CandlePlot { /** `colors` gives this bar's wick and border colours; `null` draws none, and leaving one out keeps the plot's own. */ set(bar: { open: number; high: number; low: number; close: number }, color?: Color | null, colors?: { wick?: Color | null; border?: Color | null }): void; } /** The edge a cell's width grows from, which its number lines up with too. */ type CellAlign = 'left' | 'right' | 'center'; /** One cell of a cells plot: a price band inside a bar, with a width, colours and a number. */ interface BarBand { /** The band's prices, in either order. A cell whose two prices are equal is not drawn: give it a `price` instead, for a level. */ low: number; high: number; /** * How wide the cell is, as the plot's `scale` says; leave it out to fill the column. Zero or * less draws no fill, only the border and the number. */ weight?: number; /** The number written in the cell, in the plot's format, when it fits; leave it out for none. */ value?: number; /** The fill, border and number colours; leave one out for the plot's own, `null` for none. */ color?: Color | null; border?: Color | null; textColor?: Color | null; /** Which column, from 0 to `columns - 1`. Default 0. */ column?: number; /** `'left'` (the default) grows the cell from the column's left edge, `'right'` from its right edge, `'center'` both ways. */ align?: CellAlign; /** Shown when the pointer rests on the cell, anywhere in its column's width, such as its exact value. Text only. */ tooltip?: string; } /** * A level: one price drawn as a line across the bar's column, in the box the bar's cells fill: edge to edge on a * footprint, like the footprint's own value area lines, and a few pixels clear of the edges over candles, * with an optional short label on it, such as a bar's value area high (`'VAH'`). */ interface BarLevel { /** The level's price. `na` draws nothing. */ price: number; /** `'solid'` (the default), `'dashed'` or `'dotted'`. */ line?: LineStyle; /** * A label on the line, up to 16 characters, such as `'VAH'`. It shows only where it fits: room * on the bar with some line beside it, inside the pane, clear of the bar's other labels, its * numbers and the candle behind it; otherwise the line is drawn alone. Leave it out to write `value` instead, or nothing. */ text?: string; /** How much of the column the line spans, as the plot's `scale` says; leave it out for all of it. */ weight?: number; /** A number to write as the label when there is no `text`, in the plot's format. */ value?: number; /** The line's colour, and its label's (the line's own by default); leave one out for the plot's, `null` for none. */ color?: Color | null; textColor?: Color | null; /** Which column, from 0 to `columns - 1`. Default 0. */ column?: number; /** The edge a shorter line grows from, and where its label sits: `'left'` (the default), `'right'` or `'center'`. */ align?: CellAlign; /** Shown when the pointer rests on the line, a few pixels either side of it. Text only. */ tooltip?: string; } /** A band of price, `{ low, high }`, or a level at one price, `{ price }`. */ type BarCell = BarBand | BarLevel; interface CellsPlot { /** * Add a cell to the current bar: a band, `{ low, high }`, or a level, `{ price, line, text }`. * Each run of a bar starts with none, so add every cell the bar should show; a bar holds at most * 1,024 cells, levels included, and a plot 250,000 over every bar (the oldest bars lose theirs * first). */ add(cell: BarCell): void; } /** One lane of a footprint: what it holds, where it sits and its colour. */ interface FootprintLane { /** The name `add`, `opposed` and `stats` use: letters, digits and _, starting with a letter. */ id: string; /** What the legend, the row readout and the statistics row call it, such as `'New longs'`. */ label: string; /** A shorter name for its statistics row. */ short?: string; /** * Left or right of the bar's candle, at most 2 lanes a side. On each side the first lane * declared sits nearest the candle. */ side: 'left' | 'right'; /** Its colour, shaded by size. Default `color.down` on the left and `color.up` on the right. */ color?: Color; /** * `'size'` (the default): amounts in the market's base unit, printed in the chart's USD or coin * unit as Bid × Ask is. `'count'`: amounts printed as they are, such as a number of orders. */ measure?: 'size' | 'count'; } interface FootprintOptions { /** 1 to 4 lanes. */ lanes: FootprintLane[]; /** * Up to 2 pairs of a left lane (`a`) and a right lane (`b`) whose imbalances are marked, as Bid * × Ask marks buying against selling. `compare: 'row'` (the default) weighs the two at the same * price; `'diagonal'` weighs `b` at a price against `a` one row below, which fits only taker * selling against taker buying. Leave it out and the footprint marks no imbalances. */ opposed?: { a: string; b: string; compare?: 'row' | 'diagonal' }[]; /** * The statistics rows offered first under the bars, up to 8: a lane's id is that lane summed * over the bar, and `{ net: [a, b], label }` is lane `a` less lane `b`. Default: every lane. */ stats?: (string | { net: [string, string]; label?: string })[]; hidden?: boolean; } interface FootprintPlot { /** * Add `amount` to `lane` at `price` on the trade's bar. Call it from an event handler, such as * `trades().onTrade`: a forming bar's `onBar` runs again, so it would count trades twice. * Prices snap to the market's step and amounts at one price add up. `0` and `na` are left * out; an amount below 0 is an error, so split a signed value into two lanes. */ add(lane: string, price: number, amount: number): void; } /** One of a heat's two sides: what it holds and its colour. */ interface HeatSide { /** The name `add` uses: letters, digits and _, starting with a letter. */ id: string; /** What the legend and the readout call it, such as `'Longs stopped'`. */ label: string; /** Its colour, shaded by amount. Default `color.down` for the first side and `color.up` for the second. */ color?: Color; } /** * How the chart carries a heat's values into later bars, since a bar's own trades sit under its * candle. `{ fade: n }` halves a value every `n` bars (1 to 200); `'hold'` keeps it at full * strength until a later bar's range covers its price; `'none'` draws each bar's own values only. */ type HeatCarry = { fade: number } | 'hold' | 'none'; interface HeatCommonOptions { /** * `'size'` (the default): amounts in the market's base unit, read out in USD and coin. * `'count'`: amounts read out as they are, such as a number of prints. */ measure?: 'size' | 'count'; /** The carry the heat starts with, `{ fade: 10 }` by default. The trader can change it in the heat's settings, without a rerun. */ carry?: HeatCarry; hidden?: boolean; } interface HeatOptions extends HeatCommonOptions { /** What the legend and readout call the amounts, such as `'Prints'`. Default: the title. */ label?: string; /** A ramp of this hue. Leave it out for the theme's heat ramp, the order book heatmap's blue to gold. */ color?: Color; } interface HeatSidesOptions extends HeatCommonOptions { /** Exactly 2 sides. The first is the negative one: with `combine: 'net'` it is subtracted. */ sides: [HeatSide, HeatSide]; /** * How a row's two sides meet. `'net'` (the default): they cancel, so a balanced row is quiet and * the rest shows in the larger side's colour. `'larger'`: the row's total, in its larger side's colour. */ combine?: 'net' | 'larger'; } interface HeatPlot { /** * Add `amount` at `price` on the event's bar; with two sides, `add(side, price, amount)`. Call * it from an event handler, such as `trades().onTrade`: a forming bar's `onBar` runs again, so * it would count trades twice. Prices snap to the market's step and amounts at one price add * up. `0` and `na` are left out; an amount below 0 is an error, so give a signed value two sides. */ add(price: number, amount: number): void; add(side: string, price: number, amount: number): void; } interface CellsOptions { /** Side-by-side columns in each bar, 1 to 4: two for bid × ask. Default 1. */ columns?: 1 | 2 | 3 | 4; /** * What a full-width cell means: `'bar'` (the default) the largest weight on its own bar, * `'visible'` the largest on the bars in view, `'unit'` a weight of 1 (weights are 0 to 1). */ scale?: 'bar' | 'visible' | 'unit'; /** * The candle while the cells show, on the price pane of a chart that draws candles. * `'overlay'` (the default) leaves the chart's own candles behind the cells. The rest are the * footprint chart's Candle modes, drawn as it draws them: * - `'body'`: a spine with the candle's wick and body. Two columns hang either side of it in * the middle of the bar; one, three or four sit to its right, the spine on the left edge. * - `'backdrop'`: the body's rows shaded behind the cells and edged in the candle's colour, * the range from high to low framed by a hairline. The cells take the whole bar. * - `'ticks'`: a line from high to low with the open's tick on its left and the close's on * its right, where the body's spine would be. * - `'off'`: no candle. The cells take the whole bar. * * With `'body'` and `'backdrop'`, bars 12 px apart or closer are plain candles, as on the * footprint chart. A bar with no cells keeps a slim candle (its ticks with `'ticks'`). The * first cells plot that asks for a mode draws the candle; `'off'` on any wins. `'side'` and * `'hidden'`, the older names, are `'body'` and `'off'`. */ candles?: 'overlay' | 'body' | 'backdrop' | 'ticks' | 'off' | 'side' | 'hidden'; /** * How numbers are written: `'compact'` (the default) shortens them, 3.21K; `'fixed'` writes them * in full, 3214.56; `'percent'` reads them as a fraction, 0.153 as 15.3%. A cell too small for * its number drops decimals, then shortens it, then shows none. */ format?: 'compact' | 'fixed' | 'percent'; /** Digits after the point, 0 to 8; leave it out to let the chart choose. */ decimals?: number; /** Write a + before numbers above 0. */ sign?: boolean; /** Separate thousands with commas, with `'fixed'` and `'percent'`. */ grouping?: boolean; /** The default fill, border and number colours. Without a fill a cell is the theme's study colour. */ color?: Color | null; border?: Color | null; textColor?: Color | null; /** The price pane, by default: cells are bands of price. */ pane?: PaneName; hidden?: boolean; } declare const plot: { line(title: string, options?: LinePlotOptions): Plot; histogram(title: string, options?: HistogramPlotOptions): Plot; area(title: string, options?: AreaPlotOptions): Plot; /** Dots or crosses at each value, with no line between them unless they are joined. */ points(title: string, options?: PointsPlotOptions): Plot; /** A shape, a label or a character on the bars where `set` says so. */ shape(title: string, options: ShapeOptions): ShapePlot; markers(title: string, options?: { pane?: PaneName }): MarkersPlot; /** * Arrows sized by their value, as Pine's `plotarrow`: up below the bar for a value above 0, down * above it for one below, none for 0 or `na`. An arrow's height runs from `minHeight` to * `maxHeight` by its value's size against the largest on the bars in view. `set`'s colour * replaces `up` or `down` on that bar. */ arrows(title: string, options?: ArrowsOptions): Plot; /** * Shade between two plots or levels of this script, optionally per bar. Between two levels it * is a band across the whole pane. A fill takes the offset of its first plot, colours included. */ fill(title: string, a: Plot | LevelPlot, b: Plot | LevelPlot, options?: { color?: Color | null; /** * A gradient in place of the fill's one colour, from the highest edge of each stretch of the * fill to its lowest (`{ top, bottom }`), or from its left to its right. A colour set on a bar * with the fill's `set` still paints that bar. */ gradient?: Gradient; showLast?: number; hidden?: boolean; }): FillPlot; /** Shade the whole height of the pane behind a bar. */ background(title: string, options?: { pane?: PaneName; offset?: number; showLast?: number; hidden?: boolean }): ColorPlot; /** A horizontal line across the pane, such as 70 on an RSI. Returns a handle a fill can use. */ level(title: string, price: number, options?: { color?: Color | null; style?: LineStyle; width?: LineWidth; pane?: PaneName; hidden?: boolean; /** Show the level's price as a tag on the price axis, as a plot's `axisLabel` does. Default false. */ axisLabel?: boolean; }): LevelPlot; candles(title: string, options?: CandlePlotOptions): CandlePlot; /** * Recolour the chart's own candles, bodies, borders and wicks, as Pine's `barcolor` does. * `null` leaves a bar in the chart's colours. Chart types without candles (footprints) say in * the legend that it does not apply there. */ barColor(title: string, options?: { offset?: number; showLast?: number; hidden?: boolean }): ColorPlot; /** * Cells inside each bar, such as a footprint (bid × ask per price row) or a bar's own volume * profile: rows of price bands with widths, colours and numbers, and levels across the bar with * labels, such as its value area, set from the chart's handlers with `add`. Cells never stretch * the price scale. */ cells(title: string, options?: CellsOptions): CellsPlot; /** * A footprint of the script's own: amounts by price in up to 4 named lanes, drawn by the * footprint chart type as a Data choice beside Bid × Ask, with its rows, shapes, colours and * statistics rows. One per script. On a candle chart nothing is drawn, and the legend offers to * switch to the footprint. */ footprint(title: string, options: FootprintOptions): FootprintPlot; /** * A heat of the script's own: amounts by time and price, drawn behind the candles by the order * book heatmap's painter, one column a bar, rows grouped with the zoom and toned on the view's * own scale. One or two sides; the chart carries values into later bars (`carry`). One per script. */ heat(title: string, options?: HeatOptions | HeatSidesOptions): HeatPlot; }; // --------------------------------------------------------------------------------------------- // Graphs: charts with an axis of their own (numbers, names or times rather than the chart's bars), // such as returns by RSI bucket, volume by hour of the day, or venues side by side. They show in a // panel of the workspace, which the script's legend opens. Declared at the top level with their // series; series are set by key from the chart's handlers, and roll back with the forming bar. // --------------------------------------------------------------------------------------------- /** * One series of a graph: a value per key on the graph's axis. Setting a key again replaces its * value; a series holds at most 1,000 keys. */ interface GraphSeries { /** The value at `key`, optionally in its own colour. `na` keeps the key with no value drawn. */ set(key: K, value: number, color?: Color | null): void; delete(key: K): void; clear(): void; } interface Graph { /** Bars from `base` (default 0) to each value. Several bar series side by side group their bars per key. */ bars(title: string, options?: { color?: Color | null; base?: number }): GraphSeries; /** A line through the values, in key order. */ line(title: string, options?: { color?: Color | null; width?: LineWidth; style?: LineStyle }): GraphSeries; /** A dot at each value, `size` 1 to 12 pixels (default 3). */ points(title: string, options?: { color?: Color | null; size?: number }): GraphSeries; } interface GraphOptions { /** `'percent'`: values print with a % sign. Set the values in percent. */ format?: 'percent'; /** Decimal places for values. */ precision?: number; /** Bars series stack per key, each starting where the one before it ends, as shares of a whole do. */ stack?: boolean; /** Columns of the panel's grid the graph spans when the panel is wide enough for two (default 2). */ span?: 1 | 2; } /** * A graph with an axis of its own, at most 8 per script, each with up to 8 series. * - `axis: 'category'`: keys are names (`'Asia'`, `'14:00'`), shown in the order first set. * - `axis: 'number'` (the default): keys are numbers, spaced by value (`30` for an RSI of 30). * - `axis: 'time'`: keys are times, spaced by time. */ declare function graph(title: string, options: GraphOptions & { axis: 'category' }): Graph; declare function graph(title: string, options?: GraphOptions & { axis?: 'number' }): Graph; declare function graph(title: string, options: GraphOptions & { axis: 'time' }): Graph