We’ve just launched a new portal to help you explore stocks, crypto, ETFs, and more data

Commodities

real-time JSON API spot data

Historical and real-time prices and rates REST APIs for precious metals, energies, and more.

Start now Contact sales
Reliable data

Data sourced and processed from top PRAs, brokers, governments, and reports ensures institutional-grade reliability.

No licensing

There is no need to pay additional fees or obtain a commercial license. Data can be directly used for business and personal needs.

Low Latency

REST API data is updated minutely, while WebSocket API streaming updates prices with up to 170ms latency.

Ease of integration

Seamlessly integrate our API into your platform before you finish a cup of coffee with detailed documentation and code samples.

Access any commodity

Easily access a wide range of commodities prices with Twelve Data API.

Gold
Silver
Palladium
Platinum
Copper
Explore all commodities
Visualize any commodity in the portal
Crude Oil Futures
Brent Futures
Ethanol Futures
Natural Gas
Gasoline
Explore all commodities
Visualize any commodity in the portal
Corn Futures
Cocoa Futures
Cotton Futures
Coffee Futures
Wheat Futures
Explore all commodities
Visualize any commodity in the portal
Cheese Futures
Milk Futures
Feeder Cattle Futures
Live Cattle Futures
Lean Hogs Futures
Explore all commodities
Visualize any commodity in the portal
Build faster

Powerful and
easy-to-use APIs

Our JSON API is designed with developers in mind. Rapidly integrate commodities data into your project with modern languages, from Python to Golang. Using Twelve Data's API means less code maintenance and more time to build a great product.

  • Simple commodity documentation with samples
  • Numerous SDKs
  • Institutional-level security with 256-bit SSL encryption
  • Lightweight JSON & CSV formats
  • Redistribution and commercial usage
API docs WebSocket docs
  1. from twelvedata import TDClient
  2.  
  3. td = TDClient(apikey="YOUR_API_KEY_HERE")
  4.  
  5. ts = td.time_series(
  6.     symbol="XAU/USD",
  7.     interval="1min",
  8.     outputsize=12,
  9. )
  10.  
  11. print(ts.as_json())
  12.  
  1. package main
  2.  
  3. import (
  4.    "encoding/json"
  5.    "fmt"
  6.    "io/ioutil"
  7.    "log"
  8.    "net/http"
  9. )
  10.  
  11. const apiKey = "YOUR_API_KEY_HERE"
  12.  
  13. type TimeSeriesResponse struct {
  14.    Status string `json:"status"`
  15.    Message string `json:"message"`
  16.    Meta struct {
  17.       Symbol string `json:"symbol"`
  18.       Interval string `json:"interval"`
  19.    } `json:"meta"`
  20.    Data []struct {
  21.       Datetime string `json:"datetime"`
  22.       Open string `json:"open"`
  23.       High string `json:"high"`
  24.       Low string `json:"low"`
  25.       Close string `json:"close"`
  26.       Volume string `json:"volume"`
  27.    } `json:"values"`
  28. }
  29.  
  30. func main() {
  31.    symbol := "XAU/USD"
  32.    interval := "1min"
  33.    url := fmt.Sprintf("https://api.twelvedata.com/time_series?symbol=%s&interval=%s&apikey=%s", symbol, interval, apiKey)
  34.    resp, err := http.Get(url)
  35.    if err != nil {
  36.       log.Fatal(err)
  37.    } defer resp.Body.Close()
  38.    body, err := ioutil.ReadAll(resp.Body)
  39.    if err != nil {
  40.       log.Fatal(err)
  41.    }
  42.    var response TimeSeriesResponse
  43.    if err := json.Unmarshal(body, response); err != nil {
  44.       log.Fatal(err)
  45.    }
  46.    if response.Status != "ok" {
  47.       log.Fatalf("Error: %s\n", response.Message)
  48.    }
  49.  
  50.    fmt.Printf("Time Series for symbol: %s\n", response.Meta.Symbol)
  51.    for, data := range response.Data {
  52.       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)
  53.    }
  54. }
  1. #include <cjson/cJSON.h> // https://github.com/DaveGamble/cJSON
  2. #include <curl/curl.h>
  3. #include <iostream>
  4. #include <memory>
  5.  
  6. const char* REQUEST_URL = "https://api.twelvedata.com/time_series?symbol=XAU/USD&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE";
  7.  
  8. // Take response data and write into the string
  9. std::size_t write_callback(const char* data, std::size_t size, std::size_t count, std::string* out) {
  10.     const std::size_t result = size * count;
  11.     out->append(data, result);
  12.  
  13.     return result;
  14. }
  15.  
  16. int main() {
  17.     std::unique_ptr<std::string> responseData(new std::string());
  18.     cJSON* json = nullptr;
  19.     CURL* curl = curl_easy_init();
  20.  
  21.     curl_easy_setopt(curl, CURLOPT_URL, REQUEST_URL);
  22.     curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
  23.     curl_easy_setopt(curl, CURLOPT_WRITEDATA, responseData.get());
  24.     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
  25.     curl_easy_perform(curl);
  26.  
  27.     json = cJSON_Parse(responseData->c_str());
  28.     cJSON* metaField = cJSON_GetObjectItem(json, "meta");
  29.     cJSON* valuesField = cJSON_GetObjectItem(json, "values");
  30.     cJSON* symbolField = cJSON_GetObjectItem(metaField, "symbol");
  31.     cJSON* closeField = cJSON_GetObjectItem(cJSON_GetArrayItem(valuesField, 0), "close");
  32.  
  33.     std::cout << "Received symbol: " << cJSON_GetStringValue(symbolField) << ", ";
  34.     std::cout << "close: " << cJSON_GetStringValue(closeField) << std::endl;
  35.  
  36.     cJSON_Delete(json);
  37.     curl_easy_cleanup(curl);
  38.  
  39.     return 0;
  40. }
  41.  
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text.Json;
  5.  
  6. namespace TwelveData
  7. {
  8.     public class TimeSeries
  9.     {
  10.         public Dictionary<string, string> meta { get; set; }
  11.         public IList<Dictionary<string, string>> values { get; set; }
  12.         public string status { get; set; }
  13.     }
  14.  
  15.     class Prices
  16.     {
  17.         static void Main(string[] args)
  18.         {
  19.             using WebClient wc = new WebClient();
  20.             var response = wc.DownloadString("https://api.twelvedata.com/time_series?symbol=XAU/USD&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE");
  21.             var timeSeries = JsonSerializer.Deserialize<TimeSeries>(response);
  22.             if (timeSeries.status == "ok")
  23.             {
  24.                 Console.WriteLine("Received symbol: " + timeSeries.meta["symbol"] + ", close: " + timeSeries.values[0]["close"]);
  25.             }
  26.         }
  27.     }
  28. }
  29.  
  1. import org.json.simple.parser.JSONParser;
  2. import org.json.simple.JSONArray;
  3. import org.json.simple.JSONObject;
  4.  
  5. import java.util.Scanner;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8.  
  9. public class Main {
  10.     private static final String REQUEST_URL = "https://api.twelvedata.com/time_series?symbol=XAU/USD&interval=1min&outputsize=12&apikey=YOUR_API_KEY_HERE";
  11.  
  12.     public static void main(String[] args) throws Exception {
  13.         URL requestURL = new URL(REQUEST_URL);
  14.         HttpURLConnection connection = (HttpURLConnection)requestURL.openConnection();
  15.         StringBuffer responseData = new StringBuffer();
  16.         JSONParser parser = new JSONParser();
  17.  
  18.         connection.setRequestMethod("GET");
  19.         connection.setRequestProperty("User-Agent", "twelve_java/1.0");
  20.         connection.connect();
  21.  
  22.         if (connection.getResponseCode() != 200) {
  23.             throw new RuntimeException("Request failed. Error: " + connection.getResponseMessage());
  24.         }
  25.  
  26.         Scanner scanner = new Scanner(requestURL.openStream());
  27.         while (scanner.hasNextLine()) {
  28.             responseData.append(scanner.nextLine());
  29.         }
  30.  
  31.         JSONObject json = (JSONObject) parser.parse(responseData.toString());
  32.         JSONObject meta = (JSONObject) json.get("meta");
  33.         JSONArray values = (JSONArray) json.get("values");
  34.        
  35.         connection.disconnect();
  36.     }
  37. }
  38.  
  1. # install.packages("RcppSimdJson")
  2.  
  3. apikey <- "YOUR_API_KEY_HERE"
  4. qry <- paste0(
  5.         "https://api.twelvedata.com/time_series?",
  6.         "symbol=AAPL&interval=1min&outputsize=12",
  7.         "&apikey=", apikey)
  8. res <- RcppSimdJson::fload(qry)
  9. res
  10.  
  1. # pip install twelvedata[websocket]
  2.  
  3. from twelvedata import TDClient
  4.  
  5. def on_event(e):
  6.     print(e)
  7.  
  8. td = TDClient(apikey="YOUR_API_KEY_HERE")
  9. ws = td.websocket(symbols="XAU/USD", on_event=on_event)
  10. ws.connect()
  11. ws.keep_alive()
  12.  
  1. package main
  2.  
  3. import (
  4.    "fmt"
  5.    "log"
  6.    "github.com/gorilla/websocket"
  7. )
  8.  
  9. const websocketURL = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE"
  10.  
  11. func main() {
  12.    conn, _, err := websocket.DefaultDialer.Dial(websocketURL, nil)
  13.    if err != nil {
  14.       log.Fatal("connect to WebSocket failed:", err)
  15.    }
  16.    defer conn.Close()
  17.  
  18.    subscribeMessage := `{"action": "subscribe", "params": {"symbols": "XAU/USD"}}`
  19.  
  20.    err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))
  21.    if err != nil {
  22.       log.Fatal("message send failed:", err)
  23.    }
  24.  
  25.    for {
  26.       _, message, err := conn.ReadMessage()
  27.       if err != nil {
  28.          log.Fatal("message read failed:", err)
  29.       }
  30.       fmt.Printf("Received: %s\n", message)
  31.    }
  32. }
  1. #include <websocketpp/config/asio_client.hpp>
  2. #include <websocketpp/client.hpp>
  3. #include <cjson/cJSON.h>
  4.  
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <ctime>
  8.  
  9. namespace wlib = websocketpp::lib;
  10. namespace ssl = boost::asio::ssl;
  11.  
  12. typedef websocketpp::client<websocketpp::config::asio_tls_client> wclient;
  13. typedef wlib::shared_ptr<wlib::asio::ssl::context> context_ptr;
  14.  
  15. const char* ENDPOINT = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE";
  16.  
  17. const char* SUBSCRIBE_ACTION = "{"\
  18.     "\"action\": \"subscribe\"," \
  19.     "\"params\": {" \
  20.         "\"symbols\": \"XAU/USD\"" \
  21.     "}" \
  22. "}";
  23.  
  24. int main() {
  25.     wclient::connection_ptr connection;
  26.     wlib::error_code error_code;
  27.     wclient client;
  28.    
  29.     client.set_access_channels(websocketpp::log::alevel::all);
  30.     client.clear_access_channels(websocketpp::log::alevel::frame_payload);
  31.     client.set_error_channels(websocketpp::log::elevel::all);
  32.  
  33.     // Initialize Boost.ASIO
  34.     client.init_asio();
  35.  
  36.     // Set TLS initialize handler
  37.     client.set_tls_init_handler(wlib::bind([](auto* hostname, auto hdl) {
  38.         context_ptr context = wlib::make_shared<ssl::context>(ssl::context::sslv23);
  39.         context->set_verify_mode(ssl::verify_none);
  40.  
  41.         return context;
  42.     }, ENDPOINT, websocketpp::lib::placeholders::_1));
  43.  
  44.     // Is called after the WebSocket handshake is complete
  45.     client.set_open_handler([&client](auto hdl) {
  46.         // Send subscribe action to stream
  47.         client.send(hdl, SUBSCRIBE_ACTION, websocketpp::frame::opcode::text);
  48.     });
  49.  
  50.     // Receive and handle messages from server
  51.     client.set_message_handler([](auto hdl, wclient::message_ptr message) {
  52.         cJSON* json = cJSON_Parse(message->get_payload().c_str());
  53.  
  54.         if (json == nullptr) {
  55.             std::cout << "received invalid JSON: " << std::endl << message->get_payload() << std::endl;
  56.             return;
  57.         }
  58.  
  59.         // Get event type
  60.         cJSON* eventTypeField = cJSON_GetObjectItem(json, "event");
  61.         if (eventTypeField == nullptr) {
  62.             std::cout << "unknown JSON structure" << std::endl;
  63.             return;
  64.         }
  65.  
  66.         // Extract string from event type
  67.         const char* eventType = cJSON_GetStringValue(eventTypeField);
  68.         if (strcmp(eventType, "subscribe-status") == 0) {
  69.             cJSON* statusField = cJSON_GetObjectItem(json, "status");
  70.             const char* status = cJSON_GetStringValue(statusField);
  71.  
  72.             if (strcmp(status, "ok") != 0) {
  73.                 std::cout << "Failed subscribe to stream" << std::endl;
  74.                 return;
  75.             }
  76.  
  77.             cJSON* successField = cJSON_GetObjectItem(json, "success");
  78.             cJSON* failsField = cJSON_GetObjectItem(json, "fails");
  79.  
  80.             // Iterate over the symbols that were successfully subscribed
  81.             for (int idx = 0; idx < cJSON_GetArraySize(successField); idx++) {
  82.                 cJSON* item = cJSON_GetArrayItem(successField, idx);
  83.                 cJSON* symbolField = cJSON_GetObjectItem(item, "symbol");
  84.                 const char* symbol = cJSON_GetStringValue(symbolField);
  85.  
  86.                 std::cout << "Success subscribed to `"<< symbol << "` " << "symbol." << std::endl;
  87.             }
  88.  
  89.             // If we're unable to subscribe to some symbols
  90.             for (int idx = 0; 0 < cJSON_GetArraySize(failsField); idx++) {
  91.                 cJSON* item = cJSON_GetArrayItem(failsField, idx);
  92.                 cJSON* symbolField = cJSON_GetObjectItem(item, "symbol");
  93.                 const char* symbol = cJSON_GetStringValue(symbolField);
  94.  
  95.                 std::cout << "Failed to subscribe on `"<< symbol << "` " << "symbol." << std::endl;
  96.             }
  97.  
  98.             return;
  99.         }
  100.  
  101.         if (strcmp(eventType, "price") == 0) {
  102.             cJSON* timestampField = cJSON_GetObjectItem(json, "timestamp");
  103.             cJSON* currencyField = cJSON_GetObjectItem(json, "currency");
  104.             cJSON* symbolField = cJSON_GetObjectItem(json, "symbol");
  105.             cJSON* priceField = cJSON_GetObjectItem(json, "price");
  106.             time_t time = timestampField->valueint;
  107.  
  108.             std::cout << "[" << std::put_time(gmtime(&time), "%I:%M:%S %p") << "]: ";
  109.             std::cout << "The symbol `" << cJSON_GetStringValue(symbolField) << "` ";
  110.             std::cout << "has changed price to " << priceField->valuedouble << " ";
  111.            
  112.             if (currencyField != nullptr) {
  113.                 std::cout << "(" << cJSON_GetStringValue(currencyField) << ")" << std::endl;
  114.             } else {
  115.                 std::cout << std::endl;
  116.             }
  117.            
  118.             return;
  119.         }
  120.  
  121.         // Free memory of JSON structure
  122.         cJSON_Delete(json);
  123.     });
  124.  
  125.     // New connection to WebSocket endpoint
  126.     connection = client.get_connection(ENDPOINT, error_code);
  127.     if (error_code) {
  128.         std::cout << "Failed connection. Message: " << error_code.message() << std::endl;
  129.         return -1;
  130.     }
  131.  
  132.     // Connect to websocket endpoint
  133.     client.connect(connection);
  134.     client.run();
  135. }
  136.  
  1. using System;
  2. using WebSocket4Net; //https://github.com/kerryjiang/WebSocket4Net
  3.  
  4. namespace TwelveData
  5. {
  6.     class TDWebSocket
  7.     {
  8.         WebSocket ws = new WebSocket("wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE");
  9.  
  10.         static void Main()
  11.         {
  12.             new TDWebSocket().Init();
  13.         }
  14.  
  15.         public void Init()
  16.         {
  17.             ws.Opened += OnOpen;
  18.             ws.Closed += OnClose;
  19.             ws.Error += OnError;
  20.             ws.MessageReceived += OnEvent;
  21.  
  22.             ws.Open();
  23.             Console.ReadLine();
  24.         }
  25.  
  26.         private void OnOpen(object sender, EventArgs e)
  27.         {
  28.             Console.WriteLine("TDWebSocket opened!");
  29.             ws.Send("{\"action\": \"subscribe\", \"params\":{\"symbols\": \"XAU/USD\"}}");
  30.         }
  31.  
  32.         private void OnClose(object sender, EventArgs e)
  33.         {
  34.             Console.WriteLine("TDWebSocket closed");
  35.         }
  36.  
  37.         private void OnError(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
  38.         {
  39.             Console.WriteLine("TDWebSocket ERROR: " + e.Exception.Message);
  40.         }
  41.  
  42.         private void OnEvent(object sender, MessageReceivedEventArgs e)
  43.         {
  44.             Console.WriteLine(e.Message);
  45.         }
  46.     }
  47. }
  48.  
  1. import org.java_websocket.handshake.ServerHandshake;
  2. import org.java_websocket.client.WebSocketClient;
  3.  
  4. import org.json.simple.parser.ParseException;
  5. import org.json.simple.parser.JSONParser;
  6. import org.json.simple.JSONObject;
  7.  
  8. import java.net.URI;
  9.  
  10. public class Main {
  11.     private static final String ENDPOINT = "wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE";
  12.  
  13.     public static void main(String[] args) throws Exception {
  14.         WebSocketClient client = new WebSocketClient(new URI(ENDPOINT)) {
  15.             @Override
  16.             public void onOpen(ServerHandshake handshake) {
  17.                 System.out.println("TDWebSocket opened!");
  18.                 send("{\"action\": \"subscribe\", \"params\":{\"symbols\": \"XAU/USD\"}}");
  19.             }
  20.  
  21.             @Override
  22.             public void onMessage(String message) {
  23.                 JSONParser parser = new JSONParser();
  24.                 try {
  25.                     JSONObject json = (JSONObject) parser.parse(message);
  26.                     System.out.println(json);
  27.                 } catch(ParseException e) {
  28.                     e.printStackTrace();
  29.                 }
  30.             }
  31.  
  32.             @Override
  33.             public void onClose(int status, String reason, boolean remote) {
  34.                 System.out.println("TDWebSocket closed.");
  35.                 this.close();
  36.             }
  37.  
  38.             @Override
  39.             public void onError(Exception e) {
  40.                 e.printStackTrace();
  41.             }
  42.         };
  43.  
  44.         client.connectBlocking();
  45.     }
  46. }
  47.  
  1. # install.packages("websocket")
  2.  
  3. library(websocket)
  4.  
  5. ws <- WebSocket$new("wss://ws.twelvedata.com/v1/quotes/price?apikey=YOUR_API_KEY_HERE")
  6. ws$onOpen(function(event) {
  7.     cat("TDWebSocket opened!\n")
  8. })
  9. ws$onClose(function(event) {
  10.     cat("TDWebSocket closed with code ", event$code,
  11.         " and reason ", event$reason, "\n", sep = "")
  12. })
  13. ws$onError(function(event) {
  14.     cat("TDWebSocket ERROR: ", event$message, "\n")
  15. })
  16. ws$onMessage(function(event) {
  17.     cat("Received event:", event$data, "\n")
  18. })
  19.  
  20. ws$send('{"action": "subscribe", "params":{"symbols": "XAU/USD"}}')
  21.  
 

It’s all about commodities data

Easily access a wide range of commodities prices with Twelve Data API.

Basic Reference data

Commodities pairs list, descriptions, and details.

Learn more
Basic Currency conversion

Convert commodities to currencies with a specified amount.

Learn more
Grow Market data

Real-time pricing data and years of historical prices via time series, quote, and other endpoints.

Learn more
Grow Technical indicators

Extensive collection of indicators, ready to be used for technical analysis of any commodity.

Learn more

Curious, but not a developer?

Leverage TwelveData spreadsheets add-ins.
Integrate data into your workflow - without coding.

Designed
to scale.
70,000,000+
API requests per day
60+
Commodities available
65,000+
Events per second
FAQ

Questions? Answers.

Twelve Data Commodities API provides real-time and historical access to commodities pricing data. It’s designed for developers, businesses, and financial institutions who need reliable, up-to-date information on a wide range of commodities like precious metals, agricultural products, energies, and more, all delivered via a flexible REST API. With seamless integration and low latency, it’s the perfect solution for building financial applications, trading bots, or managing international transactions.

Yes, Twelve Data Commodities API delivers real-time data directly from trusted market sources. You’ll receive up-to-the-minute pricing on commodities and exchange rates, ensuring your financial applications and trading platforms stay in sync with the latest market movements.

Yes, the API provides access to both real-time and historical data. You can query pricing information from the past, allowing you to track trends and make informed decisions based on long-term data analysis.

Twelve Data API sources its data from trusted market providers and market makers, ensuring high accuracy and reliability. With 99.9% uptime and low-latency response times, you can count on getting the data you need, exactly when you need it.

With Twelve Data Commodities API, you can access a broad array of commodities, including:

  • Precious metals like gold, silver, and platinum.
  • Industrial metals such as copper, aluminum, and zinc.
  • Energy products such as crude oil and natural gas.
  • Agricultural commodities like corn, wheat, and coffee.
  • Livestock including cattle and hogs.

Twelve Data API offers flexible pricing plans starting at just $29 per month. Whether you’re a developer, a small business, or a large financial institution, you can choose the plan that fits your needs and budget, with access to both real-time and historical data.

Yes, you can start with our free tier, which offers limited access to real-time and historical data. It’s the perfect way to test the API and explore its features before upgrading to a paid plan.

Integration is straightforward with Twelve Data API. It’s built with developers in mind, offering clear documentation, SDKs, and sample code to help you get started quickly. Whether you’re building applications in Python, JavaScript, or PHP, you’ll find integration fast and easy.

Twelve Data API is used across a variety of industries and applications, including:

  • Financial analysts using real-time data for market analysis.
  • Developers building commodities trading systems.
  • Businesses requiring commodities currency conversion for international transactions.
  • Traders making quick, informed decisions based on real-time market data.

Yes, we offer comprehensive support for all our API users. Whether you need help with integration or have technical questions, our dedicated support team is here to assist you every step of the way.

Yes, we provide SDKs and code libraries for a range of programming languages, including Python. These libraries simplify integration and make it easier to start using the API in your projects.

Absolutely. Twelve Data API is designed to integrate seamlessly with other platforms, such as Excel, Google Sheets, and various trading platforms. With flexible endpoints and easy-to-use connectors, you can bring real-time data into the tools you already use.

Yes, Twelve Data provides access to a wide range of financial data beyond commodities, including stocks, ETFs, mutual funds, forex, indices, cryptocurrencies, and more. You can build applications that integrate multiple financial data sources from a single API.

Yes, Twelve Data API is built to scale. Whether you’re a small startup or a large enterprise, our API can handle your data needs, offering flexible plans and high request limits to accommodate growth.

Getting started is simple. Just sign up on our website, choose the plan that best suits your needs, and access our detailed documentation. You’ll be able to start integrating and using the API in just a few minutes. If you need help, our support team is always available to assist.

Working with Twelve Data
Twelve Data guides you through every step of your journey in the knowledge center.
Have other questions?
If you have more questions, contact us so we can help.