wshandler

package
v0.0.0-...-4ab53fc Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NoWebsocketSupport       uint32 = 0
	WebsocketTickerSupported uint32 = 1 << (iota - 1)
	WebsocketOrderbookSupported
	WebsocketKlineSupported
	WebsocketTradeDataSupported
	WebsocketAccountSupported
	WebsocketAllowsRequests
	WebsocketSubscribeSupported
	WebsocketUnsubscribeSupported
	WebsocketAuthenticatedEndpointsSupported
	WebsocketAccountDataSupported
	WebsocketSubmitOrderSupported
	WebsocketCancelOrderSupported
	WebsocketWithdrawSupported
	WebsocketMessageCorrelationSupported
	WebsocketSequenceNumberSupported
	WebsocketDeadMansSwitchSupported

	WebsocketTickerSupportedText                 = "TICKER STREAMING SUPPORTED"
	WebsocketOrderbookSupportedText              = "ORDERBOOK STREAMING SUPPORTED"
	WebsocketKlineSupportedText                  = "KLINE STREAMING SUPPORTED"
	WebsocketTradeDataSupportedText              = "TRADE STREAMING SUPPORTED"
	WebsocketAccountSupportedText                = "ACCOUNT STREAMING SUPPORTED"
	WebsocketAllowsRequestsText                  = "WEBSOCKET REQUESTS SUPPORTED"
	NoWebsocketSupportText                       = "WEBSOCKET NOT SUPPORTED"
	UnknownWebsocketFunctionality                = "UNKNOWN FUNCTIONALITY BITMASK"
	WebsocketSubscribeSupportedText              = "WEBSOCKET SUBSCRIBE SUPPORTED"
	WebsocketUnsubscribeSupportedText            = "WEBSOCKET UNSUBSCRIBE SUPPORTED"
	WebsocketAuthenticatedEndpointsSupportedText = "WEBSOCKET AUTHENTICATED ENDPOINTS SUPPORTED"
	WebsocketAccountDataSupportedText            = "WEBSOCKET ACCOUNT DATA SUPPORTED"
	WebsocketSubmitOrderSupportedText            = "WEBSOCKET SUBMIT ORDER SUPPORTED"
	WebsocketCancelOrderSupportedText            = "WEBSOCKET CANCEL ORDER SUPPORTED"
	WebsocketWithdrawSupportedText               = "WEBSOCKET WITHDRAW SUPPORTED"
	WebsocketMessageCorrelationSupportedText     = "WEBSOCKET MESSAGE CORRELATION SUPPORTED"
	WebsocketSequenceNumberSupportedText         = "WEBSOCKET SEQUENCE NUMBER SUPPORTED"
	WebsocketDeadMansSwitchSupportedText         = "WEBSOCKET DEAD MANS SWITCH SUPPORTED"

	// WebsocketNotEnabled alerts of a disabled websocket
	WebsocketNotEnabled = "exchange_websocket_not_enabled"
	// WebsocketTrafficLimitTime defines a standard time for no traffic from the
	// websocket connection
	WebsocketTrafficLimitTime = 5 * time.Second

	// WebsocketStateTimeout defines a const for when a websocket connection
	// times out, will be handled by the routine management system
	WebsocketStateTimeout = "TIMEOUT"
)

Websocket functionality list and state consts

Variables

This section is empty.

Functions

This section is empty.

Types

type KlineData

type KlineData struct {
	Timestamp  time.Time
	Pair       currency.Pair
	AssetType  string
	Exchange   string
	StartTime  time.Time
	CloseTime  time.Time
	Interval   string
	OpenPrice  float64
	ClosePrice float64
	HighPrice  float64
	LowPrice   float64
	Volume     float64
}

KlineData defines kline feed

type TickerData

type TickerData struct {
	Timestamp  time.Time
	Pair       currency.Pair
	AssetType  string
	Exchange   string
	ClosePrice float64
	Quantity   float64
	OpenPrice  float64
	HighPrice  float64
	LowPrice   float64
}

TickerData defines ticker feed

type TradeData

type TradeData struct {
	Timestamp    time.Time
	CurrencyPair currency.Pair
	AssetType    string
	Exchange     string
	EventType    string
	EventTime    int64
	Price        float64
	Amount       float64
	Side         string
}

TradeData defines trade data

type Websocket

type Websocket struct {

	// Connected denotes a channel switch for diversion of request flow
	Connected chan struct{}
	// Disconnected denotes a channel switch for diversion of request flow
	Disconnected chan struct{}
	// DataHandler pipes websocket data to an exchange websocket data handler
	DataHandler chan interface{}
	// ShutdownC is the main shutdown channel which controls all websocket go funcs
	ShutdownC chan struct{}
	// Orderbook is a local cache of orderbooks
	Orderbook WebsocketOrderbookLocal
	// Wg defines a wait group for websocket routines for cleanly shutting down
	// routines
	Wg sync.WaitGroup
	// TrafficAlert monitors if there is a halt in traffic throughput
	TrafficAlert chan struct{}
	// Functionality defines websocket stream capabilities
	Functionality uint32
	// contains filtered or unexported fields
}

Websocket defines a return type for websocket connections via the interface wrapper for routine processing in routines.go

func New

func New() *Websocket

New initialises the websocket struct

func (*Websocket) CanUseAuthenticatedEndpoints

func (w *Websocket) CanUseAuthenticatedEndpoints() bool

CanUseAuthenticatedEndpoints gets canUseAuthenticatedEndpoints val in a thread safe manner

func (*Websocket) Connect

func (w *Websocket) Connect() error

Connect intiates a websocket connection by using a package defined connection function

func (*Websocket) FormatFunctionality

func (w *Websocket) FormatFunctionality() string

FormatFunctionality will return each of the websocket connection compatible stream methods as a string

func (*Websocket) GetDefaultURL

func (w *Websocket) GetDefaultURL() string

GetDefaultURL returns the default websocket URL

func (*Websocket) GetFunctionality

func (w *Websocket) GetFunctionality() uint32

GetFunctionality returns a functionality bitmask for the websocket connection

func (*Websocket) GetName

func (w *Websocket) GetName() string

GetName returns exchange name

func (*Websocket) GetProxyAddress

func (w *Websocket) GetProxyAddress() string

GetProxyAddress returns the current websocket proxy

func (*Websocket) GetSubscriptions

func (w *Websocket) GetSubscriptions() []WebsocketChannelSubscription

GetSubscriptions returns a copied list of subscriptions subscriptions is a private member and cannot be manipulated

func (*Websocket) GetWebsocketURL

func (w *Websocket) GetWebsocketURL() string

GetWebsocketURL returns the running websocket URL

func (*Websocket) IsConnected

func (w *Websocket) IsConnected() bool

IsConnected exposes websocket connection status

func (*Websocket) IsConnecting

func (w *Websocket) IsConnecting() bool

IsConnecting checks whether websocket is busy connecting

func (*Websocket) IsEnabled

func (w *Websocket) IsEnabled() bool

IsEnabled returns bool

func (*Websocket) RemoveSubscribedChannels

func (w *Websocket) RemoveSubscribedChannels(channels []WebsocketChannelSubscription)

RemoveSubscribedChannels removes supplied channels from channelsToSubscribe

func (*Websocket) ResubscribeToChannel

func (w *Websocket) ResubscribeToChannel(subscribedChannel WebsocketChannelSubscription)

ResubscribeToChannel calls unsubscribe func and removes it from subscribedChannels to trigger a subscribe event

func (*Websocket) SetCanUseAuthenticatedEndpoints

func (w *Websocket) SetCanUseAuthenticatedEndpoints(val bool)

SetCanUseAuthenticatedEndpoints sets canUseAuthenticatedEndpoints val in a thread safe manner

func (*Websocket) SetChannelSubscriber

func (w *Websocket) SetChannelSubscriber(subscriber func(channelToSubscribe WebsocketChannelSubscription) error)

SetChannelSubscriber sets the function to use the base subscribe func

func (*Websocket) SetChannelUnsubscriber

func (w *Websocket) SetChannelUnsubscriber(unsubscriber func(channelToUnsubscribe WebsocketChannelSubscription) error)

SetChannelUnsubscriber sets the function to use the base unsubscribe func

func (*Websocket) SetConnector

func (w *Websocket) SetConnector(connector func() error)

SetConnector sets connection function

func (*Websocket) SetDefaultURL

func (w *Websocket) SetDefaultURL(defaultURL string)

SetDefaultURL sets default websocket URL

func (*Websocket) SetExchangeName

func (w *Websocket) SetExchangeName(exchName string)

SetExchangeName sets exchange name

func (*Websocket) SetProxyAddress

func (w *Websocket) SetProxyAddress(proxyAddr string) error

SetProxyAddress sets websocket proxy address

func (*Websocket) SetWebsocketURL

func (w *Websocket) SetWebsocketURL(websocketURL string)

SetWebsocketURL sets websocket URL

func (*Websocket) SetWsStatusAndConnection

func (w *Websocket) SetWsStatusAndConnection(enabled bool) error

SetWsStatusAndConnection sets if websocket is enabled it will also connect/disconnect the websocket connection

func (*Websocket) Setup

func (w *Websocket) Setup(connector func() error,
	subscriber func(channelToSubscribe WebsocketChannelSubscription) error,
	unsubscriber func(channelToUnsubscribe WebsocketChannelSubscription) error,
	exchangeName string,
	wsEnabled,
	verbose bool,
	defaultURL,
	runningURL string,
	authenticatedWebsocketAPISupport bool) error

Setup sets main variables for websocket connection

func (*Websocket) Shutdown

func (w *Websocket) Shutdown() error

Shutdown attempts to shut down a websocket connection and associated routines by using a package defined shutdown function

func (*Websocket) SubscribeToChannels

func (w *Websocket) SubscribeToChannels(channels []WebsocketChannelSubscription)

SubscribeToChannels appends supplied channels to channelsToSubscribe

func (*Websocket) SupportsFunctionality

func (w *Websocket) SupportsFunctionality(f uint32) bool

SupportsFunctionality returns if the functionality is supported as a boolean

func (*Websocket) WebsocketReset

func (w *Websocket) WebsocketReset() error

WebsocketReset sends the shutdown command, waits for channel/func closure and then reconnects

type WebsocketChannelSubscription

type WebsocketChannelSubscription struct {
	Channel  string
	Currency currency.Pair
	Params   map[string]interface{}
}

WebsocketChannelSubscription container for websocket subscriptions Currently only a one at a time thing to avoid complexity

func (*WebsocketChannelSubscription) Equal

func (w *WebsocketChannelSubscription) Equal(subscribedChannel *WebsocketChannelSubscription) bool

Equal two WebsocketChannelSubscription to determine equality

type WebsocketConnection

type WebsocketConnection struct {
	sync.Mutex
	Verbose      bool
	RateLimit    float64
	ExchangeName string
	URL          string
	ProxyURL     string
	Wg           sync.WaitGroup
	Connection   *websocket.Conn
	Shutdown     chan struct{}
	// These are the request IDs and the corresponding response JSON
	IDResponses          map[int64][]byte
	ResponseCheckTimeout time.Duration
	ResponseMaxLimit     time.Duration
}

WebsocketConnection contains all the data needed to send a message to a WS

func (*WebsocketConnection) AddResponseWithID

func (w *WebsocketConnection) AddResponseWithID(id int64, data []byte)

AddResponseWithID adds data to IDResponses with locks and a nil check

func (*WebsocketConnection) Dial

func (w *WebsocketConnection) Dial(dialer *websocket.Dialer, headers http.Header) error

Dial sets proxy urls and then connects to the websocket

func (*WebsocketConnection) GenerateMessageID

func (w *WebsocketConnection) GenerateMessageID(useNano bool) int64

GenerateMessageID Creates a messageID to checkout

func (*WebsocketConnection) ReadMessage

func (w *WebsocketConnection) ReadMessage() (WebsocketResponse, error)

ReadMessage reads messages, can handle text, gzip and binary

func (*WebsocketConnection) SendMessage

func (w *WebsocketConnection) SendMessage(data interface{}) error

SendMessage the one true message request. Sends message to WS

func (*WebsocketConnection) SendMessageReturnResponse

func (w *WebsocketConnection) SendMessageReturnResponse(id int64, request interface{}) ([]byte, error)

SendMessageReturnResponse will send a WS message to the connection It will then run a goroutine to await a JSON response If there is no response it will return an error

func (*WebsocketConnection) WaitForResult

func (w *WebsocketConnection) WaitForResult(id int64, wg *sync.WaitGroup)

WaitForResult will keep checking w.IDResponses for a response ID If the timer expires, it will return without

type WebsocketOrderbookLocal

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

WebsocketOrderbookLocal defines a local cache of orderbooks for amending, appending and deleting changes and updates the main store in orderbook.go

func (*WebsocketOrderbookLocal) FlushCache

func (w *WebsocketOrderbookLocal) FlushCache()

FlushCache flushes w.ob data to be garbage collected and refreshed when a connection is lost and reconnected

func (*WebsocketOrderbookLocal) LoadSnapshot

func (w *WebsocketOrderbookLocal) LoadSnapshot(newOrderbook *orderbook.Base, exchName string, overwrite bool) error

LoadSnapshot loads initial snapshot of orderbook data, overite allows full orderbook to be completely rewritten because the exchange is a doing a full update not an incremental one

func (*WebsocketOrderbookLocal) Update

func (w *WebsocketOrderbookLocal) Update(bidTargets, askTargets []orderbook.Item,
	p currency.Pair,
	updated time.Time,
	exchName, assetType string) error

Update updates a local cache using bid targets and ask targets then updates main cache in orderbook.go Volume == 0; deletion at price target Price target not found; append of price target Price target found; amend volume of price target

func (*WebsocketOrderbookLocal) UpdateUsingID

func (w *WebsocketOrderbookLocal) UpdateUsingID(bidTargets, askTargets []orderbook.Item,
	p currency.Pair,
	exchName, assetType, action string) error

UpdateUsingID updates orderbooks using specified ID

type WebsocketOrderbookUpdate

type WebsocketOrderbookUpdate struct {
	Pair     currency.Pair
	Asset    string
	Exchange string
}

WebsocketOrderbookUpdate defines a websocket event in which the orderbook has been updated in the orderbook package

type WebsocketPositionUpdated

type WebsocketPositionUpdated struct {
	Timestamp time.Time
	Pair      currency.Pair
	AssetType string
	Exchange  string
}

WebsocketPositionUpdated reflects a change in orders/contracts on an exchange

type WebsocketResponse

type WebsocketResponse struct {
	Type int
	Raw  []byte
}

WebsocketResponse defines generalised data from the websocket connection

Jump to

Keyboard shortcuts

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