Realtime updates
Data
A candlestick chart that receives new prices in real time.
Interactive example — scroll, zoom, and hover the chart.
Code
// Lightweight Charts™ Example: Realtime updates
// https://tradingview.github.io/lightweight-charts/examples/data/realtime-updates
const container = document.getElementById('container');
// The chart takes the space above the buttons, which are added further down.
container.style.display = 'flex';
container.style.flexDirection = 'column';
const chartElement = document.createElement('div');
chartElement.style.flex = '1';
chartElement.style.minHeight = '0';
container.appendChild(chartElement);
/** @type {import('lightweight-charts').IChartApi} */
const chart = createChart(chartElement, chartOptions);
const series = chart.addSeries(CandlestickSeries, {
upColor: '#26a69a',
downColor: '#ef5350',
borderVisible: false,
wickUpColor: '#26a69a',
wickDownColor: '#ef5350',
});
const data = generateData(2500, 20, 1000);
series.setData(data.initialData);
chart.timeScale().fitContent();
chart.timeScale().scrollToPosition(5);
// simulate real-time data
function* getNextRealtimeUpdate(realtimeData) {
for (const dataPoint of realtimeData) {
yield dataPoint;
}
return null;
}
const streamingDataProvider = getNextRealtimeUpdate(data.realtimeUpdates);
const intervalID = setInterval(() => {
const update = streamingDataProvider.next();
if (update.done) {
clearInterval(intervalID);
return;
}
series.update(update.value);
}, 100);
const button = document.createElement('button');
button.innerText = 'Go to realtime';
button.addEventListener('click', () => chart.timeScale().scrollToRealTime());
buttonsContainer.appendChild(button);
container.appendChild(buttonsContainer);
The code expects the library’s exports, such as createChart, to be imported and a div with the id container on the page. Copy as HTML gives a page that runs on its own.
How it works
The chart starts with historical candles and then receives a new price every 100 ms, as from a live feed.
setDatasets the initial candles.- A timer passes each new price to
update. An item with the time of the last candle changes that candle; an item with a later time adds a new one. - The Go to realtime button calls
scrollToRealTime, which brings the latest candle back into view after you scroll away.
generateData only makes sample data. In your project the updates come from your data source.
Tips
- Use
updatefor live data. CallingsetDataon every tick redraws the whole series and resets the user's scroll.
Resources
ISeriesApi.updateITimeScaleApi.scrollToRealTime- Related examples: Infinite history, Yield curve with updates