Custom data providers
Implement a custom DataProvider over REST and WebSocket endpoints for historical bars, symbol lists, live streams, metadata, and calendars.
A custom data provider implements the DataProvider interface from Vela's open-source core, where getBars is the only required method. This guide builds a complete provider over REST (https://api.example.com) and WebSocket (wss://stream.example.com) endpoints in four incremental steps covering historical bars, symbol lists, live updates, and symbol metadata with market calendars. Because every method beyond getBars is optional, the chart runs after each step.
Fetch historical bars
Implement getBars(ticker, timeframe, range) and register your provider factory under a key in the workspace providers map.
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import type { DataProvider, OHLCV } from '@luxalgo/vela';
import { enableVelaPro } from '@luxalgo/vela-pro';
const API = 'https://api.example.com';
// Map Vela timeframe strings to upstream API interval codes.
const INTERVAL: Record<string, string> = { '1': '1m', '5': '5m', '15': '15m', '30': '30m', '60': '1h', '240': '4h', D: '1d', W: '1w', M: '1mo' };
type Row = [time: number, open: number, high: number, low: number, close: number, volume: number];
export const getBars: DataProvider['getBars'] = async (ticker, timeframe, range) => {
const interval = INTERVAL[timeframe];
if (!interval) return []; // unsupported interval
const query = new URLSearchParams({ symbol: ticker, interval });
if (range.from !== undefined) query.set('from', String(range.from));
if (range.to !== undefined) query.set('to', String(range.to));
if (range.limit !== undefined) query.set('limit', String(range.limit));
if (range.session) query.set('session', range.session);
const rows = (await (await fetch(`${API}/candles?${query}`)).json()) as Row[];
const bars: OHLCV[] = rows.map(([time, open, high, low, close, volume]) => ({ time, open, high, low, close, volume }));
bars.sort((a, b) => a.time - b.time);
return bars.filter((bar, i) => i === 0 || bar.time !== bars[i - 1]!.time);
};
enableVelaPro();
const workspace = new VelaWorkspace('#chart', {
layout: false,
symbol: 'acme:AAPL', // explicit provider prefix until listSymbols is added
timeframe: '60',
providers: { acme: () => ({ getBars }) },
});ticker arrives stripped of its acme: prefix. range carries from and to (bar open timestamps in epoch milliseconds, where omitting to requests up to the latest bar), limit, and session. On initial load, the chart fetches the newest bars using limit. When additional history is required (such as a deep bars setting, panning backward, or clicking a bottom-bar range preset), the core pages backward using to and limit. Returning an empty array [] marks the start of available history.
Uncaught errors thrown from getBars are logged and treated as an empty result, so retry transient network failures inside your provider before throwing. When your API does not serve a requested timeframe, either aggregate finer bars or throw DataUnavailableError as shown in Rejecting unsupported timeframes so the workspace falls back to a supported interval.
List available symbols
Until a provider implements listSymbols, its instruments can only be loaded using an explicit acme:TICKER prefix. Adding listSymbols enables unprefixed ticker resolution, populates the Vela Pro symbol picker, and routes exchange prefixes such as NASDAQ:AAPL to your provider.
import type { DataProvider, SymbolDescriptor } from '@luxalgo/vela';
const API = 'https://api.example.com';
interface Instrument {
id: string;
name: string;
kind: 'stock' | 'etf' | 'futures' | 'forex' | 'crypto';
exchange?: string;
}
async function fetchInstruments(): Promise<Instrument[]> {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(`${API}/instruments`);
if (res.ok) return (await res.json()) as Instrument[];
} catch {
// transient network error, retry with backoff
}
if (attempt === 4) throw new Error('instrument list unavailable');
await new Promise((done) => setTimeout(done, 1000 * 2 ** attempt));
}
}
export const listSymbols: NonNullable<DataProvider['listSymbols']> = async () => {
const instruments = await fetchInstruments();
return instruments.map((i): SymbolDescriptor => ({ ticker: i.id, description: i.name, type: i.kind, prefix: i.exchange }));
};Include listSymbols on your provider object (acme: () => ({ getBars, listSymbols })). Because the workspace calls listSymbols once during provider registration, retry transient failures internally so a temporary outage does not leave the provider without a symbol list. See Symbology for prefix, futures roots, and ticker formatting, and Symbol search for category type mappings.
Stream live bars
When live: true is set without subscribe, the chart polls getBars for the latest two bars every 3 seconds. Implementing subscribe replaces polling with real-time push updates.
import type { DataProvider } from '@luxalgo/vela';
declare const INTERVAL: Record<string, string>; // interval lookup from step 1
type Row = [time: number, open: number, high: number, low: number, close: number, volume: number];
export const subscribe: NonNullable<DataProvider['subscribe']> = (ticker, timeframe, onBar, opts) => {
const interval = INTERVAL[timeframe];
if (!interval) return () => {};
const query = new URLSearchParams({ symbol: ticker, interval, session: opts?.session ?? 'regular' });
let socket: WebSocket | null = null;
let closed = false;
const connect = (): void => {
socket = new WebSocket(`wss://stream.example.com/candles?${query}`);
socket.onmessage = (event) => {
const [time, open, high, low, close, volume] = JSON.parse(String(event.data)) as Row;
onBar({ time, open, high, low, close, volume });
};
socket.onclose = () => {
if (!closed) setTimeout(connect, 2000);
};
};
connect();
return () => {
closed = true;
socket?.close();
};
};Each onBar call delivers an updated or newly opened candle. Passing the current bar's time updates the forming candle in place, while passing a newer time commits the prior bar and starts the next candle without needing a separate close event. Return an unsubscribe callback that closes the stream.
Once a provider defines subscribe, the core disables automatic polling for all timeframes on that provider. For any timeframe your streaming server does not push natively, poll getBars(ticker, timeframe, { limit: 2 }) on an interval inside subscribe.
Symbol metadata and market calendar
getSymbolInfo provides tick precision (mintick), Pine Script® syminfo.* fields, exchange time zones, and trading session hours. getCalendar returns open market intervals between two timestamps; omit getCalendar if every market on your provider trades 24/7.
import type { DataProvider } from '@luxalgo/vela';
const API = 'https://api.example.com';
interface InstrumentDetail {
name: string;
kind: string;
currency: string;
tickSize: number;
timezone: string; // IANA zone such as 'America/New_York'
hours?: string; // regular hours as 'HHMM-HHMM' in that zone
extendedHours?: string;
}
export const getSymbolInfo: NonNullable<DataProvider['getSymbolInfo']> = async (ticker) => {
const res = await fetch(`${API}/instruments/${encodeURIComponent(ticker)}`);
if (!res.ok) return undefined;
const i = (await res.json()) as InstrumentDetail;
return {
ticker,
description: i.name,
type: i.kind,
currency: i.currency,
mintick: i.tickSize,
timezone: i.timezone,
session: i.hours ?? '24x7',
session_extended: i.extendedHours,
};
};
export const getCalendar: NonNullable<DataProvider['getCalendar']> = async (ticker, range) => {
const query = new URLSearchParams({ symbol: ticker, from: String(range.from), to: String(range.to), session: range.session ?? 'regular' });
const windows = (await (await fetch(`${API}/calendar?${query}`)).json()) as Array<[number, number]>;
return windows.sort((a, b) => a[0] - b[0]);
};See Symbology for metadata field consumers and Timeframes and sessions for session syntax and calendar windows.
Full implementation
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import type { DataProvider } from '@luxalgo/vela';
import { enableVelaPro } from '@luxalgo/vela-pro';
// Methods implemented in the four steps above.
declare const getBars: DataProvider['getBars'];
declare const listSymbols: NonNullable<DataProvider['listSymbols']>;
declare const subscribe: NonNullable<DataProvider['subscribe']>;
declare const getSymbolInfo: NonNullable<DataProvider['getSymbolInfo']>;
declare const getCalendar: NonNullable<DataProvider['getCalendar']>;
export const acme: DataProvider = { getBars, listSymbols, subscribe, getSymbolInfo, getCalendar };
enableVelaPro();
const workspace = new VelaWorkspace('#chart', {
layout: false,
symbol: 'AAPL',
timeframe: '60',
live: true,
timezone: 'exchange',
providers: { acme: () => acme },
persist: true,
});Bar data requirements
Every OHLCV array returned from getBars or emitted via subscribe must satisfy five invariants:
- Millisecond bar open timestamps.
timemust be the bar's opening timestamp in Unix epoch milliseconds rather than seconds or closing timestamps. If your upstream API stamps close times, subtract one bar duration before returning. Stamp daily bars at00:00:00 UTCof their trading date. - Strictly ascending, unique timestamps. Sort bars chronologically (
a.time - b.time) and remove duplicate timestamps before returning. - Forming bar at the end. The last element represents the active forming bar, whose
high,low,close, andvolumeupdate as trades arrive. The core keeps the newest bar mutable and never freezes it into closed history until a bar with a latertimearrives. - Complete window responses. Return all bars matching the requested
[from, to]window, even whenfromoverlaps bars already loaded on the chart. Requests withfromandtoand nolimit(issued by TPO and bar replay) expect every bar in that interval. - Stateless parameters. Read
ticker,timeframe, andrangestrictly from function arguments rather than tracking a "current symbol" property on the provider instance, because multiple charts and the shared cache share the same provider and may serve cached history before requesting only missing tail bars.
Caching
The core caches closed historical bars in memory, keyed by resolved provider, ticker, timeframe, and session. As a result, 'AAPL' and 'acme:AAPL' share the same cache entry, all charts in a workspace share cached series, and reloading an existing symbol fetches only new tail bars. Do not add a duplicate candle cache inside your provider.
Verification checklist
import type { VelaWorkspace } from '@luxalgo/vela/workspace';
export async function verify(workspace: VelaWorkspace): Promise<void> {
const chart = workspace.chart;
await chart.ready(); // initial bars painted
console.info(chart.data.resolve('AAPL')); // { provider: 'acme', ticker: 'AAPL' }
console.info(chart.data.symbols('acme').length); // total listed symbols
await chart.historyComplete(); // requested bar depth loaded
}- Initial candles render on mount, and
chart.historyComplete()resolves once the configuredbarsdepth loads or upstream history ends. - With
live: true, incoming updates move the rightmost candle and open a new bar when the timeframe interval rolls over. - Every top-bar timeframe preset loads cleanly, and unsupported custom intervals follow your aggregation or
DataUnavailableErrorfallback. - On session-bound instruments, the market status badge tracks
getCalendarboundaries and the bottom bar renders the regular/extended session toggle. - Automated unit tests verify
getBarsagainst recorded responses for millisecond open timestamps, ascending sort order, uniqueness, and forming-bar placement.
Extended data feeds
OHLCV candles support standard chart styles, drawings, bar replay, Pine Script® scripts, and TPO profiles. To enable the Order Book module, implement DepthFeed; to enable the Footprint chart type and order-flow indicators, implement FootprintFeed. See Quotes and market depth and Footprint data.
For optional core DataProvider hooks including info(), configure(), resolveSymbolIcon(), and replacing the entire data layer via MarketDataFeed, see Adding a data provider in the core documentation.