websocket

package
v0.0.0-...-eb215bf Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

This package provides interfaces and implementations for websocket clients using Kraken spot websocket API (both public and private environments)

Index

Constants

View Source
const (
	// URL for Kraken spot websocket client - public endpoints - Production
	KrakenSpotWebsocketPublicProductionURL = "wss://ws.kraken.com"
	// URL for Kraken spot websocket client - public endpoints - Beta
	KrakenSpotWebsocketPublicBetaURL = "wss://beta-ws.kraken.com"
	// URL for Kraken spot websocket client - private endpoints - Production
	KrakenSpotWebsocketPrivateProductionURL = "wss://ws-auth.kraken.com"
	// URL for Kraken spot websocket client - private endpoints - Beta
	KrakenSpotWebsocketPrivateBetaURL = "wss://beta-ws-auth.kraken.com"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AddOrderRequestParameters

type AddOrderRequestParameters struct {
	// Order type. Cf. OrderTypeEnum for values.
	OrderType string `json:"ordertype"`
	// Side, buy or sell. Cf. SideEnum for values.
	Type string `json:"type"`
	// Currency pair.
	Pair string `json:"pair"`
	// Order price
	Price string `json:"price,omitempty"`
	// Order secondary price
	Price2 string `json:"price2,omitempty"`
	// Order secondary price
	// Order volume in base currency
	Volume string `json:"volume"`
	// Amount of leverage desired.
	//
	// A zero value means no leverage.
	Leverage int `json:"leverage,omitempty"`
	// If true, order will only reduce a currently open position, not increase it or open a new position.
	ReduceOnly bool `json:"reduce_only,omitempty"`
	// Optional comma delimited list of order flags. Cf. OrderFlagEnum for values.
	//
	// viqc = volume in quote currency (not currently available), fcib = prefer fee in base currency, fciq = prefer fee in quote currency,
	// nompp = no market price protection, post = post only order (available when ordertype = limit)
	//
	// An empty string means no order flags to provide.
	OFlags string `json:"oflags,omitempty"`
	// Optional - scheduled start time.
	//
	// Values can be:
	//	- 0 = now (default)
	//	- +<n> = schedule start time <n> seconds from now
	//	- <n> = unix timestamp of start time
	//
	// An empty string triggers the default behavior (startm = now)
	StartTimestamp string `json:"starttm,omitempty"`
	// Optional - expiration time.
	//
	// Values can be:
	//	- 0 = no expiration (default)
	//	- +<n> = schedule start time <n> seconds from now
	//	- <n> = unix timestamp of start time
	//
	// An empty string triggers the default behavior (no expiration)
	ExpireTimestamp string `json:"expiretm,omitempty"`
	// Optional - RFC3339 timestamp (e.g. 2021-04-01T00:18:45Z) after which matching engine should reject new order request,4 in presence of latency
	// or order queueing. min now + 2 seconds, max now + 60 seconds. Defaults to now + 60 seconds if not specified.
	//
	// An empty string triggers the default behavior.
	Deadline string `json:"deadline,omitempty"`
	// Optional - user reference ID (should be an integer in quotes)
	UserReference string `json:"userref,omitempty"`
	// Optional - if true, validate inputs only; do not submit order.
	//
	// Default to false.
	Validate bool `json:"validate,omitempty"`
	// Optional close order type. Cf. OrderTypeEnum
	CloseOrderType string `json:"close[ordertype],omitempty"`
	// Optional - close order price.
	ClosePrice string `json:"close[price],omitempty"`
	// Optional - close order secondary price.
	ClosePrice2 string `json:"close[price2],omitempty"`
	// Optional - time in force. Cf. TimeInForceEnum for values.
	//
	// Default to GTC (good-til-cancelled). An empty string triggers the default behavior.
	TimeInForce string `json:"timeinforce,omitempty"`
}

AddOrder request parameters

type CancelAllOrdersAfterXRequestParameters

type CancelAllOrdersAfterXRequestParameters struct {
	// Timeout specified in seconds. 0 to disable the timer.
	Timeout int `json:"timeout"`
}

CancelAllOrdersAfterX request parameters

type CancelOrderRequestParameters

type CancelOrderRequestParameters struct {
	// Array of order IDs to be canceled. These can be user reference IDs.
	TxId []string `json:"txid"`
}

CancelOrder request parameters

type EditOrderRequestParameters

type EditOrderRequestParameters struct {
	// Original Order ID or userref.
	Id string `json:"orderid"`
	// Currency pair.
	Pair string `json:"pair"`
	// Optional dependent on order type - order price
	//
	// An empty string can be used when price2 is not used.
	Price string `json:"price,omitempty"`
	// Optional dependent on order type - order secondary price
	//
	// An empty string can be used when price2 is not used.
	Price2 string `json:"price2,omitempty"`
	// Order volume in base currency
	Volume string `json:"volume,omitempty"`
	// Optional comma delimited list of order flags. C f. OrderFlagEnum for values.
	//
	// viqc = volume in quote currency (not currently available), fcib = prefer fee in base currency, fciq = prefer fee in quote currency,
	// nompp = no market price protection, post = post only order (available when ordertype = limit)
	//
	// An empty string means no order flags to provide.
	OFlags string `json:"oflags,omitempty"`
	// Optional - user reference ID for new order (should be an integer in quotes)
	//
	// An empty string means no new user reference will be defined.
	NewUserReference string `json:"newuserref,omitempty"`
	// Optional - if true, validate inputs only; do not submit order.
	//
	// Default to false.
	Validate bool `json:"validate,omitempty"`
}

EditOrder request parameters

At least one of the optional edittable data must be set.

type KrakenSpotPrivateWebsocketClient

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

Kraken spot websocket client with access to private endpoints

func NewKrakenSpotPrivateWebsocketClient

func NewKrakenSpotPrivateWebsocketClient(
	restClient rest.KrakenSpotRESTClientIface,
	clientNonceGenerator noncegen.NonceGenerator,
	secopts *restcommon.SecurityOptions,
	onCloseCallback func(ctx context.Context, closeMessage *wsclient.CloseMessageDetails),
	onReadErrorCallback func(ctx context.Context, restart context.CancelFunc, exit context.CancelFunc, err error),
	onRestartError func(ctx context.Context, exit context.CancelFunc, err error, retryCount int),
	logger *log.Logger,
	tracerProvider trace.TracerProvider) (*KrakenSpotPrivateWebsocketClient, error)

Description

Factory which creates a KrakenSpotPrivateWebsocketClient that can be provided to a websocket engine (wscengine.WebsocketEngine - Cf. https://github.com/gbdevw/gowse).

Inputs

  • restClient: Optional Kraken spot rest client to use to get a websocket token. Must not be nil.
  • clientNonceGenerator: Optional nonce generator used to get nonces used to sign requests sent with the REST Client. Must not be nil.
  • secopts: Optional security options (like password 2FA) to use when sending requests with the REST client. Can be nil if 2FA is not used.
  • onCloseCallback: optional user defined callback which will be called when connection is closed/interrupted.
  • onReadErrorCallback: optional user defined callback which will be called when an error occurs while reading messages from the websocket server
  • onRestartError: optional user defined callback which will be called when the websocket engine fails to reconnect to the server.
  • logger: Optional logger used to log debug/vebrose messages. If nil, a logger with a discard writer (noop) will be used
  • tracerProvider: Tracer provider to use to get a tracer to instrument websocket client code. If nil, global tracer provider will be used.

Return

A new KrakenSpotPrivateWebsocketClient

func (KrakenSpotPrivateWebsocketClient) AddOrder

func (client KrakenSpotPrivateWebsocketClient) AddOrder(ctx context.Context, params AddOrderRequestParameters) (*messages.AddOrderResponse, error)

Description

Add a new order and wait until a AddOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: AddOrder request parameters.

Return

The AddOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPrivateWebsocketClient) CancelOrder

func (client KrakenSpotPrivateWebsocketClient) CancelOrder(ctx context.Context, params CancelOrderRequestParameters) (*messages.CancelOrderResponse, error)

Description

Cancel one or several existing orders and wait until a CancelOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: CancelOrder request parameters.

Return

The CancelOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPrivateWebsocketClient) CancellAllOrders

func (client KrakenSpotPrivateWebsocketClient) CancellAllOrders(ctx context.Context) (*messages.CancelAllOrdersResponse, error)

Description

Cancel all orders and wait until a CancelAllOrdersResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.

Return

The CancelAllOrdersResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPrivateWebsocketClient) CancellAllOrdersAfterX

func (client KrakenSpotPrivateWebsocketClient) CancellAllOrdersAfterX(ctx context.Context, params CancelAllOrdersAfterXRequestParameters) (*messages.CancelAllOrdersAfterXResponse, error)

Description

Set, extend or unset a timer which cancels all orders when expiring and wait until a response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: CancellAllOrdersAfterX request parameters.

Return

The CancelAllOrdersAfterXResponse message from the server if any has been received. In case the response has its error message set, an error with the error message is also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPrivateWebsocketClient) EditOrder

func (client KrakenSpotPrivateWebsocketClient) EditOrder(ctx context.Context, params EditOrderRequestParameters) (*messages.EditOrderResponse, error)

Description

Edit an existing order and wait until a EditOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: EditOrder request parameters.

Return

The EditOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPrivateWebsocketClient) GetHeartbeatChannel

func (client KrakenSpotPrivateWebsocketClient) GetHeartbeatChannel() chan event.Event

Description

Get the client's built-in channel to publish received heartbeats.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • heartbeat

    # Return

Implemetation and usage guidelines

  • The client MUST provide the channel it will use to publish heartbeats even though the cllient has not been started yet and is not connected to the server.

  • The client MUST close the channel when it definitely stops.

  • As the channel is automatically subscribed to, the client implementation must deal with possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client must indicate how congestion is handled.

Return

The client's built-in channel used to publish received heartbeats.

func (KrakenSpotPrivateWebsocketClient) GetSystemStatusChannel

func (client KrakenSpotPrivateWebsocketClient) GetSystemStatusChannel() chan event.Event

Description

Get the client's built-in channel used to publish received system status updates.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • system_status

    # Return

The client's built-in channel used to publish received system status updates.

Implemetation and usage guidelines

  • The client MUST provide the channel it will use to publish heartbeats even though the cllient has not been started yet and is not connected to the server.

  • The client MUST close the channel when it definitely stops.

  • As the channel is automatically subscribed to, the client implementation must deal with possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client must indicate how congestion is handled.

func (KrakenSpotPrivateWebsocketClient) OnClose

func (client KrakenSpotPrivateWebsocketClient) OnClose(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	closeMessage *wsclient.CloseMessageDetails) *wsclient.CloseMessageDetails

Description

Callback is called when the websocket connection is closed or about to be closed after a Stop method call or a call to the provided restart/exit functions. Callback is called once by the engine: the engine will not exit or restart until the callback has been completed.

Callback can return an optional CloseMessageDetails which will be used to build the close message sent to the server if the connection needs to be closed after OnClose has finished. In such a case, if the returned value is nil, the engine will use 1001 "Going Away" as the close message.

Do not close the websocket connection here if it is still open: It will be automatically closed by the engine with a close message.

Inputs

  • ctx: Context produced from the websocket engine context and bound to OnClose lifecycle.
  • conn: Connection to the websocket server that is closed or about to close.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • closeMessage: Websocket close message received from server or generated by the engine when connection has been closed. If nil, connection might not be closed and will be closed by the engine using the returned close message or the default 1001 "Going Away".

Returns

A specific close message to send back to the server if connection has to be closed after this callback completes.

Warning

Provided context will already be canceled.

func (KrakenSpotPrivateWebsocketClient) OnCloseError

func (client KrakenSpotPrivateWebsocketClient) OnCloseError(
	ctx context.Context,
	err error)

Description

Callback called if an error occurred when the engine called the conn.Close method during the shutdown phase.

Inputs

  • ctx: Context produced OnClose context.
  • err: Error returned by conn.Close method

func (KrakenSpotPrivateWebsocketClient) OnMessage

func (client KrakenSpotPrivateWebsocketClient) OnMessage(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	restart context.CancelFunc,
	exit context.CancelFunc,
	sessionId string,
	msgType wsadapters.MessageType,
	msg []byte)

Description

Callback called when a message is read from the server. The goroutine which has read the message will block until callback completes. Meanwhile, other goroutines, if any, can read and process other incoming messages unless read mutex is locked.

Inputs

  • ctx: context produce from websocket engine context and bound to OnMessage lifecycle.
  • conn: Websocket adapter provided during engine creation with a connection opened.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • restart: Function to call to instruct engine to stop and restart.
  • exit: Function to call to definitely stop the engine.
  • sessionId: Unique identifier produced by engine for each new websocket connection and bound to the websocket connection lifetime.
  • msgType: Message type returned by read function.
  • msg: Received message as a byte array

Engine behavior on exit/restart call

  • No other messages will be read if restart or exit is called.

  • Engine will stop after OnMessage is completed: OnClose callback is called and then the connection is closed. Depending on which function was called, the engine will restart or stop for good.

  • All pending messages will be discarded. The user can continue to read and send messages in this callback and/or in the OnClose callback until conditions are met to stop the engine and close the websocket connection.

func (KrakenSpotPrivateWebsocketClient) OnOpen

func (client KrakenSpotPrivateWebsocketClient) OnOpen(
	ctx context.Context,
	resp *http.Response,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	exit context.CancelFunc,
	restarting bool) error

Description

In case the client is reconnecting to the server, the client will attempt to resubscribe to all channels that have been previously subscribed. The client will attempts at most three times to resubscribe. THe client will not wait for resubscribe to succeed before resuming its operations.

It is up to the user to monitor interruptions in stream of data and react according its own needs and requirements. In such a case, user can either kill/restart its application, unsubscribe and resubscribe to channel or shutdown and start again the wesocket client.

OnOpen Documentation

Callback called when engine has (re)opened a connection to the websocket server. OnOpen is called once, synchronously by the engine during its (re)start phase: no messages or events will be processed until callback completes or a timeout occurs (default: 5 minutes).

If OnOpen callback returns an error, websocket engine will:

  • If starting: engine will close the opened connection and stop.
  • If restarting: engine will close the opened connection and try to restart again.

No other callbacks (OnReadError & OnClose) will be used in such cases.

During OnOpen call, the provided exit function can be called to definitely stop the engine.

Inputs

  • ctx: context produced from the websocket engine context and bound to OnOpen lifecycle.
  • resp: The server response to the websocket handshake.
  • conn: Websocket adapter provided during engine creation. Connection is now opened.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • exit: Function to call to definitely stop the engine (ex: when stuck in retry loop).
  • restarting: Flag which indicates whether engine restarts (true) or is starting (false).

Returns

nil in case of success or an error if an error occured during OnOpen execution.

When engine is restarting, returning an error will cause engine to restart again.

Engine behavior after OnOpen completes

If nil is returned and if exit function has not been called, engine will finish starting and create internal goroutines which will manage the websocket connection.

If an error is returned, engine will close the opened connection and do the following:

  • If engine is starting, engine will definitely stop. Calling exit will do nothing.
  • If engine is restarting, engine will try again to restart.
  • If engine is restarting and exit has been called, engine will definitely stop.

func (KrakenSpotPrivateWebsocketClient) OnReadError

func (client KrakenSpotPrivateWebsocketClient) OnReadError(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	restart context.CancelFunc,
	exit context.CancelFunc,
	err error)

Description

This callback is called each time an error is received when reading messages from the websocket server that is not caused by the connection being closed.

The callback is called by the engine goroutine that encountered the error. All engine goroutines will block until the callback is completed. This prevents other messages and events from being processed by the engine while the error is being handled.

The engine will restart after OnReadError has finished if one of the following conditions is met: - The websocket connection is closed and the Exit function has not been called. - The restart function has been called.

Otherwise, the engine will either continue to process messages on the same connection or shut down if the exit function has been called.

Do not close the websocket connection manually: It will be automatically closed if necessary after the OnClose callback has been completed.

Inputs

  • ctx: Context produced from the websocket engine context and bound to OnReadError lifecycle.
  • conn: Connection to the websocket server.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • restart: Function to call to instruct engine to stop and restart.
  • exit: Function to call to definitely stop the engine.
  • err: Error returned by the websocket read operation.

Engine behavior on exit/restart call

  • No other messages are read when restart or exit is called.

  • Engine will stop after OnReadError: OnClose callback is called and then the connection is closed. Depending on which function was called, the engine will restart or stop for good.

  • All pending messages will be discarded. The user can continue to read and send messages in this callback and/or in the OnClose callback until conditions are met to stop the engine and close the websocket connection.

func (KrakenSpotPrivateWebsocketClient) OnRestartError

func (client KrakenSpotPrivateWebsocketClient) OnRestartError(
	ctx context.Context,
	exit context.CancelFunc,
	err error,
	retryCount int)

Description

Callback called in case an error or a timeout occured when engine tried to restart.

Inputs

  • ctx: Context used for tracing purpose. Will be Done in case a timeout has occured.
  • exit: Function to call to stop trying to restart the engine.
  • err: Error which has occured when restarting the engine
  • retryCount: Number of restart retry since last time engine has successfully (re)started.

func (KrakenSpotPrivateWebsocketClient) Ping

func (client KrakenSpotPrivateWebsocketClient) Ping(ctx context.Context) error

Description

Send a ping to the websocket server and wait until a Pong response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.

Return

Nil in case of success. Otherwise, an error is returned when:

  • An error occurs when sending the message.
  • The provided context expires before pong is received (OperationInterruptedError).
  • An error message is received from the server (OperationError).

func (KrakenSpotPrivateWebsocketClient) SubscribeBook

func (client KrakenSpotPrivateWebsocketClient) SubscribeBook(ctx context.Context, pairs []string, depth messages.DepthEnum, rcv chan event.Event) error

Description

Subscribe to the book channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Three types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • book_snapshot: This event type is used when a snapshot of the order book is received from the websocket server.
  • book_update: This event is used when an update about the order book is received from the websocket server.

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeBook
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • book_snapshot
  • book_update

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.BookUpdate or messages.BookSnapshot depending on the event type like this:

switch(WebsocketClientEventTypeEnum(event.Type)) {
	case events.BookSnapshot:
		snapshot := new(messages.BookSnapshot)
		err := event.DataAs(snapshot)
	case events.BookUpdate:
		update := new(messages.BookUpdate)
		err := event.DataAs(update)
	case events.ConnectionInterrupted:
		panic("connection lost")
	default:
		panic("unknown message type", event.Type)
}

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish book_snapshot & book+update messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeOHLC

func (client KrakenSpotPrivateWebsocketClient) SubscribeOHLC(ctx context.Context, pairs []string, interval messages.IntervalEnum, rcv chan event.Event) error

Description

Subscribe to the ohlc channel with the given interval. In case of success, the websocket client will start publishing received events on the user's provided channel.

The client supports multiple subscriptions but for different interval. The client will return an error in case there's already a subscription for that interval.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • ohlc: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOHLC
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • ohlc

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OHLC like this:

ohlc := new(messages.OHLC)
err := event.DataAs(ohlc)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • interval: Interval for produced OHLC indicators.
  • rcv: Channel used to publish ohlc messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription for that interval.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeOpenOrders

func (client KrakenSpotPrivateWebsocketClient) SubscribeOpenOrders(ctx context.Context, rateCounter bool, rcv chan event.Event) error

Description

Subscribe to the openOrders channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • open_orders: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOpenOrders
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • open_orders

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OpenOrders like this:

openOrders := new(messages.OpenOrders)
err := event.DataAs(openOrders)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • rateCounter: If true, rate limiting information will be included in messages.
  • rcv: Channel used to publish open_orders messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeOwnTrades

func (client KrakenSpotPrivateWebsocketClient) SubscribeOwnTrades(ctx context.Context, snapshot bool, consolidateTaker bool, rcv chan event.Event) error

Description

Subscribe to the ownTrades channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • own_trades: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOwnTrades
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • own_trades

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OwnTrades like this:

ownTrade := new(messages.OwnTrades)
err := event.DataAs(ownTrade)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • snapshot: If true, upon subscription, the 50 most recent user trades will be published.
  • consolidateTaker: Whether to consolidate order fills by root taker trade(s).
  • rcv: Channel used to publish own_trades messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires (timeout/cancel) before subscription is completed.
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active susbscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeSpread

func (client KrakenSpotPrivateWebsocketClient) SubscribeSpread(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the spreads channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • spread: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeSpreads
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • spread

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Spread like this:

spread := new(messages.Spread)
err := event.DataAs(spread)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish spread messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeTicker

func (client KrakenSpotPrivateWebsocketClient) SubscribeTicker(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the tickers channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

This client implementation uses

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • ticker: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeTickers
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • ticker

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Ticker like this:

ticker := new(messages.Ticker)
err := event.DataAs(ticker)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish ticker messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) SubscribeTrade

func (client KrakenSpotPrivateWebsocketClient) SubscribeTrade(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the trades channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • trade: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeTrades
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • trade

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Trade like this:

trade := new(messages.Trade)
err := event.DataAs(trade)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish trade messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeBook

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeBook(ctx context.Context) error

Description

Unsubscribe from the book channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeOHLC

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeOHLC(ctx context.Context, interval messages.IntervalEnum) error

Description

Unsubscribe from the ohlc channel with the given interva. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • interval: Used to determine which subscription must be cancelled.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeOpenOrders

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeOpenOrders(ctx context.Context) error

Description

Unsubscribe from the openOrders channel. The channel provided on subscribe will bbe closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeOwnTrades

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeOwnTrades(ctx context.Context) error

Description

Unsubscribe from the ownTrades channel. The channel provided on subscribe will bbe closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeSpread

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeSpread(ctx context.Context) error

Description

Unsubscribe from the spread channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeTicker

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeTicker(ctx context.Context) error

Description

Unsubscribe from the ticker channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPrivateWebsocketClient) UnsubscribeTrade

func (client KrakenSpotPrivateWebsocketClient) UnsubscribeTrade(ctx context.Context) error

Description

Unsubscribe from the trade channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

type KrakenSpotPrivateWebsocketClientInterface

type KrakenSpotPrivateWebsocketClientInterface interface {
	// # Description
	//
	// Send a ping to the websocket server and wait until a Pong response is received from the
	// server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//
	// # Return
	//
	// Nil in case of success. Otherwise, an error is returned when:
	//
	//	- An error occurs when sending the message.
	//	- The provided context expires before pong is received (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	Ping(ctx context.Context) error
	// # Description
	//
	// Add a new order and wait until a AddOrderResponse response is received from the server or
	// until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//	- params: AddOrder request parameters.
	//
	// # Return
	//
	// The AddOrderResponse message from the server if any has been received. In case the response
	// has its error message set, an error with the error message will also be returned.
	//
	// An error is returned when:
	//
	//	- The client failed to send the request (no specific error type).
	//	- A timeout has occured before the request could be sent (no specific error type)
	//	- An error message is received from the server (OperationError).
	//	- A timeout or network failure occurs after sending the request to the server, while
	//    waiting for the server response. In this case, a OperationInterruptedError is returned.
	AddOrder(ctx context.Context, params AddOrderRequestParameters) (*messages.AddOrderResponse, error)
	// # Description
	//
	// Edit an existing order and wait until a EditOrderResponse response is received from the
	// server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//	- params: EditOrder request parameters.
	//
	// # Return
	//
	// The EditOrderResponse message from the server if any has been received. In case the response
	// has its error message set, an error with the error message will also be returned.
	//
	// An error is returned when:
	//
	//	- The client failed to send the request (no specific error type).
	//	- A timeout has occured before the request could be sent (no specific error type)
	//	- An error message is received from the server (OperationError).
	//	- A timeout or network failure occurs after sending the request to the server, while
	//    waiting for the server response. In this case, a OperationInterruptedError is returned.
	EditOrder(ctx context.Context, params EditOrderRequestParameters) (*messages.EditOrderResponse, error)
	// # Description
	//
	// Cancel one or several existing orders and wait until a CancelOrderResponse response is
	// received from the server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//	- params: CancelOrder request parameters.
	//
	// # Return
	//
	// The CancelOrderResponse message from the server if any has been received. In case the response
	// has its error message set, an error with the error message will also be returned.
	//
	// An error is returned when:
	//
	//	- The client failed to send the request (no specific error type).
	//	- A timeout has occured before the request could be sent (no specific error type)
	//	- An error message is received from the server (OperationError).
	//	- A timeout or network failure occurs after sending the request to the server, while
	//    waiting for the server response. In this case, a OperationInterruptedError is returned.
	CancelOrder(ctx context.Context, params CancelOrderRequestParameters) (*messages.CancelOrderResponse, error)
	// # Description
	//
	// Cancel all orders and wait until a CancelAllOrdersResponse response is received from the
	// server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//
	// # Return
	//
	// The CancelAllOrdersResponse message from the server if any has been received. In case the response
	// has its error message set, an error with the error message will also be returned.
	//
	// An error is returned when:
	//
	//	- The client failed to send the request (no specific error type).
	//	- A timeout has occured before the request could be sent (no specific error type)
	//	- An error message is received from the server (OperationError).
	//	- A timeout or network failure occurs after sending the request to the server, while
	//    waiting for the server response. In this case, a OperationInterruptedError is returned.
	CancellAllOrders(ctx context.Context) (*messages.CancelAllOrdersResponse, error)
	// # Description
	//
	// Set, extend or unset a timer which cancels all orders when expiring and wait until a
	// response is received from the server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//	- params: CancellAllOrdersAfterX request parameters.
	//
	// # Return
	//
	// The CancelAllOrdersAfterXResponse message from the server if any has been received. In case
	// the response has its error message set, an error with the error message is also be returned.
	//
	// An error is returned when:
	//
	//	- The client failed to send the request (no specific error type).
	//	- A timeout has occured before the request could be sent (no specific error type)
	//	- An error message is received from the server (OperationError).
	//	- A timeout or network failure occurs after sending the request to the server, while
	//    waiting for the server response. In this case, a OperationInterruptedError is returned.
	CancellAllOrdersAfterX(ctx context.Context, params CancelAllOrdersAfterXRequestParameters) (*messages.CancelAllOrdersAfterXResponse, error)
	// # Description
	//
	// Subscribe to the ownTrades channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- own_trades: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeOwnTrades
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- own_trades
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.OwnTrades like this:
	//
	//	ownTrade := new(messages.OwnTrades)
	//	err := event.DataAs(ownTrade)
	//
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- snapshot: If true, upon subscription, the 50 most recent user trades will be published.
	//	- consolidateTaker: Whether to consolidate order fills by root taker trade(s).
	//	- rcv: Channel used to publish own_trades messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires (timeout/cancel) before subscription is completed.
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active susbscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeOwnTrades(ctx context.Context, snapshot bool, consolidateTaker bool, rcv chan event.Event) error
	// # Description
	//
	// Subscribe to the openOrders channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- open_orders: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeOpenOrders
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- open_orders
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.OpenOrders like this:
	//
	//	openOrders := new(messages.OpenOrders)
	//	err := event.DataAs(openOrders)
	//
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- rateCounter: If true, rate limiting information will be included in messages.
	//	- rcv: Channel used to publish open_orders messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeOpenOrders(ctx context.Context, rateCounter bool, rcv chan event.Event) error
	// # Description
	//
	// Unsubscribe from the ownTrades channel. The channel provided on subscribe will bbe closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeOwnTrades(ctx context.Context) error
	// # Description
	//
	// Unsubscribe from the openOrders channel. The channel provided on subscribe will bbe closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeOpenOrders(ctx context.Context) error
	// # Description
	//
	// Get the client's built-in channel used to publish received system status updates.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- system_status
	//
	//	# Return
	//
	// The client's built-in channel used to publish received system status updates.
	//
	// # Implemetation and usage guidelines
	//
	//	- The client MUST provide the channel it will use to publish heartbeats even though the
	//    cllient has not been started yet and is not connected to the server.
	//
	//	- The client MUST close the channel when it definitely stops.
	//
	//	- As the channel is automatically subscribed to, the client implementation must deal with
	//    possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client
	//    must indicate how congestion is handled.
	GetSystemStatusChannel() chan event.Event
	// # Description
	//
	// Get the client's built-in channel to publish received heartbeats.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- heartbeat
	//
	//	# Return
	//
	// # Implemetation and usage guidelines
	//
	//	- The client MUST provide the channel it will use to publish heartbeats even though the
	//    cllient has not been started yet and is not connected to the server.
	//
	//	- The client MUST close the channel when it definitely stops.
	//
	//	- As the channel is automatically subscribed to, the client implementation must deal with
	//    possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client
	//    must indicate how congestion is handled.
	//
	// # Return
	//
	// The client's built-in channel used to publish received heartbeats.
	GetHeartbeatChannel() chan event.Event
}

Interface for a websocket client using the private environment for Kraken spot websocket API.

Private websocket client has access to:

  • Ping
  • OwnTrades feed
  • OpenOrders feed
  • Add order operation
  • Edit order operation
  • Cancel order operations

func NewDefaultEngineWithPrivateWebsocketClient

func NewDefaultEngineWithPrivateWebsocketClient(
	key string,
	b64secret string,
	secopts *restcommon.SecurityOptions,
	onCloseCallback func(ctx context.Context, closeMessage *wsclient.CloseMessageDetails),
	onReadErrorCallback func(ctx context.Context, restart context.CancelFunc, exit context.CancelFunc, err error),
	onRestartError func(ctx context.Context, exit context.CancelFunc, err error, retryCount int),
	logger *log.Logger,
	tracerProvider trace.TracerProvider,
) (*wscengine.WebsocketEngine, KrakenSpotPrivateWebsocketClientInterface, error)

Description

Create a new KrakenSpotPrivateWebsocketClient and a websocket engine to run it. The client and the engine will be configured with the following default options:

  • Target URL for the websocket client will be the production env.: wss://ws-auth.kraken.com
  • Base URL for the REST client will be the production env. : https://api.kraken.com/0
  • A HFNonceGenerator will be used as nonce generator for the Get Websocket Token requests
  • a retryablehhttpclient will be used as HTTP client (3 retries, 1sec retry delay).
  • InstrumentKrakenSpotRESTClientAuthorizer will be used to sign Get Websocket Token requests.
  • The gorilla websocket framework with default settings will be used by the wesocket engine.
  • Websocket engine settings: 4 workers, auto-reconnect enabled, 5sec exponential retry delay.

The function will return the unstarted engine and the private websocket client attached to it.

Hint

This functions eliminates a lot of the boiler plate code needed to create and gather components required to interact with Kraken websocket API:

  • The websocket server URL.
  • The base http.Client used to send HTTP requests.
  • The REST client authorizer for Kraken API.
  • The REST client for Kraken API.
  • The nonce generator used to send requests with the REST client.
  • The private websocket client for Kraken API.
  • The websocket connection adapter used by the engine to manage the websocket connection.
  • The engine to run the private websocket client.

Inputs

  • key: API key used to authorize requests to the REST API (Get Websocket Token)
  • b64secret: API secret provided as a base64 encoded bytestring.
  • secopts: Optional security options to use when sending Get Websocket Token requests.
  • onCloseCallback: Optional callback called when connection is lost/stopped.
  • onReadErrorCallback: Optional callback called when engine fails to read a message.
  • onRestartError: Optional callback called when engine fails to reconnect to the server.
  • logger: Optional logger used to log debug/vebrose messages. If nil, a logger with a discard writer (noop) will be used
  • tracerProvider: Tracer provider to use to get a tracer to instrument websocket client code. If nil, global tracer provider will be used.

Returns

In case of success, a ready to start websocket engine is returned along with the private websocket bound to the engine.

type KrakenSpotPublicWebsocketClient

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

Kraken spot websocket client with access to public endpoints

func NewKrakenSpotPublicWebsocketClient

func NewKrakenSpotPublicWebsocketClient(
	onCloseCallback func(ctx context.Context, closeMessage *wsclient.CloseMessageDetails),
	onReadErrorCallback func(ctx context.Context, restart context.CancelFunc, exit context.CancelFunc, err error),
	onRestartError func(ctx context.Context, exit context.CancelFunc, err error, retryCount int),
	logger *log.Logger,
	tracerProvider trace.TracerProvider) *KrakenSpotPublicWebsocketClient

Description

Factory which creates a KrakenSpotPublicWebsocketClient that can be provided to a websocket engine (wscengine.WebsocketEngine - Cf. https://github.com/gbdevw/gowse).

Inputs

  • onCloseCallback: optional user defined callback which will be called when connection is closed/interrupted.
  • onReadErrorCallback: optional user defined callback which will be called when an error occurs while reading messages from the websocket server
  • onRestartError: optional user defined callback which will be called when the websocket engine fails to reconnect to the server.
  • logger: Optional logger used to log debug/vebrose messages. If nil, a logger with a discard writer (noop) will be used
  • tracerProvider: Tracer provider to use to get a tracer to instrument websocket client code. If nil, global tracer provider will be used.

Return

A new KrakenSpotPublicWebsocketClient

func (KrakenSpotPublicWebsocketClient) AddOrder

func (client KrakenSpotPublicWebsocketClient) AddOrder(ctx context.Context, params AddOrderRequestParameters) (*messages.AddOrderResponse, error)

Description

Add a new order and wait until a AddOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: AddOrder request parameters.

Return

The AddOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPublicWebsocketClient) CancelOrder

func (client KrakenSpotPublicWebsocketClient) CancelOrder(ctx context.Context, params CancelOrderRequestParameters) (*messages.CancelOrderResponse, error)

Description

Cancel one or several existing orders and wait until a CancelOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: CancelOrder request parameters.

Return

The CancelOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPublicWebsocketClient) CancellAllOrders

func (client KrakenSpotPublicWebsocketClient) CancellAllOrders(ctx context.Context) (*messages.CancelAllOrdersResponse, error)

Description

Cancel all orders and wait until a CancelAllOrdersResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.

Return

The CancelAllOrdersResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPublicWebsocketClient) CancellAllOrdersAfterX

func (client KrakenSpotPublicWebsocketClient) CancellAllOrdersAfterX(ctx context.Context, params CancelAllOrdersAfterXRequestParameters) (*messages.CancelAllOrdersAfterXResponse, error)

Description

Set, extend or unset a timer which cancels all orders when expiring and wait until a response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: CancellAllOrdersAfterX request parameters.

Return

The CancelAllOrdersAfterXResponse message from the server if any has been received. In case the response has its error message set, an error with the error message is also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPublicWebsocketClient) EditOrder

func (client KrakenSpotPublicWebsocketClient) EditOrder(ctx context.Context, params EditOrderRequestParameters) (*messages.EditOrderResponse, error)

Description

Edit an existing order and wait until a EditOrderResponse response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.
  • params: EditOrder request parameters.

Return

The EditOrderResponse message from the server if any has been received. In case the response has its error message set, an error with the error message will also be returned.

An error is returned when:

  • The client failed to send the request (no specific error type).
  • A timeout has occured before the request could be sent (no specific error type)
  • An error message is received from the server (OperationError).
  • A timeout or network failure occurs after sending the request to the server, while waiting for the server response. In this case, a OperationInterruptedError is returned.

func (KrakenSpotPublicWebsocketClient) GetHeartbeatChannel

func (client KrakenSpotPublicWebsocketClient) GetHeartbeatChannel() chan event.Event

Description

Get the client's built-in channel to publish received heartbeats.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • heartbeat

    # Return

Implemetation and usage guidelines

  • The client MUST provide the channel it will use to publish heartbeats even though the cllient has not been started yet and is not connected to the server.

  • The client MUST close the channel when it definitely stops.

  • As the channel is automatically subscribed to, the client implementation must deal with possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client must indicate how congestion is handled.

Return

The client's built-in channel used to publish received heartbeats.

func (KrakenSpotPublicWebsocketClient) GetSystemStatusChannel

func (client KrakenSpotPublicWebsocketClient) GetSystemStatusChannel() chan event.Event

Description

Get the client's built-in channel used to publish received system status updates.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • system_status

    # Return

The client's built-in channel used to publish received system status updates.

Implemetation and usage guidelines

  • The client MUST provide the channel it will use to publish heartbeats even though the cllient has not been started yet and is not connected to the server.

  • The client MUST close the channel when it definitely stops.

  • As the channel is automatically subscribed to, the client implementation must deal with possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client must indicate how congestion is handled.

func (KrakenSpotPublicWebsocketClient) OnClose

func (client KrakenSpotPublicWebsocketClient) OnClose(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	closeMessage *wsclient.CloseMessageDetails) *wsclient.CloseMessageDetails

Description

Callback is called when the websocket connection is closed or about to be closed after a Stop method call or a call to the provided restart/exit functions. Callback is called once by the engine: the engine will not exit or restart until the callback has been completed.

Callback can return an optional CloseMessageDetails which will be used to build the close message sent to the server if the connection needs to be closed after OnClose has finished. In such a case, if the returned value is nil, the engine will use 1001 "Going Away" as the close message.

Do not close the websocket connection here if it is still open: It will be automatically closed by the engine with a close message.

Inputs

  • ctx: Context produced from the websocket engine context and bound to OnClose lifecycle.
  • conn: Connection to the websocket server that is closed or about to close.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • closeMessage: Websocket close message received from server or generated by the engine when connection has been closed. If nil, connection might not be closed and will be closed by the engine using the returned close message or the default 1001 "Going Away".

Returns

A specific close message to send back to the server if connection has to be closed after this callback completes.

Warning

Provided context will already be canceled.

func (KrakenSpotPublicWebsocketClient) OnCloseError

func (client KrakenSpotPublicWebsocketClient) OnCloseError(
	ctx context.Context,
	err error)

Description

Callback called if an error occurred when the engine called the conn.Close method during the shutdown phase.

Inputs

  • ctx: Context produced OnClose context.
  • err: Error returned by conn.Close method

func (KrakenSpotPublicWebsocketClient) OnMessage

func (client KrakenSpotPublicWebsocketClient) OnMessage(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	restart context.CancelFunc,
	exit context.CancelFunc,
	sessionId string,
	msgType wsadapters.MessageType,
	msg []byte)

Description

Callback called when a message is read from the server. The goroutine which has read the message will block until callback completes. Meanwhile, other goroutines, if any, can read and process other incoming messages unless read mutex is locked.

Inputs

  • ctx: context produce from websocket engine context and bound to OnMessage lifecycle.
  • conn: Websocket adapter provided during engine creation with a connection opened.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • restart: Function to call to instruct engine to stop and restart.
  • exit: Function to call to definitely stop the engine.
  • sessionId: Unique identifier produced by engine for each new websocket connection and bound to the websocket connection lifetime.
  • msgType: Message type returned by read function.
  • msg: Received message as a byte array

Engine behavior on exit/restart call

  • No other messages will be read if restart or exit is called.

  • Engine will stop after OnMessage is completed: OnClose callback is called and then the connection is closed. Depending on which function was called, the engine will restart or stop for good.

  • All pending messages will be discarded. The user can continue to read and send messages in this callback and/or in the OnClose callback until conditions are met to stop the engine and close the websocket connection.

func (KrakenSpotPublicWebsocketClient) OnOpen

func (client KrakenSpotPublicWebsocketClient) OnOpen(
	ctx context.Context,
	resp *http.Response,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	exit context.CancelFunc,
	restarting bool) error

Description

In case the client is reconnecting to the server, the client will attempt to resubscribe to all channels that have been previously subscribed. The client will attempts at most three times to resubscribe. THe client will not wait for resubscribe to succeed before resuming its operations.

It is up to the user to monitor interruptions in stream of data and react according its own needs and requirements. In such a case, user can either kill/restart its application, unsubscribe and resubscribe to channel or shutdown and start again the wesocket client.

OnOpen Documentation

Callback called when engine has (re)opened a connection to the websocket server. OnOpen is called once, synchronously by the engine during its (re)start phase: no messages or events will be processed until callback completes or a timeout occurs (default: 5 minutes).

If OnOpen callback returns an error, websocket engine will:

  • If starting: engine will close the opened connection and stop.
  • If restarting: engine will close the opened connection and try to restart again.

No other callbacks (OnReadError & OnClose) will be used in such cases.

During OnOpen call, the provided exit function can be called to definitely stop the engine.

Inputs

  • ctx: context produced from the websocket engine context and bound to OnOpen lifecycle.
  • resp: The server response to the websocket handshake.
  • conn: Websocket adapter provided during engine creation. Connection is now opened.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • exit: Function to call to definitely stop the engine (ex: when stuck in retry loop).
  • restarting: Flag which indicates whether engine restarts (true) or is starting (false).

Returns

nil in case of success or an error if an error occured during OnOpen execution.

When engine is restarting, returning an error will cause engine to restart again.

Engine behavior after OnOpen completes

If nil is returned and if exit function has not been called, engine will finish starting and create internal goroutines which will manage the websocket connection.

If an error is returned, engine will close the opened connection and do the following:

  • If engine is starting, engine will definitely stop. Calling exit will do nothing.
  • If engine is restarting, engine will try again to restart.
  • If engine is restarting and exit has been called, engine will definitely stop.

func (KrakenSpotPublicWebsocketClient) OnReadError

func (client KrakenSpotPublicWebsocketClient) OnReadError(
	ctx context.Context,
	conn wsadapters.WebsocketConnectionAdapterInterface,
	readMutex *sync.Mutex,
	restart context.CancelFunc,
	exit context.CancelFunc,
	err error)

Description

This callback is called each time an error is received when reading messages from the websocket server that is not caused by the connection being closed.

The callback is called by the engine goroutine that encountered the error. All engine goroutines will block until the callback is completed. This prevents other messages and events from being processed by the engine while the error is being handled.

The engine will restart after OnReadError has finished if one of the following conditions is met: - The websocket connection is closed and the Exit function has not been called. - The restart function has been called.

Otherwise, the engine will either continue to process messages on the same connection or shut down if the exit function has been called.

Do not close the websocket connection manually: It will be automatically closed if necessary after the OnClose callback has been completed.

Inputs

  • ctx: Context produced from the websocket engine context and bound to OnReadError lifecycle.
  • conn: Connection to the websocket server.
  • readMutex: A reference to engine read mutex user can lock to pause the engine.
  • restart: Function to call to instruct engine to stop and restart.
  • exit: Function to call to definitely stop the engine.
  • err: Error returned by the websocket read operation.

Engine behavior on exit/restart call

  • No other messages are read when restart or exit is called.

  • Engine will stop after OnReadError: OnClose callback is called and then the connection is closed. Depending on which function was called, the engine will restart or stop for good.

  • All pending messages will be discarded. The user can continue to read and send messages in this callback and/or in the OnClose callback until conditions are met to stop the engine and close the websocket connection.

func (KrakenSpotPublicWebsocketClient) OnRestartError

func (client KrakenSpotPublicWebsocketClient) OnRestartError(
	ctx context.Context,
	exit context.CancelFunc,
	err error,
	retryCount int)

Description

Callback called in case an error or a timeout occured when engine tried to restart.

Inputs

  • ctx: Context used for tracing purpose. Will be Done in case a timeout has occured.
  • exit: Function to call to stop trying to restart the engine.
  • err: Error which has occured when restarting the engine
  • retryCount: Number of restart retry since last time engine has successfully (re)started.

func (KrakenSpotPublicWebsocketClient) Ping

func (client KrakenSpotPublicWebsocketClient) Ping(ctx context.Context) error

Description

Send a ping to the websocket server and wait until a Pong response is received from the server or until an error or a timeout occurs.

Inputs

  • ctx: Context used for tracing and coordination purpose. The provided context Done channel will be watched for timeout/cancel signal.

Return

Nil in case of success. Otherwise, an error is returned when:

  • An error occurs when sending the message.
  • The provided context expires before pong is received (OperationInterruptedError).
  • An error message is received from the server (OperationError).

func (KrakenSpotPublicWebsocketClient) SubscribeBook

func (client KrakenSpotPublicWebsocketClient) SubscribeBook(ctx context.Context, pairs []string, depth messages.DepthEnum, rcv chan event.Event) error

Description

Subscribe to the book channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Three types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • book_snapshot: This event type is used when a snapshot of the order book is received from the websocket server.
  • book_update: This event is used when an update about the order book is received from the websocket server.

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeBook
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • book_snapshot
  • book_update

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.BookUpdate or messages.BookSnapshot depending on the event type like this:

switch(WebsocketClientEventTypeEnum(event.Type)) {
	case events.BookSnapshot:
		snapshot := new(messages.BookSnapshot)
		err := event.DataAs(snapshot)
	case events.BookUpdate:
		update := new(messages.BookUpdate)
		err := event.DataAs(update)
	case events.ConnectionInterrupted:
		panic("connection lost")
	default:
		panic("unknown message type", event.Type)
}

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish book_snapshot & book+update messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeOHLC

func (client KrakenSpotPublicWebsocketClient) SubscribeOHLC(ctx context.Context, pairs []string, interval messages.IntervalEnum, rcv chan event.Event) error

Description

Subscribe to the ohlc channel with the given interval. In case of success, the websocket client will start publishing received events on the user's provided channel.

The client supports multiple subscriptions but for different interval. The client will return an error in case there's already a subscription for that interval.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • ohlc: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOHLC
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • ohlc

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OHLC like this:

ohlc := new(messages.OHLC)
err := event.DataAs(ohlc)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • interval: Interval for produced OHLC indicators.
  • rcv: Channel used to publish ohlc messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription for that interval.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeOpenOrders

func (client KrakenSpotPublicWebsocketClient) SubscribeOpenOrders(ctx context.Context, rateCounter bool, rcv chan event.Event) error

Description

Subscribe to the openOrders channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • open_orders: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOpenOrders
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • open_orders

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OpenOrders like this:

openOrders := new(messages.OpenOrders)
err := event.DataAs(openOrders)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • rateCounter: If true, rate limiting information will be included in messages.
  • rcv: Channel used to publish open_orders messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeOwnTrades

func (client KrakenSpotPublicWebsocketClient) SubscribeOwnTrades(ctx context.Context, snapshot bool, consolidateTaker bool, rcv chan event.Event) error

Description

Subscribe to the ownTrades channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • own_trades: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeOwnTrades
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • own_trades

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.OwnTrades like this:

ownTrade := new(messages.OwnTrades)
err := event.DataAs(ownTrade)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • snapshot: If true, upon subscription, the 50 most recent user trades will be published.
  • consolidateTaker: Whether to consolidate order fills by root taker trade(s).
  • rcv: Channel used to publish own_trades messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires (timeout/cancel) before subscription is completed.
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active susbscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeSpread

func (client KrakenSpotPublicWebsocketClient) SubscribeSpread(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the spreads channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • spread: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeSpreads
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • spread

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Spread like this:

spread := new(messages.Spread)
err := event.DataAs(spread)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish spread messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeTicker

func (client KrakenSpotPublicWebsocketClient) SubscribeTicker(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the tickers channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

This client implementation uses

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • ticker: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeTickers
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • ticker

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Ticker like this:

ticker := new(messages.Ticker)
err := event.DataAs(ticker)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish ticker messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) SubscribeTrade

func (client KrakenSpotPublicWebsocketClient) SubscribeTrade(ctx context.Context, pairs []string, rcv chan event.Event) error

Description

Subscribe to the trades channel. In case of success, the websocket client will start publishing received events on the user's provided channel.

Two types of events can be published on the channel:

  • connection_interrupted: This event type is used when connection with the sevrer has been interrupted. The event will not have any data. It only serves as a cue for the consumer to allow the consumer to react when the connection with the server is interrupted.
  • trade: This event type is used when a message has been received from the server. Published events will contain both the received data and the tracing context to continue the tracing span from the source (= the websocket engine).

In case when the connection with the server is lost, the websocket client will publish a connection_interrupted event to warn consumer about the failure.

If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication when it reconnects to the server and it MUST reuse the previously provided channel to publish received messages.

Consumers should always watch to the event type to separate messages from the connection failure events and react according the event type.

Finally, the provided channel will be automatically closed by the client when:

  • The user unsubscribe from the topic by using UnsubscribeTrades
  • The websocket client definitely stops.

Consumers should also watch channel closure to know when no more data will be delivered.

Event types

Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):

  • connection_interrupted
  • trade

Extract data

Before parsing the data, check the event type to catch rare connection_interrupted events.

The event data contains the JSON payload from the server and can be parsed into a structure of type messages.Trade like this:

trade := new(messages.Trade)
err := event.DataAs(trade)

The event will also contain the tracing context from OpenTelemetry. This tracing context can be extracted from the event to continue tracing the event processing from the source:

ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • pair: Pairs to subscribe to.
  • rcv: Channel used to publish trade messages and connection_interrupted events.

Return

An error is returned when:

  • There is already an active subscription.
  • An error occurs when sending the subscription message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • The client MUST return an error if there is already an active subscription.

  • The client MUST use the right error type as described in the "Return" section.

  • A connection_interrupted event MUST be published on the channel each time the websocket connection is closed.

  • The provided channel MUST be closed upon unsubscribe or when the websocket client stops.

  • The websocket client implementation CAN either use blocking writes or discard messages in case the provided channel is full. It is up to the client implementation to be clear about how it deals with congestion.

  • If the client implementation has a mechanism to automatically reconnect to the server, then the websocket client MUST resubscribe to previously subscribed channels and reuse the channel that has been provided when the user subscribed to the channel.

func (KrakenSpotPublicWebsocketClient) UnsubscribeBook

func (client KrakenSpotPublicWebsocketClient) UnsubscribeBook(ctx context.Context) error

Description

Unsubscribe from the book channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeOHLC

func (client KrakenSpotPublicWebsocketClient) UnsubscribeOHLC(ctx context.Context, interval messages.IntervalEnum) error

Description

Unsubscribe from the ohlc channel with the given interva. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.
  • interval: Used to determine which subscription must be cancelled.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeOpenOrders

func (client KrakenSpotPublicWebsocketClient) UnsubscribeOpenOrders(ctx context.Context) error

Description

Unsubscribe from the openOrders channel. The channel provided on subscribe will bbe closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeOwnTrades

func (client KrakenSpotPublicWebsocketClient) UnsubscribeOwnTrades(ctx context.Context) error

Description

Unsubscribe from the ownTrades channel. The channel provided on subscribe will bbe closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeSpread

func (client KrakenSpotPublicWebsocketClient) UnsubscribeSpread(ctx context.Context) error

Description

Unsubscribe from the spread channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeTicker

func (client KrakenSpotPublicWebsocketClient) UnsubscribeTicker(ctx context.Context) error

Description

Unsubscribe from the ticker channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

func (KrakenSpotPublicWebsocketClient) UnsubscribeTrade

func (client KrakenSpotPublicWebsocketClient) UnsubscribeTrade(ctx context.Context) error

Description

Unsubscribe from the trade channel. The channel provided on subscribe will be closed by the websocket client.

Inputs

  • ctx: Context used for tracing and coordination purpose.

Return

An error is returned when:

  • The channel has not been subscribed to.
  • An error occurs when sending the unsubscribe message.
  • The provided context expires before subscription is completed (OperationInterruptedError).
  • An error message is received from the server (OperationError).

Implementation and usage guidelines

  • In case of success, the client MUST close the channel used to publish events.

  • The client MUST use the right error type as described in the "Return" section.

type KrakenSpotPublicWebsocketClientInterface

type KrakenSpotPublicWebsocketClientInterface interface {
	// # Description
	//
	// Send a ping to the websocket server and wait until a Pong response is received from the
	// server or until an error or a timeout occurs.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose. The provided context Done channel
	//    will be watched for timeout/cancel signal.
	//
	// # Return
	//
	// Nil in case of success. Otherwise, an error is returned when:
	//
	//	- An error occurs when sending the message.
	//	- The provided context expires before pong is received (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	Ping(ctx context.Context) error
	// # Description
	//
	// Subscribe to the tickers channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- ticker: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeTickers
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- ticker
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.Ticker like this:
	//
	//	ticker := new(messages.Ticker)
	//	err := event.DataAs(ticker)
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- pair: Pairs to subscribe to.
	//	- rcv: Channel used to publish ticker messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeTicker(ctx context.Context, pairs []string, rcv chan event.Event) error
	// # Description
	//
	// Subscribe to the ohlc channel with the given interval. In case of success, the websocket
	// client will start publishing received events on the user's provided channel.
	//
	// The client supports multiple subscriptions but for different interval. The client will return
	// an error in case there's already a subscription for that interval.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- ohlc: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeOHLC
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- ohlc
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.OHLC like this:
	//
	//	ohlc := new(messages.OHLC)
	//	err := event.DataAs(ohlc)
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- pair: Pairs to subscribe to.
	//	- interval: Interval for produced OHLC indicators.
	//	- rcv: Channel used to publish ohlc messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription for that interval.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeOHLC(ctx context.Context, pairs []string, interval messages.IntervalEnum, rcv chan event.Event) error
	// # Description
	//
	// Subscribe to the trades channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- trade: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeTrades
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- trade
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.Trade like this:
	//
	//	trade := new(messages.Trade)
	//	err := event.DataAs(trade)
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- pair: Pairs to subscribe to.
	//	- rcv: Channel used to publish trade messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeTrade(ctx context.Context, pairs []string, rcv chan event.Event) error
	// # Description
	//
	// Subscribe to the spreads channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Two types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- spread: This event type is used when a message has been received from the server.
	//    Published events will contain both the received data and the tracing context to continue
	//    the tracing span from the source (= the websocket engine).
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeSpreads
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- spread
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.Spread like this:
	//
	//	spread := new(messages.Spread)
	//	err := event.DataAs(spread)
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- pair: Pairs to subscribe to.
	//	- rcv: Channel used to publish spread messages and connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeSpread(ctx context.Context, pairs []string, rcv chan event.Event) error
	// # Description
	//
	// Subscribe to the book channel. In case of success, the websocket client will start
	// publishing received events on the user's provided channel.
	//
	// Three types of events can be published on the channel:
	//	- connection_interrupted: This event type is used when connection with the sevrer has been
	//    interrupted. The event will not have any data. It only serves as a cue for the consumer
	//    to allow the consumer to react when the connection with the server is interrupted.
	//	- book_snapshot: This event type is used when a snapshot of the order book is received from
	//    the websocket server.
	//	- book_update: This event is used when an update about the order book is received from the
	//    websocket server.
	//
	// In case when the connection with the server is lost, the websocket client will publish a
	// connection_interrupted event to warn consumer about the failure.
	//
	// If the websocket client has a auto-reconnect feature, it MUST resubscribe to the publication
	// when it reconnects to the server and it MUST reuse the previously provided channel to publish
	// received messages.
	//
	// Consumers should always watch to the event type to separate messages from the connection
	// failure events and react according the event type.
	//
	// Finally, the provided channel will be automatically closed by the client when:
	//	- The user unsubscribe from the topic by using UnsubscribeBook
	//	- The websocket client definitely stops.
	//
	// Consumers should also watch channel closure to know when no more data will be delivered.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- connection_interrupted
	//	- book_snapshot
	//	- book_update
	//
	// # Extract data
	//
	// Before parsing the data, check the event type to catch rare connection_interrupted events.
	//
	// The event data contains the JSON payload from the server and can be parsed into a structure
	// of type messages.BookUpdate or messages.BookSnapshot depending on the event type like this:
	//
	//	switch(WebsocketClientEventTypeEnum(event.Type)) {
	//		case events.BookSnapshot:
	//			snapshot := new(messages.BookSnapshot)
	//			err := event.DataAs(snapshot)
	//		case events.BookUpdate:
	//			update := new(messages.BookUpdate)
	//			err := event.DataAs(update)
	//		case events.ConnectionInterrupted:
	//			panic("connection lost")
	//		default:
	//			panic("unknown message type", event.Type)
	//	}
	//
	// The event will also contain the tracing context from OpenTelemetry. This tracing context can
	// be extracted from the event to continue tracing the event processing from the source:
	//
	//	ctx := otelObs.ExtractDistributedTracingExtension(context.Background(), event)
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- pair: Pairs to subscribe to.
	//	- rcv: Channel used to publish book_snapshot & book+update messages and
	//         connection_interrupted events.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- There is already an active subscription.
	//	- An error occurs when sending the subscription message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- The client MUST return an error if there is already an active subscription.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	//
	//	- A connection_interrupted event MUST be published on the channel each time the websocket
	//    connection is closed.
	//
	//	- The provided channel MUST be closed upon unsubscribe or when the websocket client stops.
	//
	//	- The websocket client implementation CAN either use blocking writes or discard messages in
	//    case the provided channel is full. It is up to the client implementation to be clear about
	//    how it deals with congestion.
	//
	//	- If the client implementation has a mechanism to automatically reconnect to the server,
	//    then the websocket client MUST resubscribe to previously subscribed channels and reuse
	//    the channel that has been provided when the user subscribed to the channel.
	SubscribeBook(ctx context.Context, pairs []string, depth messages.DepthEnum, rcv chan event.Event) error
	// # Description
	//
	// Unsubscribe from the ticker channel. The channel provided on subscribe will be closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeTicker(ctx context.Context) error
	// # Description
	//
	// Unsubscribe from the ohlc channel with the given interva. The channel provided on subscribe
	// will be closed by the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//	- interval: Used to determine which subscription must be cancelled.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeOHLC(ctx context.Context, interval messages.IntervalEnum) error
	// # Description
	//
	// Unsubscribe from the trade channel. The channel provided on subscribe will be closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeTrade(ctx context.Context) error
	// # Description
	//
	// Unsubscribe from the spread channel. The channel provided on subscribe will be closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeSpread(ctx context.Context) error
	// # Description
	//
	// Unsubscribe from the book channel. The channel provided on subscribe will be closed by
	// the websocket client.
	//
	// # Inputs
	//
	//	- ctx: Context used for tracing and coordination purpose.
	//
	// # Return
	//
	// An error is returned when:
	//
	//	- The channel has not been subscribed to.
	//	- An error occurs when sending the unsubscribe message.
	//	- The provided context expires before subscription is completed (OperationInterruptedError).
	//	- An error message is received from the server (OperationError).
	//
	// # Implementation and usage guidelines
	//
	//	- In case of success, the client MUST close the channel used to publish events.
	//
	//	- The client MUST use the right error type as described in the "Return" section.
	UnsubscribeBook(ctx context.Context) error
	// # Description
	//
	// Get the client's built-in channel used to publish received system status updates.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- system_status
	//
	//	# Return
	//
	// The client's built-in channel used to publish received system status updates.
	//
	// # Implemetation and usage guidelines
	//
	//	- The client MUST provide the channel it will use to publish heartbeats even though the
	//    cllient has not been started yet and is not connected to the server.
	//
	//	- The client MUST close the channel when it definitely stops.
	//
	//	- As the channel is automatically subscribed to, the client implementation must deal with
	//    possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client
	//    must indicate how congestion is handled.
	GetSystemStatusChannel() chan event.Event
	// # Description
	//
	// Get the client's built-in channel to publish received heartbeats.
	//
	// # Event types
	//
	// Only these types of events will be published on the channel (Cf. WebsocketClientEventTypeEnum):
	//	- heartbeat
	//
	//	# Return
	//
	// # Implemetation and usage guidelines
	//
	//	- The client MUST provide the channel it will use to publish heartbeats even though the
	//    cllient has not been started yet and is not connected to the server.
	//
	//	- The client MUST close the channel when it definitely stops.
	//
	//	- As the channel is automatically subscribed to, the client implementation must deal with
	//    possible channel congestion by discarding messages in a FIFO or LIFO fashion. The client
	//    must indicate how congestion is handled.
	//
	// # Return
	//
	// The client's built-in channel used to publish received heartbeats.
	GetHeartbeatChannel() chan event.Event
}

Interface for a websocket client using the public environment for Kraken spot websocket API.

Public websocket client has access to:

  • Ping
  • Ticker feed
  • OHLC feed
  • Trades feed
  • Spreads feed
  • Order book feed

func NewDefaultEngineWithPublicWebsocketClient

func NewDefaultEngineWithPublicWebsocketClient(
	onCloseCallback func(ctx context.Context, closeMessage *wsclient.CloseMessageDetails),
	onReadErrorCallback func(ctx context.Context, restart context.CancelFunc, exit context.CancelFunc, err error),
	onRestartError func(ctx context.Context, exit context.CancelFunc, err error, retryCount int),
	logger *log.Logger,
	tracerProvider trace.TracerProvider,
) (*wscengine.WebsocketEngine, KrakenSpotPublicWebsocketClientInterface, error)

Description

Create a new KrakenSpotPublicWebsocketClient and a websocket engine to run it. The client and the engine will be configured with the following default options:

  • Target URL for the websocket client will be the production env.: wss://ws.kraken.com
  • The gorilla websocket framework with default settings will be used by the wesocket engine.
  • Websocket engine settings: 4 workers, auto-reconnect enabled, 5sec exponential retry delay.

The function will return the unstarted engine and the public websocket client attached to it.

Hint

This functions eliminates a lot of the boiler plate code needed to create and gather components required to interact with Kraken websocket API:

  • The websocket server URL.
  • The public websocket client for Kraken API.
  • The websocket connection adapter used by the engine to manage the websocket connection.
  • The engine to run the private websocket client.

Inputs

  • onCloseCallback: Optional callback called when connection is lost/stopped.
  • onReadErrorCallback: Optional callback called when engine fails to read a message.
  • onRestartError: Optional callback called when engine fails to reconnect to the server.
  • logger: Optional logger used to log debug/vebrose messages. If nil, a logger with a discard writer (noop) will be used
  • tracerProvider: Tracer provider to use to get a tracer to instrument websocket client code. If nil, global tracer provider will be used.

Returns

In case of success, a ready to start websocket engine is returned along with the private websocket bound to the engine.

type OperationError

type OperationError struct {
	Operation string
	Root      error
}

This error is used when the reply from the server to a request contains an error message.

In this case, the error contains the error message from the server.

func (*OperationError) Error

func (e *OperationError) Error() string

func (*OperationError) Unwrap

func (e *OperationError) Unwrap() error

type OperationInterruptedError

type OperationInterruptedError struct {
	Operation string
	Root      error
}

This error is used when the reply from the server to a specific request could not be received because either connection with the websocket server was lost while waiting for the server reply or because a timeout has occured while waiting for the reply. The error will embed the root error, either the cancel error from the context or the error from the websocket engine.

When such error occurs, the client cannot tell whether its request has been successfully processed or not by the websocket server.

Recommendation is:

  • Always provide user defined IDs when adding/editing orders.
  • Use the websocket/rest client to reconciliate state. Query open or closed orders by using the expected user ID and then retry the operation if needed.
  • Retry the subscribe/unsubscribe operation

func (*OperationInterruptedError) Error

func (e *OperationInterruptedError) Error() string

func (*OperationInterruptedError) Unwrap

func (e *OperationInterruptedError) Unwrap() error

type SubscriptionError

type SubscriptionError struct {
	// Map where keys are pairs for which subscribe/unsubscribe failed and value are the cause.
	Errs map[string]error
}

This error is used to carry information about pairs for which subscribe or unsubscribe failed.

func (*SubscriptionError) Error

func (e *SubscriptionError) Error() string

func (*SubscriptionError) Unwrap

func (e *SubscriptionError) Unwrap() error

Directories

Path Synopsis
This package contains definitions of messages exchanged when interacting with Kraken spot websocket API.
This package contains definitions of messages exchanged when interacting with Kraken spot websocket API.

Jump to

Keyboard shortcuts

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