DEV Community

Cover image for How to Build Quantitative Trading Strategies Using a Free Stock API
San Si wu
San Si wu

Posted on

How to Build Quantitative Trading Strategies Using a Free Stock API

As a retail investor with years in the market and plenty of hard-learned lessons, I used to trade stocks purely on gut feeling a couple of years ago—either chasing highs and getting trapped at the peak, or missing the best exit and regretting it later. After messing around for over six months without finding a consistent rhythm, while wasting huge amounts of time and energy, I stumbled upon quantitative trading. That’s when I finally realized: “Let data speak, let rules discipline”—this is the real key to reducing risk and improving efficiency. But at first, I was completely put off by the myths of “high barriers to quant trading” and “expensive APIs,” until I discovered this free stock API. That’s when I truly took my first step into quant trading. Today, I’m sharing this battle-tested, practical experience with no reservations—for beginners who are as lost as I once was.

Let me be upfront: as a beginner in quant, you don’t need to chase complex machine learning models right away, and you definitely don’t need to spend big money on paid APIs. The free tier is more than enough to build basic strategies, connect real-time data, and run backtests. Only when you have higher needs later (e.g., high-frequency trading or Level 2 depth data) should you consider upgrading to paid plans. This is the most cost-effective and efficient path to getting started with quant trading, based on my own testing.

Today we’re keeping it real—no fluff, just my personal hands-on breakdown. I’ll walk you through using this free stock API to build a simple, beginner-friendly quantitative trading strategy, while avoiding all the pitfalls I hit along the way. Everything here is practical and implementable.

1. Preparation

The biggest worry for beginners is “the tech is too complicated” or “registration is a hassle.” But iTick’s free tier eliminates those concerns entirely—it takes just 5 minutes to get set up, zero barrier to entry, and the free version is especially friendly for individual developers and newcomers to quant trading.

Steps:

  1. Go to the iTick website, click “Get Started” in the top right, and register with your personal email—no complicated personal information required, one-step process.
  2. After registering, go straight to the dashboard, find the “API Management” section, and you’ll see your API Token. This token is crucial—you’ll need it for real-time data access and all API calls. Save it securely and never share it.
  3. Key details on free tier permissions (must-read for beginners): Supports basic real-time quotes for US stocks, Hong Kong stocks, A-shares, and other markets, plus minute-level to daily historical K-line data. Rate limit is 10 requests/minute—plenty for beginners building simple strategies (e.g., trend following, moving average crossover). It’s permanently free with no expiration, very beginner-friendly.

2. Connecting Real-Time Data

The core of quantitative trading is simple: get market data in real time → apply preset strategy logic → generate trading signals. The very first and most critical step is real-time data access—if latency is high, your strategy judgments become inaccurate and can lead to unnecessary losses. iTick’s free API supports both RESTful and WebSocket push methods with very low latency (<100 ms for major markets), perfectly suitable for non-ultra-high-frequency strategies and easy for beginners to handle.

I used Python throughout (the top choice for beginners—simple syntax, tons of online resources, quick solutions when you get stuck). Below are ready-to-run code examples. Just replace with your own API Token, copy-paste, and run to get real-time US stock data. Every line has detailed comments—take your time if something looks unfamiliar.

First, install the two required libraries (run in your terminal):
pip install requests websocket-client
These are standard Python libraries for API calls and real-time streaming—installation is straightforward.

1. RESTful API for Real-Time Quotes

import requests

# Replace with your own iTick API Token
api_token = "YOUR_API_TOKEN"

# Specify the stock (using Apple as example; format: region.US&code=TICKER)
url = "https://api.itick.org/stock/quote?region=US&code=AAPL"

# Headers—must include token or the call will fail
headers = {"accept": "application/json", "token": api_token}

# Send request and get real-time data
response = requests.get(url, headers=headers)
data = response.json()

# Print key real-time fields (beginners can reference these directly)
print("Stock Name:", data["s"])
print("Latest Price:", data["ld"])
print("Volume:", data["v"])
print("Change %:", data["chp"])
Enter fullscreen mode Exit fullscreen mode

Real-world result: Running this instantly returns Apple’s current price, volume, and percentage change with very low latency—basically in sync with regular trading apps. Beginners should start with a single stock to get familiar with the data structure before expanding to multiple.

2. WebSocket for Real-Time Streaming

If your strategy needs to monitor multiple stocks continuously (e.g., Apple, Tesla, Nvidia), WebSocket is better—it pushes updates in real time without repeated polling, more efficient and time-saving.

import websocket
import json

# Replace with your own iTick API Token
api_token = "YOUR_API_TOKEN"

def on_message(ws, message):
    data = json.loads(message)
    print(f"Stock: {data['s']} | Price: {data['ld']} | Change %: {data['chp']}%")

def on_open(ws):
    # Subscribe to multiple US stocks (Apple, Tesla, Nvidia—modify as needed)
    subscribe_msg = {
        "action": "subscribe",
        "types": "quote",
        "params": "US$AAPL,US$TSLA,US$NVDA",
    }
    ws.send(json.dumps(subscribe_msg))

# Fixed WebSocket URL—don’t modify
ws = websocket.WebSocketApp("wss://api.itick.org/stock",
                            on_open=on_open,
                            on_message=on_message)

# Keep running to receive pushes (close terminal to stop)
ws.run_forever()
Enter fullscreen mode Exit fullscreen mode

3. Building a Real Strategy

Once real-time data is connected, you can start building the actual strategy. Beginners should begin with the classic “Dual Moving Average Crossover”—simple logic, easy to understand, controllable risk, and a favorite starting point for many experienced quant traders. Combined with iTick’s real-time and historical data, it’s quick to implement without advanced coding skills.

Quick breakdown of the dual MA strategy (no complex formulas—just understand the idea):

Choose two moving averages—a short-term (e.g., 20-day) and a long-term (e.g., 60-day). Trading signals come from crossovers:

  • Short-term MA crosses above long-term MA (“Golden Cross”) → bullish trend → Buy signal
  • Short-term MA crosses below long-term MA (“Death Cross”) → bearish trend → Sell signal

Using iTick data, the program automatically detects these crossovers, removing emotional bias—this is the biggest advantage of quant: rational, disciplined, no chasing or panic selling.

Strategy Steps

  1. Get historical data: Pull a stock’s historical K-lines via iTick API (e.g., last ~3 years daily data) for backtesting—essential to validate past performance before live use.
  2. Calculate MAs: Use Python’s talib library to compute 20-day and 60-day simple moving averages.
  3. Generate signals: Automatically detect golden/death crosses.
  4. Real-time monitoring: Use WebSocket to watch price; alert on signal (beginners: alerts only, no auto-trading).

Complete Practical Code

import requests
import websocket
import json
import talib
import pandas as pd

# ---------------------- Step 1: Get historical K-line data (for backtesting) ----------------------
api_token = "YOUR_API_TOKEN"

# Apple last ~100 daily bars (adjust limit; kType="8" = daily)
url = "https://api.itick.org/stock/?region=US&code=AAPL&kType=8&limit=100"
headers = {"accept": "application/json", "token": api_token}
response = requests.get(url, headers=headers)
history_data = response.json()

# Convert to DataFrame for easy processing
df = pd.DataFrame(history_data["data"], columns=["date", "open", "high", "low", "close", "volume"])
df[["open", "high", "low", "close", "volume"]] = df[["open", "high", "low", "close", "volume"]].astype(float)

# Compute 20-day and 60-day MAs (adjust periods if desired)
df["MA20"] = talib.SMA(df["close"], timeperiod=20)
df["MA60"] = talib.SMA(df["close"], timeperiod=60)

# ---------------------- Step 2: Generate signals ----------------------
df["signal"] = 0
# Golden cross → buy (1)
df.loc[(df["MA20"] > df["MA60"]) & (df["MA20"].shift(1) < df["MA60"].shift(1)), "signal"] = 1
# Death cross → sell (-1)
df.loc[(df["MA20"] < df["MA60"]) & (df["MA20"].shift(1) > df["MA60"].shift(1)), "signal"] = -1

# Print backtest signals (focus here to see historical performance)
print("Historical Signals (only dates with signals):")
print(df[df["signal"] != 0][["date", "close", "MA20", "MA60", "signal"]])

# ---------------------- Step 3: Real-time monitoring & alerts ----------------------
def on_message(ws, message):
    data = json.loads(message)
    current_close = data["ld"]  # Latest price
    current_date = data.get("date", "Latest")

    # Simple real-time crossover check (in practice combine with full history)
    if df["MA20"].iloc[-1] > df["MA60"].iloc[-1] and df["MA20"].iloc[-2] < df["MA60"].iloc[-2]:
        print(f"【BUY ALERT】{current_date} | {data['s']} Golden Cross | Price: {current_close}")
    elif df["MA20"].iloc[-1] < df["MA60"].iloc[-1] and df["MA20"].iloc[-2] > df["MA60"].iloc[-2]:
        print(f"【SELL ALERT】{current_date} | {data['s']} Death Cross | Price: {current_close}")

def on_open(ws):
    subscribe_msg = {
        "action": "subscribe",
        "token": api_token,
        "symbols": ["US.AAPL"]  # Monitor Apple—change to other tickers as needed
    }
    ws.send(json.dumps(subscribe_msg))

ws = websocket.WebSocketApp("wss://api.itick.org/stock", on_open=on_open, on_message=on_message)
ws.run_forever()
Enter fullscreen mode Exit fullscreen mode

4. Summary

I wrote a lot, but it really boils down to one thing: getting started with quant trading as a beginner doesn’t have to be technically intimidating or expensive. Start with a free stock API and the simplest dual moving average strategy—nail real-time data first, then gradually optimize and simulate live trading. Step by step is far more reliable than trading on emotion or tips.

That’s exactly how I did it—from not even knowing what an API was to now comfortably building basic quant strategies and monitoring multiple US stocks in real time. I’m not making huge profits, but I’ve avoided most of the old emotional traps, and my trading mindset is much calmer. The real essence of quant trading has never been “beating the market”—it’s “understanding the market,” using discipline to control your behavior and overcome greed and fear. That’s the philosophy I’ve stuck with.

Reference docs: https://blog.itick.org/en/stock-api/global-stock-market-realtime-quotes-for-quantitative-trading
GitHub: https://github.com/itick-org/

Top comments (0)