Sync crosshairs between two charts
Crosshair
Two charts whose crosshairs and visible ranges move together.
Interactive example — scroll, zoom, and hover the chart.
Code
// Lightweight Charts™ Example: Sync crosshairs between two charts
// https://tradingview.github.io/lightweight-charts/examples/crosshair/sync-crosshairs
// The same price scale width on both charts keeps their time axes aligned.
// 70px fits the widest label, so neither scale grows past it.
chart1.priceScale('right').applyOptions({ minimumWidth: 70 });
chart2.priceScale('right').applyOptions({ minimumWidth: 70 });
chart1.timeScale().subscribeVisibleLogicalRangeChange(timeRange => {
chart2.timeScale().setVisibleLogicalRange(timeRange);
});
chart2.timeScale().subscribeVisibleLogicalRangeChange(timeRange => {
chart1.timeScale().setVisibleLogicalRange(timeRange);
});
function getCrosshairDataPoint(series, param) {
if (!param.time) {
return null;
}
const dataPoint = param.seriesData.get(series);
return dataPoint || null;
}
function syncCrosshair(chart, series, dataPoint) {
if (dataPoint) {
chart.setCrosshairPosition(dataPoint.value, dataPoint.time, series);
return;
}
chart.clearCrosshairPosition();
}
chart1.subscribeCrosshairMove(param => {
const dataPoint = getCrosshairDataPoint(mainSeries1, param);
syncCrosshair(chart2, mainSeries2, dataPoint);
});
chart2.subscribeCrosshairMove(param => {
const dataPoint = getCrosshairDataPoint(mainSeries2, param);
syncCrosshair(chart1, mainSeries1, dataPoint);
});
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
Two separate charts are kept in step: scrolling or zooming one moves the other, and the crosshair of one is mirrored on the other.
- Each chart's
subscribeVisibleLogicalRangeChangehandler passes the range to the other chart'ssetVisibleLogicalRange. - Each chart's
subscribeCrosshairMovehandler reads the data point under the crosshair. setCrosshairPositionputs the other chart's crosshair on the same time. When there is no data point,clearCrosshairPositionremoves it.
The upper chart hides its time scale, so the two read as one. Both right price scales get the same minimumWidth, wide enough for the widest label, so the time axes stay aligned while you scroll and zoom.
Tips
- Syncing by logical range keeps the charts aligned bar for bar. It works when both series have a point at the same times.