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

Transitioning from TradingView Advanced Charts

Migrate Datafeed and UDF connectors, PineJS custom indicators, saved layouts, drawings, and overrides from TradingView Advanced Charts to Vela Pro.

View as Markdown

Vela Pro mounts directly in your application's DOM as standard ES modules rather than inside an <iframe> backed by a static library_path folder. If your application currently embeds TradingView Advanced Charts, you can reuse your existing market data and layout storage endpoints by wrapping them behind Vela's DataProvider and storage interfaces.

This guide maps the public API surfaces of TradingView Advanced Charts (charting_library) to their counterparts in Vela's open-source core (@luxalgo/vela) and Vela Pro (@luxalgo/vela-pro).

Widget initialization and lifecycle

In TradingView Advanced Charts, new TradingView.widget(options) creates an <iframe>, and application code waits for widget.onChartReady() before calling IChartingLibraryWidget or IChartWidgetApi (widget.activeChart()) methods.

In Vela Pro, call enableVelaPro() once at module scope, then construct new VelaWorkspace(container, options). Set layout: false for a single-chart instance matching Advanced Charts. workspace.chart and workspace.active are available immediately after construction, and await workspace.chart.ready() resolves after the initial bars render.

Advanced Charts (IChartingLibraryWidget)Vela Pro (VelaWorkspace)
new TradingView.widget({ container, library_path, datafeed, symbol, interval, ... })enableVelaPro() once, then new VelaWorkspace(container, { layout: false, providers, symbol, timeframe, ... })
autosize: trueAutomatic; the workspace always fills its container element
widget.onChartReady(cb)Synchronous instance (await workspace.chart.ready() for first paint)
widget.chart() / widget.activeChart()workspace.chart (Vela) and workspace.active (WorkspaceCell)
widget.setSymbol(symbol, interval, cb)workspace.active.setSymbol(symbol) and workspace.active.setTimeframe(interval)
chart.onSymbolChanged().subscribe(null, fn)const off = workspace.chart.on('market:changed', fn)
widget.changeTheme('Dark')workspace.setTheme('dark')
widget.remove()workspace.destroy()
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro();

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    locale: 'en',
    timezone: 'Etc/UTC',
    theme: 'dark',
    providers: { binance: () => new BinanceProvider() },
    persist: true,
});

const unsubscribe = workspace.chart.on('market:changed', ({ symbol, timeframe }) => {
    console.log('Active market:', symbol, timeframe);
});

workspace.active.setSymbol('ETHUSDT');
unsubscribe();

Data connectors

Your existing IBasicDataFeed backend or UDF HTTP endpoints (/config, /search, /symbols, /history) do not need to be rewritten. Implement a DataProvider (@luxalgo/vela) that adapts request parameters and timestamp units.

Datafeed API mapping

Advanced Charts Datafeed methodVela DataProvider equivalentNotes
onReady(callback)Not requiredCapabilities are inferred from the optional methods your DataProvider implements.
searchSymbols / searchSymbolsPaginatedlistSymbols()Called once at registration to index symbols for search and unprefixed resolution. For server-paginated search over large catalogs, pass a custom picker to enableSymbolSearch({ picker }).
resolveSymbol(symbolName, onResolve, onError)getSymbolInfo(ticker)Async method returning SymbolInfo. Convert minmov / pricescale (for example 1 / 100) into mintick (0.01).
getBars(symbolInfo, resolution, periodParams, onHistory, onError)getBars(ticker, timeframe, range)Returns Promise<OHLCV[]> sorted ascending by time. Both range bounds and bar time values use epoch milliseconds.
subscribeBars(symbolInfo, resolution, onTick, listenerGuid) + unsubscribeBars(guid)subscribe(ticker, timeframe, onBar, opts)Returns an () => void cleanup function directly instead of tracking listenerGuid strings.
session_holidays and corrections on LibrarySymbolInfogetCalendar(ticker, range)Returns resolved [openMs, closeMs] market windows with holidays and early closes already applied.
getMarks and getTimescaleMarkschart.marksPush marks via chart.marks.defineGroup(...).set(...) when market:changed fires rather than pull callbacks.
getServerTimeNot requiredBar countdowns and sessions derive from bar timestamps, timezone, and getCalendar.

Verify timestamp units when porting getBars. In the Advanced Charts Datafeed API, periodParams.from and periodParams.to are Unix seconds while Bar.time is milliseconds (and UDF /history returns t[] in seconds). In Vela's DataProvider, range.from, range.to, and OHLCV.time are all epoch milliseconds.

Wrapping an existing UDF service

If you currently use Datafeeds.UDFCompatibleDatafeed, wrap the same /search, /symbols, and /history HTTP endpoints in a DataProvider:

import type { DataProvider, OHLCV, SymbolDescriptor, SymbolInfo } from '@luxalgo/vela';

interface UdfHistoryResponse {
    s: 'ok' | 'no_data' | 'error';
    t?: number[];
    o?: number[];
    h?: number[];
    l?: number[];
    c?: number[];
    v?: number[];
}

interface UdfSymbolInfo {
    ticker?: string;
    name: string;
    description?: string;
    type?: string;
    exchange?: string;
    timezone?: string;
    session?: string;
    minmov?: number;
    pricescale?: number;
    currency_code?: string;
}

export function createUdfProvider(baseUrl: string): DataProvider {
    return {
        async getBars(ticker, timeframe, range): Promise<OHLCV[]> {
            const toSec = Math.floor((range.to ?? Date.now()) / 1000);
            const fromSec = range.from !== undefined
                ? Math.floor(range.from / 1000)
                : toSec - (range.limit ?? 500) * 60;
            const params = new URLSearchParams({
                symbol: ticker,
                resolution: timeframe,
                from: String(fromSec),
                to: String(toSec),
            });
            if (range.limit !== undefined) params.set('countback', String(range.limit));

            const res = await fetch(`${baseUrl}/history?${params}`);
            const data = (await res.json()) as UdfHistoryResponse;
            if (data.s !== 'ok' || !data.t) return [];

            return data.t.map((sec, i) => ({
                time: sec * 1000, // UDF /history returns Unix seconds
                open: data.o![i]!,
                high: data.h![i]!,
                low: data.l![i]!,
                close: data.c![i]!,
                volume: data.v?.[i] ?? 0,
            }));
        },

        async listSymbols(): Promise<SymbolDescriptor[]> {
            const res = await fetch(`${baseUrl}/search?query=&limit=5000`);
            const items = (await res.json()) as Array<{
                ticker?: string;
                symbol: string;
                description: string;
                exchange: string;
                type: string;
            }>;
            return items.map((item) => ({
                ticker: item.ticker ?? item.symbol,
                description: item.description,
                prefix: item.exchange || undefined,
                type: item.type,
            }));
        },

        async getSymbolInfo(ticker): Promise<SymbolInfo | undefined> {
            const res = await fetch(`${baseUrl}/symbols?symbol=${encodeURIComponent(ticker)}`);
            if (!res.ok) return undefined;
            const info = (await res.json()) as UdfSymbolInfo;
            const mintick = info.minmov && info.pricescale ? info.minmov / info.pricescale : undefined;
            return {
                ticker: info.ticker ?? info.name,
                description: info.description,
                type: info.type,
                currency: info.currency_code,
                timezone: info.timezone,
                session: info.session ?? '24x7',
                ...(mintick !== undefined ? { mintick } : {}),
            };
        },
    };
}

Add subscribe(ticker, timeframe, onBar) when you stream real-time bars over WebSockets; calling onBar with the current bar's time updates the forming candle, and calling it with a newer time opens the next candle, matching subscribeBars onTick semantics. See Custom data providers and Timeframes and sessions.


Custom indicators (custom_indicators_getter)

In Advanced Charts, custom studies are JavaScript CustomIndicator objects returned from custom_indicators_getter(PineJS), combining a StudyMetaInfo descriptor (_metainfoVersion, id, plots, styles, inputs, and duplicated defaults) with an ES5 constructor whose init(ctx, inputCallback) and main(ctx, inputCallback) methods run bar-by-bar against PineJS.Std.

In Vela Pro, JavaScript and TypeScript studies register via registerNativeIndicator (@luxalgo/vela/plugin) before workspace construction and appear automatically in the indicator menu.

Advanced Charts (CustomIndicator)Vela (registerNativeIndicator)
metainfo.id ('MyStudy@tv-basicstudies-1')type ('acme.my-study')
metainfo.description / shortDescriptiontitle / shortTitle
metainfo.is_price_studypaneHint: 'price' and overlay: true (or 'new' and false for a lower pane)
metainfo.inputs + metainfo.defaults.inputsinputsSchema() + defaultInputs()
constructor this.init(ctx, input) + this.main(ctx, input) per barcreate() lifecycle (start, onBars, setInputs) reading chronological ctx.bars()
Return [v0, v1] matching metainfo.plotsCall ctx.emit({ series: [...] }) with stableSeriesId and { time, value } points
chart.createStudy('Custom Indicator', false, false, { length: 21 })chart.addNativeIndicator('acme.my-study', { inputs: { length: 21 } })

Unlike PineJS, where main() executes once per bar using ctx.new_var() for rolling state and ctx.new_sym() for secondary series, a NativeIndicator receives the full chronological OHLCV[] array from ctx.bars() and emits one { time, value } point per bar (null during warmup):

import { ACCENT, registerNativeIndicator, stableSeriesId, type InputValue, type NativeIndicator, type NativeIndicatorContext } from '@luxalgo/vela/plugin';

const TYPE = 'acme.hl2-ema';

registerNativeIndicator({
    type: TYPE,
    title: 'HL2 Exponential Moving Average',
    shortTitle: 'HL2 EMA',
    paneHint: 'price',
    overlay: true,
    multiInstance: true,
    waitsForHistory: true,
    inputsSchema: () => [{ key: 'length', title: 'Length', type: 'int', defval: 21, min: 1, max: 500 }],
    defaultInputs: () => ({ length: 21 }),
    create: (): NativeIndicator => {
        let ctx: NativeIndicatorContext | null = null;
        let length = 21;

        const compute = (): void => {
            if (!ctx) return;
            const bars = ctx.bars();
            const k = 2 / (length + 1);
            let ema: number | null = null;

            const points = bars.map((bar, i) => {
                const src = (bar.high + bar.low) / 2;
                ema = ema === null ? src : src * k + ema * (1 - k);
                return { time: bar.time, value: i >= length - 1 ? ema : null };
            });

            const id = stableSeriesId({ instanceId: TYPE, kind: 'line', title: 'EMA', ordinal: 0 });
            ctx.emit({
                series: [{ id, title: 'EMA', paneId: '', kind: 'line', points, style: { color: ACCENT, width: 2, lineStyle: 'solid' } }],
            });
        };

        const applyInputs = (inputs: Record<string, InputValue>): void => {
            length = Math.max(1, Number(inputs.length ?? 21));
        };

        return {
            start: (context, inputs) => { ctx = context; applyInputs(inputs); compute(); },
            onBars: compute,
            onViewport: () => {},
            setInputs: (inputs) => { applyInputs(inputs); compute(); },
            suspend: () => {},
            resume: compute,
            stop: () => { ctx = null; },
        };
    },
});

If your platform evaluates indicators on a server or through a proprietary expression engine, implement the ScriptingEngine port instead; see Custom runtimes and Custom indicators.


Saved charts, templates, and user settings

Advanced Charts offers three persistence mechanisms: the predefined REST endpoints (charts_storage_url), save_load_adapter (IExternalSaveLoadAdapter), and the low-level widget.save() / widget.load() methods, plus settings_adapter (ISettingsAdapter) for user settings.

Advanced Charts persistence APIVela Pro equivalent
widget.save() / widget.load(state) + onAutoSaveNeededworkspace.getState() / workspace.applyState(doc) + workspace.on('state:changed', ...)
load_last_chart + single-workspace storagepersist: 'workspace' + storage: VelaStorage (get(key), set(key, json))
save_load_adapter (getAllCharts, saveChart, getChartContent, removeChart)Store { id, name, state: workspace.getState() } records in your backend and restore via workspace.applyState(state)
saveStudyTemplate, getStudyTemplateContent, createStudyTemplateenableVelaPro({ indicatorTemplates: { storage } }) (IndicatorTemplatesStorage) and captureIndicators / applyTemplate
saveload_separate_drawings_storage + saveLineToolsAndGroups / loadLineToolsAndGroupsEnabled by default via enableVelaPro({ symbolDrawings: { storage, chartKey, symbolKey } }) (SymbolDrawingsStorage)
settings_adapter (initialSettings, setValue, removeValue)Constructor options for initial defaults and VelaStorage / module ports for persisted user preferences

In Advanced Charts, ChartData.content and StudyTemplateData.content are opaque internal JSON strings, so Vela cannot load raw content blobs directly. However, ChartMetaInfo / ChartData records in your save_load_adapter or /charts table already expose top-level id, name, symbol, and resolution fields. You can seed a valid Vela version: 1 state document from those metadata fields on first load, then write subsequent saves in Vela's format:

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

interface LegacyChartMeta {
    id: string | number;
    name: string;
    symbol: string;
    resolution: string;
    velaState?: unknown; // populated once the user saves in Vela Pro
}

export function restoreChartRecord(workspace: VelaWorkspace, record: LegacyChartMeta): void {
    if (record.velaState) {
        workspace.applyState(record.velaState);
        return;
    }
    // Seed from Advanced Charts ChartMetaInfo metadata when migrating an older record
    workspace.applyState({
        version: 1,
        layout: '1',
        charts: [
            {
                id: 'c1',
                symbol: record.symbol,
                timeframe: record.resolution,
            },
        ],
    });
}

See Layouts and chart state, Indicator templates, and Server-side storage.


Drawings

Programmatic drawings API

Advanced Charts splits drawing creation between createShape (single-point) and createMultipointShape (multi-point), expects PricedPoint.time in Unix seconds, and mutates shapes through getShapeById(id) (ILineDataSourceApi). Vela uses a single synchronous chart.drawings surface with epoch millisecond timestamps and plain JSON objects:

Advanced Charts (IChartWidgetApi / ILineDataSourceApi)Vela (chart.drawings)
await chart.createShape(point, { shape, lock, text, overrides })chart.drawings.add(type, { anchors: [point], locked, text, style })
await chart.createMultipointShape(points, { shape, ... })chart.drawings.add(type, { anchors: points, ... })
chart.getAllShapes() + chart.getShapeById(id).getPoints() / getProperties()chart.drawings.all() or chart.drawings.toJSON()
chart.getShapeById(id).setPoints(pts) / setProperties(props)chart.drawings.update(id, { anchors, style, text, locked })
chart.getShapeById(id).bringToFront() / sendToBack()chart.drawings.bringToFront(id) / chart.drawings.sendToBack(id)
chart.removeEntity(id) / chart.removeAllShapes()chart.drawings.remove(id) / chart.drawings.clear()

Exporting and converting drawings

In saveLineToolsAndGroups, LineToolState.state is typed as unknown and uses an internal layout format. If you export drawings through Advanced Charts' public getAllShapes() and getShapeById(id).getPoints() methods (where PricedPoint carries { time, price } with time in Unix seconds), map shape names to Vela DrawingTypeKey IDs and convert time to milliseconds:

Advanced Charts shape nameVela DrawingTypeKey
trend_line / ray / extended / info_line'trendline' / 'ray' / 'extendedline' / 'infoline'
horizontal_line / horizontal_ray / vertical_line / cross_line'hline' / 'hray' / 'vline' / 'crossline'
parallel_channel / regression_trend / flat_bottom / disjoint_angle'parallelchannel' / 'regressionchannel' / 'flattopbottom' / 'disjointchannel'
pitchfork / schiff_pitchfork_modified / schiff_pitchfork / inside_pitchfork'pitchfork' / 'modifiedschiffpitchfork' / 'schiffpitchfork' / 'insidepitchfork'
fib_retracement / trend_based_fib_extension / fib_channel'fibretracement' / 'fibextension' / 'fibchannel'
rectangle / rotated_rectangle / ellipse / circle / triangle'box' / 'rotatedrect' / 'ellipse' / 'circle' / 'triangle'
brush / highlighter / arrow / polyline'freehand' / 'highlighter' / 'arrow' / 'polyline'
text / callout / note / price_label / flag_mark'text' / 'callout' / 'note' / 'pricelabel' / 'flagmark'
anchored_vwap / fixed_range_volume_profile'anchoredvwap' / 'fixedrangevp'
long_position / short_position / date_and_price_range'position' / 'datepricerange'
import type { DrawingTypeKey } from '@luxalgo/vela';
import type { SavedDrawings } from '@luxalgo/vela-pro';

interface ExportedAclShape {
    id: string;
    name: string; // from getAllShapes()
    points: Array<{ time: number; price: number }>; // from getShapeById(id).getPoints(), Unix seconds
    locked?: boolean;
}

const SHAPE_MAP: Record<string, DrawingTypeKey> = {
    trend_line: 'trendline',
    ray: 'ray',
    horizontal_line: 'hline',
    horizontal_ray: 'hray',
    vertical_line: 'vline',
    parallel_channel: 'parallelchannel',
    fib_retracement: 'fibretracement',
    rectangle: 'box',
    text: 'text',
    callout: 'callout',
};

export function toVelaDrawings(shapes: readonly ExportedAclShape[]): SavedDrawings {
    const now = Date.now();
    return {
        version: 1,
        drawings: shapes.flatMap((shape, index) => {
            const type = SHAPE_MAP[shape.name];
            if (!type) return [];
            return [
                {
                    id: shape.id,
                    type,
                    paneId: 'price',
                    anchors: shape.points.map((pt) => ({ time: pt.time * 1000, price: pt.price })),
                    style: { lineColor: '#2962ff', lineWidth: 1, lineStyle: 'solid' },
                    locked: shape.locked ?? false,
                    visible: true,
                    zIndex: index,
                    createdAt: now,
                },
            ];
        }),
    };
}

Pass the converted payload to chart.drawings.fromJSON(doc) or return it from SymbolDrawingsStorage.load(key). Unlike saveload_separate_drawings_storage, Vela Pro's per-symbol drawing storage is enabled by default and requires only load({ chart, symbol }) and save({ chart, symbol }, doc) without manual tombstone (null) bucket merging. See Managing drawings and Drawing persistence.


Featuresets, overrides, and theming

Advanced Charts controls UI visibility and styling through enabled_features / disabled_features string arrays, dot-path overrides, and iframe stylesheets (custom_css_url with --tv-color-* variables or 19-shade custom_themes palettes). Vela Pro replaces these with typed configuration options, --vela-* design tokens, and standard CSS cascade layers:

Advanced Charts optionVela Pro equivalent
disabled_features: ['header_chart_type', 'header_indicators', 'header_undo_redo', ...]Configure visible items via topbar: { left, right } on new VelaWorkspace(...)
disabled_features: ['left_toolbar'] / hide_left_toolbar_by_defaultdrawingToolbar: false on new VelaWorkspace(...)
disabled_features: ['timeframes_toolbar']bottombar: false on new VelaWorkspace(...)
disabled_features: ['show_object_tree']enableVelaPro({ sideRail: { exclude: ['objects'] } })
disabled_features: ['items_favoriting']chart.drawings.setFavorites([]) / disable radialWheel: false
disabled_features: ['use_localstorage_for_settings']Omit persist (off by default) or pass storage: memoryStorageAdapter()
enabled_features: ['study_templates']Enabled by default (enableVelaPro({ indicatorTemplates }))
drawings_access: { type: 'white', tools: [...] }drawings: { tools: ['trendline', 'hline', ...] } on new VelaWorkspace(...)
favorites: { intervals: [...], chartTypes: [...] }Saved in the workspace state document (timeframeFavorites, favorites) or seeded via chart.drawings.setFavorites(...)
overrides: { 'mainSeriesProperties.style': 1, 'paneProperties.background': '#0b0e14' }Constructor options (priceStyle: 'candles', upColor, downColor) and createTheme({ colors })
widget.applyOverrides({ ... })workspace.setTheme(...) and workspace.chart.renderer.applyConfig({ ... })
custom_css_url (--tv-color-*) and custom_themes (color1..color7)createTheme({ base, accent, radius, font, tokens, components }) plus host CSS overriding @layer vela.pro

See Interface layout and Theming and branding.

On this page