DEV Community

Cover image for Retrieving Crypto Data with C++ REST API: A Step-by-Step Guide
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Retrieving Crypto Data with C++ REST API: A Step-by-Step Guide

If you're keen on exploring Crypto trading and harnessing the power of the C++ programming language to retrieve Crypto data, you're in the right place. This comprehensive tutorial will walk you through building your first C++ REST API client with TraderMade. By the end of this tutorial, you'll be able to fetch real-time Crypto data, granting you the insights needed to make informed decisions.

Getting Started:

First, we need to lay the groundwork. Sign up for an account with TraderMade and secure your exclusive API Key. This key is your passport to accessing the real treasure trove of Crypto data. To dive deeper into the world of real-time Crypto data, take a moment to explore the REST API documentation TraderMade provides.

Now, let's get practical. We'll break the process down into manageable steps:

Setting Up Your Coding Environment:

Before diving into the code, ensure the programming environment is set up correctly. We recommend downloading Ubuntu, which offers a seamless C++ setup if you still need to get on a Linux system. We can grab the official download from https://ubuntu.com/download.

Importing Necessary Libraries:

In C++, libraries are our toolkit for building amazing things. If you're new to C++, get the GCC compiler to compile C++ programs.
Let's open Ubuntu, update the package list, and install some essential packages for building:

sudo apt update 
Enter fullscreen mode Exit fullscreen mode

If you don't have a password or have forgotten it, you can use the following command:

sudo passwd
Enter fullscreen mode Exit fullscreen mode

Now, install the build-essentials package, a meta-package crucial for software compilation.

sudo apt install build-essential 
Enter fullscreen mode Exit fullscreen mode

Check the GCC version to ensure everything is running smoothly.

gcc --version
Enter fullscreen mode Exit fullscreen mode

We need to download and install two essential libraries: curl and jsoncpp. Here's how to do it:
Install the latest version of the CURL library with the following command.

sudo apt-get install libcurl4-openssl-dev 
Enter fullscreen mode Exit fullscreen mode

Next, install the latest version of the jsoncpp library using this command:

sudo apt-get install libjsoncpp-dev 
Enter fullscreen mode Exit fullscreen mode

We are ready to move to the next step with the libraries in place.

Writing Some Code:

The heart of our journey begins with the code. The include statement brings the necessary libraries into play, much like gathering all the materials you need for a project:

#include <iostream> 
#include <string> 
#include <curl/curl.h> 
#include <json/json.h> 
Enter fullscreen mode Exit fullscreen mode

The 'namespace' code gives us access to essential functions and classes from the 'std' namespace:

using namespace std; 
Enter fullscreen mode Exit fullscreen mode

The 'WriteCallback' function handles data retrieved from web requests using the curl library. It appends the data received to a string:

size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } 
Enter fullscreen mode Exit fullscreen mode

The 'performCurlRequest' function utilizes the libcurl library to fetch data from a URL. It sets up the tool, sends the request, manages the response using the 'WriteCallback' method, confirms if everything went well, and cleans up.

// Function to perform CURL request
bool performCurlRequest(const string& url, string& response) {
    CURL *curl = curl_easy_init();
    if (!curl) {
        cerr << "Failed to initialize CURL" << endl;
        return false;
    }

    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
        cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        return false;
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

The 'parseJsonResponse' function utilizes the JsonCpp library to parse a JSON response provided as a string. If parsing is successful, the parsed data is saved, and the function returns true. If there's a parsing error, it displays an error message and returns false. It uses a JSON reader to parse the response string and populates a Json::Value object.

// Function to parse JSON response
bool parseJsonResponse(const string& jsonResponse, Json::Value& parsedRoot) {
    Json::CharReaderBuilder builder;
    Json::CharReader *reader = builder.newCharReader();
    string errs;

    bool parsingSuccessful = reader->parse(jsonResponse.c_str(), jsonResponse.c_str() + jsonResponse.size(), &parsedRoot, &errs);
    delete reader;

    if (!parsingSuccessful) {
        cerr << "Failed to parse JSON: " << errs << endl;
        return false;
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

The main function sets the API URL, initializes CURL globally, performs the CURL request, parses the JSON response, and extracts bid and ask prices from the JSON data, printing them to the console.

int main() {
    string api_url = "https://marketdata.tradermade.com/api/v1/live?currency=BTCUSD&api_key=API_KEY";
    string response;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    if (performCurlRequest(api_url, response)) {
        Json::Value root;
        if (parseJsonResponse(response, root)) {
            const Json::Value quotes = root["quotes"];
            for (const Json::Value &quote : quotes) {
                if (quote.isMember("bid") && quote.isMember("ask")) {
                    double bid = quote["bid"].asDouble();
                    double ask = quote["ask"].asDouble();
                    cout << "Bid: " << bid << ", Ask: " << ask << endl;
                }
            }
        }
    }

    curl_global_cleanup();
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

With the code in place, we are almost ready for action.

Debugging the Code and Getting Results:

Now that we have written our code, it's time to debug, execute, and see the results.
Start by saving the code to the system and create a new file named "crypto.cpp." Remember to include the '.cpp' extension to indicate it's a C++ file.

Now, it's time to compile and execute your program. To do this, we need to add the curl and jsoncpp libraries and specify the path to the jsoncpp library. Here's the compilation command.

g++ -o crypto crypto.cpp -lcurl -ljsoncpp -I/usr/include/jsoncpp -L/usr/lib/x86_64-linux-gnu 
Enter fullscreen mode Exit fullscreen mode

With the program compiled, we can execute it. We use Bitcoin as an example here, so the code becomes BTCUSD. We ask the computer to fetch and print the "bid" and "ask" values of Bitcoin via the REST API.

./crypto
Enter fullscreen mode Exit fullscreen mode

And there we have it! Our results are out. We have successfully retrieved and parsed JSON data through a REST API using C++.

Bid: 36619.4, Ask: 36674.5
Enter fullscreen mode Exit fullscreen mode

What's Next:

TraderMade's REST API is our gateway to developing cutting-edge digital solutions and gaining valuable insights into the Crypto world. And remember, if you ever need assistance, our team is just a click or an email away. Reach out to us via live chat or send an email to support@tradermade.com.

Full code:

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <json/json.h>

using namespace std;

// Callback function to handle curl's response
size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    ((string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

// Function to perform CURL request
bool performCurlRequest(const string& url, string& response) {
    CURL *curl = curl_easy_init();
    if (!curl) {
        cerr << "Failed to initialize CURL" << endl;
        return false;
    }

    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    CURLcode res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
        cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        return false;
    }

    return true;
}

// Function to parse JSON response
bool parseJsonResponse(const string& jsonResponse, Json::Value& parsedRoot) {
    Json::CharReaderBuilder builder;
    Json::CharReader *reader = builder.newCharReader();
    string errs;

    bool parsingSuccessful = reader->parse(jsonResponse.c_str(), jsonResponse.c_str() + jsonResponse.size(), &parsedRoot, &errs);
    delete reader;

    if (!parsingSuccessful) {
        cerr << "Failed to parse JSON: " << errs << endl;
        return false;
    }

    return true;
}

int main() {
    string api_url = "https://marketdata.tradermade.com/api/v1/live?currency=BTCUSD&api_key=API_KEY";
    string response;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    if (performCurlRequest(api_url, response)) {
        Json::Value root;
        if (parseJsonResponse(response, root)) {
            const Json::Value quotes = root["quotes"];
            for (const Json::Value &quote : quotes) {
                if (quote.isMember("bid") && quote.isMember("ask")) {
                    double bid = quote["bid"].asDouble();
                    double ask = quote["ask"].asDouble();
                    cout << "Bid: " << bid << ", Ask: " << ask << endl;
                }
            }
        }
    }

    curl_global_cleanup();
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Please go through the originally published tutorial on the TraderMade website:
C++ REST API Client

Along with this, you can refer to another tutorial to retrieve live forex rates via WebSockets with C++:
C++ WebSocket Client

If you are curious about obtaining forex data via REST API programmatically, the following tutorials on the TraderMade website can be helpful:

  1. Forex REST JSON with Java

  2. Importing Forex Data in R

  3. Forex REST JSON API with PHP

  4. Forex REST API with C#

Top comments (0)