# Drawing persistence (/vela-pro/persistence/stores/drawings)



Vela Pro persists chart drawings across two coordinated stores. The workspace state document stores the drawings currently displayed on each chart, while Vela Pro's **per-symbol drawing store** saves a separate drawing document for every chart and symbol pair. When a user draws a trend line on one symbol, switches to another symbol, and later switches back, the per-symbol store swaps each symbol's drawings automatically.

```ts
import { enableVelaPro, type SymbolDrawingsStorage } from '@luxalgo/vela-pro';

const url = (key: { chart: string; symbol: string }): string =>
    `/api/users/me/drawings/${encodeURIComponent(key.chart)}/${encodeURIComponent(key.symbol)}`;

const storage: SymbolDrawingsStorage = {
    async load(key) {
        const res = await fetch(url(key));
        return res.ok ? await res.json() : null; // null when nothing is saved for this chart and symbol
    },
    async save(key, doc) {
        // doc is null when the last drawing on the symbol is removed.
        const body = doc ? JSON.stringify(doc) : undefined;
        await fetch(url(key), {
            method: doc ? 'PUT' : 'DELETE',
            headers: { 'content-type': 'application/json' },
            body,
            keepalive: (body?.length ?? 0) < 60_000, // finishes across navigation; browsers cap keepalive bodies at 64 KiB
        });
    },
};

enableVelaPro({ symbolDrawings: { storage } });
```

See [Server-side storage](/vela-pro/persistence/backend#per-symbol-drawings) for a production adapter that distinguishes failed network reads from `404` responses so transient outages cannot overwrite saved drawings.

## Storage locations [#storage-locations]

| Characteristic                    | Workspace state document                                    | Per-symbol drawing store                                        |
| --------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------- |
| Payload                           | `charts[i].drawings`, produced by `chart.drawings.toJSON()` | One `SavedDrawings` document per chart and symbol               |
| Coverage                          | Drawings for the active symbol on each chart                | Drawings for every symbol opened on each chart                  |
| Managed by                        | Workspace `persist` option or manual `getState()` calls     | `enableSymbolDrawings`, enabled by default in `enableVelaPro()` |
| Default location                  | `localStorage` under `vela-workspace` when `persist: true`  | `localStorage`, one entry per chart and symbol                  |
| Survives reload without `persist` | No                                                          | Yes                                                             |

A serialized drawings payload has the shape `{ version: 1, drawings: [...] }`. Vela's open-source core versions and migrates drawing schemas forward, and `fromJSON()` drops malformed or unrecognized entries rather than throwing, so your backend can store the payload as opaque JSON.

## Per-symbol drawing storage [#per-symbol-drawing-storage]

When a chart switches to a different symbol, Vela Pro removes the outgoing symbol's drawings from the chart and loads any saved drawings for the incoming symbol. Switching timeframes preserves active drawings, and reloading the page restores per-symbol drawings even when workspace `persist` is disabled.

In multi-chart layouts, **Sync drawings on all charts** duplicates newly created drawings onto linked charts and keeps those copies synchronized during the session. Each chart saves its copy under its respective chart and symbol key. Sync link metadata is not serialized; after a reload with drawing sync enabled, identical drawings across synced charts are re-linked automatically, while copies edited independently when sync was off remain separate.

Configure per-symbol persistence through `symbolDrawings` in `enableVelaPro()`:

| Option      | Default                     | Description                                                                                           |
| ----------- | --------------------------- | ----------------------------------------------------------------------------------------------------- |
| `storage`   | `localStorage`              | Storage adapter implementing `load(key)` and `save(key, doc)`.                                        |
| `chartKey`  | Container `id` + cell `id`  | Computes the `chart` segment of the storage key. Charts returning the same `chartKey` share drawings. |
| `symbolKey` | Ticker without venue prefix | Computes the `symbol` segment of the storage key.                                                     |

### Storage interface [#storage-interface]

```typescript
interface SymbolDrawingsStorage {
    load(key: SymbolDrawingsKey): SavedDrawings | null | Promise<SavedDrawings | null>;
    save(key: SymbolDrawingsKey, doc: SavedDrawings | null): void | Promise<void>;
}

interface SymbolDrawingsKey {
    chart: string;
    symbol: string;
}
```

* Both `load` and `save` may execute synchronously or return a `Promise`.
* `save` runs 300 ms after the most recent drawing edit on the chart and flushes immediately on `pagehide`. It receives the complete `SavedDrawings` document for that chart and symbol, or `null` when the last drawing is deleted so your adapter can delete the stored record.
* `load` runs whenever a chart displays a symbol while holding zero drawings, unless that symbol's drawings were already modified in the current session (in which case the in-memory state is reused). With an asynchronous `load`, drawings render once the promise resolves; if the user draws on the chart before `load` resolves, the late response is discarded and the new drawing is saved instead.
* Storage errors fail silently. Rejected promises from `load` or `save` are swallowed without console output, leaving drawings in memory on the chart. Log errors inside your adapter implementation, and never throw synchronously from `save`.

The default implementation is `LocalSymbolDrawingsStorage`, which writes entries under `vela-pro.drawings:<chart>:<symbol>`. Pass a custom prefix string to `new LocalSymbolDrawingsStorage(prefix)` to namespace the key.

### Naming charts with `chartKey` [#naming-charts-with-chartkey]

By default, Vela Pro derives each chart's key from the `id` of the workspace container element (or its nearest ancestor with an `id`) combined with the cell ID, such as `chart/c1` for `new VelaWorkspace('#chart', ...)`. When no ancestor carries an `id`, the prefix defaults to `shell`.

Provide a custom `chartKey` function in two scenarios:

* Multiple workspaces are mounted in DOM elements without `id` attributes (or beneath the same ancestor `id`), which would otherwise produce identical keys and share drawings.
* A single workspace switches between multiple saved layouts or tabs. Sharing one `chartKey` causes the incoming layout's drawings for a symbol to overwrite drawings saved for that symbol in the previous layout.

Vela Pro evaluates `chartKey` on every `load` and `save` call rather than caching it once at startup. Return the active layout or tab ID from `chartKey`, and update that ID **before** calling `workspace.applyState()`:

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

let documentId = 'layout-1';

enableVelaPro({
    symbolDrawings: { chartKey: ({ cellId }) => `${documentId}/${cellId}` },
});

const workspace = new VelaWorkspace('#chart', {
    layout: '2h',
    symbol: 'BTCUSDT',
    providers: { binance: () => new BinanceProvider() },
});

export async function openTab(id: string): Promise<void> {
    const res = await fetch(`/api/users/me/layouts/${encodeURIComponent(id)}`);
    if (!res.ok) return;
    const state: unknown = await res.json();
    documentId = id; // update the active key before applying the layout document
    workspace.applyState(state);
}
```

Any debounced write queued before the tab switch retains the `chartKey` captured when the edit occurred, so unsaved edits flush to the outgoing tab rather than the newly opened one.

### Naming symbols with `symbolKey` [#naming-symbols-with-symbolkey]

By default, `symbolKey` strips the venue prefix so `BTCUSDT` and `binance:BTCUSDT` resolve to the same storage key regardless of how the symbol was selected. Consequently, identical ticker symbols across two different providers share saved drawings by default.

If your application lists distinct instruments that share the same ticker across different venues, preserve the full symbol string in `symbolKey`:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({
    symbolDrawings: { symbolKey: (symbol) => symbol.toLowerCase() },
});
```

## Precedence rules [#precedence-rules]

When both a workspace state document and the per-symbol store exist for the same chart and symbol, Vela Pro resolves them using three rules:

1. **Non-empty documents take precedence.** Restoring a workspace state document, calling `workspace.applyState()`, or calling `chart.drawings.fromJSON()` with one or more drawings replaces the chart's current drawings and writes that set into the per-symbol store for the active symbol.
2. **Empty documents never erase stored drawings.** When an applied document contains zero drawings for a chart, the chart loads any saved drawings for its active symbol from the per-symbol store instead. This ensures an older layout snapshot cannot wipe out drawings created later on that symbol.
3. **Only explicit deletion clears a symbol.** Deleting all drawings in the UI or calling `chart.drawings.clear()` removes the drawings and passes `null` to `storage.save()`.

## Tool defaults, saved styles, and favorites [#tool-defaults-saved-styles-and-favorites]

Three workspace-wide drawing preferences are stored at the root of the workspace state document rather than in the per-symbol store, so they require workspace `persist` (or manual `getState()` / `applyState()` calls) to persist across reloads:

* `drawingTools.defaults`: Per-tool style and property defaults applied to newly created drawings of each type.
* `drawingTools.templates`, `drawingTools.magnet`, and `drawingTools.stay`: Saved per-tool style presets, magnet snapping mode, and stay-in-drawing-mode state.
* `favorites`: Starred drawing tool IDs, which also populate the radial tool wheel.

## Disabling per-symbol storage [#disabling-per-symbol-storage]

Pass `symbolDrawings: false` to disable per-symbol drawing swaps and storage:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({ symbolDrawings: false });
```

When disabled, drawings remain on the chart at their price coordinates when switching symbols and are saved exclusively inside the workspace state document.

## Related [#related]

* [Server-side storage](/vela-pro/persistence/backend)
* [Configuration precedence](/vela-pro/persistence/precedence)
* [Persistence, undo, and clipboard in the core drawing guide](/vela/user/drawing-tools#persistence-undo--clipboard)
