Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

WebSocket Tutorial for Traders and Python Developers

4 min read

If you’re a developer building tools for traders—or dabbling in algo trading yourself—you know speed is king. A half-second delay can turn a profitable trade into a miss. That’s where WebSockets come in, delivering real-time market data straight to your app. In this explainer, we’ll break down how WebSockets work, how they power subscriptions to live quotes and order updates using Alpaca’s API, and why Socket.IO is a developer’s secret weapon. Plus, we’ll geek out on the encoding and serialization tricks that keep the data humming. Let’s dive in!


How WebSockets Work: A Persistent Pipeline

WebSockets are like a live video call compared to HTTP’s old-school text messaging. They create a two-way, always-on connection between your app (the client) and a server (like Alpaca’s market data feed). Here’s the step-by-step:

  1. Handshake: It kicks off with an HTTP request. Your app sends a header (Upgrade: websocket), and the server says, “Cool, let’s switch!” After this handshake, the connection upgrades to WebSocket protocol.
  2. Open Channel: Unlike REST, where you ping the server every second for updates, WebSockets stay open. Data flows instantly—server to client, client to server—without extra requests.
  3. Two-Way Street: The server can push AAPL’s latest quote, and you can reply, “Hey, send me TSLA too!”—all over the same wire.
  4. Shutdown: Either side can close the connection cleanly, or it might drop if the network hiccups (we’ll handle that later).

Picture it: no more refreshing a webpage to check stock prices. WebSockets are built for speed, making them perfect for trading.


WebSockets in Trading: What Alpaca Delivers

Alpaca’s WebSocket API (wss://stream.data.alpaca.markets for market data, wss://api.alpaca.markets/stream for trading) is a free, developer-friendly way to tap into real-time US market action. It doesn’t give you everything—like full order book depth for stocks—but it’s got plenty for retail traders and algos. Here’s how you can wield it:

1. Subscribing/Unsubscribing to Real-Time Market Quotes

  • What You Get: Live Level 1 (L1) quotes—bid and ask prices with sizes (e.g., {“T”: “q”, “S”: “AAPL”, “bp”: 150.25, “bs”: 100, “ap”: 150.30, “as”: 200}). This is the top of the book, updated as the market moves.
  • How It Works: After connecting and authenticating (with your API key/secret), send a subscription message: {“action”: “subscribe”, “quotes”: [“AAPL”, “TSLA”]}. Alpaca starts streaming updates. Done? Send {“action”: “unsubscribe”, “quotes”: [“TSLA”]} to pause it.
  • Why It’s Handy: Your algo can watch the spread (ask – bid) and pounce—like buying AAPL if the bid dips below a moving average. No polling, just instant data.

2. Order Book Depth? Not for Stocks (But Yes for Crypto)

  • Stocks: Alpaca’s stock WebSocket doesn’t support Level 2 (L2) or Level 3 (L3) order book data—no deep bid/ask queues here. You’re limited to L1 quotes. Full order books (e.g., “500 shares bid at $150, 300 asked at $151”) need providers like Polygon.io or Interactive Brokers.
  • Crypto: For crypto streams (wss://stream.data.alpaca.markets/v1beta3/crypto/us), Alpaca does offer order book data. Subscribe with {“action”: “subscribe”, “orderbooks”: [“BTC/USD”]}, and you’ll get snapshots or updates of the book—handy for spotting liquidity.
  • Why It Matters: L2/L3 data lets you see market depth, but for stocks, Alpaca keeps it simple with L1. If you need more, you’ll bridge to another API.

3. Order Data (Execution, Modification, Cancellation)

  • What You Get: Real-time updates on your trades: “Order #123 filled at $305 for MSFT,” “Order #124 modified to $306,” or “Order #125 canceled.”
  • How It Works: Connect to the trading WebSocket and authenticate. Updates flow automatically—no explicit subscription needed for your account’s orders. Expect messages like {“stream”: “trade_updates”, “data”: {“event”: “fill”, “symbol”: “META”}}.
  • Why It’s Clutch: Your bot can react fast—say, canceling unfilled orders if TSLA spikes, or logging fills for analysis.

With Alpaca, you can mix quotes and trade updates over separate WebSocket streams, keeping your app lean and responsive.


Why Socket.IO Matters: Developer Superpowers

Raw WebSockets are powerful but raw—like cooking without spices. Socket.IO adds flavor, wrapping WebSockets in a library that’s a joy to use. Here’s why developers love it:

  1. Event-Driven Bliss: Instead of parsing a firehose of messages, Socket.IO uses events. Alpaca sends a quote? Just socketio.emit(‘market_data’, data) to your frontend. A trader subscribes? Catch it with socket.on(‘subscribe’, handle_subscribe). Clean and simple.
  2. Reconnection Smarts: Network drops? Socket.IO auto-reconnects with configurable retries (e.g., 5 attempts, 1-second delays). My Flask app uses this—clients stay linked even if Wi-Fi blinks.
  3. Fallback Magic: Some networks block WebSockets. Socket.IO falls back to HTTP polling seamlessly, so your app doesn’t crash mid-trade.
  4. Scalability: Broadcasting quotes to multiple clients (e.g., a trading team) is a breeze with rooms or namespaces—like /quotes for market data, /orders for trade updates.
  5. Python Friendly: Flask-SocketIO integrates with Alpaca’s WebSocket, bridging server-side Python to a JavaScript frontend. No socket reinventing needed.

In my Flask app, Socket.IO takes Alpaca’s quote stream (on_message), parses it, and fires it to the browser. Traders toggle subscriptions via the UI, and Socket.IO routes the request back—effortless.


Encoding and Serialization: Data on the Move

WebSockets transmit raw bytes, but trading data needs structure. Encoding and serialization turn quotes or orders into something sendable. Here’s the breakdown:

1. Encoding Types

  • Text: Alpaca uses UTF-8 text—readable JSON like {“T”: “q”, “S”: “AAPL”, “bp”: 150.25}. Easy to debug but bulkier than binary.
  • Binary: Some APIs send bytes (e.g., 4 bytes for a price). Smaller and faster, but Alpaca sticks to text for simplicity.

2. Serialization Methods

  • JSON: Alpaca’s go-to. It’s text-based—{“action”: “subscribe”, “quotes”: [“TSLA”]} becomes a Python dict with json.loads(). Flexible, universal, but not the leanest.
  • MessagePack: Binary JSON—cuts size and parsing time. Not used by Alpaca, but great for high-frequency streams elsewhere.
  • Protocol Buffers (Protobuf): Google’s compact format—requires schemas (e.g., message Quote { string symbol = 1; float bid = 2; }). Used by exchanges, not Alpaca.
  • Custom Binary: DIY packing (e.g., 4 bytes price, 2 bytes size). Lightning-fast but rare and rigid.

3. Trade-Offs

  • Speed: Binary (MessagePack, Protobuf) wins, but JSON’s overhead is fine for Alpaca’s retail focus.
  • Size: A JSON quote might be 100 bytes; MessagePack could halve it—key for dense streams like crypto order books.
  • Ease: Alpaca’s JSON fits Python’s json module perfectly—no extra libraries needed.

Alpaca’s WebSocket leans on JSON for everything—quotes, trade updates, crypto order books. It’s not the fastest, but it’s developer-friendly and widely compatible.


Putting It All Together

WebSockets are your ticket to real-time trading data—Alpaca streams L1 quotes and order updates for stocks, plus order books for crypto, all over a live connection. Subscribe or unsubscribe with a message, and watch the market tick. Socket.IO makes it a breeze to build on, with events and resilience baked in—no wrestling raw sockets. And JSON keeps the data flowing smoothly, balancing simplicity with function.

Ready to code? Fire up Flask-SocketIO, connect to Alpaca, and stream AAPL’s quotes live. For deeper order books on stocks, pair it with Polygon.io or another API. Trading’s fast—your app should be too.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More