bybit

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

ByBit Provider

Overview

The ByBit provider is used to fetch the ticker price from the ByBit websocket API.

Connections may be disconnected if a heartbeat ping is not sent to the server every 20 seconds to maintain the connection.

ByBit provides public and private channels.

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

Users can choose to subscribe to one or more topic, and the total length of multiple topics cannot exceed 21,000 characters. This provider is implemented assuming that the user is only subscribing to public topics.

The exact topic that is used to subscribe to the ticker price is the Tickers. This pushes data in real time if there are any price updates.

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

curl "https://api.bybit.com/v5/market/instruments-info" 

Documentation

Index

Constants

View Source
const (
	// OperationSubscribe is the operation to subscribe to a channel.
	OperationSubscribe Operation = "subscribe"
	OperationPing      Operation = "ping"
	OperationPong      Operation = "pong"

	// TickerChannel is the channel for spot price updates.
	TickerChannel Channel = "tickers"
)
View Source
const (

	// Name is the name of the ByBit provider.
	Name = "bybit_ws"

	// URLProd is the public ByBit Websocket URL.
	URLProd = "wss://stream.bybit.com/v5/public/spot"

	// URLTest is the public testnet ByBit Websocket URL.
	URLTest = "wss://stream-testnet.bybit.com/v5/public/spot"

	// DefaultPingInterval is the default ping interval for the ByBit websocket.
	DefaultPingInterval = 15 * time.Second
)

Variables

View Source
var DefaultWebSocketConfig = config.WebSocketConfig{
	Name:                          Name,
	Enabled:                       true,
	MaxBufferSize:                 1000,
	ReconnectionTimeout:           config.DefaultReconnectionTimeout,
	PostConnectionTimeout:         config.DefaultPostConnectionTimeout,
	Endpoints:                     []config.Endpoint{{URL: URLProd}},
	ReadBufferSize:                config.DefaultReadBufferSize,
	WriteBufferSize:               config.DefaultWriteBufferSize,
	HandshakeTimeout:              config.DefaultHandshakeTimeout,
	EnableCompression:             config.DefaultEnableCompression,
	ReadTimeout:                   config.DefaultReadTimeout,
	WriteTimeout:                  config.DefaultWriteTimeout,
	PingInterval:                  DefaultPingInterval,
	WriteInterval:                 config.DefaultWriteInterval,
	MaxReadErrorCount:             config.DefaultMaxReadErrorCount,
	MaxSubscriptionsPerConnection: config.DefaultMaxSubscriptionsPerConnection,
	MaxSubscriptionsPerBatch:      config.DefaultMaxSubscriptionsPerBatch,
}

DefaultWebSocketConfig is the default configuration for the ByBit Websocket.

Functions

func NewHeartbeatPingMessage

func NewHeartbeatPingMessage() ([]handlers.WebsocketEncodedMessage, error)

NewHeartbeatPingMessage returns the encoded message for sending a heartbeat message to a peer.

func NewWebSocketDataHandler

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

NewWebSocketDataHandler returns a new ByBit PriceWebSocketDataHandler.

Types

type BaseRequest

type BaseRequest struct {
	ReqID string `json:"req_id"`
	Op    string `json:"op"`
}

type BaseResponse

type BaseResponse struct {
	Success bool   `json:"success"`
	RetMsg  string `json:"ret_msg"`
	ConnID  string `json:"conn_id"`
	Op      string `json:"op"`
}

BaseResponse is the base structure for responses sent from a peer.

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.

type HeartbeatPing

type HeartbeatPing struct {
	BaseRequest
}

HeartbeatPing is the ping sent to the server.

Example:

{
   "req_id": "100010",
   "op": "ping"
}

type HeartbeatPong

type HeartbeatPong struct {
	BaseResponse
}

HeartbeatPong is the pong sent back from the server after a ping.

Example:

{
   "success": true,
   "ret_msg": "pong",
   "conn_id": "0970e817-426e-429a-a679-ff7f55e0b16a",
   "op": "ping"
}

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.

type SubscriptionRequest

type SubscriptionRequest struct {
	BaseRequest
	Args []string `json:"args"`
}

SubscriptionRequest is a request to the server to subscribe to ticker updates for currency pairs.

Example:

{
   "req_id": "test", // optional
   "op": "subscribe",
   "args": [
       "orderbook.1.BTCUSDT",
       "publicTrade.BTCUSDT",
       "orderbook.1.ETHUSDT"
   ]
}

type SubscriptionResponse

type SubscriptionResponse struct {
	BaseResponse
	ReqID string `json:"req_id"`
}

SubscriptionResponse is the response for a subscribe event.

Example:

{
   "success": true,
   "ret_msg": "subscribe",
   "conn_id": "2324d924-aa4d-45b0-a858-7b8be29ab52b",
   "req_id": "10001",
   "op": "subscribe"
}

type TickerUpdateData

type TickerUpdateData struct {
	Symbol    string `json:"symbol"`
	LastPrice string `json:"lastPrice"`
}

TickerUpdateData is the data stored inside a ticker update message.

type TickerUpdateMessage

type TickerUpdateMessage struct {
	Topic string           `json:"topic"`
	Data  TickerUpdateData `json:"data"`
}

TickerUpdateMessage is the update sent for a subscribed ticker on the ByBit websocket API.

Example:

{
   "topic": "tickers.BTCUSDT",
   "ts": 1673853746003,
   "type": "snapshot",
   "cs": 2588407389,
   "data": {
       "symbol": "BTCUSDT",
       "lastPrice": "21109.77",
       "highPrice24h": "21426.99",
       "lowPrice24h": "20575",
       "prevPrice24h": "20704.93",
       "volume24h": "6780.866843",
       "turnover24h": "141946527.22907118",
       "price24hPcnt": "0.0196",
       "usdIndexPrice": "21120.2400136"
   }

type WebSocketHandler

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

WebSocketHandler implements the WebSocketDataHandler interface. This is used to handle messages received from the ByBit 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 tickers 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 ByBit provider sends three types of messages:

  1. Subscribe response message. The subscribe response message is used to determine if the subscription was successful.
  2. Ticker update message. This is sent when a ticker update is received from the ByBit websocket API.
  3. Heartbeat update messages. This should be sent every 20 seconds to ensure the connection remains open.

func (*WebSocketHandler) HeartBeatMessages

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

HeartBeatMessages is used to construct heartbeat messages to be sent to the data provider. Note that the handler must maintain the necessary state information to construct the heartbeat messages. This can be done on the fly as messages as handled by the handler.

func (*WebSocketHandler) NewSubscriptionRequestMessage

func (h *WebSocketHandler) NewSubscriptionRequestMessage(tickers []string) ([]handlers.WebsocketEncodedMessage, error)

NewSubscriptionRequestMessage creates subscription messages corresponding to the provided tickers. If the number of tickers is greater than 10, the requests will be broken into 10-ticker messages.

Jump to

Keyboard shortcuts

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