websocket

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2019 License: BSD-2-Clause Imports: 23 Imported by: 0

Documentation

Overview

Package websocket provides a client for managing connections to the Cryptowatch Websocket API. The API consists of two separate back ends for streaming and trading. Although they are separate services, both share the same underlying connection logic. Each service has its own respective client: StreamClient and TradeClient.

Cryptowatch Websocket API

View the full websocket api documentation here: https://cryptowat.ch/docs/websocket-api

Connecting

To connect to either the streaming or trading back end, you will need an API key pair. Please inquire about obtaining API keys here: https://docs.google.com/forms/d/e/1FAIpQLSdhv_ceVtKA0qQcW6zQzBniRBaZ_cC4al31lDCeZirntkmWQw/viewform?c=0&w=1

The same API key pair will work for both streaming and trading, although we use specific access control rules on our back end to determine if your key pair can access any particular data subscription or trading functionality.

WSParams

Both StreamClient and TradeClient use WSParams to specify connection options.

type WSParams struct {
	// Required
	APIKey        string
	SecretKey     string

	// Not required
	URL           string
	ReconnectOpts *ReconnectOpts
}

Typically you will only need to supply APIKey, SecretKey, and Subscriptions as the other parameters have default values.

URL is the url of the back end to connect to. You will not need to supply it unless you are testing against a non-production environment.

ReconnectOpts determine how (and if) the client should reconnect. By default, the client will reconnect with linear backoff up to 30 seconds.

Subscriptions

The Subscriptions supplied in StreamClientParams determine what resources will be streamed. Read the streaming subscriptions documentation here: https://cryptowat.ch/docs/websocket-api#data-streaming

The Subscriptions supplied in TradeClientParams determine what markets can be traded on. Read about the trading subscription documentation here: https://cryptowat.ch/docs/websocket-api#trading

Both StreamClient and TradeClient can define OnSubscriptionResult which gives information about what was successfully subscribed to, and if there were any errors (e.g. Access Denied).

Basic Usage

The typical workflow is to create an instance of a client, set event handlers on it, then initiate the connection. As events occur, the registered callbacks will be executed. For StreamClient, the callbacks will contain data for the active subscriptions. For the TradeClient, callbacks will contain real-time information about your open orders, trades, positions, or balances.

Stream Client

The stream client can be set up to process live market-level or pair-level data as follows:

import "code.cryptowat.ch/cw-sdk-go"

client, err := websocket.NewStreamClient(&websocket.StreamClientParams{
	WSParams: &websocket.WSParams{
		APIKey:    "myapikey",
		SecretKey: "mysecretkey",
	},

	Subscriptions: []*websocket.StreamSubscription{
		&websocket.StreamSubscription{
			Resource: "markets:86:trades", // Trade feed for Kraken BTCEUR
		},
		&websocket.StreamSubscription{
			Resource: "markets:87:trades", // Trade feed for Kraken BTCEUR
		},
	},
})
if err != nil {
	log.Fatal("%s", err)
}

c.OnSubscriptionResult(func(sr websocket.SubscriptionResult) {
	// Verify subscriptions
})

client.OnError(func(err error, disconnecting bool) {
	// Handle errors
})

client.OnTradesUpdate(func(m websocket.Market, tu websocket.TradesUpdate) {
	// Handle live trade data
})

// Set more handlers for market and pair data

client.Connect()

Trade Client

The trade client maintains the state of your orders, trades, balances, and positions, while also allowing you to place and cancel orders. In order to start trading, you must wait for the internal cache to initialize, which can be accomplished using the OnReady callback.

Each subscription represents a market you intend to trade and receive updates on. You can supply API keys for the exchange, or the client will fall back on your API keys loaded in your Cryptowatch account.

import (
	"code.cryptowat.ch/cw-sdk-go"
	"code.cryptowat.ch/cw-sdk-go/common"
)

client, err := websocket.NewTradeClient(&websocket.TradeClientParams{
	WSParams: &websocket.WSParams{
		APIKey:    "myapikey",
		SecretKey: "mysecretkey",
	},

	Subscriptions: []*websocket.TradeSubscription{
		&websocket.TradeSubscription{
			MarketID: common.MarketID("86"), // Trade on Kraken BTCEUR
		},
	},
})
if err != nil {
	log.Fatal("%s", err)
}

client.OnSubscriptionResult(func(sr websocket.SubscriptionResult) {
	// Verify subscriptions (trade sessions)
})

tc.OnError(func(mID common.MarketID, err error, disconnecting bool) {
	// Handle errors
})

client.OnReady(func() {
	// Start trading
})

// Set more handlers for orders, trades, positions, or balance updates

client.Connect()

Error Handling and Connection States

Both StreamClient and TradeClient define an OnError callback which you can use to respond to any error that may occur. The OnError callback function signature is slightly different for trading because it includes a MarketID for any error that is related to trading. The MarketID is blank for any error related to the connection itself.

The "disconnecting" argument is set to true if the error is going to cause the disconnection: in this case, the app could store the error somewhere and show it later, when the actual disconnection happens; see the example of that below, together with state listener. Error handlers are always called before the state change listeners.

Both StreamClient and TradeClient can set listeners for connection state changes such as StateDisconnected, StateWaitBeforeReconnect, StateConnecting, StateAuthenticating, and StateEstablished. They can also listen for any state changes by using StateAny. The following is an example of how you would print verbose logs about a client's state transitions. "client" can represent either StreamClient or TradeClient:

var lastError error

client.OnError(func(err error, disconnecting bool) {
	// If the client is going to disconnect because of that error, just save
	// the error to print later with the disconnection message.
	if disconnecting {
		lastError = err
		return
	}

	// Otherwise, print the error message right away.
	log.Printf("Error: %s", err.Error())
})

client.OnStateChange(
	websocket.ConnStateAny,
	func(oldState, state websocket.ConnState) {
		causeStr := ""
		if lastError != nil {
			causeStr = fmt.Sprintf(" (%s)", lastError)
			lastError = nil
		}
		log.Printf(
			"State updated: %s -> %s%s",
			websocket.ConnStateNames[oldState],
			websocket.ConnStateNames[state],
			causeStr,
		)
	},
)

Strings Vs Floats

All price, ID, and subscription data is represented as strings. This is to prevent loss of significant digits from using floats, as well as to provide a consistent and simple API.

Concurrency

All methods of the StreamClient and TradeClient can be called concurrently from any number of goroutines. All callbacks and listeners are called by the same internal goroutine, unique to each connection; that is, they are never called concurrently with each other.

Stream Client CLI

Use the command line tool stream-client to subscribe to live data feeds from the command line. To install the tool, run "make" from the root of the repo. This will create the executable bin/stream-client, which can be used as follows:

./stream-client \
	-apikey=your_api_key \
	-secretkey=your_secret_key \
	-sub subscription_key \
	-sub subscription_key2

Index

Constants

View Source
const (
	DefaultStreamURL = "wss://stream.cryptowat.ch"
)
View Source
const (
	DefaultTradeURL = "wss://trading.service.cryptowat.ch"
)

Variables

View Source
var (
	// ErrNotInitialized is returned when PlaceOrder or CancelOrder is called before the client is initialized.
	// This indicates you have not waited until OnReady was called, or the client is in a disconnected state.
	ErrNotInitialized = errors.New("trade client not initialized")

	// ErrInvalidOrder is returned from PlaceOrder if the order is not valid. Not valid in this case
	// means the order was likely not placed correctly on the exchange.
	ErrInvalidOrder = errors.New("order is not valid")

	// ErrNoExchangeAccess is returned from the OnError callback when the Cryptowatch trading back end
	// does not have proper permissions to access the relevant exchange's API. Usually this means you
	// need to add your API keys to the relevant exchange at https://cryptowat.ch/account/api-keys.
	ErrNoExchangeAccess = errors.New("cryptowatch account is missing exchange api keys")

	// ErrBadProto is returned from PlaceOrder or CancelOrder if the Cryptowatch trading back end returns
	// invalid protobuf data. This should never happen.
	ErrBadProto = errors.New("request is not a valid proto type")
)

The following errors are returned from TradeClient.

View Source
var (
	// ErrNotConnected means the connection is not established when the client
	// tried to e.g. send a message, or close the connection.
	ErrNotConnected = errors.New("not connected")

	// ErrInvalidAuthn means that after the client has sent the authentication
	// info and was expecting the result from the server, it received something
	// else.
	ErrInvalidAuthn = errors.New("invalid authentication result")

	// ErrConnLoopActive means the client tried to connect when the client is
	// already connecting.
	ErrConnLoopActive = errors.New("connection loop is already active")

	// ErrBadCredentials means the provided APIKey and/or SecretKey were invalid.
	ErrBadCredentials = errors.New("bad credentials")

	// ErrTokenExpired means the authentication procedure took too long and the
	// token expired. The client retries authentication 3 times before actually
	// returning this error.
	ErrTokenExpired = errors.New("token is expired")

	// ErrBadNonce means the nonce used in the authentication request is not
	// larger than the last used nonce.
	ErrBadNonce = errors.New("bad nonce")

	// ErrUnknownAuthnError means some unexpected authentication problem;
	// possibly caused by an internal error on stream server.
	ErrUnknownAuthnError = errors.New("unknown authentication error")
)

The following errors are returned from wsConn, which applies to both StreamClient and TradeClient.

View Source
var ConnStateNames = map[ConnState]string{
	ConnStateDisconnected:        "disconnected",
	ConnStateWaitBeforeReconnect: "wait-before-reconnect",
	ConnStateConnecting:          "connecting",
	ConnStateAuthenticating:      "authenticating",
	ConnStateEstablished:         "established",
}

ConnStateNames contains human-readable names for connection states.

Functions

This section is empty.

Types

type Bandwidth

type Bandwidth struct {
	OK             bool
	BytesRemaining int64
	BytesUsed      int64
}

BandwidthUpdate contains information about your stream bandwidth usage

func (Bandwidth) String

func (b Bandwidth) String() string

type BandwidthUpdateCB

type BandwidthUpdateCB func(b Bandwidth)

type ConnClosedCallback

type ConnClosedCallback func(state ConnState)

ConnClosedCallback defines the callback function for onConnClosed.

type ConnState

type ConnState int

ConnState represents the websocket connection state

const (
	// ConnStateDisconnected means we're disconnected and not trying to connect.
	// connLoop is not running.
	ConnStateDisconnected ConnState = iota

	// ConnStateWaitBeforeReconnect means we already tried to connect, but then
	// either the connection failed, or succeeded but later disconnected for some
	// reason (see stateCause), and now we're waiting for a timeout before
	// connecting again. wsConn is nil, but connCtx and connCtxCancel are not,
	// and connLoop is running.
	ConnStateWaitBeforeReconnect

	// ConnStateConnecting means we're calling websocket.DefaultDialer.Dial() right
	// now.
	ConnStateConnecting

	// ConnStateAuthenticating means the transport (websocket) connection is
	// established, and right now we're exchanging the authentication and
	// identification messages
	ConnStateAuthenticating

	// ConnStateEstablished means the connection is ready
	ConnStateEstablished

	// ConnStateAny can be used with onStateChange() and onStateChangeOpt()
	// in order to listen for all states.
	ConnStateAny = -1
)

The following constants represent every possible ConnState.

type MarketUpdateCB

type MarketUpdateCB func(common.Market, common.MarketUpdate)

MarketUpdateCB defines a callback function for OnMarketUpdate.

type MissedMessages

type MissedMessages struct {
	// NumMissedMessages represents how many messages were dropped on the floor.
	NumMissedMessages int64
}

MissedMessages is sent to clients when the server was unable to send all requested messages to the client, so some of them were dropped on the floor. Typically it means that the client subscribed to too much, so it should reduce the number of subscriptions.

type MissedMessagesCB

type MissedMessagesCB func(mm MissedMessages)

MissedMessagesCB defines a callback function for OnMissedMessages.

type OnBalancesUpdateCB

type OnBalancesUpdateCB func(marketID common.MarketID, balances common.Balances)

Balances grep flag: Ki49fK OnBalancesUpdateCB defines a callback function for OnBalancesUpdate.

type OnErrorCB

type OnErrorCB func(err error, disconnecting bool)

OnErrorCB is a signature of an error listener. If the error is going to cause the disconnection, disconnecting is set to true. In this case, the error listeners are always called before the state listeners, so applications can just save the error, and display it later, when the disconnection actually happens.

type OnMarketReadyCB

type OnMarketReadyCB func(marketID common.MarketID, ready bool)

OnMarketReadyCB defines a callback function for OnMarketReadyChange.

type OnPositionsUpdateCB

type OnPositionsUpdateCB func(marketID common.MarketID, positions []common.PrivatePosition)

OnPositionsUpdateCB defines a callback function for OnPositionsUpdate.

type OnTradeErrorCB

type OnTradeErrorCB func(marketID common.MarketID, err error, disconnecting bool)

OnTradeErrorCB defines a callback function for OnError. If the error is specific to a market, then marketID is set; otherwise it's an empty string. If the error is going to cause the disconnection, disconnecting is set to true. In this case, the error listeners are always called before the state listeners, so applications can just save the error, and display it later, when the disconnection actually happens.

type OrdersUpdateCB

type OrdersUpdateCB func(marketID common.MarketID, orders []common.PrivateOrder)

OrdersUpdateCB defines a callback function for OnOrdersUpdate.

type PairUpdateCB

type PairUpdateCB func(common.Pair, common.PairUpdate)

PairUpdateCB defines a callback function for OnPairUpdate.

type PrivateTradesUpdateCB

type PrivateTradesUpdateCB func(marketID common.MarketID, trades []common.PrivateTrade)

PrivateTradesUpdateCB defines a callback function for OnTradesUpdate.

type ReconnectOpts

type ReconnectOpts struct {
	// Reconnect switch: if true, the client will attempt to reconnect to the websocket back
	// end if it is disconnected. If false, the client will stay disconnected.
	Reconnect bool

	// Reconnection backoff: if true, then the reconnection time will be
	// initially ReconnectTimeout, then will grow by 500ms on each unsuccessful
	// connection attempt; but it won't be longer than MaxReconnectTimeout.
	Backoff bool

	// Initial reconnection timeout: defaults to 0 seconds. If backoff=false,
	// a minimum reconnectTimeout of 1 second will be used.
	ReconnectTimeout time.Duration

	// Max reconnect timeout. If zero, then 30 seconds will be used.
	MaxReconnectTimeout time.Duration
}

ReconnectOpts are settings used to reconnect after being disconnected. By default, the client will reconnect with backoff starting with 0 seconds and increasing linearly up to 30 seconds. These are the most "aggressive" reconnect options permitted in the client. For example, you cannot set ReconnectTimeout to 0 and Backoff to false.

type StateCallback

type StateCallback func(prevState, curState ConnState)

StateCallback is a signature of a state listener. Arguments conn, oldState and state are self-descriptive; cause is the error which caused the current state. Cause is relevant only for ConnStateDisconnected and ConnStateWaitBeforeReconnect (in which case it's either the reason of failure to connect, or reason of disconnection), for other states it's always nil.

See onStateChange.

type StateListenerOpt

type StateListenerOpt struct {
	// If OneOff is true, the listener will only be called once; otherwise it'll
	// be called every time the requested state becomes active.
	OneOff bool

	// If CallImmediately is true, and the state being subscribed to is active
	// at the moment, the callback will be called immediately (with the "old"
	// state being equal to the new one)
	CallImmediately bool
}

type StreamClient

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

StreamClient is used to connect to Cryptowatch's data streaming backend. Typically you will get an instance using NewStreamClient(), set any state listeners for the connection you might need, then set data listeners for whatever data subscriptions you have. Finally, you can call Connect() to initiate the data stream.

func NewStreamClient

func NewStreamClient(params *StreamClientParams) (*StreamClient, error)

NewStreamClient creates a new StreamClient instance with the given params. Although it starts listening for data immediately, you will still have to register listeners to handle that data, and then call Connect() explicitly.

func (*StreamClient) Close

func (sc *StreamClient) Close() (err error)

Close stops the connection (or reconnection loop, if active), and if websocket connection is active at the moment, closes it as well.

func (*StreamClient) Connect

func (sc *StreamClient) Connect() (err error)

Connect either starts a connection goroutine (if state is ConnStateDisconnected), or makes it connect immediately, ignoring timeout (if the state is ConnStateWaitBeforeReconnect). For other states, this returns an error.

Connect doesn't wait for the connection to establish; it returns immediately.

func (*StreamClient) GetSubscriptions

func (sc *StreamClient) GetSubscriptions() []*StreamSubscription

GetSubscriptions returns a slice of the current subscriptions.

func (*StreamClient) OnBandwidthUpdate

func (sc *StreamClient) OnBandwidthUpdate(cb BandwidthUpdateCB)

func (*StreamClient) OnConnClosed

func (sc *StreamClient) OnConnClosed(cb ConnClosedCallback)

OnConnClosed allows the client to set a callback for when the connection is lost. The new state of the client could be ConnStateDisconnected or ConnStateWaitBeforeReconnect.

func (*StreamClient) OnError

func (sc *StreamClient) OnError(cb OnErrorCB)

OnError registers a callback which will be called on all errors. When it's an error about disconnection, the OnError callbacks are called before the state listeners.

func (*StreamClient) OnMarketUpdate

func (sc *StreamClient) OnMarketUpdate(cb MarketUpdateCB)

OnMarketUpdate sets a callback for all market updates. MarketUpdateCB contains MarketUpdate, which is a container for every type of update. For each MarketUpdate, it will contain exactly one non-nil struct, which is one of the following: OrderBookSnapshot OrderBookDelta OrderBookSpreadUpdate TradesUpdate IntervalsUpdate SummaryUpdate SparklineUpdate

func (*StreamClient) OnMissedMessages

func (sc *StreamClient) OnMissedMessages(cb MissedMessagesCB)

OnMissedMessages is sent to clients when the server was unable to send all requested messages to the client, so some of them were dropped on the floor. Typically this means that the client subscribed to too many subscriptions, so it should reduce the number of subscriptions.

func (*StreamClient) OnPairUpdate

func (sc *StreamClient) OnPairUpdate(cb PairUpdateCB)

OnPairUpdate sets a callback for all pair updates. PairUpdateCB contains PairUpdate, which is a container for every type of pair update. For each MarketUpdate, there will be exactly one non-nil property, which is one of the following: VWAPUpdate PerformanceUpdate TrendlineUpdate

func (*StreamClient) OnStateChange

func (sc *StreamClient) OnStateChange(state ConnState, cb StateCallback)

OnStateChange registers a new listener for the given state. The listener is registered with the default options (call the listener every time the state becomes active, and don't call the listener immediately for the current state). All registered callbacks for all states (and all messages, see OnMarketUpdate) will be called by the same internal goroutine, i.e. they are never called concurrently with each other.

The order of listeners invocation for the same state is unspecified, and clients shouldn't rely on it.

The listeners shouldn't block; a blocked listener will also block the whole stream connection.

To subscribe to all state changes, use ConnStateAny as a state.

func (*StreamClient) OnStateChangeOpt

func (sc *StreamClient) OnStateChangeOpt(state ConnState, cb StateCallback, opt StateListenerOpt)

OnStateChangeOpt is like OnStateChange, but also takes additional options; see StateListenerOpt for details.

func (*StreamClient) OnSubscriptionResult

func (sc *StreamClient) OnSubscriptionResult(cb SubscriptionResultCB)

OnSubscriptionResult is called whenever a subscription attempt was made; it happens after the connection and authentication is successful, as well as after the call to Subscribe().

func (*StreamClient) OnUnsubscriptionResult

func (sc *StreamClient) OnUnsubscriptionResult(cb UnsubscriptionResultCB)

OnUnsubscriptionResult is called whenever an unsubscription attempt was made; it happens after the call to Unsubscribe().

func (*StreamClient) Subscribe

func (sc *StreamClient) Subscribe(subs []*StreamSubscription) error

Subscribe makes a request to subscribe to the given keys. Example:

client.Subscribe([]*StreamSubscription{
        &StreamSubscription{
                Resource: "markets:1:book:deltas",
        },
        &StreamSubscription{
                Resource: "markets:1:book:spread",
        },
})

The client must be connected and authenticated for this to work. See StreamClientParams.Subscriptions for more details.

The subscription result, together with the current subscription status, will be delivered to the callback registered with OnSubscriptionResult.

func (*StreamClient) URL

func (sc *StreamClient) URL() string

URL returns the url the client is connected to, e.g. wss://stream.cryptowat.ch.

func (*StreamClient) Unsubscribe

func (sc *StreamClient) Unsubscribe(subs []*StreamSubscription) error

Unsubscribe unsubscribes from the given set of keys. Also see notes for subscribe.

The unsubscription result, together with the current subscription status, will be delivered to the callback registered with OnUnsubscriptionResult.

type StreamClientParams

type StreamClientParams struct {
	WSParams      *WSParams
	Subscriptions []*StreamSubscription
}

type StreamSubscription

type StreamSubscription struct {
	Resource string
}

func (*StreamSubscription) GetResource

func (s *StreamSubscription) GetResource() string

type SubscribeError

type SubscribeError struct {
	Key          string
	Error        string
	Subscription Subscription
}

SubscribeError represents an error of a single key: it contains the key and the error message explaining why subscription has failed. Sent as part of SubscriptionResult.

type Subscription

type Subscription interface {
	GetResource() string
}

type SubscriptionResult

type SubscriptionResult struct {
	// Successful subscriptions
	Subscriptions []Subscription
	// Failed subscriptions
	Failed []SubscribeError `json:"Failed,omitempty"`
	// Current status: list of the keys to which the client is now subscribed
	Status SubscriptionStatus
}

SubscriptionResult is sent to clients after subscription to some key(s) is attempted. It happens after successful authentication (if authentication message contained initial subscriptions) as well as after following requests to subscribe.

func (SubscriptionResult) String

func (v SubscriptionResult) String() string

type SubscriptionResultCB

type SubscriptionResultCB func(sr SubscriptionResult)

SubscriptionResultCB defines a callback function for OnSubscriptionResult.

type SubscriptionStatus

type SubscriptionStatus struct {
	Subscriptions []Subscription
}

SubscriptionStatus contains the key to which the client is subscribed right now. Sent as part of SubscriptionResult and UnsubscriptionResult.

type TradeClient

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

TradeClient is used to manage a connection to Cryptowatch's trading back end, and provides functions for trading on the the subscribed markets. TradeClient also has callbacks for updates related to trading.

func NewTradeClient

func NewTradeClient(params *TradeClientParams) (*TradeClient, error)

NewTradeClient creates a new TradeClient based on the given WSParams. Subscriptions should be an array of market IDs that you have access to trade on.

func (*TradeClient) CancelOrder

func (tc *TradeClient) CancelOrder(orderOpt common.CancelOrderOpt) error

CancelOrder cancels the given order on the exchange. CancelOrder blocks until the order has been placed or if an error occurs. it can be called concurrently on as many different orders as needed.

func (*TradeClient) Close

func (tc *TradeClient) Close() (err error)

Close stops the connection (or reconnection loop, if active), and if websocket connection is active at the moment, closes it as well.

func (*TradeClient) Connect

func (tc *TradeClient) Connect() (err error)

Connect either starts a connection goroutine (if state is ConnStateDisconnected), or makes it connect immediately, ignoring timeout (if the state is ConnStateWaitBeforeReconnect). For other states, this returns an error.

Connect doesn't wait for the connection to establish; it returns immediately.

func (*TradeClient) GetBalances

func (tc *TradeClient) GetBalances(marketID common.MarketID) (common.Balances, error)

Balances grep flag: Ki49fK GetBalancesWithMarketID returns a map of FundingType to a list of balances for a particular exchange. If the market is not yet ready, returns ErrNotInitialized.

func (*TradeClient) GetOrders

func (tc *TradeClient) GetOrders(marketID common.MarketID) ([]common.PrivateOrder, error)

GetOrders returns the list of current open orders ordered by execution time (oldest first). If the market is not yet ready, returns ErrNotInitialized.

func (*TradeClient) GetPositions

func (tc *TradeClient) GetPositions(marketID common.MarketID) ([]common.PrivatePosition, error)

GetPositions returns the list of open positions ordered by execution time (oldest first). If the market is not yet ready, returns ErrNotInitialized.

func (*TradeClient) GetSubscriptions

func (tc *TradeClient) GetSubscriptions() []*TradeSubscription

GetSubscriptions returns a slice of the current subscriptions.

func (*TradeClient) GetTrades

func (tc *TradeClient) GetTrades(marketID common.MarketID) ([]common.PrivateTrade, error)

GetTrades returns the 1000 most recent trades ordered by execution time (oldest first). If the market is not yet ready, returns ErrNotInitialized.

func (*TradeClient) OnBalancesUpdate

func (tc *TradeClient) OnBalancesUpdate(cb OnBalancesUpdateCB)

Balances grep flag: Ki49fK OnBalancesUpdate sets a callback for balance updates. This will be called immediately when the client initializes, and for every subsequent balance update. An internal cache of balances is kept, and can be accessed with GetBalances()

func (*TradeClient) OnConnClosed

func (tc *TradeClient) OnConnClosed(cb ConnClosedCallback)

OnConnClosed allows the client to set a callback for when the connection is lost. The new state of the client could be ConnStateDisconnected or ConnStateWaitBeforeReconnect.

func (*TradeClient) OnError

func (tc *TradeClient) OnError(cb OnTradeErrorCB)

OnError sets a callback function for errors associated with the trading client or trading back end.

func (*TradeClient) OnMarketReadyChange

func (tc *TradeClient) OnMarketReadyChange(cb OnMarketReadyCB)

OnMarketReadyChange registers a callback which is called when the market ready status changes, i.e. when the market becomes ready or not ready for placing orders.

func (*TradeClient) OnOrdersUpdate

func (tc *TradeClient) OnOrdersUpdate(cb OrdersUpdateCB)

OnOrdersUpdate sets a callback for order updates. This will be called immediately when the client initializes, and for every subsequent order update. Each time this callback is executed, the entire list of open orders is returned (including partially filled orders).

func (*TradeClient) OnPositionsUpdate

func (tc *TradeClient) OnPositionsUpdate(cb OnPositionsUpdateCB)

OnPositionsUpdate sets a callback for position updates. This will be called immediately when the client initializes, and for every subsequent position update. An internal cache of positions is kept, and can be accessed with GetPositions().

func (*TradeClient) OnReady

func (tc *TradeClient) OnReady(cb func())

OnReady sets a callback function for when the client is fully initialized and ready to place/cancel trades. PlaceOrder and CancelOrder will return ErrNotInitialized if called before OnReady is called. OnReady is called each time the client initializes, meaning if the client disconnects for whatever reason, and then reconnects, it will be called again. Any number of OnReady callbacks can be placed, and can be done so safely from multiple goroutines.

func (*TradeClient) OnStateChange

func (tc *TradeClient) OnStateChange(state ConnState, cb StateCallback)

OnStateChange registers a new listener for the given state. The listener is registered with the default options (call the listener every time the state becomes active, and don't call the listener immediately for the current state). All registered callbacks for all states (and all messages, see OnMarketData) will be called by the same internal goroutine, i.e. they are never called concurrently with each other.

The order of listeners invocation for the same state is unspecified, and clients shouldn't rely on it.

The listeners shouldn't block; a blocked listener will also block the whole stream connection.

To subscribe to all state changes, use ConnStateAny as a state.

func (*TradeClient) OnStateChangeOpt

func (tc *TradeClient) OnStateChangeOpt(state ConnState, cb StateCallback, opt StateListenerOpt)

OnStateChangeOpt is like OnStateChange, but also takes additional options; see StateListenerOpt for details.

func (*TradeClient) OnSubscriptionResult

func (tc *TradeClient) OnSubscriptionResult(cb SubscriptionResultCB)

OnSubscriptionResult is called whenever a subscription attempt was made; it happens after the connection and authentication is successful.

func (*TradeClient) OnTradesUpdate

func (tc *TradeClient) OnTradesUpdate(cb PrivateTradesUpdateCB)

OnTradesUpdate sets a callabck for trade updates. This will be called immediately when the client initializes with the 1000 most recent trades. For every subsequent update, it will contain only the most recent trades.

func (*TradeClient) PlaceOrder

func (tc *TradeClient) PlaceOrder(orderOpt common.PlaceOrderOpt) (common.PrivateOrder, error)

PlaceOrder creates a new order based on the given OrderParams. PlaceOrder blocks until the order has been placed on the exchange or an error occurs. PlaceOrder can be called concurrently as many times as needed.

func (*TradeClient) Sync

func (tc *TradeClient) Sync(marketID common.MarketID) error

Sync forces a cache update by polling the exchange on behalf of the user. This function should not normally be needed, and is only useful in two scenarios: 1) an order is placed or cancelled outside of this client. 2) there is something preventing our trading back end from actively polling for updates. This happens rarely, and for various reasons. For example, an exchange may rate limit one of our servers.

func (*TradeClient) URL

func (tc *TradeClient) URL() string

URL returns the url the client is connected to, e.g. wss://stream.cryptowat.ch.

type TradeClientParams

type TradeClientParams struct {
	WSParams      *WSParams
	Subscriptions []*TradeSubscription
}

type TradeSessionAuth

type TradeSessionAuth struct {
	APIKey        string
	APISecret     string
	CustomerID    string // Bitstamp
	KeyPassphrase string // Coinbase-pro
}

type TradeSubscription

type TradeSubscription struct {
	MarketID common.MarketID
	Auth     *TradeSessionAuth // nil defaults to CW exchange keys
}

func (*TradeSubscription) GetResource

func (s *TradeSubscription) GetResource() string

type UnsubscribeError

type UnsubscribeError struct {
	Key          string
	Error        string
	Subscription Subscription
}

UnsubscribeError represents an error of a single key: it contains the key and the error message explaining why unsubscription has failed. Sent as part of UnsubscriptionResult.

type UnsubscriptionResult

type UnsubscriptionResult struct {
	// Successful unsubscriptions
	Subscriptions []Subscription
	// Faied unsubscriptions
	Failed []UnsubscribeError `json:"Failed,omitempty"`
	// Current status: list of the keys to which the client is now subscribed
	Status SubscriptionStatus
}

UnsubscriptionResult is sent to clients in response to the request to unsubscribe.

func (UnsubscriptionResult) String

func (v UnsubscriptionResult) String() string

type UnsubscriptionResultCB

type UnsubscriptionResultCB func(sr UnsubscriptionResult)

SubscriptionResultCB defines a callback function for OnUnsubscriptionResult.

type WSParams

type WSParams struct {
	// APIKey and SecretKey are needed to authenticate with Cryptowatch back end.
	// Inquire about getting access here: https://docs.google.com/forms/d/e/1FAIpQLSdhv_ceVtKA0qQcW6zQzBniRBaZ_cC4al31lDCeZirntkmWQw/viewform?c=0&w=1
	APIKey    string
	SecretKey string

	// URL is the URL to connect to over websockets. You will not have to set this
	// unless testing against a non-production environment since a default is
	// always used.
	URL string

	// ReconnectOpts contains settings for how to reconnect if the client becomes disconnected.
	// Sensible defaults are used.
	ReconnectOpts *ReconnectOpts
}

WSParams contains options for opening a websocket connection.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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