Search code examples
javascriptmarkerstradingview-apilightweight-charts

Can't display markers. setMarkers() function returns TypeError: t.map is not a function


I've looked at the documentation on github but I couldn't find more on markers. Here's the example they give: https://github.com/tradingview/lightweight-charts/blob/ef8cfa40cb51ee1f9a5c11bd099bc510c022b010/docs/series-basics.md#setmarkers

I seem to have the right markers array but no luck.

async function getCandle() {
    while(true){
        await fetch('localhost:5000/candle.json')
        .then(res => res.text())
        .then(data => {
            /* Handling of data */
            candleSeries.setMarkers(getMarkers()); // returns TypeError: t.map is not a function at i.t.setMarkers
            // chart.setMarkers(getMarkers()); returns TypeError: chart.setMarkers is not a function
        })
        await sleep(1000);
    }
}

async function getMarkers(){
    await fetch('http://localhost:5000/markers.jsonl')
    /* markers.jsonl looks like this:
    {"time": 1592913600, "position": "belowBar", "shape": "arrowUp", "color": "green", "id": 1, "text": "BUY"}
    {"time": 1592913900, "position": "belowBar", "shape": "arrowUp", "color": "green", "id": 1, "text": "BUY"}
    */
    .then(res => res.text())
    .then(data => {
        data = data.split("\n");
        let markers = data.map(d => {
            // Parse d from string to JSON
            d = JSON.parse(d);
            return {time: d["time"], position: d["position"], shape: d["shape"], color: d["color"], id: d["id"], text: d["text"]}
        });
        return markers;
    })
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Solution

  • getMarkers is async function, which returns a Promise instance, if you don't await it.

    You need to mark data handler as async function and await getMarkers result:

    async function getCandle() {
        while(true){
            await fetch('localhost:5000/candle.json')
            .then(res => res.text())
            .then(async (data) => {
                /* Handling of data */
                candleSeries.setMarkers(await getMarkers());
            })
            await sleep(1000);
        }
    }
    

    EDIT (from @Nipheris comment): you return nothing from getMarkers function, so you need to add return statement there.