Как получить текущую цену пользовательской диаграммы с помощью API облегченной диаграммы Javascript?

Как я могу получить цену, показанную на графике в правой части моего графика, отмеченного синим цветом. введите здесь описание изображения

Это мой код до сих пор:

const chart = LightweightCharts.createChart(document.body, { width: 1500, height: 700 });
const lineSeries = chart.addLineSeries();

const log = console.log;

lineSeries.setData([
    { time: '2019-04-11', value: 80.01 },
    { time: '2019-04-12', value: 96.63 },
    { time: '2019-04-13', value: 76.64 },
    { time: '2019-04-14', value: 81.89 },
    { time: '2019-04-15', value: 74.43 },
    { time: '2019-04-16', value: 80.01 },
    { time: '2019-04-17', value: 96.63 },
    { time: '2019-04-18', value: 76.64 },
    { time: '2019-04-19', value: 81.89 },
    { time: '2019-04-20', value: 74.43 },
]);

function randomIntFromInterval(min, max) {
    return Math.round((Math.random() * (max - min + 1) + min) * 100) / 100;
}

var startDate = new Date();
var endDate = new Date(2020, 5, 1);

log(lineSeries);


// lineSeries.applyOptions({
//     priceFormat: {
//         type: 'custom',
//         minMove: 0.02,
//         formatter: function(price) {
//             log(price);                //Gives me the price in a very bad way. Also gives it when i hover over chart.
//             return '$' + price;
//         },
//     }
// });


/**
 * Updates the chart its lines randomly.
 */
function updateChartStatic() {
    setTimeout(() => {
        //For updating the date.
        let newDate = new Date(startDate);

        //Creates a random int.
        let randomInt = randomIntFromInterval(randomIntFromInterval(50, 100), randomIntFromInterval(75, 125));

        // log(randomInt);
        log(lineSeries._series._priceScale.rn.ct);

        //Updates the line of the chart.
        lineSeries.update({
            time: newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate(),
            value: randomInt,
        });

        //Makes sure the loop can actually end by adding a day to the startDate.
        startDate.setDate(startDate.getDate() + 1);

        //Make sure the function will be called again if startDate and endDate date not matches with each other. If they do, the loop will end and a console log will be shown.
        startDate <= endDate ? updateChartStatic() : log("END LOOP");
    }, 1000);
}

updateChartStatic();

Atm я случайно обновляю строки между некоторыми числами. Мне нужно знать цену, чтобы убедиться, что строки обновляются на основе текущей цены. Таким образом, новая линия будет, например, на 50 долларов/евро выше или ниже текущей цены. Это сделало бы его менее острым :) В псевдокоде:

let randomInt = randomIntFromInterval((currentPrice - 50), (currentprice + 50));

person Allart    schedule 18.04.2020    source источник


Ответы (2)


Альтернативой для получения последнего значения, добавленного к вашим данным lineSeries, является сохранение данных перед выполнением другого обновления строки с вашим setTimeout. Например.,

/**
 * Updates the chart its lines randomly.
 */
 function updateChartStatic() {

    // Array where we store all our added prices.
    var oldPrices = [];

    setTimeout(() => {

        // Creates a random int.
        let randomInt = randomIntFromInterval(randomIntFromInterval(50, 100), randomIntFromInterval(75, 125));

        // Logs OLD price. First time will be empty in this case
        log(oldPrices[oldPrices.length - 1]);

        // Updates the line of the chart.
        lineSeries.update({
            time: newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate(),
            value: randomInt,
        });

        // Add your currently set price to the array of prices.
        oldPrices.push(randomInt);
    }, 1000);
}

Старые цены хранятся в var oldPrices.

Вот еще один пример с сайта tradingview.com. https://jsfiddle.net/TradingView/8a29s0qj/

person Anarchy365    schedule 28.07.2021
comment
Пожалуйста, предоставьте подробное объяснение вашего ответа, чтобы следующий пользователь лучше понял ваш ответ. - person Elydasian; 28.07.2021
comment
Я вижу, что ты хочешь. В основном он делает то, что я делаю в своем ответе, но затем с помощью самостоятельно созданного массива с ценами, хранящимися в вашем коде. Что, я думаю, лучше, так как мой ответ проходит через множество сумасшедших массивов и переменных из библиотеки. Я также согласен с Elydasian, необходимо предоставить дополнительный код, чтобы сделать его более понятным, возможно, я могу отредактировать для вас. - person Allart; 28.07.2021

Итак, я провел небольшое исследование в переменной lineSeries. Я нашел способ получить текущую цену последней добавленной линии на графике. Вот как:

//Get price of last line
let currentPrice = Array.from(Array.from(lineSeries._dataUpdatesConsumer.de.ee)[lineSeries._dataUpdatesConsumer.de.ee.size - 1][1].mapping)[0][1].value;


//Code below ends up the same but is splitted a bit more. Might look bit more understandable :P
let map = lineSeries._dataUpdatesConsumer.de.ee;

let getLastItemInMap = Array.from(map)[map.size - 1];

let secondMap = getLastItemInMap[1].mapping;

let getItemInMap = Array.from(secondMap)[0];

// Returns the price
log(getItemInMap[1].value);
person Allart    schedule 20.04.2020
comment
Итак, я вижу, что кто-то проголосовал против, всегда приятно, что они также объясняют, почему они проголосовали против? Если мой ответ не работает, просто скажите мне. Для меня это так, но, может быть, для других это не так. Просто скажи, если это так. - person Allart; 03.06.2020