# API Reference (/docs/vela/user/api-reference)



This is a hand-written, conceptual reference for the Vela™ public surface — what each piece is for and how the pieces bind. A generated type reference (from the source declarations) may be added later; for now this prose is the source of truth.

## The mental model [#the-mental-model]

Vela™ is a small **core** plus three independently swappable **layers** — data providers, scripting engines, and renderers — each reached through a single narrow **port**.

The **neutral model** — bars, series, pane overlays, drawings, inputs, update patches — is the only thing that crosses a port. No backend-specific type ever leaks across. That opacity is what makes each layer swappable. What ships is the native renderer and the provider-backed, cache-wrapped data feed — both plain **swappable defaults**. No scripting engine ships at all: you install one (Pine Script®: `@luxalgo/vela-pinets`) or write one against the port — see [Scripting engines](/docs/vela/user/scripting-engines).

> These snippets import from the npm package `@luxalgo/vela` (see [Installation](/docs/vela/user/installation)).

The higher-level shell is documented on its own page: [the workspace](/docs/vela/user/workspace) (`@luxalgo/vela/workspace` — one chart with `layout: false`, or a multi-chart grid with one shared chrome and sync links). It exposes the state surface — `getState()` / `applyState()` / `state:changed` over one shared document format — which is also what its `persist` option writes.

***

## `class Vela(container, options?, deps?)` [#class-velacontainer-options-deps]

The public, imperative chart and the composition root — the one place that wires concrete backends.

* **`container`** — an `HTMLElement` or a CSS selector string. A missing selector throws.
* **`options`** — display, behavior, and market options. See [Options](/docs/vela/user/options).
* **`deps`** — the **swap point** for the three layers (see below).

Constructing a chart renders candles immediately. Scripting engines are opt-in.

### Core methods [#core-methods]

| Method                               | What it does                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `registerEngine(language, engine)`   | Register a scripting engine under a language id so `addIndicator` can run that language. **Vela™ ships none** — install an addon or write one ([Scripting engines](/docs/vela/user/scripting-engines)). Re-registering a language replaces it (affects future indicators only). Returns the chart for chaining.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `addIndicator(source, options?)`     | Run an indicator script over the chart's market data and render it. Returns an **`IndicatorHandle` synchronously**; values fill in asynchronously. See [Options](/docs/vela/user/options) for per-indicator options.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `addNativeIndicator(type, options?)` | Add a core-computed (non-scripting) **native indicator** by registered `type`. Returns an `IndicatorHandle` (same lifecycle: legend row, eye/remove, events). The layer-backed types `'volume'` (auto-added) and `'vpvr'` (the visible-range volume profile) are **single-instance** — a second call returns the existing handle; the built-in classic studies (`'moving-average'`, `'rsi'`, `'macd'`, …; `availableNativeIndicators()` lists every type) allow **several instances**, so each call adds one more. Plugin chart types can register more (see `multiInstance` on the descriptor). `options.inputs` seeds inputs. Native renderer only; an unregistered type returns a fail-soft handle that never mounts.                                                                                                                                                                                                         |
| `runScript(source, options?)`        | Execute a script and resolve its **first computed run** — the data-out door for editors, consoles and dashboards. Resolves `{ ok: true, run }` with the [`ScriptRun`](#capturing-what-a-script-computes) itself, plus `onUpdate(cb)` to follow later runs and `remove()` to take it off the chart; `{ ok: false, error }` on a compile/runtime failure, which removes the script again (no dead legend row). Never rejects. Prefer it over `runIndicator` — same injection semantics, but it hands you the data instead of a handle to go fetch from.                                                                                                                                                                                                                                                                                                                                                                            |
| `runIndicator(source, options?)`     | Execute a script and **inject it only if the run succeeds** — the seam for host editors/consoles. Resolves `{ ok: true, handle }` after the first successful evaluation, or `{ ok: false, error, context }` on a compile/runtime failure — `context` is the post-mortem execution-context snapshot when the engine had produced one, and the failed indicator is removed again (no dead legend row). Never rejects.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `indicators()`                       | Live `IndicatorHandle[]` of everything on the chart (script + native), in insertion order — the seam for host panels (object trees, indicator lists) that need per-id visibility/removal.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `availableNativeIndicators()`        | Returns `Promise<NativeIndicatorInfo[]>` — the catalog of built-in native indicators with their live state on this chart, for building an "add indicator" picker UI (lets a host list them, gate unsupported ones, avoid duplicates). Async because support may need to probe the provider (a type may need data the symbol lacks).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `presentNativeIndicators()`          | Returns `string[]` — the native types present on the chart **right now**, one entry per instance (a multi-instance type repeats), synchronously (the presence slice of `availableNativeIndicators()`, which stays async only for support probing). Persistence snapshots read this: an unload-time save must see an add or remove made microseconds earlier.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `setMarket(next)`                    | Switch the chart's market **in place** — `{ symbol?, timeframe?, bars?, data?, visibleRange? }` — without destroying the chart. The symbol string carries the venue: bare = registered providers in declaration order, `'coinbase:BTC-USD'` pins one. Only the fields given change. Indicators re-execute over the new bars, native indicators restart, and panes, user drawings, renderer config and event subscriptions all **survive**. Resolves once the new market's history is painted (a deep backfill continues behind it — await `historyComplete()`); a call superseded by a newer `setMarket` resolves silently. Emits `market:changed` when the market identity changed (a depth-only `bars` reload is silent). `visibleRange` frames the first paint of the new market. Drawings are kept as-is — per-symbol drawing documents are a host policy (`chart.drawings.toJSON()/fromJSON()` keyed off `market:changed`). |
| `market` (getter)                    | The current market identity — the read counterpart of `setMarket`. A **snapshot** `{ symbol?, provider?, timeframe?, bars?, offline }` of the *requested* market (`provider` = the symbol's own `EXCHANGE:` prefix, or undefined when bare — the venue that actually served it is `chart.data.resolve(symbol)`): it reflects an in-flight switch immediately (before the new bars land), which is what persist-on-close flows want. Listen to `market:changed` for *committed* identity changes. Mutating the returned object changes nothing.                                                                                                                                                                                                                                                                                                                                                                                   |
| `ready()`                            | Returns a promise that resolves once the chart is painted and interactive. On a ranged feed the first paint is a small recent head (\~200 bars) and the rest of the history keeps backfilling **behind** this — await `historyComplete()` for the full depth.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `historyComplete()`                  | Returns a promise that resolves once the **current load's** full requested history has loaded — immediately for small/offline charts, after the background backfill for deep ones. **Per-load**: each `setMarket` re-arms the cycle (the superseded load's promise resolves rather than hanging), so call it again after a switch for the new market's depth. Never rejects: on destroy or a failed backfill it resolves with whatever depth loaded.                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `on(event, handler)`                 | Subscribe to a chart-level event. Returns an unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `getVisibleRange()`                  | The current visible time range (`{ from, to }` in epoch-ms), or `null` before data loads. Both ends are **real bar times**: the empty space right of the newest bar is not part of the range, so `to` stops at the newest bar (scripts compare `time == chart.right_visible_bar_time` exactly). `null` as well when the view is scrolled entirely into that empty space. To keep room ahead of the newest bar, store your own end time and hand it to `setVisibleRange`.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `setVisibleRange(range)`             | Set the visible time range explicitly (epoch-ms). `to` may lie past the newest bar: the gap becomes empty space on the right, up to the same pan limit as dragging (a few bars must stay in view). Returns the chart for chaining.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `panBy(fraction)`                    | Pan by a fraction of the visible width — positive ⇒ toward the latest bars, negative ⇒ into history. Behaves exactly like dragging the chart: constant zoom, the same pan limits (forward stops at the newest candle plus the bounded empty space), eased on renderers that animate pans; repeated calls stack into one continuous scroll. The widget's `Ctrl/Cmd + ←/→` keys use it. Returns the chart for chaining.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `setVisibleRangePreset(preset)`      | Frame a named date range over the loaded bars: `'1D'`, `'1W'`, `'1M'`, `'3M'`, `'6M'`, `'1Y'`, `'5Y'`, `'YTD'`, or `'ALL'`. A preset deeper than the loaded history just frames everything (it doesn't fetch more bars — the widget's range chips do that for you). Every preset ends on the newest bar and keeps the chart's right margin (`margins.right` in the chart settings) as empty space past it. Returns the chart for chaining.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `setTheme(theme)`                    | Swap the app theme at runtime — `'dark'`, `'light'`, a registered theme's id, a full theme object, or a `createTheme` result (same as the `theme` option). Re-skins the chart surface, axes, legends and in-chart chrome live (no indicator re-run) and emits `theme:changed` with the resolved theme so surrounding host chrome can follow. Candle colors are shared across the built-in themes, so a swap never recolors the series. The same switch is available to users in chart settings → Canvas → Theme. Returns the chart for chaining.                                                                                                                                                                                                                                                                                                                                                                                 |
| `setLocale(next)`                    | Change the chart's language, direction or formatting at runtime — a locale tag (`'de'`) or any [localization option](/docs/vela/user/options#localization-options). Fields you pass replace their current value (an explicit `undefined` restores the default); the others are kept. The chart re-renders its axes, chips and readouts in place (no indicator re-run) and emits `locale:changed`. Register the locale's pack (`registerLocale`) first for translated text. Returns the chart for chaining. See [Localization](/docs/vela/user/localization).                                                                                                                                                                                                                                                                                                                                                                     |
| `i18n` (getter)                      | The chart's translator: its resolved `locale`, `direction`, `numberingSystem`, `hourCycle` and `weekStart`; `t(message, values?)`, which returns a plain string unchanged and translates a `msg()` descriptor through the registered packs, falling back to English; and `format`, the chart's formatters (`price`, `percent`, `compact`, `timeTick`, `timeStamp`, `duration`). The same object for the chart's lifetime; it reads the new settings after `setLocale`.                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `panes` (getter)                     | The [pane control surface](#chartpanes--the-pane-control-surface): list the panes with the indicators each holds, and move, merge, collapse or maximize them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `inspect()`                          | A renderer-agnostic snapshot of the graphic elements the core has generated (series, fills, drawings, tables, …) — a deterministic check that a feature was produced, independent of which renderer drew it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `resize()`                           | Re-measure the container and relayout. Call after the container's size changes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `destroy()`                          | Tear down the chart, renderer, engines, and subscriptions — no leaks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

Because `registerEngine` returns the chart, you can wire an engine straight off construction:

```js
const chart = new Vela('#chart', { data: myBars, timeframe: '1h' })
  .registerEngine('pine', new PineEngine());
```

### Adding an indicator: sync handle, async data [#adding-an-indicator-sync-handle-async-data]

`addIndicator` returns right away so you can wire up UI before any computation finishes. The script is prepared (its inputs are parsed) and then executed over the bar history; the plotted output appears when execution resolves. Listen on the handle's `ready` event (or `chart.ready()` for the whole chart) rather than assuming data is present on return. On a deep-history chart the indicator waits for the background backfill and then computes once over the full depth — its `ready` fires when that single run lands.

A minimal end-to-end setup — construct over data, register a scripting engine (here the Pine addon), add an indicator, then await the first render:

```js
import { Vela } from '@luxalgo/vela';
import { PineEngine } from '@luxalgo/vela-pinets';

const chart = new Vela('#chart', { data: myBars, timeframe: '1h', theme: 'dark' });
chart.registerEngine('pine', new PineEngine());

// addIndicator returns synchronously — wire UI now; plotted values fill in later.
const rsi = chart.addIndicator(`//@version=5
indicator("RSI")
plot(ta.rsi(close, input.int(14, "Length")), "RSI", color.purple)`);
rsi.on('ready', () => console.log(rsi.title, 'has computed'));

await chart.ready(); // resolves once the chart is painted and interactive
```

***

## `IndicatorHandle` [#indicatorhandle]

What `addIndicator` returns. Usable immediately.

| Member                 | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                   | This instance's identity on the chart — the `id` you passed in the options, else one the chart minted. Stable for as long as the indicator stays on it (input edits, hide/show and `updateCode` all keep it). See the `id` option in [Options](/docs/vela/user/options#per-indicator-options).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `title`                | Display title (overridable via the `title` option).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `source`               | The script source the indicator currently runs — the one it was added with, until `updateCode` replaces it; `undefined` for a native indicator.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `nativeType`           | The registered type of a native indicator (`'volume'`, `'moving-average'`, …); `undefined` for a script indicator. A handle has one of `source` or `nativeType`, never both.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `language`             | The language id of the engine running a script indicator (`'pine'`, …): the `language` option it was added with, else the chart's `defaultLanguage`. Available as soon as `addIndicator` returns, and `updateCode` keeps it. `undefined` for a native indicator. Use it to offer language-specific tools, such as an editor, only on the scripts they support.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `inputs`               | The inputs parsed from the script source — each with a `key`, `title`, `type`, `defval`, and optional `min`/`max`/`step`/`options`/`group`/`inline`/`tab`/`tooltip`. Populated once the script is prepared.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `props`                | The script's declaration properties (a strategy's `initial_capital`, an indicator's `precision`, …) in the same schema shape as `inputs`. Empty when the engine exposes none.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `visible`              | Whether the indicator is currently shown.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `setInput(key, value)` | Change one input by its key. Triggers a re-run (an input edit can restructure output, so this may remount the indicator).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `setInputs(values)`    | Change several inputs at once, keyed by input key or title.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `setProp(key, value)`  | Override one declaration property (e.g. `initial_capital`). A prop change replays the whole script.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `setProps(values)`     | Override several declaration properties at once.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `updateCode(source)`   | Replace the script and re-run it **in place** — same `id`, legend row, pane placement, visibility and handle. The new source is compiled first; only then is the running script stopped and the new one started. Until the new code's first run lands, any failure — at compile time or at run time — puts the previous code back with its input and prop values, keeps its visuals painting throughout, and reports through `error`. An input or prop the user edited survives where the new script still declares its key; one still at its old declared default takes the new default; the new code computes once, with its final values. Returns a `Promise<{ ok, error }>`: resolved once the new code's first run has landed, right after the compile check for a hidden indicator, at once for an unchanged source, and with `ok: false` after a failure. A call superseded by a later one resolves with that later call's outcome. Never rejects; a native indicator resolves `ok: false`. |
| `setVisible(visible)`  | Hide or show the indicator. Hiding suspends it — its visuals are dropped and its computation stops; showing re-runs it over the current bars.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `moveTo(target)`       | Move or merge the indicator into another pane: `'price'`, `{ pane: id }` (an existing pane, from `chart.panes.list()`), or `{ newPane: true }` / `{ newPane: { before?, after? } }` for a pane of its own. Merging into a pane it doesn't own gives it its own scale column, except an overlay moved back onto the price pane, which shares the price scale. The placement sticks through recomputes. Fires `indicator:moved` and `pane:changed`. Warns and no-ops on a renderer without pane management.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `on(event, handler)`   | Per-indicator events — `ready`, `error` (`{ error }`), `alert` (`{ id, message, title?, time }`). Returns an unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `context(select?)`     | `Promise` of a **read-only, serializable snapshot** of the engine's execution context — see [below](#capturing-what-a-script-computes). `null` when the engine lacks the capability or nothing ran yet.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `remove()`             | Remove this indicator from the chart.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |

The handle is usable the moment `addIndicator` returns; drive the indicator's lifecycle through its events and mutators:

```js
const macd = chart.addIndicator(macdSource);

// React to the computation outcome.
macd.on('ready', () => console.log('inputs:', macd.inputs.map((i) => i.key)));
macd.on('error', ({ error }) => console.error('MACD failed:', error.message));

// Retune inputs — each change triggers a re-run.
macd.setInput('fast', 8);
macd.setInputs({ slow: 21, signal: 5 });

// Swap the code under the same row — an editor's "run my edit". A source that fails
// (to compile, or as it runs) puts the current MACD back and fires `error` instead.
const { ok, error } = await macd.updateCode(editedMacdSource);
if (!ok) console.warn('kept the previous MACD:', error?.message);

// Hiding suspends it (visuals dropped, computation stopped); showing re-runs it.
macd.setVisible(false);
console.log(macd.visible); // false

macd.remove(); // drop it from the chart
```

### Capturing what a script computes [#capturing-what-a-script-computes]

Two doors, one vocabulary. `script:run` reports **every** script the chart runs; `runScript()`
executes one and hands you its first run. Both deliver the same `ScriptRun` object, so host
code reads a manifest indicator, a console `addIndicator`, and an editor's script identically.

```js
chart.on('script:run', (run) => {
    run.title;          // 'SMA cross' — the title the script DECLARED
    run.kind;           // 'indicator' | 'strategy'
    run.cause;          // why it computed (see below)
    run.bar;            // index of the last computed bar
    run.plots.fast;     // that plot's value at that bar
    run.vars.fastLen;   // the script's own variables, by their SOURCE names

    if (run.strategy) {
        run.strategy.position; // signed contracts held
        run.strategy.equity;
        run.strategy.openPnl;
        run.strategy.netPnl;
    }
});
```

The handle is already resolved and the data already extracted — there is nothing to look up
and nothing to await.

#### Provisional vs final [#provisional-vs-final]

`cause` is the field that decides whether a value can be trusted:

| `cause`      | Fires when                                              |
| ------------ | ------------------------------------------------------- |
| `'history'`  | The first computation over the loaded history.          |
| `'tick'`     | The forming bar changed — **values can still move**.    |
| `'bar'`      | A new bar opened, so the one before it is **final**.    |
| `'inputs'`   | An input was edited.                                    |
| `'code'`     | The script was replaced in place (`handle.updateCode`). |
| `'viewport'` | The visible range moved (viewport-aware scripts only).  |
| `'market'`   | The chart's market changed and the script re-executed.  |

Anything that records, alerts, or exports should key off `'bar'`:

```js
chart.on('script:run', (run) => {
    if (run.cause === 'bar') persist(run);  // a bar just closed — settled
    else updateDashboard(run);              // provisional
});
```

`'tick'` runs are **throttled to \~1/s** per indicator (a live stream re-executes the open
candle several times a second, which no dashboard can use). Every other cause is emitted
unconditionally — dropping a `'bar'` run would break exactly the case above.

Two more flags round out the picture: `forming` is true while the run's last bar is still
open (always so on a live chart, never on a static one), and `complete` is false only while
an engine that computes progressively is still being fed a deep backfill.

#### What rides the run, and what you ask for [#what-rides-the-run-and-what-you-ask-for]

Flat and at the current bar → on the run. Historical and unbounded → an explicit call, so a
per-tick listener never ships a ledger it will not read:

```js
const trades = await run.trades();      // the strategy's round trips, closed then open
const history = await run.series('fast'); // one plot's full history
```

#### Executing a script and capturing its result [#executing-a-script-and-capturing-its-result]

```js
const result = await chart.runScript(source);
if (result.ok && result.run) {
  console.log(result.run.strategy?.netPnl); // `strategy` is set only for strategy scripts
  const off = result.onUpdate((run) => console.log(run.strategy?.openPnl));
  // later: off() stops following; result.remove() takes the script off the chart
} else {
  console.error(result.error);
}
```

`runScript` resolves on the **first computed run**, injects the script only if it runs (a
failure removes it again — no dead legend row), and never rejects.

#### Across a grid [#across-a-grid]

`@luxalgo/vela/workspace` relays the same event with the cell it came from, so one subscription covers
every cell — including cells a later layout change creates:

```js
ws.on('script:run', (run) => console.log(run.cell, run.title, run.strategy?.equity));
```

#### The lower-level snapshot [#the-lower-level-snapshot]

`handle.context(select?)` remains the pull counterpart — a **read-only** deep copy of the
engine's execution context (`phase`, `barIndex`, `meta`, `plots`, `variables`, `strategy`,
`trades`, `warnings`), async on both the in-process and Web-Worker engines (the context never
leaves the worker; only the snapshot crosses), and selective via `select`. `script:run` is
built on it and is what host code should normally use; reach for `context()` when you want a
snapshot at a moment of *your* choosing rather than at a run. On a `runIndicator` failure the
same snapshot is attached post-mortem (`{ ok: false, error, context }`) — the state at the
moment of the crash.

***

## Chart-level events [#chart-level-events]

Subscribe with `chart.on(event, handler)`; every subscription returns an unsubscribe function.

| Event                          | Payload                                              | Fires when                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ready`                        | —                                                    | The chart is painted and interactive (a deep chart's history may still be backfilling).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `market:changed`               | `{ symbol, timeframe, prev: { symbol, timeframe } }` | The market switched **in place** via `setMarket` — symbol (venue prefix included), timeframe, or offline data changed (a depth-only reload does not fire). Fires after the new market's history is painted and every consumer restarted. `prev` lets hosts re-key per-symbol state (e.g. swap user-drawing documents between symbols).                                                                                                                                                                                                                                                                                                                                                                 |
| `load:start`                   | `{ symbol, timeframe, firstLoad }`                   | A bar load began with nothing painted: the first load (fires during construction — later subscribers see only its `load:end`), or an identity switch, which blanks the old series in the same breath. Fires **before** the first fetch — plugins and custom indicators hide or reset their own visuals here. A depth-only reload fires neither event.                                                                                                                                                                                                                                                                                                                                                  |
| `load:end`                     | `{ symbol, timeframe, bars }`                        | The load ended: its first bars painted (`bars` > 0 — on deep histories the quick preview), or it ended with none (`bars` = 0 — a failed fetch, an empty market, or a parked symbol). Exactly one per `load:start`; plugins restore or rebuild their visuals here.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `history:progress`             | `{ loaded, target }`                                 | A deep-history backfill chunk landed — `loaded` of `target` bars are on the chart.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `history:complete`             | `{ reason, oldestTime, barsLoaded }`                 | The history load finished. `reason`: `'depth'` (requested count loaded), `'genesis'` (the source has nothing older), or `'aborted'` (a fetch failed — the chart keeps what loaded). Fires exactly once, including for small/offline charts.                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `data:unresolved`              | `{ symbol, providers }`                              | No registered provider can serve the chart symbol. The load is **parked**, not failed: it resumes by itself once a provider that resolves the symbol registers. `providers` lists the names that were tried.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `indicator:added`              | `{ id }`                                             | An indicator was added — once, when it first computes (or at once for one added hidden). Its pane exists by then, so `chart.panes.list()` already lists it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `indicator:removed`            | `{ id }`                                             | An indicator was removed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `indicator:error`              | `{ id, error }`                                      | An indicator failed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `indicator:inputs`             | `{ id }`                                             | An indicator's input or prop values changed — the settings dialog, `setInput(s)`, `setProp(s)`. What state persistence listens to.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `indicator:visibility`         | `{ id, visible }`                                    | An indicator was shown or hidden — the legend eye, `handle.setVisible`, or an object tree.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `indicator:moved`              | `{ id, paneId }`                                     | An indicator was moved or merged into another pane — `handle.moveTo`, `chart.panes.moveIndicator`, or the legend's **Move to** menu.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `pane:changed`                 | —                                                    | The pane layout changed: a pane created with its indicator or removed with its last one, the order, a collapse or maximize, the pane heights (`chart.panes.setHeightWeight`, or the user releasing a pane separator), or an indicator moving between panes — from `chart.panes` or the in-chart controls alike. Re-read `chart.panes.list()`.                                                                                                                                                                                                                                                                                                                                                          |
| `pane:moved`                   | `{ paneId, dir }`                                    | A study pane moved one slot `'up'` or `'down'`. Fires alongside `pane:changed`, with enough detail to undo it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `script:run`                   | the [`ScriptRun`](#capturing-what-a-script-computes) | A script computed — the first pass over the history, a live tick, a new bar, an input edit, a viewport move, a market switch. Carries the run itself (title, cause, the plots/variables/broker state at the computed bar), so a listener reads it instead of resolving a handle and pulling a snapshot. Forming-bar (`'tick'`) runs are throttled to \~1/s; every other cause fires unconditionally. Never fires for native indicators — they run no script.                                                                                                                                                                                                                                           |
| `context:changed`              | `{ id }`                                             | An indicator's execution context advanced (run finished; throttled to \~1/s while streaming). Re-pull `handle.context()` if you consume it. Fires only for context-capable engines. &#x2A;*Prefer `script:run`**, which delivers the data rather than a signal to go fetch it.                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `bar`                          | the bar (OHLCV)                                      | A live tick — the forming bar updated or a new bar appended. A bar revealed by a [replay](#chartreplay--the-bar-replay-control-surface) fires it too.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `replay:start`                 | `{ cursorTime, remaining }`                          | Replay began (or seeked): the chart shows history up to `cursorTime`, `remaining` bars are hidden.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `replay:step`                  | `{ cursorTime, remaining }`                          | Replay revealed one bar (a bar played tick by tick steps when it settles).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `replay:tick`                  | `{ cursorTime, index, count }`                       | [Tick replay](#tick-replay) applied tick `index` of `count` to the bar forming at `cursorTime`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `replay:play` · `replay:pause` | `{ intervalMs }` · —                                 | Timed reveal started (or changed pace) · paused (`pause()`, or a seek while playing).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `replay:end`                   | `{ reason }`                                         | Replay ended and the full history is back: `'stopped'` (`stop()`), `'finished'` (the last bar was revealed), or `'market'` (a symbol switch replaced the history — a timeframe or session switch keeps the replay).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `viewport:changed`             | `{ from, to }` (epoch-ms)                            | The visible time range moved (pan/zoom/fit) — fires per applied change, not debounced. The seam viewport-sync links between charts build on.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `theme:changed`                | the resolved theme object                            | The app theme changed — `setTheme(...)` or the in-chart settings dialog (Canvas → Theme). Host chrome around the chart (toolbars, panels, page shells) re-skins from the payload. Plot-only cosmetic edits (a `layout.background` set through the config) do **not** fire it.                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `locale:changed`               | `{ locale, direction }`                              | The chart's localization changed through `setLocale(...)`, after the chart re-rendered. `direction` is resolved (`'ltr'` or `'rtl'`), so host chrome around the chart can follow. Fires on every `setLocale` call. A workspace emits its own after every cell has switched.                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `priceStyle:change`            | `{ from, to }`                                       | The base price style is switching (candles, line, area, a chart-type id, …). Fires **synchronously, before the chart repaints** in the new style, whatever the path: the topbar style menu, `ctx.setPriceStyle`, `chart.renderer.set('priceStyle', …)`, the settings dialog, `applyConfig` and config templates, or a state restore. Never fires for the style the chart was created with, nor for a set to the style already shown. While it runs the chart still shows `from`, so a listener can capture the outgoing frame (`chart.renderer.screenshotCanvas()`) to animate the switch. Don't change the style again from inside the listener. A workspace relays it per cell as `cell:priceStyle`. |
| `mark:click`                   | `{ id, ids, time, group? }`                          | A [timeline mark](#chartmarks--the-timeline-marks-control-surface) glyph was clicked — `ids` lists every mark under it (several marks of one group on one bar fold into a cluster), `id`/`time` its first. Fires before the popup opens; a mark without content opens none, so this is where a host shows its own UI.                                                                                                                                                                                                                                                                                                                                                                                  |
| `alert`                        | engine alert                                         | A script raised an alert. Never fires for bars a [replay](#chartreplay--the-bar-replay-control-surface) reveals.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `warning`                      | engine warning                                       | A script raised a warning.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |

***

## `chart.renderer` — the renderer control surface [#chartrenderer--the-renderer-control-surface]

A thin facade over the active renderer for reading and changing **how the chart is drawn**
at runtime, with **no indicator re-run**. Unsupported keys/methods warn and no-op, so the
chart is never left half-changed.

| Member                               | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                               | The active renderer's identity, e.g. `'native'`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `capabilities`                       | What the renderer can draw (drives graceful degradation).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `supports(feature)`                  | Whether a feature is available — use to show/hide a UI control.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `get(feature)`                       | Read a feature's current value (`undefined` if unsupported).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `set(feature, value)` / `set({ … })` | Apply one feature, or several at once (one repaint).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `screenshot()`                       | Export the chart as a PNG data URL, or `null` if unsupported. Composites the geometry and chrome layers only — the crosshair, DOM overlays (tables, legend), user drawings, and the volume-profile layer are not included.                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `getConfig()`                        | Snapshot the renderer's full cosmetics as a serializable, versioned JSON document (or `null`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `applyConfig(config)`                | Apply a full or partial config document from `getConfig()`; malformed/unknown fields are ignored.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `onConfigChanged(cb)`                | Subscribe to cosmetic-config changes — the in-chart settings dialog commits through `applyConfig`, so this is how host chrome mirroring a config value (a time-zone display, a saved template) learns about in-chart edits. Re-pull `get(…)`/`getConfig()` in the callback. Returns an unsubscribe fn; silent no-op unsubscribe on a renderer without a rich config.                                                                                                                                                                                                                                                                        |
| `onCrosshairMove(cb)`                | Subscribe to crosshair movement — `time`/`price` under the cursor, per-series values, and the hovered bar's OHLC (null fields when the cursor leaves the chart). `price` is the value on the scale of the pane under the cursor — a price on the price pane, an indicator value on a study pane — and `paneKind` (`'price'`, `'study'` or `null`) tells which; `paneId` names the pane, as [`chart.panes.list()`](#chartpanes--the-pane-control-surface) reports it (`null` off the plot). Returns an unsubscribe fn. The public seam for host status lines and data windows.                                                               |
| `onClick(cb)`                        | Subscribe to clicks — and touch taps — on the plot (never the end of a pan): `{ time, price, paneKind, paneId }`. `time` is the open time of the bar under it (`null` off the bars); `price`, `paneKind` and `paneId` read the clicked pane the way `onCrosshairMove` does, so a click on a study pane names that pane and its value. On touch a tap moves no crosshair, so this is how an interaction learns which bar was chosen. A press on a drawing belongs to the drawing and reports no click: set [`drawingsInteractive`](/docs/vela/user/renderer-features) to `false` while picking. Returns an unsubscribe fn.                   |
| `dataWindowReadout()`                | The bar under the crosshair (or the latest bar when the cursor is off the plot) as a display-ready snapshot: `date`, `time`, an `ohlc` block, and one `groups` entry per indicator with a row per plot in its own color. Values are pre-formatted on their pane's scale. `null` on a renderer without the seam — see [renderer features](/docs/vela/user/renderer-features#data-window-readout).                                                                                                                                                                                                                                            |
| `setExternalCrosshair(time, price?)` | Show (or clear, with `null`) a **ghost crosshair** at a data-space position driven from OUTSIDE this chart — the multi-chart crosshair-sync seam ([the workspace](/docs/vela/user/workspace) drives it from the linked cells' pointers). A ghost never re-emits `onCrosshairMove` (one-way by contract — no echo loops). A [`crosshairOverride`](/docs/vela/user/renderer-features) applies to the ghost too — its line style and its `shadeRight` veil, which covers every bar in view when the ghost lies left of the window. Silent no-op on a renderer without the optional port seam; feature-detect with `supportsExternalCrosshair`. |
| `set('dialogHost', el)`              | Where the renderer mounts its MODAL dialogs (chart settings, indicator settings). Multi-chart shells pass their root element so dialogs center over the whole grid instead of clipping inside one cell — the workspace does this automatically for every cell. Runtime-only; never part of the config template.                                                                                                                                                                                                                                                                                                                             |
| `supportsExternalCrosshair` (getter) | Whether the active renderer implements the optional `setExternalCrosshair` seam (the native renderer does).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `setWallClock(clock)`                | Drive the renderer's time-of-day chrome (the price-axis countdown to bar close) from the host's own second pulse — a `WallClock` (`SecondClock` is the exported second-aligned implementation) — so it ticks in step with a host clock display instead of on a separate timer that can read a different second. `null` hands the pulse back to the renderer. [The workspace](/docs/vela/user/workspace) does this for every cell with its bottom-bar clock. Silent no-op on a renderer without time-of-day chrome.                                                                                                                          |
| `focus()`                            | Move keyboard focus back onto the chart's interactive surface — call after a host control (e.g. a shared toolbar button) stole focus, so chart/drawing shortcuts keep working. Silent no-op on a renderer without a focusable surface.                                                                                                                                                                                                                                                                                                                                                                                                      |

Feature-detect, read, and change how the chart is drawn at runtime — with no indicator re-run:

```js
// Only touch a feature the active renderer actually supports.
if (chart.renderer.supports('glow')) {
    console.log('glow is', chart.renderer.get('glow'));
    chart.renderer.set('glow', 0.6);
}

// Apply several features at once (one repaint).
chart.renderer.set({ logScale: true, currentPriceLine: false });
```

See [Renderer Features](/docs/vela/user/renderer-features) for the full feature catalog (common +
native-specific) and config/screenshot examples.

### Letting the user pick a bar or a range [#letting-the-user-pick-a-bar-or-a-range]

Selecting a bar, or a range from bar A to bar B, takes no extra API: `onClick` reports the bar
that was clicked, and three runtime features shape the chart while the user picks.

* **`crosshairOverride`** restyles the crosshair for the pick — for example only the vertical
  line, with `shadeRight` dimming every bar after the one under the cursor.
* **`drawingsInteractive: false`** keeps the pointer away from user drawings, so a click on a
  trend line still reaches `onClick` instead of selecting the line.
* **`highlights`** shades the result — a single bar, or the span between two picks — and stays
  on screen as the crosshair moves.

```js
const HOUR = 3_600_000; // the chart's bar duration

function pickBar(chart) {
    chart.renderer.set({
        crosshairOverride: { horizontal: false, shadeRight: { color: 'rgba(0, 0, 0, 0.35)' } },
        drawingsInteractive: false,
    });
    return new Promise((resolve) => {
        const off = chart.renderer.onClick(({ time }) => {
            if (time == null) return; // clicked past the bars — keep waiting
            off();
            chart.renderer.set({ crosshairOverride: null, drawingsInteractive: true });
            resolve(time);
        });
    });
}

const a = await pickBar(chart);
const b = await pickBar(chart);
chart.renderer.set('highlights', [
    { from: Math.min(a, b), to: Math.max(a, b) + HOUR, color: 'rgba(41, 98, 255, 0.15)' },
]);
```

Both overrides are runtime-only and never saved with the config, so a reload mid-pick can't
leave the chart stuck in picking mode. Clear the selection with `set('highlights', [])`.

***

## `chart.panes` — the pane control surface [#chartpanes--the-pane-control-surface]

A chainable facade over the chart's **panes**: the price pane on top and a study pane per
indicator that draws in its own pane. It lists them with the indicators each holds and moves,
merges, collapses and maximizes them — the same operations as the in-chart pane buttons and the
legend's **Move to** menu, so a host toolbar and the built-in controls stay in step. The
mutations need a renderer with pane management (`capabilities.paneManagement`, the native
renderer); elsewhere they warn and no-op, and `list()` still reports the panes.

| Member                            | Description                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `supported`                       | Whether the active renderer supports pane management — use it to show or hide host UI.                                                                                                                                                                                                                                                                                                                                                           |
| `list()`                          | The panes, top to bottom: `{ id, kind, order, collapsed, maximized, heightWeight?, indicators }`, where `kind` is `'price'` or `'study'` and each indicator entry is `{ id, title, shorttitle?, ownScale }`. `heightWeight` is the pane's share of the height (see `setHeightWeight`); a renderer that doesn't report pane sizes leaves it out. A study pane is listed while it holds an indicator.                                              |
| `setHeightWeight(paneId, weight)` | Size a pane. The panes share the plot height in proportion to their weights — by default 3 for the price pane and 1 for each study pane — so `setHeightWeight('price', 6)` next to two study panes gives the price pane three quarters of the height. The weight stays when other indicators join the pane, until the user drags a separator or you set it again; a collapsed pane applies it when expanded. `weight` must be a positive number. |
| `move(paneId, dir)`               | Move a study pane one slot `'up'` or `'down'`. The price pane stays on top.                                                                                                                                                                                                                                                                                                                                                                      |
| `collapse(paneId, collapsed?)`    | Collapse a pane to a thin strip with its legend, or restore it (`false`).                                                                                                                                                                                                                                                                                                                                                                        |
| `maximize(paneId \| null)`        | Let one pane fill the plot, hiding the others, or restore the split with `null`.                                                                                                                                                                                                                                                                                                                                                                 |
| `moveIndicator(id, target)`       | Move or merge an indicator — the same as its handle's [`moveTo(target)`](#indicatorhandle).                                                                                                                                                                                                                                                                                                                                                      |
| `remove(paneId)`                  | Remove a study pane and every indicator in it. The price pane can't be removed.                                                                                                                                                                                                                                                                                                                                                                  |

Every change fires `pane:changed` — including a pane being created, and the user resizing panes
with a separator — so follow it to keep host UI current or to save the heights; `indicator:moved`
reports moves. A pane is created with its indicator, so read `list()` on that `pane:changed`, or
once the indicator's handle is `ready`, rather than right after `addIndicator` returns.

```js
const rsi = chart.addNativeIndicator('rsi');
rsi.on('ready', () => {
    const pane = chart.panes.list().find((p) => p.indicators.some((i) => i.id === rsi.id));
    chart.panes.collapse(pane.id); // a host "hide pane" toggle
});

chart.panes.setHeightWeight('price', 6); // a taller price pane

chart.on('pane:changed', () => renderPaneToolbar(chart.panes.list()));
```

***

## `chart.data` — the data control surface [#chartdata--the-data-control-surface]

A facade over the provider registry for **where candles come from**. Register one or more
market-data providers; the chart routes each symbol to the right one. No provider is bundled —
registering the one that resolves the chart symbol fires the parked initial load.

| Member                             | Description                                                                                                                                                                                         |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `registerProvider(name, provider)` | Register (or replace) a provider; chainable. Fires the parked load when it resolves the symbol.                                                                                                     |
| `unregisterProvider(name)`         | Remove a provider.                                                                                                                                                                                  |
| `providers()`                      | Metadata for every registered provider.                                                                                                                                                             |
| `resolve(symbol)`                  | How a symbol routes now (`{ provider, ticker }`, or `null`). Accepts a provider-name prefix or a descriptor-declared **listing prefix** (`NASDAQ:AAPL` — strict: a wrong venue resolves to `null`). |
| `displayPrefix(symbol)`            | The venue label to display — the descriptor's listing prefix when declared, else the resolved provider name. `null` while unresolvable.                                                             |
| `canonicalSymbol(symbol)`          | The canonical `PREFIX:TICKER` form of the symbol (`edgx:aapl` → `NASDAQ:AAPL`). `null` while unresolvable.                                                                                          |
| `symbols(provider?)`               | Indexed symbols for autocomplete — one provider, or all.                                                                                                                                            |
| `symbolInfo(symbol)`               | `Promise` of per-symbol metadata (Pine `syminfo.*`), via the owning provider.                                                                                                                       |
| `capabilities(symbol)`             | The full resolved per-symbol `ProviderCapabilities` (behavior flags), or `null` while nothing resolves the symbol.                                                                                  |
| `ready()`                          | Resolves when every provider's symbol index has settled.                                                                                                                                            |

Register the provider that resolves the chart symbol, then wait for both the index and the initial load:

```js
import { Vela } from '@luxalgo/vela';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';

const chart = new Vela('#chart', { symbol: 'BTCUSDT', timeframe: '1h' });

// Registering the provider that resolves the symbol fires the parked initial load.
chart.data.registerProvider('binance', new BinanceProvider());
await chart.data.ready(); // provider symbol indexes settled
await chart.ready();      // chart painted and interactive

console.log(chart.data.resolve('BTCUSDT'));            // { provider: 'binance', ticker: 'BTCUSDT' }
console.log(chart.data.symbols('binance').length, 'symbols indexed');
console.log(chart.data.capabilities('BTCUSDT'));       // ProviderCapabilities | null
```

On a chart given a custom `deps.dataFeed`, these warn and no-op (that feed owns its data). See
[Data Providers](/docs/vela/user/data-providers) for symbol formats, resolution, and the load lifecycle.

***

## `chart.drawings` — the drawings control surface [#chartdrawings--the-drawings-control-surface]

A chainable facade over the interactive [drawing tools](/docs/vela/user/drawing-tools). The drawing **model is
core-owned**, so the *interactive* methods are capability-gated (they warn + no-op when the renderer
can't paint drawings — `chart.drawings.supported` reports this), while the **model methods**
(reading, persisting, undo) always work.

| Member                                                                 | Gated?   | Description                                                                                                                                                                                                                                                                                                                                                                                               |
| ---------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `supported`                                                            | —        | Whether the renderer can paint interactive drawings.                                                                                                                                                                                                                                                                                                                                                      |
| `setTool(type \| null)`                                                | yes      | Arm a tool for the next clicks; `null` returns to select/idle.                                                                                                                                                                                                                                                                                                                                            |
| `getTool()`                                                            | no       | The armed tool (`null` = select/idle). Follow changes on `drawing:tool`.                                                                                                                                                                                                                                                                                                                                  |
| `setSnapMode(mode)` · `getSnapMode()`                                  | yes / no | The magnet: `'off' \| 'weak' \| 'strong'`. Changes land on `drawing:snap`.                                                                                                                                                                                                                                                                                                                                |
| `setStayMode(on)` · `getStayMode()`                                    | yes / no | Stay in drawing mode: keep the tool armed after each placement. Changes land on `drawing:stay`.                                                                                                                                                                                                                                                                                                           |
| `setMode(mode)` · `getMode()`                                          | yes / no | Renderer-local mode: `'measure' \| 'eraser' \| null`. Mutually exclusive with armed tools (the renderer enforces it); changes land on `drawing:mode`.                                                                                                                                                                                                                                                     |
| `showToolbar(visible?)`                                                | yes      | Show/hide the on-chart toolbar.                                                                                                                                                                                                                                                                                                                                                                           |
| `setToolbar(option)`                                                   | yes      | Reconfigure the toolbar groups/tools live.                                                                                                                                                                                                                                                                                                                                                                |
| `setToolShortcuts(map)`                                                | yes      | Show per-tool shortcut hints in the toolbar flyouts — `{ trendline: 'Alt+T', … }`. Values are pre-formatted display strings: the host owns the keymap and the platform formatting. The widget/workspace push their own bindings automatically.                                                                                                                                                            |
| `add(type, init?)`                                                     | yes      | Create a drawing from code; returns the `Drawing` (or `null` if unsupported).                                                                                                                                                                                                                                                                                                                             |
| `remove(id)` · `removeMany(ids)`                                       | no       | Delete drawings (one undo step for `removeMany`). A locked drawing is deleted too: the lock only protects it from the user's gestures.                                                                                                                                                                                                                                                                    |
| `update(id, patch)` · `updateMany([{ id, patch }])`                    | no       | Apply partial serialized records (for a custom settings UI; one undo step for `updateMany`).                                                                                                                                                                                                                                                                                                              |
| `select(ids \| null)` · `openSettings(id)`                             | yes      | Select drawings on the chart, or open one's settings panel, from a host list such as an object tree.                                                                                                                                                                                                                                                                                                      |
| `lock(id, v?)` · `show(id, v?)`                                        | no       | Lock/unlock · show/hide a single drawing.                                                                                                                                                                                                                                                                                                                                                                 |
| `bringToFront(id)` · `sendToBack(id)`                                  | no       | Reorder paint order. With the `drawingDepth` capability they clear the whole stack — candles and indicators included, not just the other drawings.                                                                                                                                                                                                                                                        |
| `zIndex` (on `add`'s init and `update`'s patch)                        | no       | The draw-order key. On a `drawingDepth` renderer it shares one space with the pane's series, so a drawing can sit under the candles or between two indicators — see [depth](/docs/vela/user/drawing-tools#depth-anywhere-in-the-stack). Persists with the drawing either way.                                                                                                                             |
| `undo()` · `redo()` · `canUndo()` · `canRedo()`                        | no       | Snapshot history (core-owned).                                                                                                                                                                                                                                                                                                                                                                            |
| `clone(id)` · `duplicate(ids)`                                         | yes      | Copy in place; the copies become the selection.                                                                                                                                                                                                                                                                                                                                                           |
| `copyToClipboard(ids)` · `paste()`                                     | yes      | In-memory, per-chart clipboard.                                                                                                                                                                                                                                                                                                                                                                           |
| `all()`                                                                | no       | Every drawing as plain JSON, in paint order.                                                                                                                                                                                                                                                                                                                                                              |
| `toJSON()` / `fromJSON(doc)`                                           | no       | Snapshot / restore a versioned `DrawingsDocument` (untrusted-safe). `fromJSON` replaces every drawing, keeps their ids, clears the undo history and raises no `drawing:*` event; a missing or invalid document restores an empty chart.                                                                                                                                                                   |
| `getConfig()` / `applyConfig(doc)`                                     | no       | Aliases of `toJSON` / `fromJSON`, mirroring `chart.renderer`.                                                                                                                                                                                                                                                                                                                                             |
| `toolDefaults()` · `setToolDefaults(map)` · `resetToolDefaults(type?)` | no       | Each tool's remembered settings, by type: the style, text styling and per-type settings (fib levels, position sizing…) its next drawing starts from. Plain JSON — save `toolDefaults()` and hand it back to `setToolDefaults` on the next load (malformed entries and unknown types are dropped). Changes land on `drawing:defaults`. The workspace and widget keep them in their state document for you. |
| `toolTemplates()` · `setToolTemplates(map)`                            | no       | Each tool's saved styles, by type (`{ trendline: [{ name, settings }] }`): named sets of the same settings `toolDefaults()` holds, offered in the settings panel's style menu. Plain JSON, restored leniently like `setToolDefaults`. Changes land on `drawing:templates`; the workspace and widget keep them with the tool settings.                                                                     |

Drawing lifecycle is also surfaced as chart events (`drawing:created` / `drawing:edited` /
`drawing:removed` / `drawing:selected` / `drawing:settings` — `drawing:selected` carries the
primary `id` plus `ids`, every member of a multi-selection), and the tool/mode state as
`drawing:tool` / `drawing:snap` / `drawing:stay` / `drawing:mode` — the seam an external toolbar mirrors.
`drawing:defaults` fires when a tool's remembered settings change (the user styled a drawing of
that type, or a restore or reset replaced them), and `drawing:templates` when its saved styles do.
A drawing's `showOn` (a list of timeframe bands, unset for every timeframe) limits the charts it
shows on; set it with `update(id, { showOn })`. See
[Drawing tools](/docs/vela/user/drawing-tools) for the tool catalogue, toolbar UX, and keyboard shortcuts.

***

## `chart.marks` — the timeline-marks control surface [#chartmarks--the-timeline-marks-control-surface]

Host events pinned to a moment in time — dividends, splits, earnings, releases — shown as small
colored **glyphs on a lane just above the time axis**, each opening a **popup** on click. The model
is core-owned, so every method works on any renderer; on one without the `timelineMarks`
capability nothing paints (`supported` reports it). Marks are **data, not user state**: the chart
never persists them — re-supply them on `market:changed`. What *is* saved with the chart's config
is each group's visibility (the checkboxes on the chart settings' **Events** tab, which
appears once marks name groups). The [Timeline marks](/docs/vela/user/timeline-marks) guide walks through
the whole surface with examples.

| Member                                                 | Description                                                                                                                                                                   |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `supported`                                            | Whether the active renderer paints timeline marks.                                                                                                                            |
| `add(mark)`                                            | Add one mark; an existing id is replaced in place. Chainable.                                                                                                                 |
| `set(marks)`                                           | Replace the whole set (a market switch).                                                                                                                                      |
| `remove(id)` · `clear()`                               | Drop one mark, or all of them.                                                                                                                                                |
| `all()`                                                | Every mark, in insertion order.                                                                                                                                               |
| `defineGroup({ id, label, visible? })`                 | Name a visibility group: the label of its checkbox in settings and its default visibility. A mark may name a group that was never defined — it then shows its capitalized id. |
| `groups()`                                             | The defined groups, in definition order.                                                                                                                                      |
| `setGroupVisible(id, visible?)` · `isGroupVisible(id)` | The same switch as the settings checkbox; the choice is persisted with the chart's config. On a renderer without the `marks` feature the setter warns and no-ops.             |

A mark is `{ id, time, glyph, title?, tooltip?, group?, content? }`:

* **`time`** is epoch-ms, but the glyph never sits at that exact pixel: it centers on **the bar whose
  span contains the time**. A time in a gap (a weekend, a closed session) goes to the first bar that
  follows; one past the newest bar projects onto the extrapolated grid in the right whitespace. Change
  timeframe and the marks re-snap.
* **`glyph`** is a colored token — `{ shape?, color, letter? }` (`'circle'` · `'square'` · `'diamond'` ·
  `'pin'`, one or two characters in auto-contrasted ink) or `{ shape?, color, icon }` with an id from the
  icon registry (`registerIcon` from `vela/ui`). Icons travel as ids, never inline markup, so a mark
  payload can come from data.
* **`content`** is what the popup shows under `title`: `{ text }` (escaped), `{ html }` (sanitized
  through an allowlist — scripts, styles, frames, event handlers and `javascript:` URLs never reach the
  page; links open in a new tab), or `{ panel: { items } }` — rows of `text`, `field` (label/value)
  and `button` (`run`, optional `primary`, `close`). Pass a **function** (sync or async) instead and
  it resolves when the popup needs it — details fetched on click, one entry at a time as the user
  scrolls. Without `content` a click only emits `mark:click`.
* **`group`** folds marks of one kind that land on the same bar into **one slightly larger glyph**
  listing them all (earliest first); marks of *different* groups on one bar **stack** — a small deck
  that fans out on hover (or a tap on touch) so each can be opened.

```js
import { registerIcon, svg16 } from '@luxalgo/vela/ui';

registerIcon('myco.split', svg16('<path d="M8 2v12M3 5l5-3 5 3M3 11l5 3 5-3"/>'));

chart.marks
    .defineGroup({ id: 'dividends', label: 'Dividends' })
    .defineGroup({ id: 'splits', label: 'Splits' })
    .add({
        id: 'div-2024-06-11',
        time: Date.UTC(2024, 5, 11),
        title: 'Dividends',
        group: 'dividends',
        glyph: { shape: 'circle', color: '#2962ff', letter: 'D' },
        tooltip: 'Dividend · $0.01',
        content: {
            panel: {
                items: [
                    { type: 'field', label: 'Ex-dividend date', value: "Tue 11 Jun '24" },
                    { type: 'field', label: 'Amount', value: '0.01' },
                    { type: 'button', label: 'More NVDA dividends', primary: true, run: () => openDividends('NVDA') },
                ],
            },
        },
    })
    .add({
        id: 'split-2024-06-10',
        time: Date.UTC(2024, 5, 10),
        title: 'Stock split',
        group: 'splits',
        glyph: { icon: 'myco.split', color: '#ff9800' },
        content: async () => ({ html: await fetchSplitDetails('NVDA') }),
    });

chart.on('mark:click', ({ id, ids, time }) => { /* ids = every mark under the clicked glyph */ });
chart.on('market:changed', ({ symbol }) => chart.marks.set(marksFor(symbol)));
chart.renderer.set('marks', false); // hide the whole lane (`{ groups: { splits: false } }` hides one group)
```

***

## `chart.replay` — the bar-replay control surface [#chartreplay--the-bar-replay-control-surface]

Rewind the chart to a past bar and reveal the bars that followed, one at a time, by hand or on a
timer. The replay walks the history **already loaded** — nothing is refetched per bar. Each revealed
bar travels the same path as a live bar: indicators update as if it had just closed (a script sees
it as a real-time bar), chart-type data engines are told through `onBars`, and the `bar` event
fires. While replaying, live updates are paused; stopping (or revealing the last bar) restores the
full history, resumes them, and fetches the bars that closed in the meantime. Switching the
timeframe (or session) keeps the replay going on the new bars, at the same point in time: the
chart keeps the bars that had closed by the end of what was revealed (a coarser bar still open at
that point stays hidden), and playback carries on if it was on. Switching the symbol ends the replay.
Script alerts stay quiet while a replay runs: a replayed bar is history, so it never raises the
`alert` event (on the chart or on an indicator handle). In a multi-chart workspace,
[`workspace.replay`](/docs/vela/user/workspace#bar-replay-across-the-grid) replays every chart together on
one clock.

| Member                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start({ from })`          | Enter replay at epoch-ms `from`: the chart keeps every bar that opened at or before it and hides the rest. Resolves once the rewound history is on screen — at once when `from` falls inside the loaded bars, even while older history is still streaming in (it joins the replay as it lands). An older `from` than the loaded history deepens it first (`from: 0` loads everything the source has), and the chart returns to its previous depth when the replay ends; a `from` with no bar after it warns and does nothing. Called while replaying, it **seeks** — backward or forward — and pauses. Every indicator re-runs over the rewound history. |
| `step()`                   | Reveal the next bar — or, mid-way through a bar played tick by tick, complete it. Returns `false` when replay is off.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `stepUpdate()`             | Reveal the next update: with [tick replay](#tick-replay), the forming bar's next tick, or the next bar opened at its first tick (once its ticks are in); otherwise the next whole bar. Returns `false` when nothing is left.                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `play(intervalMs?)`        | Reveal one bar every `intervalMs` — one update, with [tick replay](#tick-replay) (default: the last pace, initially 1000). Calling it again while playing changes the pace.                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `pause()`                  | Stop the timer; the replay stays where it is.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `stop()`                   | Leave replay: full history back, live updates resumed. Called while a `start()` is still loading older history, it cancels that load instead (the chart returns to its previous depth, the pending `start()` resolves without replaying).                                                                                                                                                                                                                                                                                                                                                                                                                |
| `state`                    | `{ active, playing, cursorTime, remaining, nextTime, intervalMs }` — `cursorTime` is the newest bar on screen (`null` when off, and while a timeframe switch reloads the bars — `active` stays `true` through it); `nextTime` is the open time of the next bar a step completes (`null` when nothing is left).                                                                                                                                                                                                                                                                                                                                           |
| `bounds`                   | `{ first, last }` — the open times of the oldest and newest bar a replay can start from (hidden bars included while replaying), or `null` before any bar loaded. A random start, or a "start from the first bar" button, reads it.                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `setTicks(source \| null)` | Play each revealed bar as intrabar updates instead of whole (see below); `null` goes back to whole bars.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

```js
await chart.replay.start({ from: Date.UTC(2024, 5, 3, 14) });
chart.replay.play(2000);                 // one bar every 2 s
chart.on('replay:step', ({ cursorTime, remaining }) => updateUi(cursorTime, remaining));
chart.on('replay:end', ({ reason }) => hideUi(reason));
```

### Tick replay [#tick-replay]

`setTicks(source)` makes a playing replay build each bar the way a live one forms: `source(bar, { end, signal })` returns the bar's intrabar updates, oldest first — `{ price, high?, low?, open?,
volume? }[]`, or a promise of it — covering `[bar.time, end)`. The forming candle opens at the
first update (`open`, else its price), every update moves its close to `price` and stretches its
high and low to include `high`/`low`, and the last one settles it on the stored bar, so indicators
end exactly where a whole-bar replay leaves them. Each update travels the live-tick path
(indicators, chart types and the `bar` event follow) and fires `replay:tick`; the bar still fires
`replay:step` once, when it settles.

* The play interval becomes the time between two **updates**: a bar lasts as many intervals as it
  has ticks (a 15m bar from 1m updates takes 15 intervals). Below \~16 ms, updates are batched.
* Volume adds up from the ticks' own; when none carries one, the bar's volume is spread evenly.
* The next bar's ticks are requested while the current one plays; playback waits for them if they
  are late. An empty answer, or a failure, reveals that bar whole.
* A seek, a stop or a new source aborts the requests in flight (`signal`) and puts a half-formed
  bar back in its stored form.

The source decides where the prices come from — trades, a synthetic path, or finer bars.
`lowerTimeframeTicks(chart, timeframe)` covers the last case from the chart's own provider: it
fetches the `timeframe` bars inside each replayed bar and makes each one update — its close, its
high and low, its volume (`barsToTicks` does that step on bars you already have).

```js
import { lowerTimeframeTicks } from '@luxalgo/vela';

chart.replay.setTicks(lowerTimeframeTicks(chart, '1'));   // replay 1h bars through their 1m bars
chart.replay.play(1000);                                  // one 1m update per second: 60 s per bar
chart.on('replay:tick', ({ index, count }) => showProgress(index / count));
```

The price-axis countdown to bar close reads the real clock, so it stays hidden while replaying —
every bar on screen closed long ago.

***

## `deps` — the swap point [#deps--the-swap-point]

The optional third constructor argument is where you replace a layer's default with your own implementation of that layer's port:

| Key        | Replaces                                                                                                                                                                                                                                     | Guide                                                                                                                 |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `renderer` | The drawing/output layer. Injects an already-constructed renderer *instance*, bypassing the `renderer` option's display-options wiring (a different axis from built-in vs custom — `options.renderer` already accepts any custom class too). | [Adding a renderer](/docs/vela/contributing/adding-a-renderer)                                                        |
| `engines`  | Scripting engines to register at construction (bulk form of `registerEngine`).                                                                                                                                                               | [Scripting engines](/docs/vela/user/scripting-engines) · [Adding an engine](/docs/vela/contributing/adding-an-engine) |
| `dataFeed` | The market-data source. Replaces the default provider registry entirely with your own `MarketDataFeed` (used bare — no registry, no auto-cache).                                                                                             | [Adding a data provider](/docs/vela/contributing/adding-a-data-provider)                                              |

Each layer is one narrow port — implement it, declare its honest capabilities, and inject it here. The composition root is the only place that imports concrete backends.

> The three *adding-a-backend* guides are **Contributing** docs and are still being written. Until they land, no link points at them — see the Contributing section of the [docs index](/docs/vela).

> **Stability:** The API is still stabilizing and will evolve as the library develops; pin a source revision if you need a fixed surface.
