Skip to content

WebSockets

This guide explains how to use the WebSocket client for subscriptions to market data and order updates.

All code samples use the AsyncWSClient which supports async function callbacks, however a syncronous WSClient is available if needed.

For detailed information about available stream types, parameters, and message formats, see the official documentation for updated information.

Initialize WebSocket client

import asyncio
from ethereal import AsyncWSClient, AsyncRESTClient

async def main():
    # Create a WebSocket client
    config = {
        "base_url": "wss://ws.ethereal.trade",
    }
    ws_client = AsyncWSClient(config)

    # Connect to the server
    await ws_client.open(namespaces=["/", "/v1/stream"])

Subscribe to market data

    # Get product information from REST client
    rest_client = await AsyncRESTClient.create({
        "base_url": "https://api.ethereal.trade"
    })
    products_by_ticker = await rest_client.products_by_ticker()
    btc_product_id = products_by_ticker["BTCUSD"].id

    # Define a callback function to handle market data messages
    async def market_data_callback(data):
        print(f"Price update: {data}")

    # Set the callback
    ws_client.callbacks["BookDepth"] = [market_data_callback]

    # Subscribe to market data streams
    await ws_client.subscribe(
        stream_type="BookDepth",
        product_id=btc_product_id,
    )

    await rest_client.close()

Subscribe to order updates

Account Required

This code requires that you have at least one subaccount already created. If you don't have any subaccounts, please refer to the Creating Accounts example.

    # Define callback for order updates
    async def order_update_callback(data):
        print(f"Order update: {data}")

    # Get your subaccount ID from the REST client
    rest_client = await AsyncRESTClient.create({
        "base_url": "https://api.ethereal.trade",
        "chain_config": {
            "rpc_url": "https://rpc.ethereal.trade",
            "private_key": "your_private_key"
        }
    })
    subaccounts = await rest_client.subaccounts()
    subaccount_id = subaccounts[0].id

    # Set the callback
    ws_client.callbacks["OrderFill"] = [order_update_callback]

    # Subscribe to order fills for your subaccount
    await ws_client.subscribe(
        stream_type="OrderFill",
        subaccount_id=subaccount_id
    )

    await rest_client.close()

Connection management

    # Manually close the connection when done
    await ws_client.close()

    # Reconnect if needed
    await ws_client.open(namespaces=["/", "/v1/stream"])

asyncio.run(main())