This comprehensive guide explains how to integrate OKX's WebSocket API using Python for real-time cryptocurrency market data and account updates.
Understanding OKX WebSocket API
OKX provides two primary WebSocket endpoints:
- Public WebSocket - For market data (tickers, order books, mark prices)
- Private WebSocket - For account-specific data (orders, balances, positions)
👉 Explore OKX WebSocket API documentation
Python Implementation Code
import hmac
import time
import json
import base64
import websocket
import okx.consts as c
import queue as Queue
class OkxWebSocketManager(object):
def __init__(self, apiKey, secretKey, passphrase, sandbox=False):
self.sandbox = sandbox
self.apiKey = apiKey
self.secretKey = secretKey
self.passphrase = passphrase
self.msgQueue = Queue.Queue()
self.ws = None
self.channels = []Key Components Explained
Authentication Parameters:
apiKey: Your OKX API keysecretKey: Your OKX API secretpassphrase: Your OKX API passphrasesandbox: Boolean flag for testnet/sandbox environment
Core Methods:
private_subscribe(): Connect to private channelspublic_subscribe(): Connect to public market data channels- Message handling via WebSocket callbacks
WebSocket Connection Management
Establishing Connection
def listenStreams(self):
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp(self.url,
on_message=self.on_message,
on_error=self.on_error,
on_open=self.on_open,
on_pong=self.on_pong,
on_close=self.on_close)
self.ws.run_forever(ping_interval=15)Authentication Process
def login_params(self):
timestamp = self.get_local_timestamp()
message = str(timestamp) + 'GET' + '/users/self/verify'
mac = hmac.new(bytes(self.secretKey, encoding='utf8'),
bytes(message, encoding='utf-8'),
digestmod='sha256')
sign = base64.b64encode(mac.digest())
login_param = {"op": "login", "args": [{
"apiKey": self.apiKey,
"passphrase": self.passphrase,
"timestamp": timestamp,
"sign": sign.decode("utf-8")
}]}
return json.dumps(login_param)Subscription Management
Public Channels Example
def _add_pubilc_subscribe(self, bassAsset):
instId = str(bassAsset.upper() + "-USDT-SWAP").strip()
self.channels.append(
{"channel": "mark-price", "instType": "SWAP", "instId": instId})
self.channels.append(
{"channel": "tickers", "instType": "SWAP", "instId": instId})
sub_param = {'op': 'subscribe', 'args': self.channels}
self.ws.send(json.dumps(sub_param))👉 Learn more about OKX WebSocket subscriptions
Message Handling
Core Callback Functions
def on_message(self, msg):
message = json.loads(msg)
if 'event' in message:
# Handle subscription events
self.handle_ws_events(message)
else:
# Process market data or account updates
self.messagePublish(message)
def messagePublish(self, message):
channel = message['arg']['channel']
if channel == 'orders':
print("Order update:", message['data'][0])
elif channel == 'tickers':
print("Ticker update:", message)
elif channel == 'mark-price':
print("Mark price update:", message)Best Practices for WebSocket Integration
Connection Stability:
- Implement automatic reconnection logic
- Handle ping/pong messages for connection health
- Manage rate limits appropriately
Error Handling:
- Monitor WebSocket error events
- Implement fallback mechanisms
- Log connection issues for debugging
Performance Considerations:
- Use message queues for high-frequency updates
- Optimize subscription channels
- Implement efficient message parsing
FAQ Section
Q1: What's the difference between OKX's sandbox and production WebSocket endpoints?
A: The sandbox environment (WS_SANBOX_ URLs) is for testing with fake funds, while production endpoints (WS_ URLs) connect to real trading systems.
Q2: How often should I send ping messages?
A: The example uses 15-second intervals (ping_interval=15), which is generally recommended for maintaining stable connections.
Q3: Can I subscribe to multiple instruments simultaneously?
A: Yes, you can include multiple instrument IDs in your subscription arguments array.
Q4: What authentication method does OKX WebSocket use?
A: OKX uses HMAC-SHA256 signatures with your API credentials for WebSocket authentication.
Q5: How do I handle disconnections?
A: Implement reconnection logic in your on_close callback and monitor connection state.
Q6: Are there rate limits for WebSocket connections?
A: Yes, OKX enforces rate limits on both connection attempts and message frequency.
Conclusion
This guide has demonstrated a comprehensive Python implementation for connecting to OKX's WebSocket API. By following these patterns, you can:
- Establish secure WebSocket connections
- Subscribe to market data and account updates
- Implement robust message handling
- Manage subscriptions dynamically
👉 Start integrating with OKX WebSocket API today
Remember to always test your integration thoroughly in the sandbox environment before moving to production trading.