OKEX WebSocket API Python Connection Example

ยท

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:

Key Features

  1. Real-time Market Data: Subscribe to depth and trade feeds
  2. Automatic Reconnection: Handles connection drops gracefully
  3. Efficient Data Compression: Uses zlib for message compression
  4. 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

  1. WebSocket Connection: Establishes persistent connection to OKEX's API endpoint
  2. Subscription Management: Handles channel subscriptions for market data
  3. Heartbeat Mechanism: Sends regular "ping" messages to maintain connection
  4. 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:

  1. Network restrictions (try disabling firewall temporarily)
  2. Incorrect API endpoint
  3. 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:

Best Practices

  1. Error Handling: Implement robust error recovery mechanisms
  2. Rate Limiting: Avoid sending too many requests per second
  3. Data Storage: Consider persisting important market data
  4. Connection Monitoring: Track connection status and latency

Troubleshooting

SymptomPossible CauseSolution
Connection dropsNetwork issuesImplement automatic reconnection
No data receivedWrong subscriptionVerify instrument ID format
High latencyLocal networkCheck 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:

Remember to test thoroughly before deploying in production environments.