Twelve Data

  1. from twelvedata import TDClient

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

  3. ts = td.time_series(

  4. symbol="AAPL",

  5. interval="1min",

  6. outputsize=12,

  7. )

  8. print(ts.as_json())

  9.  
  1. package main

  2. import (

  3. "encoding/json"

  4. "fmt"

  5. "io/ioutil"

  6. "log"

  7. "net/http"

  8. )

  9. const apiKey = "YOUR_API_KEY_HERE"

  10. type TimeSeriesResponse struct {

  11. Status string `json:"status"`

  12. Message string `json:"message"`

  13. Meta struct {

  14. Symbol string `json:"symbol"`

  15. Interval string `json:"interval"`

  16. } `json:"meta"`

  17. Data []struct {

  18. Datetime string `json:"datetime"`

  19. Open string `json:"open"`

  20. High string `json:"high"`

  21. Low string `json:"low"`

  22. Close string `json:"close"`

  23. Volume string `json:"volume"`

  24. } `json:"values"`

  25. }

  26. func main() {

  27. symbol := "AAPL"

  28. interval := "1min"

  29. url := fmt.Sprintf("https://api.twelvedata.com/time_series?symbol=%s&interval=%s&apikey=%s", symbol, interval, apiKey)

  30. resp, err := http.Get(url)

  31. if err != nil {

  32. log.Fatal(err)

  33. } defer resp.Body.Close()

  34. body, err := ioutil.ReadAll(resp.Body)

  35. if err != nil {

  36. log.Fatal(err)

  37. }

  38. var response TimeSeriesResponse

  39. if err := json.Unmarshal(body, response); err != nil {

  40. log.Fatal(err)

  41. }

  42. if response.Status != "ok" {

  43. log.Fatalf("Error: %s\n", response.Message)

  44. }

  45. fmt.Printf("Time Series for symbol: %s\n", response.Meta.Symbol)

  46. for, data := range response.Data {

  47. fmt.Printf("Time: %s, Open: %s, High: %s, Low: %s, Close: %s, Volume: %s\n", data.Datetime, data.Open, data.High, data.Low, data.Close, data.Volume)

  48. }

  49. }

  50.  
  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=AAPL&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. }

  32.  
  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=AAPL&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. }

  27.  
  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=AAPL&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE";

  9. URL requestURL = new URL(REQUEST_URL);

  10. JSONParser parser = new JSONParser();

  11. connection.setRequestMethod("GET");

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

  13. connection.connect();

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

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

  16. }

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

  18. while (scanner.hasNextLine()) {

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

  20. }

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

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

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

  24. connection.disconnect();

  25. }

  26. }

  27.  
  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

  9.  
  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="AAPL", on_event=on_event)

  7. ws.connect()

  8. ws.keep_alive()

  9.  
  1. package main

  2. import (

  3. "fmt"

  4. "log"

  5. "github.com/gorilla/websocket"

  6. )

  7. const websocketURL = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE"

  8. func main() {

  9. conn, _, err := websocket.DefaultDialer.Dial(websocketURL, nil)

  10. if err != nil {

  11. log.Fatal("connect to WebSocket failed:", err)

  12. }

  13. defer conn.Close()

  14. subscribeMessage := `{"action": "subscribe", "params": {"symbols": "AAPL"}}`

  15. err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))

  16. if err != nil {

  17. log.Fatal("message send failed:", err)

  18. }

  19. for {

  20. _, message, err := conn.ReadMessage()

  21. if err != nil {

  22. log.Fatal("message read failed:", err)

  23. }

  24. fmt.Printf("Received: %s\n", message)

  25. }

  26. }

  27.  
  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\": \"AAPL\"" \

  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. }

  107.  
  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\": \"AAPL\"}}");

  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. }

  40.  
  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. WebSocketClient client = new WebSocketClient(new URI(ENDPOINT)) {

  10. @Override

  11. public void onOpen(ServerHandshake handshake) {

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

  13. send("{\"action\": \"subscribe\", \"params\":{\"symbols\": \"AAPL\"}}");

  14. }

  15. @Override

  16. public void onMessage(String message) {

  17. JSONParser parser = new JSONParser();

  18. try {

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

  20. System.out.println(json);

  21. e.printStackTrace();

  22. }

  23. }

  24. @Override

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

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

  27. this.close();

  28. }

  29. @Override

  30. e.printStackTrace();

  31. }

  32. };

  33. client.connectBlocking();

  34. }

  35. }

  36.  
  1. # install.packages("websocket")

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

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

  4. })

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

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

  7. })

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

  9. })

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

  11. })

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

  13.  

Read the original on twelvedata.com ↗