cryptodotcom

package
v2.3.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: 10 Imported by: 0

README

Crypto.com Provider

Overview

The Crypto.com provider is used to fetch the ticker price from the Crypto.com websocket API. The websocket is rate limited with a maximum of 100 requests per second. This provider does not require any API keys. To determine the acceptable set of base and quote currencies, you can reference the get instruments API.

To better distribute system load, a single market data websocket connection is limited to a maximum of 400 subscriptions. Once this limit is reached, further subscription requests will be rejected with the EXCEED_MAX_SUBSCRIPTIONS error code. A user should establish multiple connections if additional market data subscriptions are required. The names of the markets (BTCUSD-PERP vs. BTC_USD) represent the perpetual vs. spot markets.

Documentation

Index

Constants

View Source
const (

	// Name is the name of the Crypto.com provider.
	Name = "crypto_dot_com_ws"

	// URL_PROD is the URL used to connect to the Crypto.com production websocket API.
	URL_PROD = "wss://stream.crypto.com/exchange/v1/market"

	// URL_SANDBOX is the URL used to connect to the Crypto.com sandbox websocket API. This will
	// return static prices.
	URL_SANDBOX = "wss://uat-stream.3ona.co/exchange/v1/market"

	// DefaultMaxSubscriptionsPerConnection is the default maximum number of subscriptions per connection.
	// Crypto.com has a limit of 400 but we set it to 200 to be safe.
	//
	// ref: https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#introduction-2
	DefaultMaxSubscriptionsPerConnection = 200

	// DefaultPostConnectionTimeout is the default timeout for post connection. This is the recommended behaviour
	// from the Crypto.com documentation.
	//
	// ref: https://exchange-docs.crypto.com/exchange/v1/rest-ws/index.html#introduction-2
	DefaultPostConnectionTimeout = 1 * time.Second
)
View Source
const (
	// TickerChannel is the channel used to subscribe to the ticker of an instrument.
	TickerChannel string = "ticker.%s"
)

Variables

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

DefaultWebSocketConfig is the default configuration for the Crypto.com Websocket.

Functions

func NewHeartBeatResponseMessage

func NewHeartBeatResponseMessage(id int64) ([]byte, error)

NewHeartBeatResponseMessage returns a new HeartBeatResponse message that can be sent to the Crypto.com websocket API.

func NewWebSocketDataHandler

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

NewWebSocketDataHandler returns a new Crypto.com PriceWebSocketDataHandler.

Types

type HeartBeatResponseMessage

type HeartBeatResponseMessage struct {
	// ID is the ID of the heartbeat message. This must be the same ID that is received
	// from the Crypto.com websocket API.
	ID int64 `json:"id"`

	// Method is the method of the heartbeat message.
	Method string `json:"method"`
}

HeartBeatResponseMessage is the response format that must be sent to the Crypto.com websocket API when a heartbeat message is received.

{
	"id": 1587523073344,
	"method": "public/respond-heartbeat"
}

type InstrumentData

type InstrumentData struct {
	// LatestTradePrice is the price of the latest trade, null if there weren't any trades.
	LatestTradePrice string `json:"a"`

	// Name is the instrument name.
	Name string `json:"i"`
}

InstrumentData is the data of the subscribe message.

type InstrumentParams

type InstrumentParams struct {
	// Channels is the channels that we want to subscribe to.
	Channels []string `json:"channels"`
}

InstrumentParams is the params of the subscribe message.

type InstrumentRequestMessage

type InstrumentRequestMessage struct {
	// Method is the method of the subscribe message.
	Method string `json:"method"`

	// Params is the params of the subscribe message.
	Params InstrumentParams `json:"params"`
}

InstrumentRequestMessage is the request format that must be sent to the Crypto.com websocket API when subscribing to an instrument.

{
		"id": 1,
		"method": "subscribe",
		"params": {
	  		"channels": ["ticker.BTCUSD-PERP", "ticker.ETHUSD-PERP"]
		},
		"nonce": 1587523073344
 }

type InstrumentResponseMessage

type InstrumentResponseMessage struct {
	// ID is the ID of the subscribe message.
	ID int64 `json:"id"`

	// Method is the method of the subscribe message.
	Method string `json:"method"`

	// Result is the result of the subscribe message.
	Result InstrumentResult `json:"result"`

	// Code is the status of the response. 0 means success.
	Code int64 `json:"code"`
}

InstrumentResponseMessage is the response received from the Crypto.com websocket API when subscribing to an instrument i.e. price feed.

{
	"id": -1,
	"method": "subscribe",
	"code": 0,
	"result": {
	  "instrument_name": "BTCUSD-PERP",
	  "subscription": "ticker.BTCUSD-PERP",
	  "channel": "ticker",
	  "data": [{
		"h": "51790.00",        // Price of the 24h highest trade
		"l": "47895.50",        // Price of the 24h lowest trade, null if there weren't any trades
		"a": "51174.500000",    // The price of the latest trade, null if there weren't any trades
		"c": "0.03955106",      // 24-hour price change, null if there weren't any trades
		"b": "51170.000000",    // The current best bid price, null if there aren't any bids
		"bs": "0.1000",         // The current best bid size, null if there aren't any bids
		"k": "51180.000000",    // The current best ask price, null if there aren't any asks
		"ks": "0.2000",         // The current best ask size, null if there aren't any bids
		"i": "BTCUSD-PERP",     // Instrument name
		"v": "879.5024",        // The total 24h traded volume
		"vv": "26370000.12",    // The total 24h traded volume value (in USD)
		"oi": "12345.12",       // Open interest
		"t": 1613580710768
	  }]
	}
}

type InstrumentResult

type InstrumentResult struct {
	// Data is the data of the subscribe message.
	Data []InstrumentData `json:"data"`
}

InstrumentResult is the result of the subscribe message.

type Method

type Method string

Method is the method of the message received from the Crypto.com websocket API.

const (
	// InstrumentMethod is the method used to subscribe to an instrument. This should
	// be called when the initial connection is established.
	InstrumentMethod Method = "subscribe"

	// HeartBeatRequestMethod is the method used to send a heartbeat message to the
	// Crypto.com websocket API. The heartbeat message is sent to the Crypto.com websocket
	// API every 30 seconds.
	HeartBeatRequestMethod Method = "public/heartbeat"

	// HeartBeatResponseMethod is the method used to respond to a heartbeat message
	// from the Crypto.com websocket API. Any heartbeat message received from the Crypto.com
	// websocket API must be responded to with a heartbeat response message with the same ID.
	HeartBeatResponseMethod Method = "public/respond-heartbeat"
)

type StatusCode

type StatusCode int64

StatusCode is the status code of the message received from the Crypto.com websocket API.

const (
	// SuccessStatusCode is the status code of a successful message received from the
	// Crypto.com websocket API.
	SuccessStatusCode StatusCode = iota
)

type WebSocketHandler

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

WebSocketHandler implements the WebSocketDataHandler interface. This is used to handle messages received from the Crypto.com 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 a message to send to the data provider. This is used to subscribe to the given tickers. This is called when the connection to the data provider is first established.

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 Crypto.com websocket API sends a heartbeat message every 30 seconds. If a heartbeat message is received, a heartbeat response message must be sent back to the Crypto.com websocket API, otherwise the connection will be closed. If a subscribe message is received, the message must be parsed and a response must be returned. No update message is required for subscribe messages.

func (*WebSocketHandler) HeartBeatMessages

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

HeartBeatMessages is not used for Crypto.com.

func (*WebSocketHandler) NewInstrumentMessage

func (h *WebSocketHandler) NewInstrumentMessage(instruments []string) ([]handlers.WebsocketEncodedMessage, error)

NewInstrumentMessage returns a new InstrumentRequestMessage that can be sent to the Crypto.com websocket API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳