The websocketAPIpublic class is a powerful tool for developers seeking real-time access to public market data from the OKX exchange through its v5 API. Designed for seamless integration into R-based applications, this class enables efficient communication with OKX's WebSocket servers, allowing users to subscribe to live updates on trading pairs, candlestick data, order books, and more—without the latency associated with REST APIs.
Whether you're building a high-frequency trading bot, a real-time analytics dashboard, or a market monitoring system, understanding how to properly utilize the websocketAPIpublic class is essential for staying ahead in today’s fast-moving crypto markets.
👉 Discover how to connect to real-time crypto data streams with ease.
Understanding the WebSocket Public Channel
The websocketAPIpublic class serves as the interface to the public channel of the OKX WebSocket API. Unlike private channels that require authentication for order or account data, public channels provide open access to non-sensitive market information such as:
- Price tickers
- Order book depth (books and books5)
- Candlestick (k-line) data
- Trade history
- Index prices
- Funding rates
This makes it ideal for applications focused on market analysis, price prediction models, or visualizing live trading activity.
For full technical specifications, refer to the official OKX WebSocket API documentation. However, this guide will walk you through practical usage, method implementation, and best practices using the R okxAPI package.
Core Components of the websocketAPIpublic Class
Public Fields
The class exposes several key fields that manage the connection state and behavior:
channel: The WebSocket URL endpoint used to connect to the OKX server. This is typically set automatically based on whether demo mode is enabled.simulate: A boolean flag indicating whether the connection should use the demo trading environment (TRUE) or the live production environment (FALSE).ws: An internalWebSocketobject (from thewebsocketR package) responsible for managing the actual TCP-level connection, message sending, and event handling.
These fields are accessible after instantiation and can be inspected or modified depending on your application’s needs.
Key Methods and Their Functions
Each method in the websocketAPIpublic class plays a specific role in establishing, maintaining, and interacting with the WebSocket connection.
websocketAPIpublic$new(simulate = FALSE)
Initializes a new instance of the class.
Parameters:
simulate: Set toTRUEto connect to the demo/testnet environment. Default isFALSE, meaning it connects to the live market.
client <- websocketAPIpublic$new(simulate = FALSE)This creates a client ready to connect to real-time data feeds without requiring API keys—perfect for read-only monitoring tools.
websocketAPIpublic$connect()
Establishes the WebSocket connection to the OKX server.
client$connect()Once called, the client attempts to open a persistent two-way communication channel. It’s important to ensure network connectivity and proper firewall settings allow outbound WebSocket connections (wss://).
👉 Start streaming live crypto market data directly in your R environment.
Event Handlers: Responding to Connection States
The following methods allow you to define custom callback functions that execute when certain events occur:
on_open(func)
Triggers when the connection successfully opens.
client$on_open(function() {
print("Connected to OKX WebSocket!")
})Use this to initiate subscriptions or log successful connections.
on_close(func)
Fires when the connection closes. The event includes code (status code) and reason (description).
client$on_close(function(event) {
cat("Connection closed:", event$reason, "\n")
})Helpful for debugging disconnections or implementing auto-reconnect logic.
on_message(func)
Executes every time a message is received from the server. The message payload is stored in event$data.
client$on_message(function(event) {
message <- jsonlite::fromJSON(event$data)
print(message)
})This is where most of your data processing will happen—parsing candlesticks, order book changes, etc.
on_error(func)
Called when an error occurs during connection setup or transmission.
client$on_error(function(event) {
warning("WebSocket error:", event$message)
})Essential for robust error handling in production systems.
Sending and Managing Messages
send(msg)
Sends a JSON-formatted message to the server—typically used to subscribe or unsubscribe from data channels.
Example: Subscribe to BTC-USDT-SWAP 1-minute candles
subscription_msg <- list(
op = "subscribe",
args = list(list(channel = "candle1m", instId = "BTC-USDT-SWAP"))
)
client$send(jsonlite::toJSON(subscription_msg, auto_unbox = TRUE))close()
Gracefully terminates the WebSocket connection.
client$close()Always call this when shutting down your application to free resources.
clone(deep = FALSE)
Creates a copy of the current object. Use deep = TRUE if you need independent copies of nested objects.
client_copy <- client$clone(deep = TRUE)Useful in multi-threaded or modular applications.
Practical Example: Live Candlestick Monitor
Here’s a complete working example that connects to OKX, subscribes to BTC/USDT 5-minute candlesticks, logs incoming data, and handles basic events:
library(okxAPI)
library(jsonlite)
# Initialize client
ws <- websocketAPIpublic$new()
# Define event callbacks
ws$on_open(function() {
cat("WebSocket opened. Subscribing...\n")
msg <- list(op = "subscribe", args = list(list(channel = "candle5m", instId = "BTC-USDT-SWAP")))
ws$send(toJSON(msg, auto_unbox = TRUE))
})
ws$on_message(function(event) {
data <- fromJSON(event$data)
if (is.list(data) && "data" %in% names(data)) {
cat("New candle:", data$data[[1]], "\n")
}
})
ws$on_error(function(event) {
cat("Error:", event$message, "\n")
})
ws$on_close(function(event) {
cat("Disconnected:", event$reason, "\n")
})
# Connect
ws$connect()
# Later: close connection
# ws$close()Frequently Asked Questions (FAQ)
What kind of data can I retrieve using websocketAPIpublic?
You can access real-time public market data including ticker information, order books, candlestick charts (k-lines), trade history, index prices, and funding rates for perpetual swaps—all without authentication.
Do I need an API key to use this class?
No. Since it only accesses public channels, no API key is required. Authentication is only needed for private endpoints like account balance or placing orders.
Can I use this in a production trading system?
Yes, but ensure you implement proper error handling, reconnection logic, and rate limiting. Network interruptions are common, so always monitor on_error and on_close events.
How do I unsubscribe from a data stream?
Send an unsubscribe message with the same channel and instrument ID:
msg <- list(op = "unsubscribe", args = list(list(channel = "candle5m", instId = "BTC-USDT-SWAP")))
client$send(toJSON(msg, auto_unbox = TRUE))Is there a rate limit for subscriptions?
OKX allows multiple subscriptions per connection but limits total concurrent subscriptions. Check the latest OKX API docs for current thresholds.
Can I run multiple instances simultaneously?
Yes. Each websocketAPIpublic object manages its own connection. Just be mindful of system resource usage under heavy load.
👉 Access powerful trading tools and real-time data feeds today.