Skip to main content

Data Loading

Altrady Charts uses a two-layer data loading system:

  1. Datafeed — a standardized Datafeed interface that your application implements. It handles fetching OHLCV bars from whatever source you have (REST API, WebSocket, exchange SDK).
  2. DataLoader (AltradyChartsDataLoader) — a klinecharts-compatible adapter created by createDataLoader(datafeed). It is what you pass to new AltradyCharts({ dataLoader }).

You never instantiate DataLoader directly. You implement Datafeed and call createDataLoader.


The Datafeed Interface​

export interface Datafeed {
onReady(callback: (config: DatafeedConfiguration) => void): void

searchSymbols(
userInput: string,
exchange: string,
symbolType: string,
onResult: (results: SearchSymbolResult[]) => void
): void

resolveSymbol(
symbolName: string,
onResolve: (symbolInfo: LibrarySymbolInfo) => void,
onError: (reason: string) => void
): void

getBars(
symbolInfo: LibrarySymbolInfo,
resolution: string,
periodParams: PeriodParams,
onResult: (bars: Bar[], meta?: HistoryMetadata) => void,
onError: (reason: string) => void
): void

subscribeBars(
symbolInfo: LibrarySymbolInfo,
resolution: string,
onTick: (bar: Bar) => void,
subscriberUID: string,
onResetCacheNeeded?: () => void
): void

unsubscribeBars(subscriberUID: string): void

/** Optional. Symbol types offered as tabs in the symbol search. */
getSymbolTypes?(onResult: (types: DatafeedSymbolType[]) => void): void
}

Method responsibilities​

onReady(callback)​

Called once when the chart initializes. Invoke callback with a DatafeedConfiguration describing supported resolutions. Must be called asynchronously (use setTimeout(..., 0)).

export interface DatafeedConfiguration {
/** resolution strings, e.g. ['1', '5', '15', '60', '240', '1D', '1W'] */
supportedResolutions: string[]
exchanges?: { value: string; name: string }[]
symbols_types?: DatafeedSymbolType[]
supports_marks?: boolean
supports_timescale_marks?: boolean
}

searchSymbols(userInput, exchange, symbolType, onResult)​

Called when the user types in the symbol search modal. Call onResult with matching symbols. Can call onResult([]) if search is not supported.

export interface SearchSymbolResult {
symbol: string
full_name: string
description?: string
exchange?: string
type?: string
}

getSymbolTypes(onResult) (optional)​

Returns the symbol types offered as tabs in the symbol search. Each DatafeedSymbolType is { name, value }; the tab's value is passed back as searchSymbols' symbolType.

  • It is called every time the symbol search opens, so the list can differ between openings. Call onResult exactly once, synchronously or later. The search is held until you do, so if onResult is never called, results never load.
  • It takes precedence over DatafeedConfiguration.symbols_types, which is used only when this method is absent (or throws; the error is logged).
  • With at most one real type (a value other than ''), no tab row is shown and the search runs with symbolType = ''. With two or more, an "All" tab (value: '') comes first, followed by your types in your order. Supply your own '' entry to rename "All".
  • The tab the user picked is remembered per chart instance, in memory only: reopening the search selects it again if it is still offered, otherwise "All". It is not saved with the chart state and does not survive a reload.
  • A result whose type is empty or missing shows no type label.
getSymbolTypes(onResult) {
onResult([
{ name: 'Crypto', value: 'crypto' },
{ name: 'Forex', value: 'forex' },
])
}

resolveSymbol(symbolName, onResolve, onError)​

Called to get full symbol metadata for a given ticker string. The returned LibrarySymbolInfo.pricescale controls decimal precision displayed on the y-axis.

export interface LibrarySymbolInfo {
ticker: string
name: string
type?: string
exchange?: string
timezone?: string
/** Price scale: 100 = 2 decimals, 1000 = 3 decimals, 100000000 = 8 decimals */
pricescale: number
minmov?: number
has_intraday?: boolean
has_daily?: boolean
supported_resolutions?: string[]
session?: string
logo?: string
currency_code?: string
}

getBars(symbolInfo, resolution, periodParams, onResult, onError)​

Fetches historical OHLCV bars. periodParams.firstDataRequest is true on the initial load and false when the user scrolls backward. Call onResult(bars, meta) with the fetched bars. Set meta.noData = true when there is no more historical data to prevent further backward requests.

export interface PeriodParams {
from: number // Unix seconds
to: number // Unix seconds
countBack: number // Requested bar count (default: 500)
firstDataRequest: boolean
}

export interface Bar {
time: number // Unix milliseconds
open: number
high: number
low: number
close: number
volume?: number
}

export interface HistoryMetadata {
noData?: boolean // true if no more historical data
nextTime?: number // Unix seconds of next available bar
}

subscribeBars(symbolInfo, resolution, onTick, subscriberUID)​

Start streaming real-time bar updates. Call onTick(bar) on each new tick. The subscriberUID is a deterministic string ${ticker}_${resolution} — use it to identify the subscription.

unsubscribeBars(subscriberUID)​

Stop streaming updates for the given subscriberUID.


createDataLoader​

function createDataLoader(datafeed: Datafeed): AltradyChartsDataLoader

Wraps a Datafeed into the klinecharts DataLoader interface. The returned object is passed directly to new AltradyCharts({ dataLoader }).

What it does internally:

  • Calls datafeed.onReady() on construction.
  • Caches resolved symbols (resolveSymbol is only called once per ticker).
  • Converts Period to resolution strings using periodToResolution().
  • Aligns from/to timestamps to period boundaries (e.g. hourly bars snap to whole hours).
  • Tracks active subscriberUID strings and cleans them up on unsubscribeBar.
  • Converts Bar objects to KLineData (klinecharts format).

Custom timeframes (client-side aggregation)​

Users can pick intervals such as 7m, 45m, 3h, 5D or 2W. If the datafeed cannot serve one natively, createDataLoader requests a smaller native "base" resolution and aggregates it (open = first, high = max, low = min, close = last, volume = sum), for both history and realtime. This follows TradingView's contract: declare what you serve natively on the resolved symbol info.

resolveSymbol: (name, onResolve) => onResolve({
ticker: name, name, pricescale: 100,
has_seconds: true,
seconds_multipliers: ['1'], // seconds
intraday_multipliers: ['1', '5', '15', '60'], // minutes (3h = 180)
has_daily: true,
daily_multipliers: ['1'],
has_weekly_and_monthly: true,
weekly_multipliers: ['1'],
monthly_multipliers: ['1'],
})
  • A requested resolution that is listed is passed through unchanged. A family whose list is absent is treated as fully native, so feeds that declare nothing behave exactly as before.
  • Otherwise the largest listed multiple that divides the request is the base (45m from 15, 7m from 1, 180m from 60, 5D from 1D, 2W from 1W). Weeks fall back to daily bars when no weekly base divides. If nothing divides, the resolution is requested as-is and one warning is logged.
  • Buckets align to epoch-UTC multiples of the span (weeks to Monday 00:00 UTC, months to the 1st). TradingView aligns intraday buckets to the session start; epoch alignment is exact for 24/7 markets only.
  • createDataLoader wraps the datafeed with aggregatingDatafeed(datafeed) itself. Anything else that calls the datafeed directly, notably a script provider such as WasmScriptProvider, must be given the wrapped feed too, or it will request the raw custom resolution (e.g. 7) from the backend and fail: const feed = aggregatingDatafeed(new MyDatafeed()); createDataLoader(feed); new WasmScriptProvider({ datafeed: feed }). Wrapping is idempotent, and every method other than resolveSymbol/getBars/subscribeBars/unsubscribeBars/getFirstCandleTime is forwarded untouched.
  • The base requests: getBars receives the base resolution, from aligned down to a bucket start, and countBack scaled by the ratio. Realtime subscribes to the base resolution under the same subscriber UID, so subscribeBars/unsubscribeBars are called with base resolutions, not the one the user picked.

AltradyChartsDataLoader​

The return type of createDataLoader. Extends the klinecharts DataLoader with additional methods:

export interface AltradyChartsDataLoader extends DataLoader {
/** Delegates to Datafeed.searchSymbols */
searchSymbols(
userInput: string,
exchange: string,
symbolType: string,
onResult: (results: SearchSymbolResult[]) => void
): void

/**
* Symbol types for the search tabs: `Datafeed.getSymbolTypes` when present,
* else the onReady `symbols_types`, else `[]`. Calls `onResult` once.
*/
getSymbolTypes(onResult: (types: DatafeedSymbolType[]) => void): void

/**
* Register a callback that fires after each successful bar load.
* The callback receives fromMs — the start of the loaded range in Unix ms.
* Use this to trigger historical backfill in providers.
*/
setOnBarsLoaded(callback: (fromMs: number) => void): void
}

setOnBarsLoaded — Indicator History Backfill​

When a user scrolls backward and older OHLCV bars are loaded, indicator providers need to fetch corresponding historical data. setOnBarsLoaded provides this hook.

After calling createDataLoader, call setOnBarsLoaded with a callback that forwards the timestamp to your providers:

import { createDataLoader } from '@altrady/charts'

const dataLoader = createDataLoader(datafeed)

// Wire the backfill hook
dataLoader.setOnBarsLoaded((fromMs: number) => {
indicatorProvider.loadHistoryBefore(fromMs)
scriptProvider.loadHistoryBefore(fromMs)
})

loadHistoryBefore is not part of the provider interfaces. It is a method on your own provider classes: each one computes, or asks its backend for, values over the older range and delivers the IndicatorDataPoint[] through the onHistory handler registered on the subscription.


Full Datafeed Implementation Example​

import type {
Datafeed,
DatafeedConfiguration,
LibrarySymbolInfo,
Bar,
PeriodParams,
HistoryMetadata,
SearchSymbolResult,
} from '@altrady/charts'

export class RestDatafeed implements Datafeed {
constructor(private baseUrl: string) {}

onReady(callback: (config: DatafeedConfiguration) => void): void {
setTimeout(() => {
callback({
supportedResolutions: ['1', '5', '15', '60', '240', '1D', '1W', '1M'],
})
}, 0)
}

searchSymbols(
userInput: string,
_exchange: string,
_symbolType: string,
onResult: (results: SearchSymbolResult[]) => void
): void {
fetch(`${this.baseUrl}/symbols/search?q=${encodeURIComponent(userInput)}`)
.then(res => res.json())
.then(data => onResult(data.results ?? []))
.catch(() => onResult([]))
}

resolveSymbol(
symbolName: string,
onResolve: (symbolInfo: LibrarySymbolInfo) => void,
onError: (reason: string) => void
): void {
fetch(`${this.baseUrl}/symbols/${symbolName}`)
.then(res => {
if (!res.ok) throw new Error(`Symbol not found: ${symbolName}`)
return res.json()
})
.then(data => onResolve({
ticker: data.ticker,
name: data.name,
pricescale: data.pricescale ?? 100,
has_intraday: true,
has_daily: true,
supported_resolutions: ['1', '5', '15', '60', '240', '1D', '1W', '1M'],
}))
.catch(err => onError(err.message))
}

getBars(
symbolInfo: LibrarySymbolInfo,
resolution: string,
periodParams: PeriodParams,
onResult: (bars: Bar[], meta?: HistoryMetadata) => void,
onError: (reason: string) => void
): void {
const { from, to, countBack } = periodParams
const url = `${this.baseUrl}/bars?symbol=${symbolInfo.ticker}&resolution=${resolution}&from=${from}&to=${to}&countBack=${countBack}`

fetch(url)
.then(res => res.json())
.then(data => {
const bars: Bar[] = data.bars.map((b: any) => ({
time: b.timestamp * 1000, // server returns Unix seconds; convert to ms
open: b.open,
high: b.high,
low: b.low,
close: b.close,
volume: b.volume,
}))
onResult(bars, { noData: bars.length === 0 })
})
.catch(err => onError(err.message))
}

private subscriptions = new Map<string, () => void>()

subscribeBars(
symbolInfo: LibrarySymbolInfo,
resolution: string,
onTick: (bar: Bar) => void,
subscriberUID: string
): void {
const ws = new WebSocket(`${this.baseUrl.replace('http', 'ws')}/stream?symbol=${symbolInfo.ticker}&resolution=${resolution}`)
ws.onmessage = (event) => {
const b = JSON.parse(event.data)
onTick({
time: b.timestamp * 1000,
open: b.open,
high: b.high,
low: b.low,
close: b.close,
volume: b.volume,
})
}
this.subscriptions.set(subscriberUID, () => ws.close())
}

unsubscribeBars(subscriberUID: string): void {
this.subscriptions.get(subscriberUID)?.()
this.subscriptions.delete(subscriberUID)
}
}

Usage:

import { createDataLoader, AltradyCharts, PERIODS } from '@altrady/charts'
import { RestDatafeed } from './RestDatafeed'

const datafeed = new RestDatafeed('https://api.example.com')
const dataLoader = createDataLoader(datafeed)

const chart = new AltradyCharts({
container: 'chart',
symbol: { ticker: 'ETHUSDT', pricePrecision: 4, volumePrecision: 2 },
period: PERIODS['1h'],
dataLoader,
})