Imagine checking your phone every two seconds to ask a friend, "Did the price change? How about now? How about now?" That is called polling (repeatedly sending REST API requests). It is slow, wastes bandwidth, and gets your IP address rate-limited by Binance if you ask too fast.
Instead, professional trading bots use WebSockets. A WebSocket opens one persistent, two-way pipe to Binance, and Binance pushes every price update to your script the millisecond it happens.
In this lesson, you will connect to the Binance Spot Testnet (https://testnet.binance.vision) WebSocket stream to watch the live orderbook—the real-time list of buyers (bids) and sellers (asks) waiting to trade—and make your listener self-healing so a Wi-Fi hiccup never crashes your bot.
What You Are Actually Watching: Bids, Asks, and Spread
Every live market has two sides:
- Best Bid: The highest price a buyer is currently willing to pay.
- Best Ask: The lowest price a seller is currently willing to accept.
- Spread: The gap between Best Ask and Best Bid (
Ask - Bid). A tight spread means a healthy, liquid market.
And just as a reminder: we are streaming from the Binance Spot Testnet (fake money environment) without even needing API keys. Whenever you do create API keys later, never enable withdrawal permissions.
Prerequisites
Install the lightweight websockets library:
pip install websockets
The Self-Healing Live Market Watcher
Save this script as live_orderbook_watcher.py. It connects to Binance Spot Testnet's combined WebSocket stream for btcusdt@bookTicker (instant best bid/ask) and btcusdt@depth5@100ms (top 5 orderbook levels). If your internet drops or Binance resets the socket, the script automatically waits a few seconds and reconnects with exponential backoff.
import asyncio
import json
from datetime import datetime, timezone
import websockets
SYMBOL = "btcusdt"
# Binance Spot Testnet WebSocket combined stream endpoint (safe sandbox)
TESTNET_WS_URL = (
f"wss://stream.testnet.binance.vision/stream"
f"?streams={SYMBOL}@bookTicker/{SYMBOL}@depth5@100ms"
)
def format_orderbook_line(data):
"""Format a compact snapshot of the top bid, top ask, and spread."""
best_bid = float(data["b"])
bid_qty = float(data["B"])
best_ask = float(data["a"])
ask_qty = float(data["A"])
spread = best_ask - best_bid
now = datetime.now(timezone.utc).strftime("%H:%M:%S")
return (
f"[{now} UTC] {SYMBOL.upper()} | "
f"BID: ${best_bid:,.2f} ({bid_qty:.4f}) | "
f"ASK: ${best_ask:,.2f} ({ask_qty:.4f}) | "
f"SPREAD: ${spread:,.2f}"
)
async def listen_forever():
"""
Connect to Binance Spot Testnet WebSockets and automatically reconnect
with exponential backoff if the connection ever drops.
"""
backoff_seconds = 1
max_backoff = 30
last_depth_print = 0.0
while True:
try:
print(f"Connecting to Binance Spot Testnet stream for {SYMBOL.upper()}...")
# ping_interval & ping_timeout detect silent Wi-Fi drops automatically
async with websockets.connect(
TESTNET_WS_URL,
ping_interval=20,
ping_timeout=10,
) as ws:
print("Connected! Streaming live market data (Ctrl+C to stop)...\n")
# Reset backoff once we have a healthy connection
backoff_seconds = 1
async for raw_message in ws:
payload = json.loads(raw_message)
stream_name = payload.get("stream", "")
data = payload.get("data", {})
if stream_name.endswith("@bookTicker"):
print(format_orderbook_line(data))
elif stream_name.endswith("@depth5@100ms"):
# Print top-3 depth summary every 5 seconds to keep terminal readable
now_ts = asyncio.get_running_loop().time()
if now_ts - last_depth_print >= 5.0:
last_depth_print = now_ts
top_bids = data.get("bids", [])[:3]
top_asks = data.get("asks", [])[:3]
print(" --- Top 3 Orderbook Levels ---")
for price, qty in reversed(top_asks):
print(f" ASK ${float(price):>10,.2f} | qty {float(qty):.4f}")
for price, qty in top_bids:
print(f" BID ${float(price):>10,.2f} | qty {float(qty):.4f}")
print(" ------------------------------")
except (websockets.ConnectionClosed, OSError, asyncio.TimeoutError) as exc:
print(f"\n[DISCONNECTED] Network/socket issue: {exc}")
print(f"Reconnecting in {backoff_seconds}s...")
await asyncio.sleep(backoff_seconds)
# Double wait time on repeated failures (1s -> 2s -> 4s ... up to 30s)
backoff_seconds = min(backoff_seconds * 2, max_backoff)
except Exception as exc:
print(f"\n[UNEXPECTED ERROR] {exc}")
print(f"Retrying in {backoff_seconds}s...")
await asyncio.sleep(backoff_seconds)
backoff_seconds = min(backoff_seconds * 2, max_backoff)
def main():
try:
asyncio.run(listen_forever())
except KeyboardInterrupt:
print("\nStopped by user. Goodbye!")
if __name__ == "__main__":
main()
Run the watcher in your terminal:
python live_orderbook_watcher.py
Try turning your Wi-Fi off for 5 seconds and turning it back on—you will watch the script detect the drop, wait, and seamlessly resume streaming without crashing.
Expected Terminal Output
Connecting to Binance Spot Testnet stream for BTCUSDT...
Connected! Streaming live market data (Ctrl+C to stop)...
[11:55:01 UTC] BTCUSDT | BID: $94,210.50 (0.4200) | ASK: $94,211.00 (0.3150) | SPREAD: $0.50
[11:55:01 UTC] BTCUSDT | BID: $94,210.50 (0.4200) | ASK: $94,211.20 (0.1800) | SPREAD: $0.70
--- Top 3 Orderbook Levels ---
ASK $ 94,212.50 | qty 0.8500
ASK $ 94,211.80 | qty 0.5000
ASK $ 94,211.20 | qty 0.1800
BID $ 94,210.50 | qty 0.4200
BID $ 94,210.00 | qty 0.9100
BID $ 94,209.40 | qty 1.2500
------------------------------
[DISCONNECTED] Network/socket issue: no close frame received or sent
Reconnecting in 1s...
Connecting to Binance Spot Testnet stream for BTCUSDT...
Connected! Streaming live market data (Ctrl+C to stop)...
Common Beginner Mistake: Writing a WebSocket script without a
while Truereconnect loop orping_intervalheartbeat. Binance automatically drops every WebSocket connection after 24 hours—and home Wi-Fi drops far more often than that. Without auto-reconnect and ping timeouts, your bot will silently freeze overnight while thinking it is still connected.
Study & Practice Recap
- WebSockets beat polling: One persistent connection gives you millisecond-fast price updates without burning through REST API rate limits.
- Orderbooks show real liquidity: Watching bids, asks, and spread tells you the actual price you can buy or sell at right now, not just the last traded price.
- Always design for disconnects: Pairing
ping_intervalwith an exponential-backoff reconnect loop turns a fragile script into a 24/7 market watcher.
Tiny Hands-On Exercise: Change SYMBOL to "ethusdt" and add an alert inside the @bookTicker block that prints *** WIDE SPREAD ALERT *** whenever spread > 1.00.