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)

FAQs

Is twelve data good? ›

Twelve Data in a Nutshell

provides high-quality financial data across the whole world for individuals and companies. It also helps to develop complex FinTech systems. The company offers stocks, forex, crypto, ETFs, indices, fundamentals, and other data accessible via API and WebSocket.

What is the best stock market data API? ›

Best 6 stock market APIs for 2022
  1. 6 best stock APIs. Finnhub Stock API. ...
  2. Finnhub.io Stock API. Coverage: Stock API with Global markets (60+ stock exchanges) data, forex, crypto. ...
  3. Morningstar stock API. ...
  4. Xignite stock API. ...
  5. Bloomberg stock API. ...
  6. Google sheet finance. ...
  7. Exegy. ...
  8. ValueInvesting.io Valuation API.

Where can I get realtime stock data? ›

NYSE BBO feed is a real-time data feed that provides NYSE Quotes (best bid/ask quotations) for all NYSE-traded securities. This is a top of book feed that publishes updates for every event in real-time. NYSE Trades feed is a real-time data feed providing the NYSE Last Sale for all NYSE-traded securities.

What is twelve data API? ›

Welcome to the Twelve Data! You can use this API to access world financial markets including stocks, forex, ETFs, indices, and cryptocurrencies. Most of the exchanges are available in real-time, while others have some delays. Over 20+ years of end-of-day data and a couple of years for intraday historical data.

Which API is free to get NSE stock data? ›

The Breeze API is a powerful Indian stock market API through which you can fetch live/historical stock market data, real-time OHLC and Options Chain data, order status over Websockets, automate your trading strategies, monitor your portfolio in real-time, and most importantly, pay zero brokerage for all F&O trades ...

Where can I get stock market data for free? ›

Internet Sources for Historical Market & Stock Data
  • Yahoo! Finance - Historical Prices. ...
  • Dow Jones Industrial Averages. Historical and current performance data. ...
  • S&P Indices. Historical performance data.
  • IPL Newspaper Collection. ...
  • Securities Industry and Financial Markets Association. ...
  • FINRA: Market Data Center.
Apr 15, 2024

What is the best free stock market API? ›

1. Alpha Vantage. Alpha Vantage offers a comprehensive Financial Stock Market API, providing developers with access to a diverse range of financial data. One of its unique points is the availability of a free tier that allows developers to access essential market data without a subscription.

Is there an API to get stock data? ›

1. Twelve Data. The Twelve Data API provides financial data for developers to enter the world markets. Instant access for real-time and historical data of stocks, forex, crypto, ETFs, indices, and more.

How can I get historical stock data for free? ›

If you're looking for a historical range of data on an individual security then you can use Investopedia's Markets section to find what you need. In order to navigate to the historical data, enter the ticker symbol of the equity you're looking for into the "Search Company or Symbol" search box on the page.

What is the best website for stock financial data? ›

A quick look at the best stock research websites
Our pickBest forPricing
Seeking AlphaOpinionated researchPaid
TradingViewCharts and technical analysisPrimarily paid
Motley FoolPaid stock recommendationsPaid
MorningstarMutual fundsPrimarily free
3 more rows
Mar 6, 2024

What app gives real-time stock prices? ›

The MarketWatch app for iOS and Android delivers market data and quotes alongside the latest business and finance news, updated in real-time.

What are the intervals for twelve data? ›

Through Twelve Data, you can also fetch the data of various intervals. Following time frames are supported: 1min , 5min , 15min , 30min , 45min , 1h , 2h , 4h , 8h , 1day , 1week , 1month .

Who owns API data? ›

API Ownership: A Definition

You may have used open APIs from other companies to access specific datasets from their applications. This effectively means that the organization as an entity owns the API. However, when you look closer, different personas are responsible for a variety of aspects of every API.

How to pull data from APIs? ›

How to use data extraction API?
  1. Step 1 - Kickstart your journey by signing up! ...
  2. Step 2 - Go through API documentation. ...
  3. Step 3 - Set up the platform. ...
  4. Step 4 - Send an API request. ...
  5. Step 5 - API authentication. ...
  6. Step 6 - Parameterizing requests. ...
  7. Step 7 - Errors handling. ...
  8. Step 8 - Extraction and integration.

What is a good amount of data to have? ›

How much data do I need on my phone?
User typeMonthly data usage
Minimal use (basic browsing, messaging)Up to 2GB
Light use (social media, some video streaming)2-5GB
Regular use (frequent video streaming, many app downloads)5-10GB
Heavy use (extensive video streaming, large file transfers)10GB+
1 more row

How much data is enough data? ›

How Much Data Do I Need?
Online activityRecommended minimum monthly data
Basic web browsing and email40 GB
Streaming in HD (Netflix, Hulu, etc)300 GB
Smart home setup (security cameras, smart lighting, and live monitoring)150 GB
Online gaming50 GB
Nov 29, 2023

How much data do you actually need? ›

Determining the right amount of mobile data for your needs depends on how you use your phone. Users can generally be categorised as low, medium, high, or power users. Low users might only need 1-2 GB per month, while power users may require 100GB or more to support their extensive online activities.

How do you know if data is good? ›

Data quality should reflect accuracy, completeness, and consistency—and fit within your data governance framework. Using the right data tools will provide granular insights into user behavior.

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.