Documentation ¶
Index ¶
- Constants
- Variables
- func NewHeartbeatMessage() ([]handlers.WebsocketEncodedMessage, error)
- func NewWebSocketDataHandler(logger *zap.Logger, ws config.WebSocketConfig) (types.PriceWebSocketDataHandler, error)
- func PreDialHook(cfg config.APIConfig, requestHandler apihandlers.RequestHandler) wshandlers.PreDialHook
- type BaseMessage
- type BulledPublicResponseData
- type BulletPublicResponse
- type BulletPublicResponseInstanceServer
- type MessageType
- type PingRequestMessage
- type SubjectType
- type SubscribeRequestMessage
- type TickerResponseMessage
- type TickerResponseMessageData
- type TopicType
- type WebSocketHandler
- func (h *WebSocketHandler) Copy() types.PriceWebSocketDataHandler
- func (h *WebSocketHandler) CreateMessages(tickers []types.ProviderTicker) ([]handlers.WebsocketEncodedMessage, error)
- func (h *WebSocketHandler) HandleMessage(message []byte) (types.PriceResponse, []handlers.WebsocketEncodedMessage, error)
- func (h *WebSocketHandler) HeartBeatMessages() ([]handlers.WebsocketEncodedMessage, error)
- func (h *WebSocketHandler) NewSubscribeRequestMessage(instruments []string) ([]handlers.WebsocketEncodedMessage, error)
Constants ¶
const ( // BulletPublicEndpoint is the endpoint to connect to the public WSS feed. This // requires a POST request with no body to receive a token and endpoints to // connect to. BulletPublicEndpoint = "/api/v1/bullet-public" // SuccessCode is the success code returned from the KuCoin API. SuccessCode = "200000" // WebSocketProtocol is the expected protocol type for the KuCoin websocket feed. WebSocketProtocol = "websocket" )
const ( // WelcomeMessage represents the welcome message received when first connecting // to the websocket. // // ref: https://www.kucoin.com/docs/websocket/basic-info/create-connection WelcomeMessage MessageType = "welcome" // PingMessage represents a ping / heartbeat message that must be sent to the // websocket server every ping interval. The Ping interval is received and configured // when first connecting to the websocket. // // ref: https://www.kucoin.com/docs/websocket/basic-info/ping PingMessage MessageType = "ping" // PongMessage represents a pong / heartbeat message that is sent from the server // to the client in response to a ping message. // // ref: https://www.kucoin.com/docs/websocket/basic-info/ping PongMessage MessageType = "pong" // SubscribeMessage represents the subscribe message that must be sent to the // websocket server to subscribe to a channel. // // ref: https://www.kucoin.com/docs/websocket/basic-info/subscribe/introduction SubscribeMessage MessageType = "subscribe" // AckMessage represents the response message received from the websocket server // after sending a subscribe message. // // ref: https://www.kucoin.com/docs/websocket/basic-info/subscribe/introduction AckMessage MessageType = "ack" // Message represents a message received from the websocket server. This is returned // after subscribing to a channel and contains the payload for the desired data. // // ref: https://www.kucoin.com/docs/websocket/spot-trading/public-channels/ticker Message MessageType = "message" // TickerTopic represents the ticker topic. This will subscribe to the spot market // ticker for the specified trading pairs. // // ref: https://www.kucoin.com/docs/websocket/spot-trading/public-channels/ticker TickerTopic TopicType = "/market/ticker:" // TickerSubject represents the ticker subject. This should be returned in the // response message when subscribing to the ticker topic. // // ref: https://www.kucoin.com/docs/websocket/spot-trading/public-channels/ticker TickerSubject SubjectType = "trade.ticker" )
const ( // ExpectedTopicLength is the expected length of the topic field in the // TickerResponseMessage. ExpectedTopicLength = 2 // TickerIndex is the index of the ticker in the topic field of the // TickerResponseMessage. TickerIndex = 1 )
const ( // Name is the name of the KuCoin provider. Name = "kucoin_ws" // WSSEndpoint contains the endpoint format for Kucoin websocket API. Specifically // this inputs the dynamically generated token from the user and the endpoint. WSSEndpoint = "%s?token=%s" // WSS is the websocket URL for Kucoin. Note that this may change as the URL is // dynamically generated. A token is required to connect to the websocket feed. WSS = "wss://ws-api-spot.kucoin.com/" // URL is the Kucoin websocket URL. This URL specifically points to the public // spot and maring REST API. URL = "https://api.kucoin.com" // DefaultPingInterval is the default ping interval for the KuCoin websocket. DefaultPingInterval = 10 * time.Second // DefaultMaxSubscriptionsPerConnection is the default maximum number of subscriptions // per connection. By default, KuCoin accepts up to 300 subscriptions per connection. // However we limit this to 50 to prevent overloading the connection. // // ref: https://www.kucoin.com/docs/basic-info/request-rate-limit/websocket DefaultMaxSubscriptionsPerConnection = 25 // DefaultWriteInterval is the default write interval for the KuCoin websocket. // Kucoin allows 100 messages to be sent per 10 seconds. We set this to 300ms to // prevent overloading the connection. // // https://www.kucoin.com/docs/basic-info/request-rate-limit/websocket DefaultWriteInterval = 300 * time.Millisecond // DefaultHandShakeTimeout is the default handshake timeout for the KuCoin websocket. // Assuming that we can create 40 subscriptions every 7.5 seconds, we want to space // out the subscriptions to prevent overloading the connection. So we set the // handshake timeout to 20 seconds. DefaultHandShakeTimeout = 20 * time.Second )
Variables ¶
var ( // DefaultWebSocketConfig defines the default websocket config for Kucoin. DefaultWebSocketConfig = config.WebSocketConfig{ Enabled: true, MaxBufferSize: config.DefaultMaxBufferSize, ReconnectionTimeout: config.DefaultReconnectionTimeout, PostConnectionTimeout: config.DefaultPostConnectionTimeout, Endpoints: []config.Endpoint{{URL: WSS}}, Name: Name, ReadBufferSize: config.DefaultReadBufferSize, WriteBufferSize: config.DefaultWriteBufferSize, HandshakeTimeout: DefaultHandShakeTimeout, EnableCompression: config.DefaultEnableCompression, ReadTimeout: config.DefaultReadTimeout, WriteTimeout: config.DefaultWriteTimeout, PingInterval: DefaultPingInterval, WriteInterval: DefaultWriteInterval, MaxReadErrorCount: config.DefaultMaxReadErrorCount, MaxSubscriptionsPerConnection: DefaultMaxSubscriptionsPerConnection, MaxSubscriptionsPerBatch: config.DefaultMaxSubscriptionsPerBatch, } // DefaultAPIConfig defines the default API config for KuCoin. This is // only utilized on the initial connection to the websocket feed. DefaultAPIConfig = config.APIConfig{ Enabled: false, Timeout: 5 * time.Second, Interval: 1 * time.Minute, MaxQueries: 1, Endpoints: []config.Endpoint{{URL: URL}}, Name: Name, } )
Functions ¶
func NewHeartbeatMessage ¶
func NewHeartbeatMessage() ([]handlers.WebsocketEncodedMessage, error)
NewHeartbeatMessage returns a new heartbeat message.
func NewWebSocketDataHandler ¶
func NewWebSocketDataHandler( logger *zap.Logger, ws config.WebSocketConfig, ) (types.PriceWebSocketDataHandler, error)
NewWebSocketDataHandler returns a new Kucoin PriceWebSocketDataHandler.
func PreDialHook ¶
func PreDialHook(cfg config.APIConfig, requestHandler apihandlers.RequestHandler) wshandlers.PreDialHook
PreDialHook is a function that is called before the connection is established. This function is used to fetch the token and WSS URL from the KuCoin API.
Types ¶
type BaseMessage ¶
type BaseMessage struct { // ID is the ID of the message. ID string `json:"id"` // Type is the type of message. Type string `json:"type"` }
BaseMessage is utilized to determine the type of message that was received.
type BulledPublicResponseData ¶
type BulledPublicResponseData struct { // Token is the token to use for authentication. Token string `json:"token"` // InstanceServers is the list of instance servers to connect to. InstanceServers []BulletPublicResponseInstanceServer `json:"instanceServers"` }
BulledPublicResponseData is the data field of the BulletPublicResponse.
type BulletPublicResponse ¶
type BulletPublicResponse struct { // Code is the response code. Code string `json:"code"` // Data is the response data. Data BulledPublicResponseData `json:"data"` }
BulletPublicResponse represents the response from the bullet-public endpoint for the KuCoin exchange. This response is utilized when initially connecting to the websocket feed. Specifically, the response is utilized to determine the token and endpoints to connect to.
{ "code": "200000", "data": { "token": "token1234567890", // Used to suffix the WSS URL "instanceServers": [ { "endpoint": "wss://ws-api-spot.kucoin.com/", // It is recommended to use a dynamic URL, which may change "encrypt": true, "protocol": "websocket", "pingInterval": 18000, // We use this as the ping interval "pingTimeout": 10000 // We use this as the read timeout } ] } }
type BulletPublicResponseInstanceServer ¶
type BulletPublicResponseInstanceServer struct { // Endpoint is the endpoint to connect to. Endpoint string `json:"endpoint"` // Encrypt is a flag that indicates if the connection should be encrypted. Encrypt bool `json:"encrypt"` // Protocol is the protocol to use for the connection. Protocol string `json:"protocol"` // PingInterval is the interval to ping the server. PingInterval int64 `json:"pingInterval"` // PingTimeout is the timeout for the ping. PingTimeout int64 `json:"pingTimeout"` }
BulletPublicResponseInstanceServer is the instance server to connect to.
type MessageType ¶
type MessageType string
MessageType represents the type of message received from the KuCoin websocket.
type PingRequestMessage ¶
type PingRequestMessage struct {
BaseMessage
}
PingRequestMessage represents the ping message that must be sent to the websocket server every ping interval.
{ "id": "1545910590801", "type": "ping" }
type SubjectType ¶
type SubjectType string
SubjectType represents the type of subject that was subscribed to i.e. ticker.
type SubscribeRequestMessage ¶
type SubscribeRequestMessage struct { // ID is the ID of the message. ID int64 `json:"id"` // Type is the type of message. Type string `json:"type"` // Topic is the topic to subscribe to. Topic string `json:"topic"` // PrivateChannel is a flag that indicates if the channel is private. PrivateChannel bool `json:"privateChannel"` // Response is a flag that indicates if the server should return the receipt // information of this subscription. Response bool `json:"response"` }
SubscribeRequestMessage represents the subscribe message that must be sent to the websocket server to subscribe to a channel.
Spot Demo
{ "id": 1545910660739, // The id should be a unique value "type": "subscribe", "topic": "/market/ticker:BTC-USDT,ETH-USDT", // Topic needs to be subscribed. Some topics support to divisional subscribe the information of multiple trading pairs through ",". "privateChannel": false, // Adopted the private channel or not. Set as false by default. "response": true // Whether the server needs to return the receipt information of this subscription or not. Set as false by default. }
ref: https://www.kucoin.com/docs/websocket/basic-info/subscribe/introduction
type TickerResponseMessage ¶
type TickerResponseMessage struct { // Type is the type of message. Type string `json:"type"` // Topic is the topic of the message. Topic string `json:"topic"` // Subject is the subject of the message. Subject string `json:"subject"` // Data is the data of the message. Data TickerResponseMessageData `json:"data"` }
TickerResponseMessage represents the ticker response message received from the websocket server.
{ "type": "message", "topic": "/market/ticker:BTC-USDT", "subject": "trade.ticker", "data": { "sequence": "1545896668986", // Sequence number "price": "0.08", // Last traded price "size": "0.011", // Last traded amount "bestAsk": "0.08", // Best ask price "bestAskSize": "0.18", // Best ask size "bestBid": "0.049", // Best bid price "bestBidSize": "0.036", // Best bid size "Time": 1704873323416 //The matching time of the latest transaction } }
ref: https://www.kucoin.com/docs/websocket/spot-trading/public-channels/ticker
type TickerResponseMessageData ¶
type TickerResponseMessageData struct { // Sequence is the sequence number. Sequence string `json:"sequence"` // Price is the last traded price. Price string `json:"price"` }
TickerResponseMessageData is the data field of the TickerResponseMessage.
type TopicType ¶
type TopicType string
TopicType represents the type of topic to subscribe to i.e. spot for this implementation.
type WebSocketHandler ¶
type WebSocketHandler struct {
// contains filtered or unexported fields
}
WebSocketDataHandler implements the WebSocketDataHandler interface. This is used to handle messages received from the KuCoin websocket API.
func (*WebSocketHandler) Copy ¶
func (h *WebSocketHandler) Copy() types.PriceWebSocketDataHandler
Copy is used to create a copy of the data handler.
func (*WebSocketHandler) CreateMessages ¶
func (h *WebSocketHandler) CreateMessages( tickers []types.ProviderTicker, ) ([]handlers.WebsocketEncodedMessage, error)
CreateMessages is used to create the initial set of subscribe messages to send to the KuCoin websocket API. The subscribe messages are created based on the currency pairs that are configured for the provider.
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 KuCoin web socket expects the client to send a subscribe message within 10 seconds of the connection, with a ping message sent every 10 seconds. There are 4 types of messages that can be received from the KuCoin websocket:
- WelcomeMessage: This is sent by the KuCoin websocket when the connection is established.
- PongMessage: This is sent by the KuCoin websocket in response to a ping message.
- AckMessage: This is sent by the KuCoin websocket in response to a subscribe message.
- Message: This is sent by the KuCoin websocket when a match happens.
func (*WebSocketHandler) HeartBeatMessages ¶
func (h *WebSocketHandler) HeartBeatMessages() ([]handlers.WebsocketEncodedMessage, error)
HeartBeatMessages is used to create the set of heartbeat messages to send to the KuCoin websocket API. Per the KuCoin websocket documentation, the interval between heartbeats should be around 10 seconds, however, this is dynamic. As such, the websocket connection handler will determine both the credentials and desired ping interval during the pre-dial hook.
func (*WebSocketHandler) NewSubscribeRequestMessage ¶
func (h *WebSocketHandler) NewSubscribeRequestMessage( instruments []string, ) ([]handlers.WebsocketEncodedMessage, error)
NewSubscribeRequestMessage returns a new SubscribeRequestMessage.