Learn how to fetch real-time stock prices using C++ by integrating with a stock price API.
Introduction
In this tutorial, we will learn how to track and display stock prices in real-time using C++ programming language. We will use an API to retrieve the stock data and then display it to the user. The program will send HTTP requests to a stock price service and parse the returned JSON data. This is a practical application of working with APIs in C++ and handling real-time data.
Objective
The main objective is to create a C++ program that fetches stock data from an API and displays the current stock price of a given company. We will be using an open stock price API like Alpha Vantage or Yahoo Finance, and the program will process the data and show it in a user-friendly format.
Code Implementation
#include #include #include <curl/curl.h> #include <json/json.h> // Function to write data fetched by curl into a string size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } int main() { // Define the stock symbol and API key for Alpha Vantage std::string symbol = "AAPL"; // Apple Inc stock std::string apiKey = "your_api_key_here"; // Replace with your actual Alpha Vantage API key // Create the API request URL std::string url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=" + symbol + "&interval=5min&apikey=" + apiKey; // Initialize curl CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if(curl) { std::string response_string; curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); // Perform the request res = curl_easy_perform(curl); // Check if the request was successful if(res != CURLE_OK) { std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl; } else { // Parse the JSON response Json::Value root; Json::Reader reader; if (reader.parse(response_string, root)) { std::string lastRefreshed = root["Meta Data"]["3. Last Refreshed"].asString(); std::string latestPrice = root["Time Series (5min)"][lastRefreshed]["1. open"].asString(); std::cout << "Stock Symbol: " << symbol << std::endl; std::cout << "Last Refreshed: " << lastRefreshed << std::endl; std::cout << "Latest Price: $" << latestPrice << std::endl; } else { std::cerr << "Failed to parse JSON data." << std::endl; } } // Cleanup curl curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
Explanation of the Program Structure
Here’s a breakdown of the program:
- Libraries: The program uses the
curl
library to make HTTP requests and thejsoncpp
library to parse the JSON response from the API. - API Request: We build a URL that sends a request to the Alpha Vantage API to fetch the latest stock price of a specified symbol (in this case, AAPL for Apple). The response is in JSON format.
- Handling the Response: The
WriteCallback
function is used to store the HTTP response data into a string. Then, we parse the JSON data to extract the required stock price and display it to the user. - Data Display: The stock’s latest price and the time it was last refreshed are printed to the console for the user.
How to Run the Program
Follow these steps to run the program:
- Ensure you have the libcurl and jsoncpp libraries installed on your system.
- Get an API key from Alpha Vantage by signing up on their website.
- Replace
"your_api_key_here"
in the code with your actual Alpha Vantage API key. - Compile the C++ code using a C++ compiler. For example:
g++ -o stock_price stock_price.cpp -lcurl -ljsoncpp
- Run the compiled program:
./stock_price
- The stock price information will be displayed in the terminal.