Alpaca Websockets

You can leverage websockets and stream data for stocks, crypto, and options using Alpaca.

Below, I’ll show the stock websocket example in full and then show the different code to use for crypto and websockets. The main difference between each is the uri used and the symbols. Copies to each py file can be found on my GitHub.

In later posts/videos, I’ll build upon these examples and show trading bots.

Stock Websocket Example

import asyncio
import websockets
import json

api_key = 'ENTER API KEY'
api_secret ='ENTER API SECRET'

async def connect_to_websocket():
    uri = "wss://stream.data.alpaca.markets/v2/iex"
    async with websockets.connect(uri) as websocket:
        auth_data = {
            "action": "auth",
            "key": api_key,
            "secret": api_secret
        }
        await websocket.send(json.dumps(auth_data))

        subscribe_data = {
            "action": "subscribe",
            "trades": ["SPY"],
            "quotes": ["AAPL", "AMZN"],
            "bars": ["TSLA"]
        }
        await websocket.send(json.dumps(subscribe_data))

        async for message in websocket:
            print(message)

asyncio.run(connect_to_websocket())

Sample Output

Crypto

async def connect_to_websocket():
    uri = "wss://stream.data.alpaca.markets/v1beta3/crypto/us"
    async with websockets.connect(uri) as websocket:
        auth_data = {
            "action": "auth",
            "key": api_key,
            "secret": api_secret
        }
        await websocket.send(json.dumps(auth_data))

        subscribe_data = {
            "action": "subscribe",
            "trades": ["BTC/USD"],
            "quotes": ["LTC/USD", "ETH/USD"],
            "bars": ["BCH/USD"]
        }
        await websocket.send(json.dumps(subscribe_data))

        async for message in websocket:
            print(message)

asyncio.run(connect_to_websocket())

Options

async def connect_to_websocket():
    uri = "wss://stream.data.alpaca.markets/v1beta1/indicative"
    async with websockets.connect(uri) as websocket:
        auth_data = {
            "action": "auth",
            "key": api_key,
            "secret": api_secret
        }

        await websocket.send(msgpack.packb(auth_data))

        subscribe_data = {
            "action": "subscribe",
            "quotes": ["TSLA240621C00185000", "AAPL240621C00195000"],
            "trades": ["AAPL240621C00190000"]
        }

        await websocket.send(msgpack.packb(subscribe_data))

        async for message in websocket:
            msg = msgpack.unpackb(message)
            print(msg)

asyncio.run(connect_to_websocket())

Sharing

Related Articles

  • All Post
  • Articles
  • Blog Post
  • General Business Automation
  • Portfolio
  • Stock Market & Finance