Skip to content

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

  1. Login to Alpaca Dashboard
  2. Navigate to Settings → API Keys
  3. Generate new key pair
  4. Set in .env: ALPACA_API_KEY and ALPACA_API_SECRET

What It Does

  1. Connects to Alpaca crypto stream with API key auth
  2. Subscribes to BTC/USD orderbooks
  3. Receives incremental L3 order book updates
  4. Stores top 20 levels to state store (examples/btcusd-orderbook)
  5. Publishes to pub/sub topic btcusd-orderbook

Running

source .env  # Must have ALPACA_API_KEY and ALPACA_API_SECRET
python python/websocketmanager/alpaca_clob_example.py