okx

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 16, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

OKX Provider

Overview

The OKX provider is used to fetch the ticker price from the OKX websocket API. The websocket request size for data transmission between the client and server is only 2 bytes. The total number of requests to subscribe to new markets is limited to 3 requests per second. The total number of 'subscribe'/'unsubscribe'/'login' requests per connection is limited to 480 times per hour. WebSocket login and subscription rate limits are based on connection.

Connections will break automatically if the subscription is not established or data has not been pushed for more than 30 seconds. Per OKX documentation,

If there’s a network problem, the system will automatically disable the connection.

The connection will break automatically if the subscription is not established or data has not been pushed for more than 30 seconds.

To keep the connection stable:

1. Set a timer of N seconds whenever a response message is received, where N is less than 30.
2. If the timer is triggered, which means that no new message is received within N seconds, send the String 'ping'.
3. Expect a 'pong' as a response. If the response message is not received within N seconds, please raise an error or reconnect.

OKX provides public and private channels.

  • Public channels -- No authentication is required, include tickers channel, K-Line channel, limit price channel, order book channel, and mark price channel etc.
  • Private channels -- including account channel, order channel, and position channel, etc -- require log in.

Users can choose to subscribe to one or more channels, and the total length of multiple channels cannot exceed 64 KB. This provider is implemented assuming that the user is only subscribing to public channels.

The exact channel that is used to subscribe to the ticker price is the Index Tickers Channel. This pushes data every 100ms if there are any price updates, otherwise it will push updates once a minute.

To retrieve all supported spot markets, please run the following command:

curl https://www.okx.com/api/v5/public/instruments?instType=SPOT

Documentation

Index

Constants

View Source
const (
	// ExpectedErrorPrefix is the prefix of an error message that is returned by the OKX API.
	// Specifically, this is the prefix of the error message that is returned when the user
	// attempts to subscribe to a channel but could not be subscribed.
	ExpectedErrorPrefix = "Invalid request: "

	// ExpectedErrorElements is the number of elements that are expected in the error message.
	ExpectedErrorElements = 2
)
View Source
const (

	// Name is the name of the OKX provider.
	Name = "okx_ws"

	// URL_PROD is the public OKX Websocket URL.
	URL_PROD = "wss://ws.okx.com:8443/ws/v5/public"

	// URL_PROD_AWS is the public OKX Websocket URL hosted on AWS.
	URL_PROD_AWS = "wss://wsaws.okx.com:8443/ws/v5/public"

	// URL_DEMO is the public OKX Websocket URL for test usage.
	URL_DEMO = "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"

	// WriteInterval is the interval at which the OKX Websocket will write to the connection.
	// By default, there can be 3 messages written to the connection every second. Or 480
	// messages every hour.
	//
	// ref: https://www.okx.com/docs-v5/en/#overview-websocket-overview
	WriteInterval = 3000 * time.Millisecond

	// MaxSubscriptionsPerConnection is the maximum number of subscriptions that can be
	// assigned to a single connection for the OKX provider.
	//
	// ref: https://www.okx.com/docs-v5/en/#overview-websocket-overview
	MaxSubscriptionsPerConnection = 50

	// MaxSubscriptionsPerBatch is the maximum number of subscriptions that can be
	// assigned to a single batch for the OKX provider. We set the limit to 5 to be safe.
	MaxSubscriptionsPerBatch = 25

	// ReadTimeout is the timeout for reading from the OKX Websocket connection.
	ReadTimeout = 15 * time.Second
)

Variables

DefaultWebSocketConfig is the default configuration for the OKX Websocket.

Functions

func NewWebSocketDataHandler

func NewWebSocketDataHandler(
	logger *zap.Logger,
	ws config.WebSocketConfig,
) (types.PriceWebSocketDataHandler, error)

NewWebSocketDataHandler returns a new OKX PriceWebSocketDataHandler.

Types

type BaseMessage

type BaseMessage struct {
	// Event is the event that occurred.
	Event string `json:"event" validate:"required"`
}

BaseMessage is utilized to determine the type of message that was received.

type Channel

type Channel string

Channel is the channel to subscribe to. The channel is used to determine the type of price data that we want. This can later be extended to support other channels. Currently, only the index tickers (spot markets) channel is supported.

const (
	// TickersChannel is the channel for tickers. This includes the spot price of the instrument.
	//
	// ref: https://www.okx.com/docs-v5/en/#order-book-trading-market-data-ws-tickers-channel
	TickersChannel Channel = "tickers"
)

type EventType

type EventType string

EventType is the event type. This is the expected event type that we want to receive from the websocket. The event types pertain to subscription events.

const (
	// EventSubscribe is the event denoting that we have successfully subscribed to a channel.
	EventSubscribe EventType = "subscribe"
	// EventTickers is the event for tickers. By default, this field will not be populated
	// in a properly formatted message. So we set the default value to an empty string.
	EventTickers EventType = ""
	// EventError is the event for an error.
	EventError EventType = "error"
)

type IndexTicker

type IndexTicker struct {
	// ID is the instrument ID.
	ID string `json:"instId" validate:"required"`

	// LastPrice is the last price.
	LastPrice string `json:"last" validate:"required"`
}

IndexTicker is the index ticker data.

type Operation

type Operation string

Operation is the operation to perform. This is used to construct subscription messages when initially connecting to the websocket. This can later be extended to support other operations.

const (
	// OperationSubscribe is the operation to subscribe to a channel.
	OperationSubscribe Operation = "subscribe"
)

type SubscribeRequestMessage

type SubscribeRequestMessage struct {
	// Operation is the operation to perform.
	Operation string `json:"op" validate:"required"`

	// Arguments is the list of arguments for the operation.
	Arguments []SubscriptionTopic `json:"args" validate:"required"`
}

SubscribeRequestMessage is the request message for subscribing to a channel. The format of the message is:

{
		"op": "subscribe",
		"args": ["<SubscriptionTopic>"]
}

Example:

{
	"op": "subscribe",
	"args": [
		{
			"channel": "index-tickers",
			"instId": "LTC-USD-200327"
		},
		{
			"channel": "candle1m",
			"instId": "LTC-USD-200327"
		}
	]
}

For more information, see https://www.okx.com/docs-v5/en/?shell#overview-websocket-subscribe

type SubscribeResponseMessage

type SubscribeResponseMessage struct {
	// Arguments is the list of arguments for the operation.
	Arguments SubscriptionTopic `json:"arg"`

	// Event is the event that occurred.
	Event string `json:"event" validate:"required"`

	// ConnectionID is the connection ID.
	ConnectionID string `json:"connId" validate:"required"`

	// Code is the error code.
	Code string `json:"code,omitempty"`

	// Message is the error message. Note that the field will be populated with the same exact
	// initial message that was sent to the websocket.
	Message string `json:"msg,omitempty"`
}

SubscribeResponseMessage is the response message for subscribing to a channel. The format of the message is: Good Response:

{
		"arg": {
			"channel": "tickers",
			"instId": "LTC-USD-200327"
		},
		"event": "subscribe",
		"connId": "asdf"
}

Bad Response:

{
		"event": "error",
		"code": "60012",
		"msg": "Invalid request: {\"op\": \"subscribe\", \"argss\":[{ \"channel\" : \"index-tickers\", \"instId\" : \"BTC-USDT\"}]}",
		"connId": "a4d3ae55"
}

For more information, see https://www.okx.com/docs-v5/en/?shell#overview-websocket-subscribe

type SubscriptionTopic

type SubscriptionTopic struct {
	// Channel is the channel to subscribe to.
	Channel string `json:"channel" validate:"required"`

	// InstrumentID is the instrument ID to subscribe to.
	InstrumentID string `json:"instId" validate:"required"`
}

SubscriptionTopic is the topic to subscribe to.

type TickersResponseMessage

type TickersResponseMessage struct {
	// Arguments is the list of arguments for the operation.
	Arguments SubscriptionTopic `json:"arg" validate:"required"`

	// Data is the list of index ticker data.
	Data []IndexTicker `json:"data" validate:"required"`
}

TickersResponseMessage is the response message for index ticker updates. This message type is sent when the index price changes. Price changes are pushed every 100ms if there is a change in price. Otherwise, the message is sent every second. The format of the message is:

{
	"arg": {
	  "channel": "tickers",
	  "instId": "BTC-USDT"
	},
	"data": [
	  {
		"instType": "SPOT",
		"instId": "BTC-USDT",
		"last": "9999.99",
		"lastSz": "0.1",
		"askPx": "9999.99",
		"askSz": "11",
		"bidPx": "8888.88",
		"bidSz": "5",
		"open24h": "9000",
		"high24h": "10000",
		"low24h": "8888.88",
		"volCcy24h": "2222",
		"vol24h": "2222",
		"sodUtc0": "2222",
		"sodUtc8": "2222",
		"ts": "1597026383085"
	  }
	]
}

For more information, see https://www.okx.com/docs-v5/en/?shell#public-data-websocket-index-tickers-channel

type WebSocketHandler

type WebSocketHandler struct {
	// contains filtered or unexported fields
}

WebSocketHandler implements the WebSocketDataHandler interface. This is used to handle messages received from the OKX websocket API.

func (*WebSocketHandler) Copy

Copy is used to create a copy of the WebSocketHandler.

func (*WebSocketHandler) CreateMessages

func (h *WebSocketHandler) CreateMessages(
	tickers []types.ProviderTicker,
) ([]handlers.WebsocketEncodedMessage, error)

CreateMessages is used to create an initial subscription message to send to the data provider. Only the currency pairs that are specified in the config are subscribed to. The only channel that is subscribed to is the index tickers channel - which supports spot markets.

func (*WebSocketHandler) HandleMessage

func (h *WebSocketHandler) HandleMessage(
	message []byte,
) (types.PriceResponse, []handlers.WebsocketEncodedMessage, error)

HandleMessage is used to handle a message received from the data provider. The OKX provider sends two types of messages:

  1. Subscribe response message. The subscribe response message is used to determine if the subscription was successful.
  2. Ticker response message. This is sent when a ticker update is received from the OKX websocket API.

Heartbeat messages are NOT sent by the OKX websocket. The connection is only closed iff no data is received within a 30-second interval or if all subscriptions fail. In the case where no data is received within a 30-second interval, the OKX will be restarted after the configured restart interval.

func (*WebSocketHandler) HeartBeatMessages

func (h *WebSocketHandler) HeartBeatMessages() ([]handlers.WebsocketEncodedMessage, error)

HeartBeatMessages is not used for okx.

func (*WebSocketHandler) NewSubscribeToTickersRequestMessage

func (h *WebSocketHandler) NewSubscribeToTickersRequestMessage(
	instruments []SubscriptionTopic,
) ([]handlers.WebsocketEncodedMessage, error)

NewSubscribeToTickersRequestMessage returns a new SubscribeRequestMessage for subscribing to the tickers channel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL