# Events and subscriptions (/vela-pro/charts/events)



Host applications control a workspace through cell and workspace methods and react to user or market updates through typed event subscriptions. The example below keeps an external HTML `<select>` element synchronized in both directions with the active chart's symbol:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';
import { onActiveSymbol } from '@luxalgo/vela-pro/plugin';

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
    persist: true,
});

const select = document.querySelector<HTMLSelectElement>('#symbol')!;

// Update the active chart when the external selector changes.
select.addEventListener('change', () => workspace.active.setSymbol(select.value));

// Update the external selector on symbol search picks, watchlist clicks, or state restores.
const stop = onActiveSymbol(workspace.context(), (symbol) => {
    if (!symbol) return;
    const ticker = workspace.chart.data.resolve(symbol)?.ticker ?? symbol;
    if (![...select.options].some((option) => option.value === ticker)) select.add(new Option(ticker));
    select.value = ticker;
});
```

`onActiveSymbol` is imported from `@luxalgo/vela-pro/plugin`, the plugin SDK entry used by Vela Pro modules. It invokes your callback immediately with the initial symbol, again whenever the active chart's symbol changes, and whenever focus moves to another chart cell.

Because symbol identifiers may carry a provider prefix (such as `'binance:BTCUSDT'`), `workspace.chart.data.resolve(symbol)` extracts the bare `ticker`. Setting `select.value` in JavaScript dispatches no DOM `change` event, preventing feedback loops. Call `stop()` when tearing down the page.

## Accessing charts and cells [#accessing-charts-and-cells]

A workspace contains either a single chart or a multi-chart grid, and shared workspace controls target whichever cell is currently active. Each chart slot in the workspace is represented by a cell handle:

| Expression              | Return value                                                                                                            |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `workspace.chart`       | Active `Vela` chart instance from Vela's open-source core (`on`, `setMarket`, `renderer`, `drawings`, `replay`)         |
| `workspace.active`      | Active cell handle (`id`, `symbol`, `timeframe`, `priceStyle`, and cell setters)                                        |
| `workspace.cell('eth')` | Cell handle matching the given ID, or `undefined` if not present                                                        |
| `workspace.cells()`     | Array of all cell handles currently mounted, in grid order                                                              |
| `workspace.context()`   | `WidgetContext` object passed to contributed actions and panels (`symbol`, `togglePanel`, `openSymbolSearch`, `panels`) |

Read `workspace.chart` dynamically when you need it rather than caching the reference in a variable, because clicking another grid cell, switching layouts, or applying a saved state document can change or replace the underlying chart object.

## Programmatic control [#programmatic-control]

| Target                   | Method call                                                                      |
| ------------------------ | -------------------------------------------------------------------------------- |
| Symbol                   | `workspace.active.setSymbol('ETHUSDT')`                                          |
| Timeframe                | `workspace.active.setTimeframe('15')`                                            |
| Chart type               | `workspace.active.setPriceStyle('footprint')`                                    |
| Grid layout              | `workspace.setLayout('2h')`                                                      |
| Active cell              | `workspace.setActiveCell('eth')`                                                 |
| Maximize or restore cell | `workspace.maximizeCell('eth')` (`null` to restore the grid)                     |
| Visible time range       | `workspace.chart.setVisibleRangePreset('1M')` or `setVisibleRange({ from, to })` |
| Theme                    | `workspace.setTheme('light')`                                                    |
| Time zone                | `workspace.setTimezone('America/New_York')`                                      |
| Side panel               | `workspace.context().togglePanel('vela-pro.watchlist', true)`                    |
| Full workspace state     | `workspace.applyState(state)`                                                    |

Unprefixed symbols route to the first registered provider that supports them, while prefixed strings (`'binance:ETHUSDT'`) target a named provider explicitly. Cell setters update the chart in place, recomputing active indicators while preserving chart settings and event listeners. Because Vela Pro scopes drawings per symbol, switching symbols automatically swaps the displayed drawings (see [Drawing persistence](/vela-pro/persistence/stores/drawings)).

Built-in layout IDs are `'1'`, `'2h'`, `'2v'`, `'4'`, and `'8'`, and `layoutForGrid(rows, columns)` from `@luxalgo/vela/workspace` builds custom grids up to 4×4 (`setLayout` is ignored when `layout: false`). Panel IDs are listed in [Workspace layout](/vela-pro/charts/interface#side-rail-and-side-panels), and state serialization is covered in [Layouts and chart state](/vela-pro/persistence/layouts).

Setter methods return immediately before network requests finish. Listen to `market:changed` or `await workspace.chart.ready()` after construction when you need to run code after bars have rendered.

## Workspace events [#workspace-events]

`workspace.on(event, handler)` returns an unsubscribe function. A single workspace listener covers every cell in the grid, including cells created later by layout changes:

| Event                            | Payload                 | Trigger                                                                   |
| -------------------------------- | ----------------------- | ------------------------------------------------------------------------- |
| `cell:active`                    | `{ id, prev }`          | Focus moved to a different chart cell                                     |
| `cell:created`, `cell:destroyed` | `{ id }`                | A layout change or state restore mounted or removed a cell                |
| `layout:changed`                 | `{ layout }`            | The workspace switched grid layouts or rebuilt from saved state           |
| `cell:priceStyle`                | `{ id, from, to }`      | A cell is switching chart types, emitted before repaint                   |
| `cell:maximized`                 | `{ id }`                | A cell maximized over the grid, or returned to grid view (`id` is `null`) |
| `script:run`                     | Run result plus `cell`  | An indicator or strategy finished executing in any cell                   |
| `state:changed`                  | None                    | Workspace state changed (debounced by approximately 500 ms)               |
| `locale:changed`                 | `{ locale, direction }` | `setLocale()` updated the active language or text direction               |

Subscribe to `state:changed` to persist state documents to a backend (see [Layouts and chart state](/vela-pro/persistence/layouts)), and use `script:run` to inspect indicator outputs or strategy metrics (see [Backtest results](/vela-pro/indicators/backtesting/results)).

## Chart events [#chart-events]

`chart.on(event, handler)` subscribes to events on an individual `Vela` chart instance:

| Event                                                  | Payload                                                        | Trigger                                                                                      |
| ------------------------------------------------------ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `market:changed`                                       | `{ symbol, timeframe, prev }`                                  | Symbol or timeframe changed and initial bars finished painting (`prev` holds the prior pair) |
| `load:start`                                           | `{ symbol, timeframe, firstLoad }`                             | Initial series fetch started on an empty chart                                               |
| `load:end`                                             | `{ symbol, timeframe, bars }`                                  | Initial series load painted (`bars` is `0` when no data was returned)                        |
| `data:unresolved`                                      | `{ symbol, providers }`                                        | No registered provider matched the requested symbol                                          |
| `data:unavailable`                                     | `{ symbol, timeframe, reason, finest, default }`               | The provider permanently rejected the series (for example, an unsupported timeframe)         |
| `bar`                                                  | `Bar`                                                          | Live tick update, newly closed bar, or bar revealed during replay                            |
| `viewport:changed`                                     | `{ from, to }`                                                 | Visible time range panned or zoomed                                                          |
| `indicator:added`, `indicator:removed`                 | `{ id }`                                                       | An indicator was added to or removed from the chart                                          |
| `indicator:error`                                      | `{ id, error }`                                                | A script indicator encountered a compile or runtime error                                    |
| `drawing:created`, `drawing:edited`, `drawing:removed` | `{ id }`                                                       | A drawing was created, modified, or deleted                                                  |
| `alert`                                                | Script alert payload                                           | A running script triggered an alert condition                                                |
| `theme:changed`                                        | Resolved theme object                                          | Chart theme updated via API or Chart settings                                                |
| `replay:start`, `replay:step`, `replay:end`            | See [Bar replay](/vela-pro/charts/replay#programmatic-control) | Replay started, stepped forward, or ended                                                    |

For the complete catalog of core chart events and payload types, see [Chart-level events](/vela/user/api-reference#chart-level-events) in the core API reference.

Because `chart.on()` attaches to a single chart instance, listeners tracking whichever chart is active should rebind on `cell:active` and `layout:changed`:

```ts
import type { VelaWorkspace } from '@luxalgo/vela/workspace';

declare const workspace: VelaWorkspace;
declare function showLastPrice(price: number): void;

let off = (): void => {};
const follow = (): void => {
    off();
    off = workspace.chart.on('bar', (bar) => showLastPrice(bar.close));
};

follow();
workspace.on('cell:active', follow);
workspace.on('layout:changed', follow);
```

Alternatively, `onActiveChart(workspace.context(), callback)` from `@luxalgo/vela-pro/plugin` tracks active-chart changes automatically on a 400 ms polling interval. Prefer the explicit `cell:active` and `layout:changed` subscriptions above when you need synchronous rebinding.

## Vela Pro feature handles and events [#vela-pro-feature-handles-and-events]

Vela Pro features expose dedicated controller handles for programmatic inspection and event subscriptions. `codeEditor()` and `bottomDock()` return `null` when the corresponding feature is disabled:

```ts
import type { VelaWorkspace } from '@luxalgo/vela/workspace';
import { bottomDock, codeEditor } from '@luxalgo/vela-pro';

declare const workspace: VelaWorkspace;

const editor = codeEditor(workspace);
editor?.onDidEndRun(({ mode, ok, error }) => {
    if (!ok) console.warn(`${mode} failed: ${error?.message}`);
});

workspace.replay.on('replay:start', () => console.log('replay started'));
workspace.replay.on('replay:end', ({ reason }) => console.log(`replay ended: ${reason}`));

const dock = bottomDock(workspace.root);
dock?.onChange(() => console.log(dock.isOpen ? `bottom panel: ${dock.active}` : 'bottom dock closed'));

const panels = workspace.context().panels;
panels.onDidChange(() => console.log(`side panel: ${panels.openId() ?? 'none'}`));
```

| Feature     | Accessor                                                             | Events and state                                                                                                                                                                                                  |
| ----------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Code editor | `codeEditor(workspace)`                                              | `onDidStartRun` (`{ mode }`), `onDidEndRun` (`{ mode, ok, error }`), `onDidChangeTarget`, `onDidChangeCode`, where `mode` is `'run'` or `'update'`. See [Pine code editor](/vela-pro/indicators/pine/code-editor) |
| Replay      | `workspace.replay`                                                   | `replay:*` events across the shared workspace clock. See [Bar replay](/vela-pro/charts/replay)                                                                                                                    |
| Bottom dock | `bottomDock(workspace.root)`                                         | `onChange`, plus `isOpen` and `active` properties                                                                                                                                                                 |
| Side panels | `workspace.context().panels`                                         | `onDidChange`, plus `openId()` (provided by the core)                                                                                                                                                             |
| Modules     | `tradingController()`, `alertsController()`, and sibling controllers | Order lifecycle, fills, triggered alerts, and watchlist updates. See [Modules and widgets](/vela-pro/modules/overview)                                                                                            |

Menus, dialogs, and panels also dispatch DOM custom events on the workspace root element so host code can observe UI state without MutationObservers. See [Following menus and panels](/vela/user/workspace#following-menus-and-panels) in the core documentation.

## Related [#related]

* [Layouts and chart state](/vela-pro/persistence/layouts)
* [Modules and widgets](/vela-pro/modules/overview)
* [API reference](/vela/user/api-reference) in the core documentation
