Drawing persistence
Configure per-symbol drawing storage, workspace state document persistence, chart and symbol keys, and conflict resolution rules.
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.
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 for a production adapter that distinguishes failed network reads from 404 responses so transient outages cannot overwrite saved drawings.
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
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
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
loadandsavemay execute synchronously or return aPromise. saveruns 300 ms after the most recent drawing edit on the chart and flushes immediately onpagehide. It receives the completeSavedDrawingsdocument for that chart and symbol, ornullwhen the last drawing is deleted so your adapter can delete the stored record.loadruns 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 asynchronousload, drawings render once the promise resolves; if the user draws on the chart beforeloadresolves, the late response is discarded and the new drawing is saved instead.- Storage errors fail silently. Rejected promises from
loadorsaveare swallowed without console output, leaving drawings in memory on the chart. Log errors inside your adapter implementation, and never throw synchronously fromsave.
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
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
idattributes (or beneath the same ancestorid), which would otherwise produce identical keys and share drawings. - A single workspace switches between multiple saved layouts or tabs. Sharing one
chartKeycauses 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():
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
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:
import { enableVelaPro } from '@luxalgo/vela-pro';
enableVelaPro({
symbolDrawings: { symbolKey: (symbol) => symbol.toLowerCase() },
});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:
- Non-empty documents take precedence. Restoring a workspace state document, calling
workspace.applyState(), or callingchart.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. - 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.
- Only explicit deletion clears a symbol. Deleting all drawings in the UI or calling
chart.drawings.clear()removes the drawings and passesnulltostorage.save().
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, anddrawingTools.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
Pass symbolDrawings: false to disable per-symbol drawing swaps and storage:
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.