Alpaca CLOB Example
File: python/websocketmanager/alpaca_clob_example.py
Streams BTC/USD order book from Alpaca crypto WebSocket with API key authentication.
API Details
| Property | Value |
|---|---|
| WebSocket URL | wss://stream.data.alpaca.markets/v1beta3/crypto |
| Authentication | Message-based: {"action":"auth","key":"...","secret":"..."} |
| Subscribe | {"action":"subscribe","orderbooks":["BTC/USD"]} |
| Order book type | L3 (full depth) |
| Environment | Paper: paper-api.alpaca.markets, Live: api.alpaca.markets |
Authentication Flow
Unlike Binance where the stream is public, Alpaca requires API key authentication over the WebSocket itself:
# Step 1: Authenticate
await client.send_raw(conn_id,
json.dumps({"action": "auth", "key": ALPACA_API_KEY, "secret": ALPACA_API_SECRET}))
# Step 2: Subscribe
await client.send_raw(conn_id,
json.dumps({"action": "subscribe", "orderbooks": ["BTC/USD"]}))
# Step 3: Stream receives L3 orderbook updates
Getting Alpaca API Keys
- Login to Alpaca Dashboard
- Navigate to Settings → API Keys
- Generate new key pair
- Set in
.env:ALPACA_API_KEYandALPACA_API_SECRET
What It Does
- Connects to Alpaca crypto stream with API key auth
- Subscribes to BTC/USD orderbooks
- Receives incremental L3 order book updates
- Stores top 20 levels to state store (
examples/btcusd-orderbook) - Publishes to pub/sub topic
btcusd-orderbook