javascriptnode.jslightweight-charts

How to render Candlestick Series above Area Series in Lightweight Charts?


I am trying to ensure that the Candlestick Series is rendered above the Area Series in a Lightweight Charts graph. However, changing the sequence of the code does not work and results in a blank graph.

Here’s the script I’m using to create the chart:

fetch('/data')
    .then((response) => response.json())  // Get the JSON data
    .then((data) => {
        // Create the chart instance
        const chart = LightweightCharts.createChart(document.getElementById('chartContainer'), {
            layout: {
                textColor: 'black',
                background: { type: 'solid', color: 'white' },
            },
        });
        const candlestickSeries = chart.addCandlestickSeries({
            upColor: '#26a69a',
            downColor: '#ef5350',
            borderVisible: false,
            wickUpColor: '#26a69a',
            wickDownColor: '#ef5350',
        });
        candlestickSeries.setData(data.candlestickSeries);
 // Risk Zone (Stop Loss area)
        const riskZoneSeries = chart.addAreaSeries({
            lineColor: 'transparent',  // No border for the block
            topColor: 'rgba(252, 215, 218, 0.7)',  // Transparent red
            bottomColor: 'rgba(252, 215, 218, 0.7)', // Same color as top for solid fill
        });


 riskZoneSeries.setData([
            { time: startTime, value: entrancePrice }, // Start of the area at Entrance Price
            { time: endTime, value: entrancePrice },   // End of the area at Entrance Price
            { time: endTime, value: stopLossLevel },   // End of the area at Stop Loss
            { time: startTime, value: stopLossLevel }, // Start of the area at Stop Loss
        ]);

I expected the candlestick chart to appear above the area chart, but currently, it doesn't render as intended. How can I control the rendering order of the series in Lightweight Charts?


Solution

  • When using lightweight-charts, it’s important to note that series initialization happens when you call methods like .addAreaSeries() or .addCandlestickSeries(), not at .setData(). The .setData() method is used to populate the series with data after it has been created.

    Therefore you should assign

    const riskZoneSeries = chart.addAreaSeries({
                lineColor: 'transparent',  // No border for the block
                topColor: 'rgba(252, 215, 218, 0.7)',  // Transparent red
                bottomColor: 'rgba(252, 215, 218, 0.7)', // Same color as top for solid fill
            });
    

    before

    const candlestickSeries = chart.addCandlestickSeries({
                upColor: '#26a69a',
                downColor: '#ef5350',
                borderVisible: false,
                wickUpColor: '#26a69a',
                wickDownColor: '#ef5350',
            });