cxtgo

package module
v0.0.0-...-ab7db8c Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2018 License: MIT Imports: 9 Imported by: 0

README

GoDoc Build Status Go Report Card Codecov

Cxtgo provides an general interface for popular cryptocurrency exchanges. It's inspired by https://www.ccxt.trade library but with a more idiomatic interface for go. Cxtgo primary focus is based on performance, making it very suitable for high frequency trading algorithms.

The goal is to keep the api as simple as possible and to adapt every exchange to this generic interface and types.

Install

go get -u github.com/barthr/cxtgo

Supported exchanges

This is very much a work in progress. The goal is to have the most popular 50 crypto exchanges included.

Exchange Implemented Work in progess Order book streaming Ticker streaming Trade streaming
Binance No Yes Yes Yes Yes
Bitfinex No Yes
Bitmex No Yes

Contributing

ToDo.

Contributors

ToDo.

Author

Bart Fokker

License

MIT.

Documentation

Index

Constants

View Source
const (
	// Version indicates cxtgo version
	Version = 0.1
)

Variables

This section is empty.

Functions

func AmountToLots

func AmountToLots(info MarketInfo, amount float64) float64

AmountToLots converts an amount to a lot sized amount according to the precisions in `MarketInfo`.

func Err

func Err(args ...interface{}) error

Err is the standard error function for creating errors in cxtgo.

func Is

func Is(kind ErrorKind, err error) bool

Is reports whether err is an *Error of the given Kind. If err is nil then Is returns false.

func Zeros

func Zeros(input string, splitter string) int

Zeros calculates the amount of zero's after the splitter including the first item which is not '0'. For example 0,0001 returns the value 4.

Types

type AccountAPI

type AccountAPI interface {
	// Balances returns the balances from the exchange
	Balances(ctx context.Context, params ...Params) (Balances, error)
	// MyTrades returns the trades made by that account
	MyTrades(ctx context.Context, params ...Params) ([]Trade, error)
	// FreeBalance returns the free balance in the account
	FreeBalance(ctx context.Context, params ...Params) (PartialBalances, error)
	// UsedBalance returns the used balance (in trade) in the account
	UsedBalance(ctx context.Context, params ...Params) (PartialBalances, error)
	// TotalBalance returns the total used + free balance in the account
	TotalBalance(ctx context.Context, params ...Params) (PartialBalances, error)
	// Currently unused
	Deposit(ctx context.Context, params ...Params) error
	// Currently unused
	Withdraw(ctx context.Context, params ...Params) error
}

AccountAPI are the private user api calls for an exchange.

type Ask

type Ask Offer

Ask represents an ask offer from the order book

type Balance

type Balance struct {
	Asset string
	Free  float64
	Used  float64
	Total float64
}

Balance represents a balance for a currency

type Balances

type Balances map[string]Balance

Balances represent all the balances from an exchange. Currency mapped to the actual balance.

type Base

type Base struct {
	ID           ExchangeID
	Name         ExchangeName
	Raw          bool
	Debug        bool
	DebugLog     io.Writer
	UserAgent    string
	BaseURL      string
	Proxy        string
	APIKEY       string
	APISecret    string
	Ratelimit    ratelimit.Limiter
	Market       MarketInfos
	CustomParams Params
}

Base is the base information and methods for an exchange.

func NewBase

func NewBase(opts ...BaseOpt) Base

NewBase returns a new base exchange with the given opts applied.

type BaseOpt

type BaseOpt func(*Base)

BaseOpt mutates the settings for the exchange.

func WithAPIKey

func WithAPIKey(key string) BaseOpt

WithAPIKey sets the api key for the exchange.

func WithAPISecret

func WithAPISecret(secret string) BaseOpt

WithAPISecret sets the api secret for the exchange.

func WithBaseURL

func WithBaseURL(url string) BaseOpt

WithBaseURL sets the base url for the exchange

func WithCustom

func WithCustom(custom Params) BaseOpt

WithCustom sets custom parameters for the exchange. Additional exchange specific parameters can be passed in here and used in the exchange implemenations.

func WithDebug

func WithDebug(toggle bool) BaseOpt

WithDebug sets the debug flag for the exchange.

func WithDebuglogger

func WithDebuglogger(w io.Writer) BaseOpt

WithDebuglogger sets the debug logger output to w for the exchange.

func WithID

func WithID(id ExchangeID) BaseOpt

WithID sets the id for the exchange. This can be used to identify different instances of the same exchange.

func WithIncludeRaw

func WithIncludeRaw(toggle bool) BaseOpt

WithIncludeRaw sets the toggle to include the raw response from the exchange.

func WithName

func WithName(name ExchangeName) BaseOpt

WithName sets the name for the exchange.

func WithProxyURL

func WithProxyURL(proxy string) BaseOpt

WithProxyURL sets the proxy to use for the http requests

func WithRatelimit

func WithRatelimit(rl ratelimit.Limiter) BaseOpt

WithRatelimit sets a rate limit to use for the api calls to the exchange.

func WithUserAgent

func WithUserAgent(userAgent string) BaseOpt

WithUserAgent sets the user agent for the exchange.

type Bid

type Bid Offer

Bid represents a bid offer from the order book

type Currencies

type Currencies map[string]Currency

Currencies represent multiple currencies from the exchange.

type Currency

type Currency struct {
	ID   string
	Code string
}

Currency represents a currency from the exchange.

type Error

type Error struct {
	// Exchange is the name of the exchange being used.
	Exchange ExchangeName
	// Op is the operation being performed, usually the name of the method
	Op Op
	// Kind is the class of error, as defined by the error kinds.
	// Other is used if its class is unknown or irrelevant.
	Kind ErrorKind
	// The underlying error that triggered this one, if any.
	Err error
}

Error is the type that implements the error interface. It contains a number of fields, each of different type. An Error value may leave some values unset. Adapted from https://github.com/upspin/upspin/blob/master/errors/errors.go

func (*Error) Error

func (e *Error) Error() string

type ErrorKind

type ErrorKind uint8

ErrorKind defines the kind of error this is.

const (
	Other                  ErrorKind = iota // Unclassified error. This value is not printed in the error message.
	SymbolNotFound                          // Kind for when executing an action on the exchange for a symbol which is not found.
	Network                                 // Kind for when there are Network problems.
	Conversion                              // Kind for when there is a conversion error.
	NotSupported                            // Kind for when an operation is not supported by the exchange.
	Authentication                          // Kind for when the authentication to the exchange fails.
	InsufficientFunds                       // Kind for when there are not enough funds in the account to execute the action.
	Ratelimited                             // Kind for when there are not enough funds in the account to execute the action.
	InvalidOrder                            // Kind for when an order is submitted which doesn't pass the criteria from the exchange.
	OrderNotFound                           // Kind for when an order is not found on the exchange.
	ExchangeNotAvailable                    // Kind for when the given exchange is not available.
	StreamClosedByExchange                  // Kind for when the stream has been closed by the exchange.
	StreamUnavailable                       // Kind for when the stream from the exchange is currently unavailable.
)

Kinds of errors.

These are the different error kinds from cxtgo. Do not reorder this list or remove any items since that will change their values. New items must be added only to the end.

func (ErrorKind) String

func (ek ErrorKind) String() string

type Exchange

type Exchange interface {
	Info() Base

	PublicAPI
	AccountAPI
	OrderAPI
}

Exchange defines all the api calls for an exchange.

type ExchangeID

type ExchangeID string

ExchangeID identifies an id for an exchange.

type ExchangeName

type ExchangeName string

ExchangeName identifies the name of the exchange.

type MarketInfo

type MarketInfo struct {
	Symbol    Symbol
	ID        string
	Base      string
	Quote     string
	Active    bool
	Precision MarketPrecision
	Limits    MarketLimit
	Lot       float64
	Taker     float64
	Maker     float64
	Raw       []byte
}

MarketInfo defines all the info for a market (given pair). Things likes what kind of maker and taker fee etc.

type MarketInfos

type MarketInfos map[Symbol]MarketInfo

MarketInfos defines all the info for a market for every symbol.

type MarketLimit

type MarketLimit struct {
	Amount MinMax
	Price  MinMax
	Cost   MinMax
}

MarketLimit defines the limits for a market, what min and max amounts/prices and costs.

type MarketPrecision

type MarketPrecision struct {
	Base   int
	Quote  int
	Amount int
	Price  int
}

MarketPrecision defines the precision for a given pair, how many decimals for the amount and prices

type MinMax

type MinMax struct {
	Min float64
	Max float64
}

MinMax defines the minimum and maximum value

type Offer

type Offer struct {
	Price  float64
	Amount float64
}

Offer defines an offer from the order book

type Op

type Op string

Op describes an operation, usually as the interface and the respective method, such as "public.Ticker" or "accountAPI.Balance".

type Order

type Order struct {
	Symbol    Symbol
	ID        string
	Timestamp time.Time
	Status    OrderStatus
	Type      OrderType
	Price     float64
	Cost      float64
	Amount    float64
	Filled    float64
	Remaining float64
	Fee       float64
	Raw       []byte
}

Order represents an order at an exchange.

type OrderAPI

type OrderAPI interface {
	// LimitOrder creates a limit order at the exchange.
	LimitOrder(ctx context.Context, symbol Symbol, side Side, offer Offer, params ...Params) error
	// MarketOrder creates an market order at the exchange.
	MarketOrder(ctx context.Context, symbol Symbol, side Side, amount float64, params ...Params) error
	// CancelOrder cancels the order for the given id.
	CancelOrder(ctx context.Context, ID string, symbol *Symbol, params ...Params) error
	// Order returns the order information for the given order id.
	Order(ctx context.Context, params ...Params) (Order, error)
	// Orders returns the order information for all the orders for that symbol.
	Orders(ctx context.Context, params ...Params) ([]Order, error)
	// OpenOrders is like orders but only returning orders which are open.
	OpenOrders(ctx context.Context, params ...Params) ([]Order, error)
	// ClosedOrders is like orders but only returning orders which are closed.
	ClosedOrders(ctx context.Context, params ...Params) ([]Order, error)
}

OrderAPI are all the calls for creating updating and fetching orders.

type OrderStatus

type OrderStatus uint8

OrderStatus represents the state of an order.

const (
	// UnknownStatus status for the zero value of order status.
	UnknownStatus OrderStatus = iota
	// OrderOpen represents the open order status.
	OrderOpen
	// OrderClosed represents the closed order status.
	OrderClosed
	// OrderCanceled represents the canceled order status.
	OrderCanceled
)

func (OrderStatus) String

func (os OrderStatus) String() string

String returns the string value of os

type OrderType

type OrderType uint8

OrderType represents the type of the order.

const (
	// UnknownOrderType represents the zero value of the order type.
	UnknownOrderType OrderType = iota
	// MarketOrder defines the market order type.
	MarketOrder
	// LimitOrder defines the limit order type.
	LimitOrder
)

func (OrderType) String

func (ot OrderType) String() string

String returns the string value of ot.

type Orderbook

type Orderbook struct {
}

Orderbook is a definition for an orderbook

type OrderbookStreamer

type OrderbookStreamer interface {
	StreamOrderbook(onUpdate func(s Summary), onError func(err error), opts ...StreamOpt) error
}

OrderbookStreamer is a streamer interface for the orderbook

type Params

type Params map[string]interface{}

Params are additional parameters which can be send for specific options per exchange

func UnionParams

func UnionParams(pp []Params) Params

UnionParams merges the parameters to one single parameter map. It handles the element in a sequential way, this means that `Params` with the same key will override earlier values. It always returns a valid `Params` maps, this map could be empty but never `nil`.

func (Params) GetBool

func (p Params) GetBool(key string) (bool, bool)

GetBool return `key` in params as an `bool`. Indicating if the actual `value` was an bool.

func (Params) GetFloat32

func (p Params) GetFloat32(key string) (float32, bool)

GetFloat32 return `key` in params as a float32. Indicating if the actual `value` was a float32.

func (Params) GetFloat64

func (p Params) GetFloat64(key string) (float64, bool)

GetFloat64 return `key` in params as a float64. Indicating if the actual `value` was a float64.

func (Params) GetInt

func (p Params) GetInt(key string) (int, bool)

GetInt return `key` in params as an `int`. Indicating if the actual `value` was an int.

func (Params) GetInt32

func (p Params) GetInt32(key string) (int32, bool)

GetInt32 return `key` in params as an int32. Indicating if the actual `value` was an int32.

func (Params) GetInt64

func (p Params) GetInt64(key string) (int64, bool)

GetInt64 return `key` in params as an `int64`. Indicating if the actual `value` was an int64.

func (Params) GetString

func (p Params) GetString(key string) (string, bool)

GetString return `key` in params as a string. Indicating if the actual `value` was a string.

type PartialBalances

type PartialBalances map[string]float64

PartialBalances represents partial balances for a currency (for example Free, Used, Total).

type PublicAPI

type PublicAPI interface {
	// Markets return the market information for an exchange.
	Markets(ctx context.Context, params ...Params) (MarketInfos, error)
	// Currencies return the currencies used by the exchange.
	Currencies(ctx context.Context, params ...Params) (Currencies, error)
	// Ticker returns the ticker information for a given symbol.
	Ticker(ctx context.Context, symbol Symbol, params ...Params) (Ticker, error)
	// Tickers returns all the ticker information for the given symbols.
	Tickers(ctx context.Context, symbols Symbols, params ...Params) (Tickers, error)
	// Orderbook returns order book information for a given symbol.
	OrderBook(ctx context.Context, symbol Symbol, params ...Params) (Orderbook, error)
	// OHLCV returns the Open high low close volume infromation for a symbol.
	OHLCV(ctx context.Context, params ...Params) error
	// Trades return all the trades for a given symbol.
	Trades(ctx context.Context, params ...Params) ([]Trade, error)
}

PublicAPI are the public available calls for an exchange.

type Side

type Side uint8

Side defines the side for the order (f.e. Sell or Buy).

const (
	// Unknown side for the zero value of side.
	Unknown Side = iota
	// Sell defines the sell side.
	Sell
	// Buy defines the buy side.
	Buy
)

func (Side) String

func (s Side) String() string

String returns the string value of s.

type StreamConfig

type StreamConfig struct {
	Ctx       context.Context
	Symbol    Symbol
	Params    Params
	Reconnect bool
}

StreamConfig defines the configuration options for the stream

type StreamOpt

type StreamOpt func(*StreamConfig)

StreamOpt defines a function option to modify the streamconfiguration

func WithReconnect

func WithReconnect(toggle bool) StreamOpt

WithReconnect set's the reconnect toggle for the streamer. This will handle the reconnection of the underlying websocket connection. In case of an error when reconnecting it will retry 5 times with a exponential backoff. Note that the `Stream` functions can still return an error when a abnormal closure happens.

func WithStreamContext

func WithStreamContext(ctx context.Context) StreamOpt

WithStreamContext set's the context for the stream

func WithStreamParams

func WithStreamParams(params Params) StreamOpt

WithStreamParams set's the stream parameters to the given params.

func WithStreamSymbol

func WithStreamSymbol(s Symbol) StreamOpt

WithStreamSymbol set's the stream symbol the the given symbol.

type StreamType

type StreamType int

StreamType defines which type of stream it is. This is helpfull for debuggin errors

const (
	// UnknownStream indicates a stream which isn't known
	UnknownStream StreamType = iota
	// TradeStream indicates a trade stream
	TradeStream
	// TickerStream indicates a ticker stream
	TickerStream
	// OrderbookStream indicates a orderbook stream type
	OrderbookStream
)

type StreamingAPI

type StreamingAPI interface {
	OrderbookStreamer
	TickerStreamer
	TradeStreamer
}

StreamingAPI defines the streaming api endpoints for an exchange.

type Summary

type Summary struct {
	Bids []Bid
	Asks []Ask
	// contains filtered or unexported fields
}

Summary defines a view of the order book. The bids are sorted descending and the ask ascending.

func (Summary) Head

func (s Summary) Head(n int) (Summary, error)

Head returns n items from the orderbook returning a new summary with the reflected

func (Summary) Spread

func (s Summary) Spread() float64

Spread calculates the spread between bid and ask.

func (Summary) Symbol

func (s Summary) Symbol() Symbol

Symbol returns the symbol from the summary

type Symbol

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

Symbol represents a combination of two currencies (BTCUSD). this type is immutable.

func NewSymbol

func NewSymbol(from, to string, delim ...string) Symbol

NewSymbol create's a new Pair from the given string, optional taking a delimiter.

func (Symbol) Base

func (p Symbol) Base() string

Base returns the base currency from the Symbol.

func (Symbol) Delim

func (p Symbol) Delim() string

Delim returns the delim (this is optional to use the symbol).

func (Symbol) Quote

func (p Symbol) Quote() string

Quote returns the quote currency from the Symbol.

func (Symbol) Reverse

func (p Symbol) Reverse() Symbol

Reverse reverse the currencies (fe. BTCUSD to USDBTC or BTC/USD to USD/BTC).

func (Symbol) String

func (p Symbol) String() string

String returns the string version of the Symbol

type Symbols

type Symbols []Symbol

Symbols is a container type for multiple symbols.

func SymbolSet

func SymbolSet(data Symbols) Symbols

SymbolSet returns Symbols with the duplicates removed.

func (Symbols) Len

func (s Symbols) Len() int

Len returns the length of s.

func (Symbols) Less

func (s Symbols) Less(i int, j int) bool

Less defines the order of s for sorting.

func (Symbols) Swap

func (s Symbols) Swap(i int, j int)

Swap swaps elements in s.

type Ticker

type Ticker struct {
	Symbol      Symbol
	Ask         float64
	Bid         float64
	Basevolume  float64
	Quotevolume float64
	Average     float64
	Change      float64
	Open        float64
	Close       float64
	First       float64
	Last        float64
	High        float64
	Low         float64
	Percentage  float64
	Vwap        float64

	Datetime  time.Time
	Timestamp int64

	Raw []byte
}

Ticker represents a ticker from an exchange.

type TickerStreamer

type TickerStreamer interface {
	StreamTicker(onUpdate func(t Ticker), onError func(err error), opts ...StreamOpt) error
}

TickerStreamer is a streamer interface for tickers

type Tickers

type Tickers map[Symbol]Tickers

Tickers represents multiple tickers from an exchange.

type Trade

type Trade struct {
}

Trade represents an trade from the exchange.

type TradeStreamer

type TradeStreamer interface {
	StreamTrades(onUpdate func(t Trade), onError func(err error), opts ...StreamOpt) error
}

TradeStreamer is a streamer interface for the trades

Directories

Path Synopsis
exchanges

Jump to

Keyboard shortcuts

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