Цена TradingView Lightweight Chart не масштабируется правильно

Я просто добавил данные биткойна в свой график в реальном времени. Был пик, который настолько высок, что даже торговый взгляд не может с ним справиться... По крайней мере, на моем графике. Вот как это выглядит: Как вы можете видеть, второго июня биткойн поднялся настолько высоко, что ушел за пределы экрана. Это должно быть исправлено, так как на самой странице обзора торговли все выглядит хорошо и нормально: Также, если я уменьшу масштаб на моем графике, он будет выглядеть совершенно нормально: Итак, я хочу, чтобы мой график масштабировался так же, как и на сайте tradingview.com..

Это мой код:

// Predifined variables
var chart, priceArea, fetchedData;

// Faster to write log();
const log = console.log;

// Get data.
fetch('./getData.php', {
    method: 'GET'
}).then(response => response.json()).then(function (data) {
    // Set data to a global variable for global usage.
    fetchedData = data;

    // To make sure the chart is initialized and set after this fetch is done. Else I would get a error for setting data that I do not yet have.
    initChartSettings();
});


/**
 * Initializes the chart and its settings.
 */
function initChartSettings() {
    // Create chart canvas
    chart = LightweightCharts.createChart(document.getElementById('Chart'), {width: 1500, height: 700,});

    // Could also be done in the width and height code line but thought it might work for scaling.
    chart.applyOptions({
        timeScale: {
            // Adds hours and minutes to the chart.
            timeVisible: true,
            secondsVisible: false
        }
    });

    // Init price line
    priceArea = chart.addAreaSeries();

    // This array is needed to make the setData work. It expects an array with objects.
    let arrayWithOldData = [];

    // Get each item in the fetchedData array. Since it gives more data then I need I use this for loop to take the time and value. Used to create chart lines.
    for (let i = 0; i < fetchedData.length; i++) {
        let dataElement = fetchedData[i];

        // Object needed for the arrayWithOldData.
        let oldData = {
            // Timestamp / 1000 to make it a workable timestamp for tradingview chart and + 7200 seconds to make sure I get a timestamp of amsterdam (+2:00).
            time: (dataElement[0] / 1000) + 7200,
            value: dataElement[4]
        };

        // Add the data to the array.
        arrayWithOldData.push(oldData);
    }

    log(arrayWithOldData);

    // Set data
    priceArea.setData(arrayWithOldData);

    // PriceLine options
    priceArea.applyOptions({
        topColor: 'rgba(70, 130, 180, 0.5)',
        bottomColor: 'rgba(70, 130, 180, 0.1)',
        lineColor: '#4682B4',
        lineWidth: 2
    });

    startTime = new Date();
    updateLiveChartData();
}

Что я пробовал:

Я пробовал в своем коде следующее:https://github.com/tradingview/lightweight-charts/blob/master/docs/customization.md -> ценовая ось -> priceScale() -> autoScale: true и scaleMargins с разными верх и низ. Кажется, что scaleMargins работает, но потом, когда я возвращаюсь в прошлое и убеждаюсь, что больше не вижу пика, все так же хорошо, как плоское:(Я также пытался поставить в конце кода: chart.timeScale(). FitContent(); Но это дает тот же результат, что и у меня сейчас, но с уменьшением масштаба.Если я увеличиваю масштаб с помощью timeScale, он все равно выглядит так же.

1 ответ

Похоже, проблема вызвана неверным форматом данных (вы передали строки, в которых ожидаются числа). Мы будем предупреждать в режиме отладки о недопустимых типах после https://github.com/tradingview/lightweight-charts/issues/315.

Другие вопросы по тегам