DEV Community

Cover image for Access The Latest Gold And Silver Prices With The Precious Metals API
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on

Access The Latest Gold And Silver Prices With The Precious Metals API

In today's ever-changing financial landscape, understanding the current prices of precious metals is essential for everyone, from investors to software developers and hobbyists alike. This guide will teach you how to retrieve gold and silver prices using the precious metals API.

This tutorial provides you with the resources to obtain accurate, up-to-the-minute information, regardless of your level of experience. It thoroughly explains how to get spot prices for precious metals data through TraderMade's REST API using various programming languages.

Why Precious Metals Data Matters

For hundreds of years, gold, silver, and other precious metals have been highly valued because they are rare and possess inherent worth. Precise pricing information for these metals is essential for making decisions in investment, manufacturing, jewelry, and financial analysis. Knowing how to retrieve and interpret data from the Precious Metals Prices API is necessary for informed decisions in these fields.

Methods to Receive Real-Time Financial Data

APIs

What is an API? An Application Programming Interface (API) enables you to obtain current financial data from various platforms programmatically.

  • Sign Up: To obtain an API key, you must register on the provider's website.

  • Choose a Plan: Pick a free or paid subscription that fits your data requirements.

  • Access Data: Then, use your API key to request the data with your chosen programming language, such as Python or JavaScript.

Python

This Python code uses the requests library to fetch real-time Gold prices from an API. The same request also retrieves Silver and Platinum prices, as demonstrated.

import requests
from pprint import PrettyPrinter

url = "https://marketdata.tradermade.com/api/v1/live"
currency = "XAUUSD,XAGUSD,XPTUSD,XPDUSD"
api_key = "API_KEY"  # Replace with your actual API key
querystring = {"currency": currency, "api_key": api_key}

response = requests.get(url, params=querystring)

# Check if the request was successful
if response.status_code == 200:
    pp = PrettyPrinter()
    pp.pprint(response.json())
else:
    print(f"Error {response.status_code}: {response.text}")
Enter fullscreen mode Exit fullscreen mode

Java Programming

This Java program uses an HTTP GET request to get the Gold price data from the API. You can also expand it to fetch silver and other live precious metal prices. The "FetchMarketData" class sets up the API's URL and necessary parameters, like currency codes and the API key.

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

public class RESTClient {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {

            HttpGet request = new HttpGet("https://marketdata.tradermade.com/api/v1/live
currency=XAUUSD&api_key=YOUR_API_KEY");
            CloseableHttpResponse response = httpClient.execute(request);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // return it as a String
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                    JSONObject obj = new JSONObject(result);
                    JSONArray quotes = obj.getJSONArray("quotes");
                    System.out.println(quotes.toString());

                    for (int i = 0; i < quotes.length(); i++) {
                        JSONObject quote = quotes.getJSONObject(i);
                        System.out.println(" Quote " + quote.getString("base_currency") +
quote.getString("quote_currency") + " " + quote.getFloat("bid") + " " + quote.getFloat("ask"));
                    }

                }

            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Node.js Programming

This Node.js script uses the Axios library to get real-time Gold price data from the live API endpoint.

const axios = require('axios');
const util = require('util');

const url = "https://marketdata.tradermade.com/api/v1/live";
const currency = "XAUUSD";
const apiKey = "API_KEY";  // Replace with your actual API key

async function fetchMarketData() {

    try {
        const response = await axios.get(url, {
            params: {
                currency: currency,
                api_key: apiKey
            }
        });

        if (response.status === 200) {
                console.log(util.inspect(response.data, { depth: null, colors: true }));
            } else {
                  console.log("Error");
              }

          } catch (error) {
              console.error("Error");
          }

      }

      fetchMarketData();
Enter fullscreen mode Exit fullscreen mode

C++ Programming

This C++ code snippet demonstrates how to get Gold prices from the live API endpoint using the libcurl library. The code starts by including the essential libcurl functions and standard input/output headers.

#include <curl/curl.h>
#include <stdio.h>

int main(void)
{
    CURL *curl;
    CURLcode res;

    // URL to be requested

    const char *url = "https://marketdata.tradermade.com/api/v1/live?currency=XAUUSD&api_key=API_KEY";

    // Initialize global curl environment
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Initialize curl session
    curl = curl_easy_init();

    if(curl) {

        // Set URL
        curl_easy_setopt(curl, CURLOPT_URL, url);

        // Perform the request
        res = curl_easy_perform(curl);

        // Check for errors
        if(res != CURLE_OK) {

            fprintf(stderr, "Request failed: %s
", curl_easy_strerror(res));
        } else {
            printf("Request was successful!
");
        }


        // Cleanup curl session
        curl_easy_cleanup(curl);
    }

    // Cleanup curl global environment
    curl_global_cleanup();

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This tutorial explains how to access and use precious metals data from a JSON API using various programming languages. By using these methods, you can easily add live market data for Gold, Silver, Platinum, and Palladium prices into your applications and workflows.

For more examples in other programming languages and information on live and historical rates for world currencies, check our documentation page.

Also, follow our original tutorial published on our website: Get Live Gold and Silver Prices Instantly with Precious Metals API

You can explore more by reading the blog: How the Gold and Silver Prices Are Determined

Top comments (0)

OSZAR »