DEV Community

Cover image for How to Quickly Access Precious Metal Futures Real-Time Quotes API: Python Practical Guide
San Si wu
San Si wu

Posted on

How to Quickly Access Precious Metal Futures Real-Time Quotes API: Python Practical Guide

In precious metal futures trading and quantitative analysis, real-time market data is the core foundation. Whether it's gold, silver, or other precious metals, or energy futures like crude oil and natural gas, timely access to main contracts and real-time quotes provides critical support for trading decisions. This article uses Python as the tool to guide you through quickly integrating a precious metal futures real-time quotes API, covering key varieties and main contract selection, with complete runnable code.

I. Preliminary Preparation: Environment and API Selection

1. Development Environment Setup

This practical guide is based on Python 3.6+ versions. You need to install the core dependency libraries in advance:

  • requests: For sending HTTP requests to call API interfaces;
  • pandas: For data parsing, filtering, and formatting to facilitate subsequent analysis.

Run the installation command directly in the terminal:

pip install requests pandas
Enter fullscreen mode Exit fullscreen mode

2. API Selection Recommendations

When choosing an API, focus on three key points:

  • 1. Variety coverage (must include gold, silver, crude oil, natural gas);
  • 2. Real-time performance (latency ≤2 seconds);
  • 3. Support for main contract queries;

The code examples in this article use the iTick API as an example (you need to register an account and obtain an API token in advance). It supports varieties such as gold (AU), silver (AG), crude oil (CL), and natural gas (NG), and can directly return main contract quotes.

II. Python Code Practice: Integrating Real-Time Quotes and Main Contract Filtering

1. Core Code Implementation

The following code fully implements the entire process of "API call - data parsing - main contract filtering - result output." You can directly replace the API token and run it:

import requests
import pandas as pd
from datetime import datetime

def get_precious_metal_quote(token):
    # API base URL
    base_url = "https://api.itick.org/future/quotes"
    # Variety configuration: grouped by region
    symbol_groups = {
        "CN": "AU,AG",  # Gold, Silver
        "US": "CL,NG"   # Crude Oil, Natural Gas
    }

    quote_list = []

    headers = {
        "accept": "application/json",
        "token": token
    }

    try:
        for region, codes in symbol_groups.items():
            # Build request parameters
            params = {
                "region": region,
                "codes": codes
            }

            # Send GET request
            response = requests.get(base_url, params=params, headers=headers, timeout=5)
            response.raise_for_status()  # Raise HTTP request exceptions
            data = response.json()

            # Data validation
            if data["code"] != 0:
                print(f"API call failed for {region}: {data.get('msg', 'Unknown error')}")
                continue

            quotes_data = data["data"]

            for code, quote_data in quotes_data.items():
                # Extract key fields and adapt to the original format
                quote = {
                    "symbol": quote_data["s"],
                    "contract": f"{quote_data['s']} Main",  # Assume it returns the main contract
                    "price": quote_data["ld"],
                    "change": f"{quote_data['ch']} ({quote_data['chp']}%)",
                    "volume": quote_data["v"],
                    "update_time": datetime.fromtimestamp(quote_data["t"] / 1000).strftime("%Y-%m-%d %H:%M:%S")
                }
                quote_list.append(quote)

        if not quote_list:
            return None

        # Convert to DataFrame
        df = pd.DataFrame(quote_list)

        # Since the API directly returns main quotes, no additional filtering is needed
        result_df = df[[
            "symbol", "contract", "price", "change", "volume", "update_time"
        ]]

        return result_df

    except requests.exceptions.RequestException as e:
        print(f"Network request exception: {e}")
        return None
    except Exception as e:
        print(f"Data processing exception: {e}")
        return None

# Main program
if __name__ == "__main__":
    # Replace with your API token
    TOKEN = "your_token_here"
    # Get market quotes
    market_quote = get_precious_metal_quote(TOKEN)
    if market_quote is not None:
        print("Precious Metal Futures Main Contract Real-Time Quotes:")
        print(market_quote.to_string(index=False))
    else:
        print("Failed to retrieve quote data")
Enter fullscreen mode Exit fullscreen mode

2. Key Code Explanations

  • Variety code adaptation: The iTick API uses region and codes parameters, for example, CN&codes=AU,AG for gold and silver, US&codes=CL,NG for crude oil and natural gas. Refer to the API documentation to confirm specific codes;

  • Main contract filtering: The quotes returned by the iTick API usually correspond to the main or continuous contracts. If precise main contracts are needed, adjust the codes according to the documentation (e.g., use continuous contract codes like AU0);

  • Exception handling: Added timeout control and HTTP exception capture to prevent program crashes due to network fluctuations or API restrictions.

3. Example Run Results

After successful execution, it will output the main contract real-time quotes in the following format (data is simulated):

symbol contract  price         change volume         update_time
    AU  AU Main  480.5  2.3 (0.48%)  15000 2023-10-01 14:30:00
    AG  AG Main  25.8  -0.2 (-0.77%) 12000 2023-10-01 14:30:00
    CL  CL Main  85.2  1.5 (1.79%)   20000 2023-10-01 14:30:00
    NG  NG Main  3.45 0.05 (1.47%)  18000 2023-10-01 14:30:00
Enter fullscreen mode Exit fullscreen mode

III. Key Considerations

1. API Call Specifications

Free APIs usually have call frequency limits (e.g., ≤10 times per minute), so avoid high-frequency requests that could lead to account bans; Commercial APIs must comply with paid plan agreements and enable request rate limiting (use time.sleep() to control call intervals).

2. Data Accuracy Validation

Real-time quotes may have network delays or data anomalies. It is recommended to add validation logic: for example, check if the latest price is within a reasonable range (e.g., gold price won't suddenly drop to 100 yuan/gram), and ensure volume is non-negative to confirm data usability.

3. Handling Main Contract Switches

Main contracts switch over time (usually 1-2 months before contract expiration). Regularly update contract codes or use the API's continuous contract feature to dynamically obtain them, avoiding retrieval of expired contract quotes.

IV. Expansion Directions

Based on the real-time quotes integrated in this guide, you can further implement:

  • Quote visualization: Use matplotlib or plotly to draw candlestick charts or real-time price trend charts;

  • Alert mechanisms: Send email or SMS reminders when prices break set thresholds (e.g., gold ≥490 yuan/gram);

  • Strategy backtesting: Combine historical quote data to verify the effectiveness of trading strategies based on real-time quotes.

Summary

Integrating precious metal futures real-time quotes API with Python focuses on selecting the right API interface, accurately parsing data, and filtering main contracts. The code provided in this article can be directly adapted to most mainstream APIs, with minor adjustments for retrieving quotes of varieties like gold, silver, crude oil, and natural gas. You can optimize functions based on actual needs for more flexible quote analysis and trading assistance.

Reference Documentation: https://docs.itick.org/rest-api/future/future-quote

GitHub: https://github.com/itick-org/

Top comments (0)