lightweight-charts

Get X Y position of Y-Axis element


I'm looking for a way to position my custom chart legend on the chart. However, I can't find any API to get Y-Axis element so I can't calculate the x,y position of legend that I should use (knowing that size of y-axis is dynamic, depends on price value).

Any suggestion please?


Solution

  • The position of the various chart elements can be determined by:

    1. Querying the PriceScale API for it's current width (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/IPriceScaleApi).
    2. Querying the TimeScale API for it's current height and width (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/ITimeScaleApi).
    3. Knowing the current layout of the chart, for example if the price scale is on the left or right side.

    Lightweight charts uses a table layout to position the various main components of the chart, thus by knowing these values it is then possible to determine all the positions relative to top left corner of the container element.

    So for example if you want to know the position and dimensions of the PriceScale and TimeScale (assuming that the price scale is on the right side):

    // Run inside a RequestAnimationFrame 
    // so that the chart has a chance to 
    // render once before querying the dimensions.
    requestAnimationFrame(() => {
        const containerElement = document.getElementById("container");
        const containerDimensions = containerElement.getBoundingClientRect();
    
        // chart is the IChartAPI reference returned by LightweightCharts.createChart
        const timeScale = chart.timeScale();
        const timeScaleWidth = timeScale.width();
        const timeScaleHeight = timeScale.height();
    
        // mainSeries is the ISeriesAPI reference returned when adding data
        // for example with: chart.addLineSeries(...)
        const priceScale = mainSeries.priceScale();
        const priceScaleWidth = priceScale.width();
    
        const priceScalePositionAndSize = {
            x: timeScaleWidth,
            y: 0,
            height: containerDimensions.height - timeScaleHeight,
            width: priceScaleWidth,
        };
    
        const timeScalePositionAndSize = {
            x: 0,
            y: containerDimensions.height - timeScaleHeight,
            height: timeScaleHeight,
            width: timeScaleWidth,
        };
    
        console.log({ timeScalePositionAndSize, priceScalePositionAndSize });
    });