Okx Exchange WebSocket API Public Channel Class Guide

·

Introduction to websocketAPIpublic Class

The websocketAPIpublic class provides access to the public WebSocket channel for Okx Exchange V5 API. This R6 class enables real-time data streaming from Okx's public channels, including market data, tickers, and candlestick information.

Key Features

Class Implementation Details

websocketAPIpublic <- R6::R6Class(
  "websocketAPIpublic",
  public = list(
    #' @field channel Public WebSocket url
    channel = "wss://ws.okx.com:8443/ws/v5/public",
    
    #' @field simulate Whether to use demo trading service
    simulate = NA,
    
    #' @field ws A websocket::WebSocket connection object
    ws = NA,
    
    #' @description Create new websocketAPIpublic object
    #' @param simulate Whether to use demo trading service
    initialize = function(simulate = FALSE) {
      self$simulate <- simulate
      if (simulate) self$channel <- "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"
      self$ws <- websocket::WebSocket$new(self$channel, autoConnect = FALSE)
    },
    
    #' @description Initiate connection to server
    connect = function() {
      self$ws$onOpen(function(event) {
        cat("Connection opened\n")
      })
      self$ws$onMessage(function(event) {
        cat("Client got msg: ", event$data, "\n")
      })
      self$ws$onClose(function(event) {
        cat("Client disconnected with code ", event$code, ": ", event$reason, "\n")
      })
      self$ws$onError(function(event) {
        cat("Client failed to connect: ", event$message, "\n")
      })
      self$ws$connect()
    },
    
    # Additional methods documented in original implementation...
  )
)

Usage Examples

Basic Connection Setup

tmp <- websocketAPIpublic$new()
tmp$connect()

👉 Learn more about Okx WebSocket API best practices

Subscribing to Market Data

# Subscribe to BTC-USDT-SWAP 5m candlesticks
msg <- list(
  op = "subscribe",
  args = list(
    list(channel = "candle5m", instId = "BTC-USDT-SWAP")
  )
)
msg <- jsonlite::toJSON(msg, auto_unbox = TRUE)
tmp$send(msg)

Implementing Custom Callbacks

tmp$on_message(function(event) {
  if (event$data == "pong") {
    cat("Pong received\n")
  } else {
    # Process market data
    print(event$data)
  }
})

Best Practices for WebSocket Connections

  1. Always implement proper error handling
  2. Manage connection state carefully
  3. Implement heartbeat/ping-pong mechanism
  4. Consider rate limits when subscribing to channels

👉 Official Okx API documentation for rate limits

FAQ Section

Q: How do I switch to demo trading environment?
A: Initialize the class with simulate = TRUE parameter.

Q: What channels are available in public API?
A: The public API includes tickers, candles, trades, funding rates, and other market data channels.

Q: How do I unsubscribe from a channel?
A: Send an unsubscribe message with the same arguments used in subscription.

Q: What happens if my connection drops?
A: You should implement reconnect logic in your application.

Q: Is there authentication required for public channels?
A: No, public channels don't require authentication.

Q: Can I use this for trading operations?
A: No, this class is only for public data. For trading, use the private WebSocket API.

Conclusion

The websocketAPIpublic class provides a robust interface for accessing Okx's real-time market data. By following the examples and best practices outlined above, you can effectively integrate WebSocket data into your R applications.