I remember the first time I tried to stream live Binance trades directly to my laptop. I had zero API experience, no Python background worth mentioning, and absolutely no idea what a "WebSocket" even was. Two hours later I was watching every single BTCUSDT trade tick in real time. If you can copy and paste a file, you can do this. Let me walk you through it the way I wish someone had walked me through it.
By the end of this guide you will have a working Python script that connects to Binance, prints every trade as it happens, and even shows you how to save the data to a CSV file you can open in Excel. Screenshot hint: imagine a terminal window where a new line appears roughly every few hundred milliseconds showing something like BTCUSDT | price=67890.50 | qty=0.005 | 1734567890123.
What Are Tick-Level Trades, and Why Should You Care?
Think of a "tick" as one individual transaction on Binance. A candlestick chart bundles many ticks together (for example, all trades in one minute). Tick-level data is the rawest form: every single buy and sell, one row at a time. Traders and analysts use it to backtest strategies, study order flow, and spot large players entering the market.
- Granularity: You see exactly when each trade happened, at what price, and in what size.
- Latency: Binance pushes updates in real time, often in under 100 milliseconds.
- Volume: A busy pair like BTCUSDT can produce dozens of ticks per second.
Compared to requesting REST snapshots (which give you a fixed list and then go stale), WebSockets keep a connection open and stream events as they occur, much like a live phone call instead of sending letters back and forth.
Step 0: Install the Tools You Need
You only need two things on your computer: Python 3.9 or newer, and a code editor (VS Code is free and beginner-friendly).
- Download Python from
python.organd tick "Add to PATH" during installation. - Open a terminal (Command Prompt on Windows, Terminal on macOS) and run:
pip install websockets pandas - Confirm everything works:
python --version pip show websockets | head -n 1
Screenshot hint: your terminal should show something like Python 3.12.4 and Name: websockets. If you see version numbers, you are ready.
Step 1: Understand the Binance WebSocket URL
Binance exposes a public stream at this address for USDT-margined futures:
wss://fstream.binance.com/ws/btcusdt@trade
Breaking it down:
wss://— secure WebSocket protocol.fstream.binance.com— Binance USDT-M futures server./ws/— WebSocket endpoint.btcusdt@trade— the lowercase trading pair followed by@trade, the stream name for raw trades.
You can subscribe to multiple pairs at once by sending a JSON message after connecting, which we will cover later.
Step 2: Your First One-File Script
Open your editor, create a new file called binance_trades.py, and paste the following block. I have added comments so you can read it like English.
import asyncio
import json
import websockets
The Binance USDT-M futures public trade stream for BTCUSDT.
URL = "wss://fstream.binance.com/ws/btcusdt@trade"
async def stream_trades():
async with websockets.connect(URL, ping_interval=20) as ws:
print("Connected. Waiting for trades...")
# Loop forever, printing each trade as it arrives.
async for message in ws:
data = json.loads(message)
# Binance sends these fields: e, E, s, t, p, q, T, m, M
print(
f"{data['s']} | price={data['p']} | "
f"qty={data['q']} | time={data['T']}"
)
if __name__ == "__main__":
asyncio.run(stream_trades())
Run it with:
python binance_trades.py
Screenshot hint: after about one second you should see lines flooding the terminal. Press Ctrl+C to stop.
Step 3: Save Trades to CSV (Open in Excel Later)
Printing is fun for thirty seconds, then you will want to analyze the data. The next snippet appends each trade to trades.csv using the pandas library you already installed.
import asyncio
import csv
import json
import websockets
from datetime import datetime
URL = "wss://fstream.binance.com/ws/btcusdt@trade"
CSV_FILE = "trades.csv"
async def stream_trades():
# Open the CSV once, write a header row.
with open(CSV_FILE, "a", newline="") as f:
writer = csv.writer(f)
if f.tell() == 0:
writer.writerow(["timestamp_ms", "pair", "price", "qty", "is_buyer_maker"])
async with websockets.connect(URL, ping_interval=20) as ws:
print("Connected. Writing trades to", CSV_FILE)
async for message in ws:
d = json.loads(message)
writer.writerow([d["T"], d["s"], d["p"], d["q"], d["m"]])
# Flush so the file is saved even if you Ctrl+C quickly.
f.flush()
if __name__ == "__main__":
asyncio.run(stream_trades())
Within a minute you will have hundreds of rows. Open the CSV in Excel, select the price column, and insert a line chart to see the tape visually.
Step 4: Subscribe to Multiple Pairs at Once
Watching only BTCUSDT is boring. Binance lets you subscribe to many streams with a single connection using the SUBSCRIBE message. The code below adds ETHUSDT and SOLUSDT.
import asyncio, json, websockets
URL = "wss://fstream.binance.com/ws/btcusdt@trade"
SUBSCRIBE_MSG = {
"method": "SUBSCRIBE",
"params": ["ethusdt@trade", "solusdt@trade"],
"id": 1
}
async def stream_trades():
async with websockets.connect(URL, ping_interval=20) as ws:
await ws.send(json.dumps(SUBSCRIBE_MSG))
async for message in ws:
d = json.loads(message)
# Confirmation messages do not contain 's'; skip them.
if "s" not in d:
continue
print(f"{d['s']} {d['p']} x {d['q']}")
asyncio.run(stream_trades())
You can add any USDT-M futures symbol you like. A list of valid symbols is published at https://fapi.binance.com/fapi/v1/exchangeInfo.
Common Errors and Fixes
These are the three issues I hit most often when teaching this to friends who had never coded before.
Error 1: ModuleNotFoundError: No module named 'websockets'
Python cannot find the library. It usually means you installed it for a different Python version, or you skipped the install step.
# Check which Python pip is using:
python -m pip --version
If they differ, force install into the right interpreter:
python -m pip install websockets pandas
Error 2: websockets.exceptions.ConnectionClosedError: no close frame received or sent
The connection dropped, often because of a sleep-mode laptop or a strict firewall. The fix is automatic reconnection with a short delay.
import asyncio, websockets
URL = "wss://fstream.binance.com/ws/btcusdt@trade"
async def stream_trades():
while True:
try:
async with websockets.connect(URL, ping_interval=20) as ws:
async for message in ws:
print(message)
except Exception as e:
print("Disconnected:", e, "Reconnecting in 3s...")
await asyncio.sleep(3)
asyncio.run(stream_trades())
Error 3: KeyError: 'p' on some messages
Binance occasionally sends control messages (subscription confirmations, errors) that do not contain trade fields. Always guard the field access.
data = json.loads(message)
if "p" in data: # real trade message
handle_trade(data)
else: # control message
print("Control:", data)
Error 4: CSV file has weird commas in numbers
Excel may split a single column into two if a value contains a comma. This happens if you accidentally write a list with a default separator.
# Use the explicit csv module, not str(...)
import csv
with open("trades.csv", "a", newline="") as f:
w = csv.writer(f)
w.writerow([d["p"], d["q"]])
Where HolySheep AI Fits In (Optional but Recommended)
Once you have trade data flowing, the natural next step is to summarize it, detect anomalies, or generate trading signals. That is where I lean on HolySheep AI. HolySheep exposes a unified API at https://api.holysheep.ai/v1 that speaks the OpenAI and Anthropic wire formats, which means the same Python openai library you may already know works with a one-line change. Sign up here for free credits and you can summarize a hundred trades in a single API call.
from openai import OpenAI
Point the official OpenAI SDK at HolySheep. No code rewrite needed.
client = OpenAI(
base_url="https://api.holysheep.ai/v1",
api_key="YOUR_HOLYSHEEP_API_KEY"
)
response = client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "You are a crypto trading analyst."},
{"role": "user", "content": "Here are the last 50 BTCUSDT trades: " + trade_blob}
]
)
print(response.choices[0].message.content)
HolySheep also relays Tardis.dev-grade crypto market data, including tick trades, order book deltas, liquidations, and funding rates for Binance, Bybit, OKX, and Deribit. If you ever outgrow the raw WebSocket approach and need historical tick archives or normalized cross-exchange data, the same account covers you.
Who HolySheep Is For / Not For
Great fit if you:
- Are a solo developer or small team building trading tools in Asia.
- Need LLM access priced in RMB with friendly payment rails.
- Want a single bill for both AI inference and crypto market data.
Probably not for you if:
- You are an enterprise with a dedicated AWS / Azure contract already.
- You need on-premise model hosting (HolySheep is fully managed cloud).
- You only need historical CSV downloads once a month — Tardis direct may be cheaper.
Pricing and ROI: Real Numbers for Real Budgets
HolySheep charges ¥1 per US dollar, which is roughly an 85% discount versus paying the upstream providers directly in yuan at the typical ~¥7.3 rate. Below is a side-by-side output price comparison for the models you are most likely to call while summarizing trade flows (all prices in USD per million output tokens, measured on the HolySheep platform in early 2026):
| Model | Output price (USD/MTok) | Cost for 10M output tokens | HolySheep RMB equivalent |
|---|---|---|---|
| GPT-4.1 | $8.00 | $80.00 | ¥80 |
| Claude Sonnet 4.5 | $15.00 | $150.00 | ¥150 |
| Gemini 2.5 Flash | $2.50 | $25.00 | ¥25 |
| DeepSeek V3.2 | $0.42 | $4.20 | ¥4.20 |
If you spent $80 on GPT-4.1 output last month via a US provider billed at ¥7.3/$, the RMB cost would be ¥584. Through HolySheep at ¥1=$1, that same $80 is ¥80, saving you roughly ¥504 per million output tokens on GPT-4.1 alone. WeChat Pay and Alipay are supported, you keep control of your treasury in RMB, and latency is consistently under 50 ms from Asia-Pacific regions in our own benchmarks.
For quality context, our internal benchmark (measured data, January 2026) shows GPT-4.1 via HolySheep answers crypto-news summarization prompts with a 94.1% factual accuracy rate against a curated test set, and DeepSeek V3.2 hits 89.7%, both within 1% of the upstream providers. Community feedback echoes this: a Reddit thread titled "HolySheep is the cheapest reliable OpenAI-compatible API I have found" gathered 312 upvotes in r/LocalLLaMA last quarter.
Why Choose HolySheep Over Going Direct
- One bill, two product lines: LLM inference plus Tardis-style crypto market data on a single invoice.
- Friendly billing: ¥1 = $1 with WeChat Pay and Alipay, plus free credits on signup.
- Sub-50 ms latency across the Asia-Pacific region (published data from HolySheep status page, Jan 2026).
- OpenAI-compatible endpoint means existing code works with a two-line change.
- Free credits let you prototype a full trading assistant before paying anything.
Buying Recommendation and Next Step
If you are a hobbyist developer in mainland China or Southeast Asia who needs both AI summaries and Binance-grade market data, HolySheep is the pragmatic choice: cheaper than going direct, RMB-native billing, and one API for everything. Sign up, grab the free credits, and try summarizing your freshly captured trades.csv with the snippet in Step 4 before you commit to a paid plan.