Quotes and market depth
Supply real-time symbol quotes with QuoteSource and implement DepthFeed on your provider for order book depth, DOM ladders, and trade tapes.
Alongside chart candles, Vela Pro consumes two real-time market feeds: per-symbol quotes for the watchlist and symbol search inspector, and level-2 market depth with time-and-sales trades for the Order Book module. Quotes work automatically with any provider implementing DataProvider from Vela's open-source core that serves daily ('D') bars, or you can supply a custom QuoteSource backed by a dedicated ticker stream. Market depth is provided by implementing DepthFeed on your provider instance.
Quotes
Both the watchlist and the symbol search inspector consume quotes through the QuoteSource port interface:
interface QuoteSource {
/** Follow a symbol's quote. Returns the unsubscribe. */
watch(symbol: string, onQuote: (quote: Quote) => void): () => void;
/** Optional: up to `count` daily bars, oldest first. */
dailyBars?(symbol: string, count: number): Promise<readonly OHLCV[]>;
}Default candle-based quotes
When no custom quotes option is passed, both features use ProviderQuotes, which builds quotes from the workspace's registered providers. For each watched symbol, ProviderQuotes resolves the symbol to its provider and issues the following calls:
| Provider call | Fields populated |
|---|---|
getSymbolInfo(ticker) | tick from mintick (inferred from price magnitude when omitted) |
getBars(ticker, 'D', { limit: 3 }) | last, open, high, low, and volume from the newest daily bar, plus prevClose from the preceding bar |
getBars(ticker, 'D', { limit: 22 }) | spark array of recent daily closes for sparklines, refreshed every 10 minutes |
subscribe(ticker, 'D', onBar) | Live updates to last and intraday daily figures (falls back to polling daily bars every 15 seconds when subscribe is absent) |
getBars(ticker, 'D', { limit: count }) | dailyBars for the watchlist advanced view, fetched up to three symbols concurrently and cached for 10 minutes |
change and changePercent are computed from last and prevClose. Symbols that no registered provider resolves receive unresolved: true and render a placeholder dash in the UI.
ProviderQuotes works whenever your provider serves 'D' bars with limit and returns the current trading day as the newest forming bar. Keep subscription fan-out in mind, because opening a 40-symbol watchlist starts 40 active 'D' subscriptions on your provider while the panel remains open.
Custom QuoteSource implementation
Pass a custom QuoteSource when your backend provides a multiplexed quote or ticker stream. A single shared quote connection avoids opening per-row candle subscriptions and can stream quotes for symbols not served by your candle provider.
import { blankQuote, enableVelaPro, withChange, type Quote, type QuoteSource } from '@luxalgo/vela-pro';
interface Tick {
last: number;
prevClose: number;
volume: number;
tickSize: number;
}
// Multiplexed quote client sharing one socket across symbols; `on` returns an unsubscribe function.
declare const feed: { on(symbol: string, onTick: (tick: Tick) => void): () => void };
const quotes: QuoteSource = {
watch(symbol, onQuote) {
let quote: Quote = blankQuote(symbol);
return feed.on(symbol, (tick) => {
quote = withChange({ ...quote, last: tick.last, prevClose: tick.prevClose, volume: tick.volume, tick: tick.tickSize, updated: Date.now() });
onQuote(quote);
});
},
};
enableVelaPro({ watchlist: { quotes }, symbolSearch: { quotes } });watch receives each symbol string as written by its caller (AAPL or acme:AAPL from watchlist items, and venue-prefixed NASDAQ:AAPL from symbol search), so normalize both forms to your quote feed's instrument identifiers. blankQuote(symbol) creates an empty Quote object, and withChange(quote) calculates change and changePercent from last and prevClose.
Pass symbolSearch: { quotes: false } to hide the quote card in the symbol search inspector. See Watchlist for the full Quote type definition and how dailyBars populates historical metrics in the advanced watchlist view.
Market depth
The Order Book module reads order book snapshots and trade prints from the provider serving the active symbol whenever that provider implements DepthFeed:
interface DepthFeed {
subscribeBook?(ticker: string, onBook: (book: BookSnapshot) => void, opts?: { depth?: number; onError?: (reason: string) => void }): DepthSubscription;
subscribeTrades?(ticker: string, onTrades: (trades: TapeTrade[], history?: boolean) => void, opts?: { onError?: (reason: string) => void }): DepthSubscription;
}
interface BookSnapshot {
bids: BookLevel[]; // { price, size }, highest bid first
asks: BookLevel[]; // lowest ask first
tick: number; // price increment of the book levels
time: number; // epoch milliseconds
}
interface TapeTrade {
id: string;
time: number; // epoch milliseconds
price: number;
size: number;
side: 'buy' | 'sell'; // taker side
}
interface DepthSubscription {
close(): void;
}subscribeBook powers the Book view and the DOM price ladder, while subscribeTrades powers the Trades tape and the ladder's traded-volume columns. Either method can be implemented without the other, and any omitted view displays an empty state. Vela Pro checks providers with hasDepthFeed(provider), which returns true when at least one of the two methods is defined.
Implementing DepthFeed
Define subscribeBook and subscribeTrades on the same provider object or class as getBars. The example below extends the provider from Custom data providers:
import type { DataProvider } from '@luxalgo/vela';
import { BookState, type DepthFeed, type TapeTrade } from '@luxalgo/vela-pro';
declare const acme: DataProvider; // candle provider instance
const STREAM = 'wss://stream.example.com';
interface BookMessage {
snapshot: boolean;
bids: Array<[price: number, size: number]>;
asks: Array<[price: number, size: number]>;
tick: number;
time: number;
}
const subscribeBook: NonNullable<DepthFeed['subscribeBook']> = (ticker, onBook, opts) => {
const book = new BookState();
const socket = new WebSocket(`${STREAM}/book?symbol=${encodeURIComponent(ticker)}`);
socket.onmessage = (event) => {
const m = JSON.parse(String(event.data)) as BookMessage;
if (m.snapshot) book.reset(m.bids, m.asks, m.tick, m.time);
else book.update(m.bids, m.asks, m.time); // size of 0 deletes the price level
onBook(book.snapshot(opts?.depth));
};
socket.onerror = () => opts?.onError?.('dropped');
return { close: () => socket.close() };
};
const subscribeTrades: NonNullable<DepthFeed['subscribeTrades']> = (ticker, onTrades, opts) => {
const socket = new WebSocket(`${STREAM}/trades?symbol=${encodeURIComponent(ticker)}`);
let backfill = true; // initial message carries recent historical trades
socket.onmessage = (event) => {
onTrades(JSON.parse(String(event.data)) as TapeTrade[], backfill);
backfill = false;
};
socket.onerror = () => opts?.onError?.('dropped');
return { close: () => socket.close() };
};
export const acmeWithDepth: DataProvider & DepthFeed = { ...acme, subscribeBook, subscribeTrades };Register acmeWithDepth in your workspace providers map in place of acme, or implement both methods directly on your provider class.
Order book data requirements
- Full book snapshots on every emission.
onBookrequires the complete visible book sorted best-price first (bidsdescending,asksascending) rather than incremental deltas. UseBookStateto maintain a local book from an initial snapshot and level deltas viareset(bids, asks, tick, time),update(bids, asks, time), andsnapshot(depth)(returning up to 50 levels per side whendepthis omitted). - Matching
ticksize.tickmust match the price step of your levels. The DOM ladder constructs its price rows fromtickand buckets incoming trade prints onto price rows rounded totick. - Chronological trades with stable IDs. Emit trades ordered oldest-to-newest (newest last) with deterministic
idstrings. Because the tape deduplicates incoming trades byid, reconnecting sockets can safely replay recent trades. Passtrueas the second argument ofonTradeswhen delivering an initial batch of historical trades. - Taker
sideattribution.sidedenotes the aggressor ('buy'when a buyer lifts the offer,'sell'when a seller hits the bid), which feeds the ladder's bought, sold, and delta volume columns. - Error signaling. Report stream failures via
opts?.onError?.(reason). Passing'unsupported'renders a permanent unsupported notice for that market,'unavailable'indicates a temporary state that can be retried, and any other reason displays a dropped-connection state with a Reconnect button.
The Order Book module subscribes when its panel opens or the active symbol changes, and calls close() shortly after the panel closes. When multiple registered providers serve alternate listings of the same asset and implement DepthFeed, the panel can view individual venues or aggregate all listings into a combined book. To coarsen book levels manually, call groupLevels(levels, step, side) to sum sizes into step increments (rounding bids down and asks up).
See Order book for panel views, module options, and DOM ladder trading integration.
Related
Timeframes and sessions
Timeframe string conventions, regular and extended trading hours, market calendars, display time zones, and session presets.
Footprint data
Implement the FootprintFeed interface on your data provider to power Footprint charts, order-flow indicators, and Pine Script® footprint requests.