Twelve Data | Stock Market Data APIs (Real Time & Historical) (2024)

  1. #include <cjson/cJSON.h> // https://github.com/DaveGamble/cJSON

  2. #include <curl/curl.h>

  3. #include <iostream>

  4. #include <memory>

  5. const char* REQUEST_URL = "https://api.twelvedata.com/time_series?symbol=TSLA&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE";

  6. // Take response data and write into the string

  7. std::size_t write_callback(const char* data, std::size_t size, std::size_t count, std::string* out) {

  8. const std::size_t result = size * count;

  9. out->append(data, result);

  10. return result;

  11. }

  12. int main() {

  13. std::unique_ptr<std::string> responseData(new std::string());

  14. cJSON* json = nullptr;

  15. CURL* curl = curl_easy_init();

  16. curl_easy_setopt(curl, CURLOPT_URL, REQUEST_URL);

  17. curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);

  18. curl_easy_setopt(curl, CURLOPT_WRITEDATA, responseData.get());

  19. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

  20. curl_easy_perform(curl);

  21. json = cJSON_Parse(responseData->c_str());

  22. cJSON* metaField = cJSON_GetObjectItem(json, "meta");

  23. cJSON* valuesField = cJSON_GetObjectItem(json, "values");

  24. cJSON* symbolField = cJSON_GetObjectItem(metaField, "symbol");

  25. cJSON* closeField = cJSON_GetObjectItem(cJSON_GetArrayItem(valuesField, 0), "close");

  26. std::cout << "Received symbol: " << cJSON_GetStringValue(symbolField) << ", ";

  27. std::cout << "close: " << cJSON_GetStringValue(closeField) << std::endl;

  28. cJSON_Delete(json);

  29. curl_easy_cleanup(curl);

  30. return 0;

  31. }

  1. using System;

  2. using System.Collections.Generic;

  3. using System.Net;

  4. using System.Text.Json;

  5. namespace TwelveData

  6. {

  7. public class TimeSeries

  8. {

  9. public Dictionary<string, string> meta { get; set; }

  10. public IList<Dictionary<string, string>> values { get; set; }

  11. public string status { get; set; }

  12. }

  13. class Prices

  14. {

  15. static void Main(string[] args)

  16. {

  17. using WebClient wc = new WebClient();

  18. var response = wc.DownloadString("https://api.twelvedata.com/time_series?symbol=TSLA&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE");

  19. var timeSeries = JsonSerializer.Deserialize<TimeSeries>(response);

  20. if (timeSeries.status == "ok")

  21. {

  22. Console.WriteLine("Received symbol: " + timeSeries.meta["symbol"] + ", close: " + timeSeries.values[0]["close"]);

  23. }

  24. }

  25. }

  26. }

  1. import org.json.simple.parser.JSONParser;

  2. import org.json.simple.JSONArray;

  3. import org.json.simple.JSONObject;

  4. import java.util.Scanner;

  5. import java.net.HttpURLConnection;

  6. import java.net.URL;

  7. public class Main {

  8. private static final String REQUEST_URL = "https://api.twelvedata.com/time_series?symbol=TSLA&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE";

  9. public static void main(String[] args) throws Exception {

  10. URL requestURL = new URL(REQUEST_URL);

  11. HttpURLConnection connection = (HttpURLConnection)requestURL.openConnection();

  12. StringBuffer responseData = new StringBuffer();

  13. JSONParser parser = new JSONParser();

  14. connection.setRequestMethod("GET");

  15. connection.setRequestProperty("User-Agent", "twelve_java/1.0");

  16. connection.connect();

  17. if (connection.getResponseCode() != 200) {

  18. throw new RuntimeException("Request failed. Error: " + connection.getResponseMessage());

  19. }

  20. Scanner scanner = new Scanner(requestURL.openStream());

  21. while (scanner.hasNextLine()) {

  22. responseData.append(scanner.nextLine());

  23. }

  24. JSONObject json = (JSONObject) parser.parse(responseData.toString());

  25. JSONObject meta = (JSONObject) json.get("meta");

  26. JSONArray values = (JSONArray) json.get("values");

  27. connection.disconnect();

  28. }

  29. }

  1. # install.packages("RcppSimdJson")

  2. apikey <- "YOUR_API_KEY_HERE"

  3. qry <- paste0(

  4. "https://api.twelvedata.com/time_series?",

  5. "symbol=AAPL&interval=1min&outputsize=12",

  6. "&apikey=", apikey)

  7. res <- RcppSimdJson::fload(qry)

  8. res

  1. # pip install twelvedata[websocket]

  2. from twelvedata import TDClient

  3. def on_event(e):

  4. print(e)

  5. td = TDClient(apikey="YOUR_API_KEY_HERE")

  6. ws = td.websocket(symbols="TSLA", on_event=on_event)

  7. ws.connect()

  8. ws.keep_alive()

  1. #include <websocketpp/config/asio_client.hpp>

  2. #include <websocketpp/client.hpp>

  3. #include <cjson/cJSON.h>

  4. #include <iostream>

  5. #include <iomanip>

  6. #include <ctime>

  7. namespace wlib = websocketpp::lib;

  8. namespace ssl = boost::asio::ssl;

  9. typedef websocketpp::client<websocketpp::config::asio_tls_client> wclient;

  10. typedef wlib::shared_ptr<wlib::asio::ssl::context> context_ptr;

  11. const char* ENDPOINT = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE";

  12. const char* SUBSCRIBE_ACTION = "{"\

  13. "\"action\": \"subscribe\"," \

  14. "\"params\": {" \

  15. "\"symbols\": \"TSLA\"" \

  16. "}" \

  17. "}";

  18. int main() {

  19. wclient::connection_ptr connection;

  20. wlib::error_code error_code;

  21. wclient client;

  22. client.set_access_channels(websocketpp::log::alevel::all);

  23. client.clear_access_channels(websocketpp::log::alevel::frame_payload);

  24. client.set_error_channels(websocketpp::log::elevel::all);

  25. // Initialize Boost.ASIO

  26. client.init_asio();

  27. // Set TLS initialize handler

  28. client.set_tls_init_handler(wlib::bind([](auto* hostname, auto hdl) {

  29. context_ptr context = wlib::make_shared<ssl::context>(ssl::context::sslv23);

  30. context->set_verify_mode(ssl::verify_none);

  31. return context;

  32. }, ENDPOINT, websocketpp::lib::placeholders::_1));

  33. // Is called after the WebSocket handshake is complete

  34. client.set_open_handler([&client](auto hdl) {

  35. // Send subscribe action to stream

  36. client.send(hdl, SUBSCRIBE_ACTION, websocketpp::frame::opcode::text);

  37. });

  38. // Receive and handle messages from server

  39. client.set_message_handler([](auto hdl, wclient::message_ptr message) {

  40. cJSON* json = cJSON_Parse(message->get_payload().c_str());

  41. if (json == nullptr) {

  42. std::cout << "received invalid JSON: " << std::endl << message->get_payload() << std::endl;

  43. return;

  44. }

  45. // Get event type

  46. cJSON* eventTypeField = cJSON_GetObjectItem(json, "event");

  47. if (eventTypeField == nullptr) {

  48. std::cout << "unknown JSON structure" << std::endl;

  49. return;

  50. }

  51. // Extract string from event type

  52. const char* eventType = cJSON_GetStringValue(eventTypeField);

  53. if (strcmp(eventType, "subscribe-status") == 0) {

  54. cJSON* statusField = cJSON_GetObjectItem(json, "status");

  55. const char* status = cJSON_GetStringValue(statusField);

  56. if (strcmp(status, "ok") != 0) {

  57. std::cout << "Failed subscribe to stream" << std::endl;

  58. return;

  59. }

  60. cJSON* successField = cJSON_GetObjectItem(json, "success");

  61. cJSON* failsField = cJSON_GetObjectItem(json, "fails");

  62. // Iterate over the symbols that were successfully subscribed

  63. for (int idx = 0; idx < cJSON_GetArraySize(successField); idx++) {

  64. cJSON* item = cJSON_GetArrayItem(successField, idx);

  65. cJSON* symbolField = cJSON_GetObjectItem(item, "symbol");

  66. const char* symbol = cJSON_GetStringValue(symbolField);

  67. std::cout << "Success subscribed to `"<< symbol << "` " << "symbol." << std::endl;

  68. }

  69. // If we're unable to subscribe to some symbols

  70. for (int idx = 0; 0 < cJSON_GetArraySize(failsField); idx++) {

  71. cJSON* item = cJSON_GetArrayItem(failsField, idx);

  72. cJSON* symbolField = cJSON_GetObjectItem(item, "symbol");

  73. const char* symbol = cJSON_GetStringValue(symbolField);

  74. std::cout << "Failed to subscribe on `"<< symbol << "` " << "symbol." << std::endl;

  75. }

  76. return;

  77. }

  78. if (strcmp(eventType, "price") == 0) {

  79. cJSON* timestampField = cJSON_GetObjectItem(json, "timestamp");

  80. cJSON* currencyField = cJSON_GetObjectItem(json, "currency");

  81. cJSON* symbolField = cJSON_GetObjectItem(json, "symbol");

  82. cJSON* priceField = cJSON_GetObjectItem(json, "price");

  83. time_t time = timestampField->valueint;

  84. std::cout << "[" << std::put_time(gmtime(&time), "%I:%M:%S %p") << "]: ";

  85. std::cout << "The symbol `" << cJSON_GetStringValue(symbolField) << "` ";

  86. std::cout << "has changed price to " << priceField->valuedouble << " ";

  87. if (currencyField != nullptr) {

  88. std::cout << "(" << cJSON_GetStringValue(currencyField) << ")" << std::endl;

  89. } else {

  90. std::cout << std::endl;

  91. }

  92. return;

  93. }

  94. // Free memory of JSON structure

  95. cJSON_Delete(json);

  96. });

  97. // New connection to WebSocket endpoint

  98. connection = client.get_connection(ENDPOINT, error_code);

  99. if (error_code) {

  100. std::cout << "Failed connection. Message: " << error_code.message() << std::endl;

  101. return -1;

  102. }

  103. // Connect to websocket endpoint

  104. client.connect(connection);

  105. client.run();

  106. }

  1. using System;

  2. using WebSocket4Net; //https://github.com/kerryjiang/WebSocket4Net

  3. namespace TwelveData

  4. {

  5. class TDWebSocket

  6. {

  7. WebSocket ws = new WebSocket("wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE");

  8. static void Main()

  9. {

  10. new TDWebSocket().Init();

  11. }

  12. public void Init()

  13. {

  14. ws.Opened += OnOpen;

  15. ws.Closed += OnClose;

  16. ws.Error += OnError;

  17. ws.MessageReceived += OnEvent;

  18. ws.Open();

  19. Console.ReadLine();

  20. }

  21. private void OnOpen(object sender, EventArgs e)

  22. {

  23. Console.WriteLine("TDWebSocket opened!");

  24. ws.Send("{\"action\": \"subscribe\", \"params\":{\"symbols\": \"TSLA\"}}");

  25. }

  26. private void OnClose(object sender, EventArgs e)

  27. {

  28. Console.WriteLine("TDWebSocket closed");

  29. }

  30. private void OnError(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)

  31. {

  32. Console.WriteLine("TDWebSocket ERROR: " + e.Exception.Message);

  33. }

  34. private void OnEvent(object sender, MessageReceivedEventArgs e)

  35. {

  36. Console.WriteLine(e.Message);

  37. }

  38. }

  39. }

  1. import org.java_websocket.handshake.ServerHandshake;

  2. import org.java_websocket.client.WebSocketClient;

  3. import org.json.simple.parser.ParseException;

  4. import org.json.simple.parser.JSONParser;

  5. import org.json.simple.JSONObject;

  6. import java.net.URI;

  7. public class Main {

  8. private static final String ENDPOINT = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE";

  9. public static void main(String[] args) throws Exception {

  10. WebSocketClient client = new WebSocketClient(new URI(ENDPOINT)) {

  11. @Override

  12. public void onOpen(ServerHandshake handshake) {

  13. System.out.println("TDWebSocket opened!");

  14. send("{\"action\": \"subscribe\", \"params\":{\"symbols\": \"TSLA\"}}");

  15. }

  16. @Override

  17. public void onMessage(String message) {

  18. JSONParser parser = new JSONParser();

  19. try {

  20. JSONObject json = (JSONObject) parser.parse(message);

  21. System.out.println(json);

  22. } catch(ParseException e) {

  23. e.printStackTrace();

  24. }

  25. }

  26. @Override

  27. public void onClose(int status, String reason, boolean remote) {

  28. System.out.println("TDWebSocket closed.");

  29. this.close();

  30. }

  31. @Override

  32. public void onError(Exception e) {

  33. e.printStackTrace();

  34. }

  35. };

  36. client.connectBlocking();

  37. }

  38. }

  1. # install.packages("websocket")

  2. library(websocket)

  3. ws <- WebSocket$new("wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE")

  4. ws$onOpen(function(event) {

  5. cat("TDWebSocket opened!\n")

  6. })

  7. ws$onClose(function(event) {

  8. cat("TDWebSocket closed with code ", event$code,

  9. " and reason ", event$reason, "\n", sep = "")

  10. })

  11. ws$onError(function(event) {

  12. cat("TDWebSocket ERROR: ", event$message, "\n")

  13. })

  14. ws$onMessage(function(event) {

  15. cat("Received event:", event$data, "\n")

  16. })

  17. ws$send('{"action": "subscribe", "params":{"symbols": "TSLA"}}')

As an expert in the field of financial data retrieval and processing using various programming languages, libraries, and APIs, I have hands-on experience with multiple technologies involved in fetching and parsing real-time stock data. My expertise spans languages such as C++, C#, Java, Python, and R, as well as the usage of popular libraries like cJSON, libcurl, WebSocketPP, WebSocket4Net, RcppSimdJson, and TwelveData.

Let's break down the key concepts used in the provided code snippets:

  1. C++ (libcurl, cJSON):

    • The code uses libcurl for making HTTP requests to the Twelve Data API.
    • The cJSON library is employed for parsing and manipulating JSON data received from the API.
    • The program fetches real-time stock data for TSLA, extracts metadata, and prints the symbol and closing price.
  2. C# (.NET, System.Net, System.Text.Json):

    • The code uses the WebClient class from System.Net to download JSON data from the Twelve Data API.
    • It utilizes System.Text.Json for deserializing the JSON response into C# objects, making it easier to work with the data.
  3. Java (HttpURLConnection, org.json.simple):

    • The code establishes an HTTP connection using HttpURLConnection to retrieve JSON data from the Twelve Data API.
    • It uses the org.json.simple library for parsing and processing the JSON response.
  4. R (RcppSimdJson):

    • RcppSimdJson is used for fetching and parsing JSON data in R.
    • The code requests real-time stock data for AAPL, and RcppSimdJson is employed for loading and processing the JSON response.
  5. Python (twelvedata, WebSocket):

    • The code demonstrates the usage of the TwelveData Python library for fetching real-time stock data through WebSocket.
    • It subscribes to the TSLA symbol and prints events received from the WebSocket connection.
  6. C++ (WebSocketPP, cJSON):

    • WebSocketPP is utilized for establishing a WebSocket connection to Twelve Data's real-time quotes endpoint.
    • The code subscribes to the TSLA symbol and processes events received via WebSocket, including handling subscribe status and price change events.
  7. C# (.NET, WebSocket4Net):

    • WebSocket4Net is used to create a WebSocket client for connecting to Twelve Data's WebSocket endpoint.
    • The program subscribes to the TSLA symbol and handles events such as open, close, error, and message reception.
  8. Java (java_websocket, org.json.simple):

    • The code establishes a WebSocket connection to Twelve Data's real-time quotes endpoint using the java_websocket library.
    • It subscribes to the TSLA symbol and processes received JSON messages.
  9. R (websocket):

    • The websocket R library is employed for creating a WebSocket client.
    • The code establishes a WebSocket connection to the Twelve Data quotes endpoint, subscribes to TSLA, and handles open, close, error, and message events.

These snippets collectively showcase how to fetch real-time stock data using different programming languages, HTTP requests, and WebSocket connections while leveraging various libraries and APIs for JSON processing and data manipulation.

Twelve Data | Stock Market Data APIs (Real Time & Historical) (2024)
Top Articles
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5655

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.