Vela, our next-generation charting platform, is live at vela.luxalgo.com.
LuxAlgo
Feature and plugin stores

Drawing persistence

Configure per-symbol drawing storage, workspace state document persistence, chart and symbol keys, and conflict resolution rules.

View as Markdown

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

CharacteristicWorkspace state documentPer-symbol drawing store
Payloadcharts[i].drawings, produced by chart.drawings.toJSON()One SavedDrawings document per chart and symbol
CoverageDrawings for the active symbol on each chartDrawings for every symbol opened on each chart
Managed byWorkspace persist option or manual getState() callsenableSymbolDrawings, enabled by default in enableVelaPro()
Default locationlocalStorage under vela-workspace when persist: truelocalStorage, one entry per chart and symbol
Survives reload without persistNoYes

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():

OptionDefaultDescription
storagelocalStorageStorage adapter implementing load(key) and save(key, doc).
chartKeyContainer id + cell idComputes the chart segment of the storage key. Charts returning the same chartKey share drawings.
symbolKeyTicker without venue prefixComputes 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 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

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():

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:

  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

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

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.

On this page