lightweight-charts

Add new markers to existing chart


I'm trying to understand if it is possible to add a NEW marker on an existing (already rendered) chart.

For example, following the documentation I rendered a candle stick series with markers:

import { createChart, SeriesMarker } from "lightweight-charts";
const candleSeries = chart.addCandlestickSeries

// Prepare candleDataPoints and charMarkers with some logic ...

candleSeries.setMarkers(charMarkers);
candleSeries.setData(candleDataPoints);

This works fine, I renders the candlestick series with all the markers I want just in the place I need them.

I can then update the "candleSeries" with new datathe, as described in the documentation for the IChartApi interface: https://tradingview.github.io/lightweight-charts/docs/api/interfaces/IChartApi

Markers seem to be "attached" to the candleSeries, for which I can update candles but not the markers

Is this actually possible?

Thanks in advance


Solution

  • The setMarkers method doesn't allow you to update (append) to the current set of markers but rather you set or replace all the markers with the new values. Therefore in order to append to the current set of markers you need to keep a reference to those markers and create a new array containing all the markers you use to display.

    const myMarkers = [{ 
      time: data[data.length - 40].time, 
      position: 'aboveBar', 
      color: '#f68410', 
      shape: 'circle', 
      text: 'A'
     }, /* more series markers... */
    ];
    
    
    // ... some time later
    
    // create another marker data point
    const myNewMarker = {
      time: data[data.length - 20].time,
      position: 'aboveBar',
      color: '#f68410',
      shape: 'circle',
      text: 'B'
    };
    
    // Create a new array with the existing markers and the new marker
    // and use it within setMarkers
    series.setMarkers([...myMarkers, myNewMarker]);
    

    So in summary:

    Upcoming update: From version 4.0, there will be a markers() method on the ISeriesAPI which will return the current markers array for that series.