Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. Dynamic CandleStickSeries not working

Dynamic CandleStickSeries not working

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
1 Posts 1 Posters 214 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    Kiovtorov
    wrote on last edited by
    #1

    I am trying to fetch data from an api to dynamically display CandleSticks
    .cpp

    #include "alphavintageapi.hpp"
    #include <QDateTime>
    
    AlphaVantageAPI::AlphaVantageAPI(QObject *parent) : QObject(parent) {
        manager = new QNetworkAccessManager(this);
    }
    
    void AlphaVantageAPI::fetchHistoricalData(const QString &symbol, const QString &interval) {
        qDebug() << "Fetching historical data for symbol:" << symbol << "with interval:" << interval;
    
        QString apiKey = "API";
        QString url = QString("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=%1&interval=%2&apikey=%3&outputsize=compact&datatype=json")
                          .arg(symbol, interval, apiKey);
    
        qDebug() << "API URL:" << url; // Debug: Print the API URL
    
        QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(url)));
        connect(reply, &QNetworkReply::finished, this, &AlphaVantageAPI::onHistoricalDataReceived);
    }
    void AlphaVantageAPI::onHistoricalDataReceived() {
        qDebug() << "called";
        QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            qDebug() << "API Response:" << data; // Debug: Print the raw API response
    
            QJsonDocument json = QJsonDocument::fromJson(data);
            if (json.isNull()) {
                qDebug() << "Failed to parse JSON response.";
                return;
            }
    
            QJsonObject root = json.object();
            if (root.contains("Time Series (5min)")) {
                QJsonObject timeSeries = root.value("Time Series (5min)").toObject();
                qDebug() << "Number of candles received:" << timeSeries.size(); // Debug: Print the number of candles
    
                QJsonArray candles;
                for (auto it = timeSeries.begin(); it != timeSeries.end(); ++it) {
                    QJsonObject candle;
                    candle["timestamp"] = it.key();
                    candle["open"] = it.value().toObject()["1. open"].toString();
                    candle["high"] = it.value().toObject()["2. high"].toString();
                    candle["low"] = it.value().toObject()["3. low"].toString();
                    candle["close"] = it.value().toObject()["4. close"].toString();
                    candles.append(candle);
                }
    
                emit dataReceived(candles);
            } else {
                qDebug() << "Error: 'Time Series (5min)' not found in API response.";
            }
        } else {
            qDebug() << "API Request Failed:" << reply->errorString(); // Debug: Print the error message
        }
        reply->deleteLater();
    }
    

    The data is being fetched correctly but I still can't display it in the QML

    import QtQuick 2.15
    import QtQuick.Controls 2.15
    import QtCharts 2.15
    
    Window {
        visible: true
        width: 800
        height: 600
        title: "Stock Chart"
    
        ChartView {
            id: chartView
            anchors.fill: parent
            theme: ChartView.ChartThemeLight
    
            // Predefine an empty CandlestickSeries
            CandlestickSeries {
                id: candlestickSeries
                name: "Candlesticks"
                increasingColor: "green"
                decreasingColor: "red"
            }
        }
    
        Button {
            text: "Fetch Data"
            anchors.bottom: parent.bottom
            background: Rectangle {
                color: "black"
            }
            anchors.horizontalCenter: parent.horizontalCenter
            onClicked: {
                alphaVantageAPI.fetchHistoricalData("AAPL", "5min");
            }
        }
    
        Connections {
            target: alphaVantageAPI
            function onDataReceived(candles) {
                // Clear existing data from the series
                candlestickSeries.clear();
    
                // Add candlestick data to the series
                for (var i = 0; i < candles.length; i++) {
                    var candle = candles[i];
                    console.log("Candle:", candle); // Debug: Print each candle
    
                    // Parse data and append to the series
                    var timestamp = new Date(candle.timestamp + "Z").getTime(); // Ensure UTC timestamp
                    var open = candle.open;
                    var high = candle.high;
                    var low = candle.low;
                    var close = candle.close;
    
                    // Append the candlestick data directly
                    candlestickSeries.append(timestamp, open, high, low, close);
                }
            }
        }
    }
    
    
    1 Reply Last reply
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved