A Comprehensive Guide to the OKEx Spot WebSocket API for Real-Time Market Data

·

Navigating the world of cryptocurrency trading requires access to fast, reliable, and real-time market data. The OKEx Spot WebSocket API provides a powerful solution for developers and traders seeking to build applications or automate strategies with live market feeds. This protocol enables efficient, bidirectional communication between clients and servers, making it ideal for high-frequency data streams like order books, tickers, and trades.

Unlike traditional HTTP requests, a WebSocket connection remains open, allowing the server to push updates to the client instantly whenever changes occur. This eliminates the need for constant polling, reduces latency, and conserves bandwidth. For anyone serious about developing trading tools or monitoring the markets, mastering this API is a crucial step.

Getting Started with the WebSocket Protocol

WebSocket is a communication protocol that provides full-duplex channels over a single TCP connection. It is part of the HTML5 specification and is designed to be implemented in web browsers and web servers. The connection is established with a simple handshake, after which data can flow freely in both directions.

The key advantages of using WebSocket for market data are substantial. The header overhead for data transfer is minimal, at roughly two bytes. Both the client and server can initiate data transmission. Most importantly, it avoids the repeated establishment and termination of TCP connections, which saves significant bandwidth and computational resources.

For these reasons, using the WebSocket API is the strongly recommended method for obtaining real-time market information, including live tickers and order book depth from OKEx.

Establishing the Connection and Request Flow

The base URL for connecting to the OKEx Spot WebSocket service is: wss://real.okex.com:10440/ws/v1.

Sending Requests to the Server

To request data, you must send a message to the server after establishing the connection. The request must be formatted as a JSON object. The basic structure for a request is:

{'event':'addChannel','channel':'channelValue','parameters':{'api_key':'value1','sign':'value2'}}

You can subscribe to multiple channels at once by sending an array of request objects:
websocket.send("[{'event':'addChannel','channel':'channel1'},{'event':'addChannel','channel':'channel2'}]")

Understanding Server Responses

The server responds with data in a consistent JSON array format. A typical response looks like:

[{"channel":"channelName","success":"","errorcode":"","data":{}}, ...]

Data Push Mechanics and the Heartbeat

To optimize for speed and efficiency, OKEx does not push market data at fixed intervals. Instead, ticker and order book depth data are only sent when a change in the market occurs. Trade data (deals) is pushed as incremental updates, containing only the new trades since the last push.

A critical practice for maintaining a stable connection is implementing a heartbeat. The client should send a ping message every 30 seconds: {'event':'ping'}. The server will respond with a pong: {"event":"pong"}. If the client fails to receive a pong response after sending a ping, it should assume the connection is broken and initiate a reconnection. 👉 Explore more strategies for maintaining stable connections

Spot Market Data API Reference

This section details the specific channels available for accessing real-time spot market data.

1. Subscribing to Ticker Data

Channel: ok_sub_spot_X_ticker
Replace X with the trading pair (e.g., btc_usdt).

Example Request:

{'event':'addChannel','channel':'ok_sub_spot_btc_usdt_ticker'}

Example Response:

[
 {
 "channel": "ok_sub_spot_btc_usdt_ticker",
 "data": {
 "high": "55000.0",
 "vol": "12045.8374",
 "last": "54872.5",
 "low": "53210.3",
 "buy": "54870.0",
 "change": "2.5",
 "sell": "54872.5",
 "dayLow": "53210.3",
 "dayHigh": "55000.0",
 "timestamp": 1641234567890
 }
 }
]

Response Fields:

2. Subscribing to Order Book Depth (Incremental)

Channel: ok_sub_spot_X_depth
This channel provides incremental updates to the top 200 levels of the order book. The first response is a full snapshot; subsequent messages contain only the changes (additions, modifications, deletions).

Example Request:

{'event':'addChannel','channel':'ok_sub_spot_btc_usdt_depth'}

Example Response:

[
 {
 "channel": "ok_sub_spot_btc_usdt_depth",
 "data": {
 "asks": [
 ["54875.0", "1.52"],
 ["54880.5", "0.75"]
 ],
 "bids": [
 ["54870.0", "2.10"],
 ["54865.5", "1.30"]
 ],
 "timestamp": 1641234567890
 }
 }
]

Response Fields:

3. Subscribing to Specific Order Book Depth

Channel: ok_sub_spot_X_depth_Y
For a fixed-size order book snapshot. Replace X with the pair and Y with the desired depth (e.g., 5, 10, 20).

Example Request:

{'event':'addChannel','channel':'ok_sub_spot_btc_usdt_depth_10'}

4. Subscribing to Trade History

Channel: ok_sub_spot_X_deals
This channel pushes new public trades as they occur.

Example Request:

{'event':'addChannel','channel':'ok_sub_spot_btc_usdt_deals'}

Example Response:

[{
 "channel":"ok_sub_spot_btc_usdt_deals",
 "data":[["10254", "54872.5", "0.05", "12:34:56", "sell"]]
}]

Response Fields: [Trade ID, Price, Volume, Time, Side (ask/sell or bid/buy)]

5. Subscribing to K-Line/Candlestick Data

Channel: ok_sub_spot_X_kline_Y
Replace X with the pair and Y with the timeframe (e.g., 1min, 1hour, 4hour, day, week).

Example Request:

{'event':'addChannel','channel':'ok_sub_spot_btc_usdt_kline_1hour'}

Example Response:

[{
 "channel":"ok_sub_spot_btc_usdt_kline_1hour",
 "data":[
 ["1641232800000", "54750.0", "54900.0", "54650.0", "54872.5", "25.112"],
 ["1641236400000", "54872.5", "54950.0", "54800.0", "54900.0", "18.745"]
 ]
}]

Response Fields: [Timestamp, Open, High, Low, Close, Volume]

Spot Trading API for User Data

Accessing private user data, such as order updates and account balances, requires authentication.

1. Login and Authentication

Before subscribing to private channels, you must authenticate your session.

Example Request:

{"event":"login","parameters":{"api_key":"your_api_key_here","sign":"your_generated_signature"}}

Example Response:

[
 {
 "channel": "login",
 "data": {
 "result": true
 }
 }
]

A successful login is required before subscribing to ok_sub_spot_X_order and ok_sub_spot_X_balance.

2. Subscribing to Order Updates

Channel: ok_sub_spot_X_order
This channel provides real-time updates on the status of your orders for a specific market.

Example Response:

[
 {
 "channel": "ok_sub_spot_btc_usdt_order",
 "data": {
 "orderId": 123456789,
 "symbol": "btc_usdt",
 "tradeType": "buy",
 "tradeUnitPrice": "54500.0",
 "tradeAmount": "0.1",
 "completedTradeAmount": "0.0",
 "status": 0,
 "createdDate": "1641234567890"
 }
 }
]

Key Status Codes: -1: Canceled, 0: Pending, 1: Partially Filled, 2: Fully Filled.

3. Subscribing to Balance Updates

Channel: ok_sub_spot_X_balance
This channel provides updates on your account balances for the currencies in a specific trading pair.

Example Response:

[
 {
 "channel": "ok_sub_spot_btc_usdt_balance",
 "data": {
 "info": {
 "free": {"btc": "1.50000000", "usdt": "5000.00"},
 "freezed": {"btc": "0.20000000", "usdt": "0.00"}
 }
 }
 }
]

Frequently Asked Questions

Q: What is the main benefit of using WebSocket over REST API for market data?
A: WebSocket provides real-time, streaming data with low latency. The server pushes updates the instant they happen, eliminating the delay and overhead associated with repeatedly polling a REST endpoint.

Q: How do I handle disconnections and reconnect gracefully?
A: Implement the ping/pong heartbeat. If a pong response is not received after a ping, close the connection and restart the entire process: reconnect, re-authenticate (if needed), and re-subscribe to all your data channels.

Q: Why am I not receiving constant updates for the ticker channel?
A: This is by design. The ticker channel only pushes a new message when one of its values (e.g., last price, best bid/ask) changes. During periods of high volatility, updates will be frequent; in calm markets, they will be less so.

Q: What is the difference between the depth and depth_Y channels?
A: The depth channel provides incremental updates for the top 200 levels. The depth_Y channel (e.g., depth_10) provides periodic snapshots of the top Y levels of the order book.

Q: Is SSL encryption used for the WebSocket connection?
A: Yes, the connection URL uses wss://, which signifies a secure WebSocket connection encrypted via TLS/SSL, protecting your data in transit.

Q: Can I subscribe to multiple trading pairs in a single request?
A: Absolutely. You can batch channel subscriptions by sending a single message containing an array of addChannel objects, which is more efficient than sending multiple individual requests.