Skip to content

WebSockets

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

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 WSClient, AsyncRESTClient

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

    # Connect to the server
    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
    def market_data_callback(data):
        print(f"Price update: {data}")

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

    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.

    # Subscribe to your order fills and updates
    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

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

    await rest_client.close()

Connection management

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

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

asyncio.run(main())