-- import "github.com/bitfinexcom/bitfinex-api-go/v2/websocket"
const (
ChanBook = "book"
ChanTrades = "trades"
ChanTicker = "ticker"
ChanCandles = "candles"
ChanStatus = "status"
)Available channels
const (
EventSubscribe = "subscribe"
EventUnsubscribe = "unsubscribe"
EventPing = "ping"
)Events
const (
ErrorCodeUnknownEvent int = 10000
ErrorCodeUnknownPair int = 10001
ErrorCodeUnknownBookPrecision int = 10011
ErrorCodeUnknownBookLength int = 10012
ErrorCodeSubscriptionFailed int = 10300
ErrorCodeAlreadySubscribed int = 10301
ErrorCodeUnknownChannel int = 10302
ErrorCodeUnsubscribeFailed int = 10400
ErrorCodeNotSubscribed int = 10401
)error codes pulled from v2 docs & API usage
const DMSCancelOnDisconnect int = 4DMSCancelOnDisconnect cancels session orders on disconnect.
const KEEP_ALIVE_TIMEOUT = 10seconds to wait in between re-sending the keep alive ping
const MaxChannels = 25const WS_READ_CAPACITY = 10size of channel that the websocket reader routine pushes websocket updates into
const WS_WRITE_CAPACITY = 5000size of channel that the websocket writer routine pulls from
var (
ErrWSNotConnected = fmt.Errorf("websocket connection not established")
ErrWSAlreadyConnected = fmt.Errorf("websocket connection already established")
)ws-specific errors
func ConvertBytesToJsonNumberArray(b []byte) ([]interface{}, error)type Asynchronous interface {
Connect() error
Send(ctx context.Context, msg interface{}) error
Listen() <-chan []byte
Close()
Done() <-chan error
}Asynchronous interface decouples the underlying transport from API logic.
type AsynchronousFactory interface {
Create() Asynchronous
}AsynchronousFactory provides an interface to re-create asynchronous transports during reconnect events.
func NewWebsocketAsynchronousFactory(parameters *Parameters) AsynchronousFactoryNewWebsocketAsynchronousFactory creates a new websocket factory with a given URL.
type AuthEvent struct {
Event string `json:"event"`
Status string `json:"status"`
ChanID int64 `json:"chanId,omitempty"`
UserID int64 `json:"userId,omitempty"`
SubID string `json:"subId"`
AuthID string `json:"auth_id,omitempty"`
Message string `json:"msg,omitempty"`
Caps Capabilities `json:"caps"`
}type AuthState authState // prevent user construction of authStatesAuthState provides a typed authentication state.
const (
NoAuthentication AuthState = 0
PendingAuthentication AuthState = 1
SuccessfulAuthentication AuthState = 2
RejectedAuthentication AuthState = 3
)Authentication states
type BookFactory struct {
}func (f *BookFactory) Build(sub *subscription, objType string, raw []interface{}, b []byte) (interface{}, error)func (f *BookFactory) BuildSnapshot(sub *subscription, raw [][]interface{}, b []byte) (interface{}, error)func (s BookFactory) Close()Close is terminal. Do not call heartbeat after close.
func (s BookFactory) ListenDisconnect() <-chan HeartbeatDisconnectListenDisconnect returns an error channel which receives a message when a heartbeat has expired a channel.
func (s BookFactory) ResetAll()Removes all tracked subscriptions
func (s BookFactory) ResetSocketSubscriptions(socketId SocketId) []*subscriptionReset clears all subscriptions assigned to the given socket ID, and returns a slice of the existing subscriptions prior to reset
type CandlesFactory struct {
}func (f *CandlesFactory) Build(sub *subscription, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error)func (f *CandlesFactory) BuildSnapshot(sub *subscription, raw [][]interface{}, raw_bytes []byte) (interface{}, error)func (s CandlesFactory) Close()Close is terminal. Do not call heartbeat after close.
func (s CandlesFactory) ListenDisconnect() <-chan HeartbeatDisconnectListenDisconnect returns an error channel which receives a message when a heartbeat has expired a channel.
func (s CandlesFactory) ResetAll()Removes all tracked subscriptions
func (s CandlesFactory) ResetSocketSubscriptions(socketId SocketId) []*subscriptionReset clears all subscriptions assigned to the given socket ID, and returns a slice of the existing subscriptions prior to reset
type Capabilities struct {
Orders Capability `json:"orders"`
Account Capability `json:"account"`
Funding Capability `json:"funding"`
History Capability `json:"history"`
Wallets Capability `json:"wallets"`
Withdraw Capability `json:"withdraw"`
Positions Capability `json:"positions"`
}type Capability struct {
Read int `json:"read"`
Write int `json:"write"`
}type Client struct {
Authentication AuthState
}Client provides a unified interface for users to interact with the Bitfinex V2 Websocket API. nolint:megacheck,structcheck
func New() *ClientNew creates a default client.
func NewWithAsyncFactory(async AsynchronousFactory) *ClientNewWithAsyncFactory creates a new default client with a given asynchronous transport factory interface.
func NewWithAsyncFactoryNonce(async AsynchronousFactory, nonce utils.NonceGenerator) *ClientNewWithAsyncFactoryNonce creates a new default client with a given asynchronous transport factory and nonce generator.
func NewWithParams(params *Parameters) *ClientNewWithParams creates a new default client with a given set of parameters.
func NewWithParamsAsyncFactory(params *Parameters, async AsynchronousFactory) *ClientNewWithParamsAsyncFactory creates a new default client with a given set of parameters and asynchronous transport factory interface.
func NewWithParamsAsyncFactoryNonce(params *Parameters, async AsynchronousFactory, nonce utils.NonceGenerator) *ClientNewWithParamsAsyncFactoryNonce creates a new client with a given set of parameters, asynchronous transport factory, and nonce generator interfaces.
func NewWithParamsNonce(params *Parameters, nonce utils.NonceGenerator) *ClientNewWithParamsNonce creates a new default client with a given set of parameters and nonce generator.
func (c *Client) AvailableCapacity() intGet the available capacity of the current websocket connections
func (c *Client) CancelOnDisconnect(cxl bool) *ClientCancelOnDisconnect ensures all orders will be canceled if this API session is disconnected.
func (c *Client) Close()Close the websocket client which will cause for all active sockets to be exited and the Done() function to be called
func (c *Client) CloseFundingCredit(ctx context.Context, fundingOffer *fundingcredit.CancelRequest) errorCloseFundingCredit - cancels funding credit by ID. Emits an error if not authenticated.
func (c *Client) CloseFundingLoan(ctx context.Context, flcr *fundingloan.CancelRequest) errorCloseFundingLoan - cancels funding loan by ID. Emits an error if not authenticated.
func (c *Client) Connect() errorConnect to the Bitfinex API, this should only be called once.
func (c *Client) ConnectionCount() intGen the count of currently active websocket connections
func (c *Client) Credentials(key string, secret string) *ClientCredentials assigns authentication credentials to a connection request.
func (c *Client) EnableFlag(ctx context.Context, flag int) (string, error)Submit a request to enable the given flag
func (c *Client) GetAuthenticatedSocket() (*Socket, error)Get the authenticated socket. Due to rate limitations there can only be one authenticated socket active at a time
func (c *Client) GetOrderbook(symbol string) (*Orderbook, error)Retrieve the Orderbook for the given symbol which is managed locally. This requires ManageOrderbook=True and an active chanel subscribed to the given symbols orderbook
func (c *Client) IsConnected() boolReturns true if the underlying asynchronous transport is connected to an endpoint.
func (c *Client) Listen() <-chan interface{}Listen for all incoming api websocket messages When a websocket connection is terminated, the publisher channel will close.
func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error)Get a subscription request using a subscription ID
func (c *Client) Send(ctx context.Context, msg interface{}) errorSend publishes a generic message to the Bitfinex API.
func (c *Client) StartNewConnection() errorStart a new websocket connection. This function is only exposed in case you want to implicitly add new connections otherwise connection management is already handled for you.
func (c *Client) SubmitCancel(ctx context.Context, ocr *order.CancelRequest) errorSubmit a cancel request for an existing order
func (c *Client) SubmitFundingCancel(ctx context.Context, fundingOffer *fundingoffer.CancelRequest) errorSubmit a request to cancel and existing funding offer
func (c *Client) SubmitFundingOffer(ctx context.Context, fundingOffer *fundingoffer.SubmitRequest) errorSubmit a new funding offer request
func (c *Client) SubmitOrder(ctx context.Context, onr *order.NewRequest) errorSubmit a request to create a new order
func (c *Client) SubmitUpdateOrder(ctx context.Context, our *order.UpdateRequest) errorSubmit and update request to change an existing orders values
func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (string, error)Submit a request to subscribe to the given SubscriptionRequuest
func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision common.BookPrecision, frequency common.BookFrequency, priceLevel int) (string, error)Submit a subscription request for market data for the given symbol, at the given frequency, with the given precision, returning no more than priceLevels price entries. Default values are Precision0, Frequency0, and priceLevels=25.
func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution common.CandleResolution) (string, error)Submit a subscription request to receive candle updates
func (c *Client) SubscribeStatus(ctx context.Context, symbol string, sType common.StatusType) (string, error)Submit a subscription request for status updates
func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, error)Submit a request to receive ticker updates
func (c *Client) SubscribeTrades(ctx context.Context, symbol string) (string, error)Submit a request to receive trade updates
func (c *Client) Unsubscribe(ctx context.Context, id string) errorUnsubscribe from the existing subscription with the given id
type ConfEvent struct {
Flags int `json:"flags"`
}type ErrorEvent struct {
Code int `json:"code"`
Message string `json:"msg"`
// also contain members related to subscription reject
SubID string `json:"subId"`
Channel string `json:"channel"`
ChanID int64 `json:"chanId"`
Symbol string `json:"symbol"`
Precision string `json:"prec,omitempty"`
Frequency string `json:"freq,omitempty"`
Key string `json:"key,omitempty"`
Len string `json:"len,omitempty"`
Pair string `json:"pair"`
}type FlagRequest struct {
Event string `json:"event"`
Flags int `json:"flags"`
}type Heartbeat struct {
}type HeartbeatDisconnect struct {
Subscription *subscription
Error error
}type InfoEvent struct {
Version float64 `json:"version"`
ServerId string `json:"serverId"`
Platform PlatformInfo `json:"platform"`
Code int `json:"code"`
Msg string `json:"msg"`
}type Orderbook struct {
}func (ob *Orderbook) Asks() []book.Bookfunc (ob *Orderbook) Bids() []book.Bookfunc (ob *Orderbook) Checksum() uint32func (ob *Orderbook) SetWithSnapshot(bs *book.Snapshot)func (ob *Orderbook) Symbol() stringfunc (ob *Orderbook) UpdateWith(b *book.Book)type Parameters struct {
AutoReconnect bool
ReconnectInterval time.Duration
ReconnectAttempts int
ShutdownTimeout time.Duration
CapacityPerConnection int
Logger *logging.Logger
ResubscribeOnReconnect bool
HeartbeatTimeout time.Duration
LogTransport bool
URL string
ManageOrderbook bool
}Parameters defines adapter behavior.
func NewDefaultParameters() *Parameterstype PlatformInfo struct {
Status int `json:"status"`
}type RawEvent struct {
Data interface{}
}type Socket struct {
Id SocketId
Asynchronous
IsConnected bool
ResetSubscriptions []*subscription
IsAuthenticated bool
}type SocketId inttype StatsFactory struct {
}func (f *StatsFactory) Build(sub *subscription, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error)func (f *StatsFactory) BuildSnapshot(sub *subscription, raw [][]interface{}, raw_bytes []byte) (interface{}, error)func (s StatsFactory) Close()Close is terminal. Do not call heartbeat after close.
func (s StatsFactory) ListenDisconnect() <-chan HeartbeatDisconnectListenDisconnect returns an error channel which receives a message when a heartbeat has expired a channel.
func (s StatsFactory) ResetAll()Removes all tracked subscriptions
func (s StatsFactory) ResetSocketSubscriptions(socketId SocketId) []*subscriptionReset clears all subscriptions assigned to the given socket ID, and returns a slice of the existing subscriptions prior to reset
type SubscribeEvent struct {
SubID string `json:"subId"`
Channel string `json:"channel"`
ChanID int64 `json:"chanId"`
Symbol string `json:"symbol"`
Precision string `json:"prec,omitempty"`
Frequency string `json:"freq,omitempty"`
Key string `json:"key,omitempty"`
Len string `json:"len,omitempty"`
Pair string `json:"pair"`
}type SubscriptionRequest struct {
SubID string `json:"subId"`
Event string `json:"event"`
// authenticated
APIKey string `json:"apiKey,omitempty"`
AuthSig string `json:"authSig,omitempty"`
AuthPayload string `json:"authPayload,omitempty"`
AuthNonce string `json:"authNonce,omitempty"`
Filter []string `json:"filter,omitempty"`
DMS int `json:"dms,omitempty"` // dead man switch
// unauthenticated
Channel string `json:"channel,omitempty"`
Symbol string `json:"symbol,omitempty"`
Precision string `json:"prec,omitempty"`
Frequency string `json:"freq,omitempty"`
Key string `json:"key,omitempty"`
Len string `json:"len,omitempty"`
Pair string `json:"pair,omitempty"`
}func (s *SubscriptionRequest) String() stringtype SubscriptionSet []*subscriptionSubscriptionSet is a typed version of an array of subscription pointers, intended to meet the sortable interface. We need to sort Reset()'s return values for tests with more than 1 subscription (range map order is undefined)
func (s SubscriptionSet) Len() intfunc (s SubscriptionSet) Less(i, j int) boolfunc (s SubscriptionSet) RemoveByChannelId(chanId int64) SubscriptionSetfunc (s SubscriptionSet) RemoveBySubscriptionId(subID string) SubscriptionSetfunc (s SubscriptionSet) Swap(i, j int)type TickerFactory struct {
}func (f *TickerFactory) Build(sub *subscription, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error)func (f *TickerFactory) BuildSnapshot(sub *subscription, raw [][]interface{}, raw_bytes []byte) (interface{}, error)func (s TickerFactory) Close()Close is terminal. Do not call heartbeat after close.
func (s TickerFactory) ListenDisconnect() <-chan HeartbeatDisconnectListenDisconnect returns an error channel which receives a message when a heartbeat has expired a channel.
func (s TickerFactory) ResetAll()Removes all tracked subscriptions
func (s TickerFactory) ResetSocketSubscriptions(socketId SocketId) []*subscriptionReset clears all subscriptions assigned to the given socket ID, and returns a slice of the existing subscriptions prior to reset
type TradeFactory struct {
}func (f *TradeFactory) Build(sub *subscription, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error)func (f *TradeFactory) BuildSnapshot(sub *subscription, raw [][]interface{}, raw_bytes []byte) (interface{}, error)func (s TradeFactory) Close()Close is terminal. Do not call heartbeat after close.
func (s TradeFactory) ListenDisconnect() <-chan HeartbeatDisconnectListenDisconnect returns an error channel which receives a message when a heartbeat has expired a channel.
func (s TradeFactory) ResetAll()Removes all tracked subscriptions
func (s TradeFactory) ResetSocketSubscriptions(socketId SocketId) []*subscriptionReset clears all subscriptions assigned to the given socket ID, and returns a slice of the existing subscriptions prior to reset
type UnsubscribeEvent struct {
Status string `json:"status"`
ChanID int64 `json:"chanId"`
}type UnsubscribeRequest struct {
Event string `json:"event"`
ChanID int64 `json:"chanId"`
}type WebsocketAsynchronousFactory struct {
}WebsocketAsynchronousFactory creates a websocket-based asynchronous transport.
func (w *WebsocketAsynchronousFactory) Create() AsynchronousCreate returns a new websocket transport.