DEV Community

Cover image for Comprehensive Guide to Accessing Major Hong Kong and US Futures APIs: TradingView Charting Strategies
San Si wu
San Si wu

Posted on

Comprehensive Guide to Accessing Major Hong Kong and US Futures APIs: TradingView Charting Strategies

Recently, I helped a friend set up an automated trading system for Hong Kong and US futures, and I encountered quite a few pitfalls with API integration—for example, not paying attention to the fee structure when selecting an API. It worked fine during initial testing, but in live trading, the transaction fees were much higher than expected. Also, overlooking data latency issues led to delayed strategy signals.

So, I've compiled a complete process guide, from basic concepts to hands-on code examples, all based on real experience. Whether you're into quantitative trading or just need futures data for analysis, following this guide will help you avoid many detours.

I. First, Understand the Basics: What Are Futures and Futures APIs?

Let's clear up a common misconception: many people confuse futures with stocks. The core difference is "agreeing on the future"—futures are standardized contracts to buy or sell a specific quantity of a particular commodity (like crude oil or gold) or financial asset (like the Hang Seng Index or Nasdaq Index) at a predetermined price on a specific future date.

A futures API is simply an "interface" provided by futures brokers or data service providers. Through this interface, we can achieve three core functions via code without manually logging into trading software:

  • Retrieve market data (e.g., real-time transaction prices, trading volume, open interest, and historical K-line data);

  • Submit trading orders (buy, sell, close positions, or even set conditional orders);

  • Query account information (positions, available funds, profit and loss details).

Without an API, quantitative strategies are just "talk on paper"—you can't rely on manually watching the market and placing orders, right? It's inefficient and prone to errors.

II. What Are the Major Hong Kong and US Futures APIs? Divided into Three Categories by Use

The API providers in the Hong Kong and US futures markets mainly fall into two types: one is legitimate futures brokers (like Interactive Brokers or Futu), whose APIs can both fetch data and execute trades; the other is specialized data providers (like Quandl or IEX Cloud), which mainly provide market data and do not support direct trading.

Divided into three categories by use, making it easier to match your needs:

1. Comprehensive APIs (Both Trading and Data Fetching)

These are the most commonly used, suitable for friends who want to implement trading strategies directly. I'll focus on two mainstream ones:

① Interactive Brokers API: Covers the most comprehensive Hong Kong and US futures, from Hang Seng Index futures and FTSE China A50 to US crude oil and gold futures. Supports REST API and WebSocket (WebSocket is better for real-time market data with lower latency). The documentation is detailed, but initial setup is a bit complex, requiring API permission applications and trading permission settings.

② Futu Securities API: More friendly to domestic users, with detailed Chinese documentation and strong community support, clear setup process. Core coverage includes Hong Kong stocks, US stocks, and major futures varieties in the Singapore market, such as Hang Seng Index, Nasdaq 100 Index, FTSE China A50, and other popular ones. Real-time market data and trading functions are stably covered, suitable for beginners. The downside is incomplete coverage of some niche futures varieties (like some European futures), and it requires pairing with the FutuOpenD gateway program.

2. Pure Data APIs (Data Only, No Trading Support)

Suitable for backtesting, data analysis, for friends who don't need live trading:

  • Quandl: Extremely comprehensive historical data, including Hong Kong and US futures' historical K-lines and open interest reports. The free quota is sufficient for personal use, with charges per item beyond the quota. The downside is slightly higher real-time market latency (about 10-15 minutes), not suitable for real-time trading.

  • IEX Cloud: Good quality real-time market data with low latency (millisecond level), supports data fetching by minute or hour granularity. Tiered pricing, more cost-effective with higher trading volume, suitable for analysis scenarios requiring high real-time market data.

  • iTick Futures API: Specially focused on Hong Kong and US futures data API, covering popular varieties like Hang Seng Index, US crude oil, gold, etc. Low real-time market latency (hundred-millisecond level), complete historical data granularity (minute/hour/day lines). Clear Chinese documentation, supports multiple languages like Python/Java, free version meets personal testing needs, paid version offers high cost-performance, suitable for individuals and small to medium teams needing stable futures data.

Of course, there are also Bloomberg, TradingView, and other super-comprehensive data APIs, but they are expensive and suitable for large institutional users; not recommended for individuals.

III. How to Choose a Futures API? Don't Fall into These 4 Pitfalls

Choosing an API isn't about picking the most famous one, but matching your needs. Here are 4 core evaluation dimensions I've summarized from personal experience, proven practical:

1. Clarify the Purpose First: Trading or Data Analysis?

For live trading, prioritize broker-provided APIs (like Interactive Brokers or Futu) to avoid combining "data API + third-party trading API," which can lead to integration issues and potential security risks. If it's just for backtesting or strategy linkage (e.g., with TradingView), choose pure data APIs like Quandl or iTick for high cost-performance.

2. Check Variety Coverage: Does It Include the Futures You Want to Trade?

For example, if you want to trade Hang Seng Index futures, confirm if the API covers HKEX varieties; for US crude oil futures, it needs to cover NYMEX varieties. Many APIs clearly list supported exchanges; make sure to check before integrating to avoid discovering missing varieties after setup.

3. Pay Attention to Costs: Calculate Both Transaction Fees and API Fees

Some APIs seem free but hide costs in transaction fees—for example, some brokers' APIs have slightly higher per-trade fees than manual trading. Some data APIs charge heavily after the free quota. Suggest calculating your "monthly expected usage" first, then compare different APIs' pricing models to avoid budget overruns later.

4. Ease of Use and Stability: Beginners Prioritize Chinese Documentation

Beginners shouldn't start with Interactive Brokers' API (complex setup); begin with Futu's API, which has understandable Chinese documentation and comprehensive community support, making problem-solving easy. Also, stability is crucial—API lag or disconnection during live trading can cause huge losses; check the provider's reputation for frequent downtimes before choosing.

IV. Python Code Integration Example: Strategy Linked with TradingView Charts (Beginner-Friendly)

Finally, the hands-on part: Use Python to implement "fetch futures data + generate strategy signals + link to TradingView charts," with super-detailed steps that even beginners can follow. The core logic is: Use API to fetch market data, run strategy locally to generate signals, then push signals to TradingView for visual display.

1. Preliminary Preparation: API Permissions and TradingView Setup

  • Data API Preparation: Register an iTick account (directly on the official website), enter the console to view the API Key (free version sufficient for testing);
  • TradingView Setup: Log in to TradingView, create a custom chart (e.g., select US crude oil futures contract), enable Webhook functionality (for receiving Python-pushed strategy signals), record the Webhook URL;
  • Environment Preparation: Ensure local installation of Python 3.7+, and install required dependency libraries later.

2. Install Dependency Libraries

Need to install requests (for pushing signals to TradingView), pandas (for data processing), directly use pip to install:

pip install requests==2.31.0
pip install pandas==2.1.4
pip install python-dotenv  # For managing API Key and Webhook URL
Enter fullscreen mode Exit fullscreen mode

3. Code Implementation: Fetch Data + Generate Strategy Signals + Link Charts

The following code includes three core functions:

  • 1. Fetch US crude oil futures historical + real-time market data via iTick Futures API;
  • 2. Generate buy/sell signals using a simple moving average crossover strategy;
  • 3. Push signals to TradingView to achieve strategy-chart linkage.

Note: Replace the API Key and Webhook URL in the code with your own.

from datetime import datetime, timedelta
import pandas as pd
import requests
import os
from dotenv import load_dotenv

# Load secrets and URL (avoid hardcoding for security)
load_dotenv()
ITICK_TOKEN = os.getenv('ITICK_TOKEN')  # iTick API token
TRADINGVIEW_WEBHOOK_URL = os.getenv('TRADINGVIEW_WEBHOOK_URL')

# Define API headers
headers = {
    "accept": "application/json",
    "token": ITICK_TOKEN
}

# 1. Fetch US Crude Oil Futures Data (Contract Code: CL, Region: US)
# ① Fetch Historical Daily Data (Last 1 Year, limit=365 covers about 1 year)
url_history = "https://api.itick.org/future/kline?region=US&code=CL&kType=8&limit=365"
response_history = requests.get(url_history, headers=headers)
history_data = response_history.json().get('data', [])

# Convert to DataFrame, keep core fields (assuming data is newest to oldest, reverse to sort oldest to newest)
history_data.reverse()  # Ensure oldest to newest for rolling calculations
df_history = pd.DataFrame(history_data)
df_history = df_history[['t', 'o', 'h', 'l', 'c', 'v']]
df_history.rename(columns={'t': 'date', 'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close', 'v': 'volume'}, inplace=True)
df_history['date'] = pd.to_datetime(df_history['date'], unit='ms')  # Convert timestamp to datetime
df_history.set_index('date', inplace=True)
print("US Crude Oil Futures Historical Daily Data (Last 5 Rows):")
print(df_history.tail())

# ② Fetch Real-Time Market Data (Using Real-Time Quote API)
url_realtime = "https://api.itick.org/future/quote?region=US&code=CL"
response_realtime = requests.get(url_realtime, headers=headers)
realtime_data = response_realtime.json().get('data', {})
latest_close = realtime_data.get('ld')  # ld is the latest price, used as close
latest_date = datetime.fromtimestamp(realtime_data.get('t', 0) / 1000).strftime('%Y-%m-%d')  # Get date from timestamp
print(f"\nUS Crude Oil Futures Real-Time Price: {latest_close} ({latest_date})")

# Merge Historical and Real-Time Data (For Strategy Calculations)
df_strategy = df_history.copy()
# If today's data is not updated, supplement with real-time data (using real-time OHLCV, note ld as close, o/h/l/v available)
if latest_date not in df_strategy.index.strftime('%Y-%m-%d'):
    new_row = pd.DataFrame({
        'open': [realtime_data.get('o')],
        'high': [realtime_data.get('h')],
        'low': [realtime_data.get('l')],
        'close': [latest_close],
        'volume': [realtime_data.get('v')]
    }, index=[pd.to_datetime(latest_date)])
    df_strategy = pd.concat([df_strategy, new_row])

# 2. Simple Moving Average Crossover Strategy: Generate Buy/Sell Signals
# Calculate 5-day and 20-day Moving Averages
df_strategy['MA5'] = df_strategy['close'].rolling(window=5).mean()
df_strategy['MA20'] = df_strategy['close'].rolling(window=20).mean()
# Generate Signals: 5-day MA crossing above 20-day MA for Buy (1), below for Sell (-1), no signal as 0
df_strategy['Signal'] = 0
df_strategy.loc[df_strategy['MA5'] > df_strategy['MA20'], 'Signal'] = 1
df_strategy.loc[df_strategy['MA5'] < df_strategy['MA20'], 'Signal'] = -1
# Remove NaN values from initial MA calculations
df_strategy = df_strategy.dropna()

print("\nData with Moving Averages and Strategy Signals (Last 5 Rows):")
print(df_strategy[['close', 'MA5', 'MA20', 'Signal']].tail())

# 3. Extract Latest Strategy Signal, Push to TradingView
latest_signal = df_strategy['Signal'].iloc[-1]
signal_date = df_strategy.index[-1].strftime('%Y-%m-%d')
# Construct Signal Data (Compatible with TradingView Webhook Format)
signal_data = {
    "symbol": "CME/CL",  # TradingView-recognizable US Crude Oil Futures Identifier
    "date": signal_date,
    "signal": "BUY" if latest_signal == 1 else "SELL" if latest_signal == -1 else "HOLD",
    "close_price": round(df_strategy['close'].iloc[-1], 2),
    "MA5": round(df_strategy['MA5'].iloc[-1], 2),
    "MA20": round(df_strategy['MA20'].iloc[-1], 2),
    "realtime_flag": "Yes" if signal_date == latest_date else "No"
}

# Send POST Request to TradingView Webhook
try:
    response = requests.post(
        url=TRADINGVIEW_WEBHOOK_URL,
        json=signal_data,
        headers={"Content-Type": "application/json"}
    )
    if response.status_code == 200:
        print(f"\nSignal Push Successful! Latest Signal: {signal_data['signal']} ({signal_data['date']}, Real-Time Data: {signal_data['realtime_flag']})")
    else:
        print(f"\nSignal Push Failed, Status Code: {response.status_code}, Response Content: {response.text}")
except Exception as e:
    print(f"\nSignal Push Exception: {str(e)}")

# 4. Optional: Save Data Locally for Later Review
df_strategy.to_csv('crude_oil_strategy_data_itick.csv')
print("\nStrategy Data Saved to crude_oil_strategy_data_itick.csv File")
Enter fullscreen mode Exit fullscreen mode

4. Key Notes

  • Data Identifiers: iTick uses unified simplified identifiers for futures varieties, e.g., "CL" for US crude oil, "HSI" for Hang Seng Index; specific variety codes can be queried on the iTick official website;
  • Strategy Logic: This uses a simple 5-day/20-day moving average crossover strategy; you can replace it with your own (e.g., MACD, RSI strategies) by modifying the "generate signals" part of the code;
  • TradingView Linkage: Pushed signals will display on TradingView charts; you can add "alerts" in the chart to automatically notify on BUY/SELL signals;
  • Free Quota: iTick free version's daily real-time data request limit is sufficient for personal testing; upgrade to paid version if exceeded.

V. Final Summary

Accessing Hong Kong and US futures APIs isn't that complicated; the core is "choosing the right tool + finding the right method." For trading, choose broker APIs like Interactive Brokers or Futu; for strategy linkage with TradingView, use iTick to fetch data directly, and modify the parameters in the code from this article to get it running.

I hope my experience helps you avoid some detours. If you have any questions, chat in the comments section; I'll try to answer. Wishing everyone a quick API setup, lying back watching TradingView auto-generate strategy signals!

Reference Documentation: https://docs.itick.org/rest-api/future/future-kline
GitHub: https://github.com/itick-org/

Top comments (0)