Infinite history
Data
A candlestick chart that loads older data as you scroll back in time.
Interactive example — scroll, zoom, and hover the chart.
Code
// Lightweight Charts™ Example: Infinite history
// https://tradingview.github.io/lightweight-charts/examples/data/infinite-history
const container = document.getElementById('container');
/** @type {import('lightweight-charts').IChartApi} */
const chart = createChart(container, chartOptions);
const series = chart.addSeries(CandlestickSeries, {
upColor: '#26a69a',
downColor: '#ef5350',
borderVisible: false,
wickUpColor: '#26a69a',
wickDownColor: '#ef5350',
});
const datafeed = new Datafeed();
// Estimate how many bars fit in the visible area and load 20% extra bars to allow scrolling
const timeScale = chart.timeScale();
const visibleBars = Math.ceil(timeScale.width() / timeScale.options().barSpacing);
series.setData(datafeed.getBars(visibleBars + (visibleBars * 0.2)));
chart.timeScale().subscribeVisibleLogicalRangeChange(logicalRange => {
if (logicalRange.from < 10) {
// load more data
const numberBarsToLoad = 50 - logicalRange.from;
const data = datafeed.getBars(numberBarsToLoad);
setTimeout(() => {
series.setData(data);
}, 250); // add a loading delay
}
});
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 only enough data to fill the screen and loads older data as you scroll back, the way a chart backed by a server would.
- The number of bars that fit on screen is the time scale's
widthdivided by itsbarSpacing. The chart loads that many bars plus 20%. See Number of visible bars. subscribeVisibleLogicalRangeChangereports each scroll. When fewer than 10 bars are left to the left of the screen, the handler asks the data feed for more.- The data feed returns the older bars together with the ones already loaded, and
setDatareplaces the series data. A short delay stands in for a network request.
Datafeed only makes sample data. Replace getBars with a request to your server.