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

from ethereal import WSClient

# Create a WebSocket client
config = {
    "base_url": "wss://ws.etherealtest.net",
}
ws_client = WSClient(config)

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

Subscribe to market data

# Get product information from REST client
from ethereal import RESTClient
rest_client = RESTClient()
btc_product_id = rest_client.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
)

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 = RESTClient()
subaccount_id = rest_client.subaccounts[0].id

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

Connection management

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

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