# Custom data providers (/vela-pro/data/custom-source)



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.

<Steps>
  <Step title="Fetch historical bars">
    Implement `getBars(ticker, timeframe, range)` and register your provider factory under a key in the workspace `providers` map.

    ```ts
    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](/vela-pro/data/symbols/sessions#rejecting-unsupported-timeframes) so the workspace falls back to a supported interval.
  </Step>

  <Step title="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.

    ```ts
    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](/vela-pro/data/symbols/symbology) for `prefix`, futures roots, and ticker formatting, and [Symbol search](/vela-pro/data/symbols/symbol-search) for category `type` mappings.
  </Step>

  <Step title="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.

    ```ts
    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`.
  </Step>

  <Step title="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.

    ```ts
    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](/vela-pro/data/symbols/symbology#symbol-metadata) for metadata field consumers and [Timeframes and sessions](/vela-pro/data/symbols/sessions) for session syntax and calendar windows.
  </Step>
</Steps>

## Full implementation [#full-implementation]

```ts
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 [#bar-data-requirements]

Every `OHLCV` array returned from `getBars` or emitted via `subscribe` must satisfy five invariants:

* **Millisecond bar open timestamps.** `time` must 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 at `00:00:00 UTC` of 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`, and `volume` update as trades arrive. The core keeps the newest bar mutable and never freezes it into closed history until a bar with a later `time` arrives.
* **Complete window responses.** Return all bars matching the requested `[from, to]` window, even when `from` overlaps bars already loaded on the chart. Requests with `from` and `to` and no `limit` (issued by TPO and bar replay) expect every bar in that interval.
* **Stateless parameters.** Read `ticker`, `timeframe`, and `range` strictly 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 [#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 [#verification-checklist]

```ts
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 configured `bars` depth 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 `DataUnavailableError` fallback.
* On session-bound instruments, the market status badge tracks `getCalendar` boundaries and the bottom bar renders the regular/extended session toggle.
* Automated unit tests verify `getBars` against recorded responses for millisecond open timestamps, ascending sort order, uniqueness, and forming-bar placement.

## Extended data feeds [#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](/vela-pro/data/feeds/quotes-and-depth) and [Footprint data](/vela-pro/data/feeds/footprints).

For optional core `DataProvider` hooks including `info()`, `configure()`, `resolveSymbolIcon()`, and replacing the entire data layer via `MarketDataFeed`, see [Adding a data provider](/vela/contributing/adding-a-data-provider) in the core documentation.
