lightweight-charts

Draw price line onClick event


I am using lightweight-charts. I looked over the documentation bellow and the library documentation and I don't seem to find onClick or similar events for the charts. Am I missing something?

I am trying to add line to my chart at a crosshair location user clicks on. I was thinking its just simple as handling the onClick event and doing series.createPriceLine(myNewPriceLine);

https://tradingview.github.io/lightweight-charts/tutorials/how_to/price-line

Update:

https://jsfiddle.net/kf7yjpr0/25/

I added the following and i am able to get price from the series.

    function myClickHandler(param) {
        if (!param.point) {
            return;
        }
        console.log(param)
        if (param.time) {
            const data = param.seriesData.get(series);
            const price = data.value !== undefined ? data.value : data.close;
            const priceFormatted = price.toFixed(2);
            console.log("price is ",priceFormatted)
        }
    
        console.log(`Click at ${param.point.x}, ${param.point.y}. The time is ${param.time}.`);
    }


chart.subscribeClick(myClickHandler);

But the price i am looking for is where the red X is at...thats where i clicked. Perhaps what i am looking for comes from somewhere that deals with the crosshair...as shown from the image from the demos.

enter image description here CrossHair price value from the demos


Solution

  • The chart instance (IChartApi) has a method called subscribeClick which allows you to add a click event handler to the chart.

    The parameter passed when the event fires contains a seriesData map which can be used to get the price value for the point where you clicked. This could then be used to create a new price line. The map expects that you will use the series instance as the index key.