WebSockets¶
This guide explains how to use the WebSocket client for subscriptions to market data and order updates.
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¶
# Subscribe to market data for a specific product
btc_product_id = 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 the BookDepth stream type
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 updates (requires authentication)
def order_update_callback(data):
print(f"Order {data['id']} status: {data['status']}")
# Get your subaccount ID from the REST client
subaccount_id = client.subaccounts[0].id
# Subscribe to the OrderUpdate stream type
ws_client.subscribe(
stream_type="OrderFill",
product_id=btc_product_id,
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"])