Introduction
This guide demonstrates how to connect to OKEX's WebSocket API using Python, focusing on futures market data subscriptions. We'll use the websocket-client library (version 0.46.0) to establish a stable connection and receive real-time market data.
Prerequisites
Before starting, ensure you have:
- Python 3 installed
websocket-clientversion 0.46.0 (pip3 install websocket-client==0.46.0)- Basic understanding of WebSocket protocols
- OKEX trading account (for accessing live market data)
Key Features
- Real-time Market Data: Subscribe to depth and trade feeds
- Automatic Reconnection: Handles connection drops gracefully
- Efficient Data Compression: Uses zlib for message compression
- Callback Support: Customizable message handling
Python Implementation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import json
import zlib
import threading
import websocket
class WSSubscription:
def __init__(self, instrument_id='BTC-USD-190517', market='futures', on_message=None):
self.__iid = instrument_id
self.__market = market
self.__Depth = {}
if on_message:
self.__callbackEnabled = True
self.__callback = on_message
else:
self.__callbackEnabled = False
thread = threading.Thread(target=self.sub)
thread.daemon = True
thread.start()
def GetDepth(self):
return self.__Depth
def subscribe(self, ws):
def operator(op, args):
message = {'op': op, 'args': args}
ws.send(json.dumps(message))
def run():
operator('subscribe', [f'{self.__market}/depth5:{self.__iid}'])
operator('subscribe', [f'{self.__market}/trade:{self.__iid}'])
while True:
ws.send("ping")
time.sleep(30)
threading.Thread(target=run).start()
def sub(self):
websocket.enableTrace(False)
URL = "wss://real.okex.com:10442/ws/v3"
ws = websocket.WebSocketApp(URL,
on_message=self.incoming,
on_error=self.error_handling,
on_close=self.closing)
ws.on_open = self.subscribe
while True:
try:
ws.run_forever()
except Exception:
time.sleep(5)
continue
def incoming(self, ws, message):
message = zlib.decompress(message, -zlib.MAX_WBITS).decode('utf-8')
if 'pong' in message:
pass
elif 'asks' in message and 'bids' in message:
d = json.loads(message)
self.__Depth = d['data'][0]
if self.__callbackEnabled:
self.__callback(message)
def error_handling(self, ws, error):
print(f"WebSocket Error: {str(error)}")
def closing(self, ws):
print("WebSocket connection closed")
# Example usage
if __name__ == "__main__":
okex_ws = WSSubscription('BTC-USD-190517', 'futures')
while True:
print(okex_ws.GetDepth())
time.sleep(1)Key Components Explained
- WebSocket Connection: Establishes persistent connection to OKEX's API endpoint
- Subscription Management: Handles channel subscriptions for market data
- Heartbeat Mechanism: Sends regular "ping" messages to maintain connection
- Data Processing: Decompresses and parses incoming WebSocket messages
๐ Check OKEX's official API documentation for the latest endpoint information and supported instruments.
FAQ
What version of websocket-client should I use?
You must use version 0.46.0 (pip3 install websocket-client==0.46.0) as newer versions have compatibility issues with OKEX's API.
How do I subscribe to different markets?
Modify the instrument_id and market parameters when initializing the WSSubscription class. For example:
# For spot market
ws = WSSubscription('BTC-USDT', 'spot')Why am I getting connection errors?
Common causes include:
- Network restrictions (try disabling firewall temporarily)
- Incorrect API endpoint
- Server-side issues at OKEX
๐ Visit OKEX status page to check for service outages.
How can I add custom message handling?
Pass a callback function when initializing the class:
def my_callback(message):
print("Received:", message)
ws = WSSubscription(on_message=my_callback)What markets and instruments are available?
OKEX supports:
- Spot trading (
spotmarket) - Futures (
futuresmarket) - Swap contracts
- Options
Best Practices
- Error Handling: Implement robust error recovery mechanisms
- Rate Limiting: Avoid sending too many requests per second
- Data Storage: Consider persisting important market data
- Connection Monitoring: Track connection status and latency
Troubleshooting
| Symptom | Possible Cause | Solution |
|---|---|---|
| Connection drops | Network issues | Implement automatic reconnection |
| No data received | Wrong subscription | Verify instrument ID format |
| High latency | Local network | Check your internet connection |
๐ For advanced trading features, consider using OKEX's REST API alongside WebSocket.
Conclusion
This implementation provides a solid foundation for accessing OKEX's real-time market data. You can extend it to include:
- Order book tracking
- Trade execution
- Strategy implementation
- Portfolio monitoring
Remember to test thoroughly before deploying in production environments.