HomePhase 1: Python FoundationsLesson 4
Lesson 4 of 24Phase 1: Python FoundationsBeginner

Listening to Live Prices Without Freezing Your Script

Stream real-time crypto prices for 10+ coins at once using Python asyncio and WebSockets without freezing your script or hitting exchange rate limits.

Bitfoster Team
December 3, 2026
9 Min Read
lesson-04-live-price-streams/
Listening to Live Prices Without Freezing Your Script

Hands-On Deliverable

A live terminal price ticker watching 10+ coins update in real time.

Why Polling Freezes Your Bot (and Why WebSockets Fix It)

When beginners want live crypto prices, they usually write a loop that asks the exchange API over and over: "What is BTC's price now? What about ETH? What about SOL?" This is called HTTP polling.

Polling has two big problems:

  1. It freezes your script: While Python waits for an HTTP reply for Bitcoin, it cannot check Ethereum or react to a sudden crash.
  2. It triggers rate limits: Asking an exchange for 12 coins every second can quickly get your IP address temporarily banned.

WebSockets flip the model around. Instead of repeatedly calling the exchange, you open one persistent connection and say: "Send me an update whenever any of these 10 coins moves." Paired with Python's asyncio library, your script can listen to dozens of coins simultaneously while staying fast, responsive, and well within exchange limits.

In this lesson, you will build a live terminal price ticker that streams 10 major coins in real time over a public, read-only WebSocket feed—no API keys or real funds required.


Prerequisites

Activate your .venv and install the websockets library (asyncio is built into Python):

pip install websockets

Because we are connecting to Binance's public market-data stream, you do not need an account or API key. (If Binance is geo-restricted in your region, you can swap the URL for wss://stream.binance.us:9443/stream?streams=.)

Common Beginner Mistake: Calling time.sleep(1) inside an async def function. Regular time.sleep() freezes the entire event loop, causing missed price ticks and sudden WebSocket disconnects. Inside async functions, always use await asyncio.sleep(1) so other tasks keep running smoothly.


Checkpoint Script: live_ticker.py

Save this code as live_ticker.py. It opens a single combined WebSocket stream for 10 coins, updates an in-memory price board asynchronously, and refreshes your terminal cleanly twice per second without freezing. Press Ctrl+C at any time to stop cleanly.

"""
Lesson 4 Checkpoint: Live Async Multi-Coin Price Ticker
Streams 10 crypto pairs in real time over a single public WebSocket
using Python asyncio—zero API keys required.
"""

import asyncio
import json
from datetime import datetime, timezone
import websockets

SYMBOLS = [
    "btcusdt",
    "ethusdt",
    "solusdt",
    "bnbusdt",
    "xrpusdt",
    "adausdt",
    "dogeusdt",
    "avaxusdt",
    "dotusdt",
    "linkusdt",
]

# Combined public mini-ticker stream (read-only market data)
STREAMS = "/".join(f"{sym}@miniTicker" for sym in SYMBOLS)
WS_URL = f"wss://stream.binance.com:9443/stream?streams={STREAMS}"

# Shared live price board updated by the WebSocket listener
latest_prices: dict[str, dict[str, float]] = {}


async def listen_for_prices(stop_event: asyncio.Event) -> None:
    """Connect to the WebSocket and keep latest_prices updated."""
    while not stop_event.is_set():
        try:
            async with websockets.connect(WS_URL, ping_interval=20, ping_timeout=20) as ws:
                while not stop_event.is_set():
                    raw_msg = await asyncio.wait_for(ws.recv(), timeout=5.0)
                    payload = json.loads(raw_msg).get("data", {})

                    symbol = payload.get("s")
                    if symbol:
                        price = float(payload["c"])       # Latest close/trade price
                        open_24h = float(payload["o"])    # 24h open price
                        pct_24h = ((price - open_24h) / open_24h) * 100 if open_24h else 0.0
                        latest_prices[symbol] = {"price": price, "pct_24h": pct_24h}

        except asyncio.TimeoutError:
            continue
        except (websockets.ConnectionClosed, OSError) as err:
            print(f"[RECONNECT] Stream interrupted ({err}). Retrying in 3s...")
            await asyncio.sleep(3)


async def render_dashboard(stop_event: asyncio.Event) -> None:
    """Print the live terminal ticker twice per second without blocking the stream."""
    while not stop_event.is_set():
        now = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")
        # Clear terminal screen and move cursor to top-left
        print("\033[2J\033[H", end="")
        print("=" * 48)
        print(f"  BITFOSTER LIVE CRYPTO TICKER  |  {now}")
        print("=" * 48)
        print(f"{'SYMBOL':<12}{'PRICE (USDT)':>16}{'24H CHANGE':>16}")
        print("-" * 48)

        for sym in SYMBOLS:
            key = sym.upper()
            info = latest_prices.get(key)
            if info:
                sign = "+" if info["pct_24h"] >= 0 else ""
                pct_str = f"{sign}{info['pct_24h']:.2f}%"
                print(f"{key:<12}{info['price']:>16,.4f}{pct_str:>16}")
            else:
                print(f"{key:<12}{'waiting...':>16}{'--':>16}")

        print("-" * 48)
        print("Press Ctrl+C to stop.")
        await asyncio.sleep(0.5)


async def main() -> None:
    stop_event = asyncio.Event()
    listener_task = asyncio.create_task(listen_for_prices(stop_event))
    display_task = asyncio.create_task(render_dashboard(stop_event))

    try:
        await asyncio.gather(listener_task, display_task)
    except asyncio.CancelledError:
        stop_event.set()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nTicker stopped cleanly. Goodbye!")

Run it from your terminal:

python live_ticker.py

Expected Terminal Output

================================================
  BITFOSTER LIVE CRYPTO TICKER  |  14:22:08 UTC
================================================
SYMBOL          PRICE (USDT)      24H CHANGE
------------------------------------------------
BTCUSDT          94,215.4000          +2.14%
ETHUSDT           3,412.8500          +1.87%
SOLUSDT             218.4200          +4.05%
BNBUSDT             642.1000          +0.63%
XRPUSDT               1.4820          -0.91%
ADAUSDT               0.8940          +3.12%
DOGEUSDT              0.3615          +5.44%
AVAXUSDT             41.2800          +1.22%
DOTUSDT               8.1450          -0.45%
LINKUSDT             19.8300          +2.76%
------------------------------------------------
Press Ctrl+C to stop.

Watch the prices tick smoothly in real time while your CPU usage stays near zero.


Study & Practice Recap

  • One WebSocket beats hundreds of HTTP polls: Combined streams let you watch 10+ coins over a single connection with minimal latency and zero rate-limit drama.
  • asyncio runs listening and display side-by-side: Using asyncio.create_task() allows your bot to receive prices and update the screen concurrently without freezing.
  • Plan for disconnects from day one: Real internet connections drop; wrapping your WebSocket in a reconnect loop keeps your bot resilient.

Tiny Hands-On Exercise: Add two more coins of your choice (for example "ltcusdt" and "nearusdt") to the SYMBOLS list, and highlight any coin whose 24H CHANGE is above +3.00% by printing a * next to its symbol.

Topics:#Python#Asyncio#WebSockets#Live Data#Crypto Ticker